30 Commits

Author SHA1 Message Date
Gerhard Stein
d480cc0484 Bump CG 2021-06-19 18:10:58 +00:00
Gerhard Stein
5b4e368938 CG Update 2021-03-27 18:43:26 +00:00
Gerhard Stein
a2285e949c Updated Commander Genius 2020-10-29 19:10:31 +00:00
Gerhard Stein
c50c43db6f Bump Version 2.6.1 2020-10-16 17:09:57 +00:00
Gerhard Stein
7566e05ee6 Updated Commander Genius 2020-10-15 13:48:35 +00:00
Gerhard Stein
39d55b5d19 code fix 2020-10-11 19:25:53 +00:00
Gerhard Stein
fed2b2469b Updated CG, and added a request permission 2020-10-11 19:22:39 +00:00
Gerhard Stein
d2c77299ff Using static curl and openssl. 2020-10-10 16:48:23 +00:00
Gerhard Stein
57a23c6a56 Adding proper app icon 2020-10-10 07:13:46 +00:00
Gerhard Stein
315dec4b42 Better Template File for SDL2 so the SDL2 can be replaced by a newer version at any time 2020-10-10 06:36:22 +00:00
Gerhard Stein
ec0b9d5ebe Use Virtualpad option added for android builds 2020-10-09 17:23:14 +00:00
Gerhard Stein
61ec755987 More stuff starting to work on CG and SDL 2.0 2020-10-09 17:20:17 +00:00
Gerhard Stein
4a82d315d5 Enabled Commander Genius fully using SDL2. 2020-10-09 14:41:09 +00:00
Gerhard Stein
0ce5f5dee3 SDL 2.0 does not require an icon as external file anymore. So fewer android permission are required for playing that 2020-10-09 14:39:50 +00:00
Gerhard Stein
99393e2dbe SDL2 test application finally, running, but still crashes, for a not found file. Meh. 2020-10-04 19:34:12 +00:00
Gerhard Stein
17c547a43f SDL2 Test updates 2020-10-04 11:52:43 +00:00
Gerhard Stein
d611b7655b Updated javaSDL2 2020-10-04 10:19:21 +00:00
Gerhard Stein
a0bded0cce c++ must be enabled for sdl2, because hid api implementation uses some c++ code. 2020-10-03 12:00:58 +00:00
Gerhard Stein
015fb7ad45 Blacklisting for projects which do not work with SDL2 2020-10-03 11:04:21 +00:00
Gerhard Stein
d0558f22d9 Cleanups 2020-10-03 10:37:24 +00:00
Gerhard Stein
32046e051c More target names changes 2020-10-03 10:28:18 +00:00
Gerhard Stein
487062dd11 Using proper official target name 2020-10-03 10:25:22 +00:00
Gerhard Stein
4741fe77bb Added SDL2_mixer 2020-10-03 09:49:54 +00:00
Gerhard Stein
d9267a1653 Updated Sprite minimal test 2020-10-03 09:42:01 +00:00
Gerhard Stein
9fd75f119e Renaming SDL test code 2020-10-03 09:35:53 +00:00
Gerhard Stein
6962dd59fa Added Blacklist feature for SDL2 stuff 2020-09-29 16:40:03 +00:00
Gerhard Stein
99effe98c4 Setting CG using SDL2 2020-09-28 15:32:01 +00:00
Gerhard Stein
712e3b1624 Added case for SDL2, reduction of base libs 2020-09-28 15:31:27 +00:00
Gerhard Stein
817c0ac596 Updated SDL2_Image 2020-09-28 16:43:02 +02:00
Gerhard Stein
2ecfbd1189 Updated SDL2 2020-09-28 16:41:30 +02:00
5918 changed files with 2154563 additions and 149200 deletions

View File

@@ -1 +0,0 @@
project/app/build/outputs/apk/release/app-release.apk

View File

@@ -68,11 +68,16 @@ if [ "$AppUsesJoystick" != "y" ]; then
AppUsesSecondJoystick=n
fi
if [ "$LibSdlVersion" = "2.0" ]; then
echo Patch of settings menu not supported in SDL 2.0
else
MenuOptionsAvailable=
for FF in Menu MenuMisc MenuMouse MenuKeyboard ; do
MenuOptionsAvailable1=`grep 'extends Menu' $JAVA_SRC_PATH/Settings$FF.java | sed "s/.* class \(.*\) extends .*/Settings$FF.\1/" | tr '\n' ' '`
MenuOptionsAvailable="$MenuOptionsAvailable $MenuOptionsAvailable1"
done
fi
FirstStartMenuOptionsDefault='new SettingsMenuMisc.ShowReadme(), (AppUsesMouse \&\& \! ForceRelativeMouseMode \? new SettingsMenuMouse.DisplaySizeConfig(true) : new SettingsMenu.DummyMenu()), new SettingsMenuMisc.OptionalDownloadConfig(true), new SettingsMenuMisc.GyroscopeCalibration()'
@@ -747,7 +752,15 @@ else
MultiABI="$MultiABI"
fi
LibrariesToLoad="\\\"sdl_native_helpers\\\", \\\"sdl-$LibSdlVersion\\\""
if [ "$LibSdlVersion" = "2.0" ] ; then
LibrariesToLoad="\\\"sdl_native_helpers\\\", \\\"SDL2\\\""
else
LibrariesToLoad="\\\"sdl_native_helpers\\\", \\\"sdl-$LibSdlVersion\\\""
fi
StaticLibraries="`echo '
include project/jni/SettingsTemplate.mk
all:
@@ -801,6 +814,7 @@ fi
rm -rf project/src
mkdir -p project/src
cd $JAVA_SRC_PATH
for F in *.java; do
echo '// DO NOT EDIT THIS FILE - it is automatically generated, ALL YOUR CHANGES WILL BE OVERWRITTEN, edit the file under $JAVA_SRC_PATH dir' | cat - $F > ../src/$F
done
@@ -809,26 +823,41 @@ if [ -e ../jni/application/src/java.diff ]; then patch -d ../src --no-backup-if-
if [ -e ../jni/application/src/java.patch ]; then patch -d ../src --no-backup-if-mismatch < ../jni/application/src/java.patch || exit 1 ; fi
if ls ../jni/application/src/*.java > /dev/null 2>&1; then cp -f ../jni/application/src/*.java ../src ; fi
for F in ../src/*.java; do
if [ "$LibSdlVersion" = "2.0" ] ; then
echo Patching java with SDL 2.0 not supported
else
for F in ../src/*.java; do
echo Patching $F
$SEDI "s/^package .*;/package $AppFullName;/" $F
done
done
fi
cd ../..
# In case we use SDL2 let simlink the SDLActivity source file
echo Patching project/AndroidManifest.xml
if [ "$LibSdlVersion" = "2.0" ] ; then
ln -s ../jni/sdl-2.0/android-project/src/org/libsdl/app/SDLActivity.java project/src/SDLActivity.java
cat project/AndroidManifestTemplateSDL2.xml | \
sed "s/package=.*/package=\"$AppFullName\"/" | \
sed "s^android:versionCode=.*^android:versionCode=\"$AppVersionCode\"^" | \
sed "s^android:versionName=.*^android:versionName=\"$AppVersionName\"^" > \
project/AndroidManifest.xml
else
cat project/AndroidManifestTemplate.xml | \
sed "s/package=.*/package=\"$AppFullName\"/" | \
sed "s/android:screenOrientation=.*/android:screenOrientation=\"$ScreenOrientation1\"/" | \
sed "s^android:versionCode=.*^android:versionCode=\"$AppVersionCode\"^" | \
sed "s^android:versionName=.*^android:versionName=\"$AppVersionName\"^" > \
project/AndroidManifest.xml
fi
if [ "$LibSdlVersion" = "2.0" ] ; then
echo Copying some SDL 2.0 resources
cp -pr project/jni/sdl-2.0/android-project/app/src/main/res/* project/res/
fi
echo Patching project/AndroidManifest.xml
cat project/AndroidManifestTemplate.xml | \
sed "s/package=.*/package=\"$AppFullName\"/" | \
sed "s/android:screenOrientation=.*/android:screenOrientation=\"$ScreenOrientation1\"/" | \
sed "s^android:versionCode=.*^android:versionCode=\"$AppVersionCode\"^" | \
sed "s^android:versionName=.*^android:versionName=\"$AppVersionName\"^" > \
project/AndroidManifest.xml
if [ "$AdmobPublisherId" = "n" -o -z "$AdmobPublisherId" ] ; then
$SEDI "/==ADMOB==/ d" project/AndroidManifest.xml
AdmobPublisherId=""
@@ -844,6 +873,7 @@ cat project/app/build-template.gradle | \
project/app/build.gradle
echo "-keep class $AppFullName.** { *; }" > project/proguard-local.cfg
echo "-keep class org.libsdl.app.** { *; }" >> project/proguard-local.cfg
if [ "$AppRecordsAudio" = "n" -o -z "$AppRecordsAudio" ] ; then
$SEDI "/==RECORD_AUDIO==/ d" project/AndroidManifest.xml
@@ -929,6 +959,25 @@ else
fi
if [ "$LibSdlVersion" = "2.0" ] ; then
echo Patching java files not fully supported in SDL 2.0 yet.
ACTIVITY="${AppShortName}Activity"
sed -i -e "s|\"SDLActivity\"|\"$ACTIVITY\"|g" project/AndroidManifest.xml
echo Creating $JAVA_SRC_PATH/$ACTIVITY.java ...
# Fill in a default Activity
cat >"$JAVA_SRC_PATH/$ACTIVITY.java" <<__EOF__
package $AppFullName;
import org.libsdl.app.SDLActivity;
public class $ACTIVITY extends SDLActivity
{
}
__EOF__
else
echo Patching project/src/Globals.java
$SEDI "s/public static String ApplicationName = .*;/public static String ApplicationName = \"$AppShortName\";/" project/src/Globals.java
$SEDI "s/public static final boolean Using_SDL_1_3 = .*;/public static final boolean Using_SDL_1_3 = $UsingSdl13;/" project/src/Globals.java
@@ -994,12 +1043,21 @@ $SEDI "s/public static String AdmobBannerSize = .*/public static String AdmobBan
$SEDI "s%public static String GooglePlayGameServicesId = .*%public static String GooglePlayGameServicesId = \"$GooglePlayGameServicesId\";%" project/src/Globals.java
$SEDI "s/public static String AppLibraries.*/public static String AppLibraries[] = { $LibrariesToLoad };/" project/src/Globals.java
$SEDI "s/public static String AppMainLibraries.*/public static String AppMainLibraries[] = { $MainLibrariesToLoad };/" project/src/Globals.java
fi
# TODO: We should not build png, jpeg if SDL2_image is used
if [ "$LibSdlVersion" = "2.0" ]; then
APP_MODULES_BASE="SDL2"
else
APP_MODULES_BASE="sdl-$LibSdlVersion sdl_main sdl_native_helpers jpeg png ogg flac vorbis freetype"
fi
echo Patching project/jni/Settings.mk
echo '# DO NOT EDIT THIS FILE - it is automatically generated, edit file SettingsTemplate.mk' > project/jni/Settings.mk
cat project/jni/SettingsTemplate.mk | \
sed "s/APP_MODULES := .*/APP_MODULES := sdl-$LibSdlVersion sdl_main sdl_native_helpers jpeg png ogg flac vorbis freetype $CompiledLibraries application/" | \
sed "s/APP_MODULES := .*/APP_MODULES := $APP_MODULES_BASE $CompiledLibraries application/" | \
sed "s/APP_ABI := .*/APP_ABI := $MultiABI/" | \
sed "s/SDL_JAVA_PACKAGE_PATH := .*/SDL_JAVA_PACKAGE_PATH := $AppFullNameUnderscored/" | \
sed "s^SDL_CURDIR_PATH := .*^SDL_CURDIR_PATH := $DataPath^" | \
@@ -1034,13 +1092,16 @@ echo Patching strings.xml
rm -rf project/res/values*/strings.xml
cd $JAVA_SRC_PATH/translations
for F in */strings.xml; do
mkdir -p ../../res/`dirname $F`
cat $F | \
sed "s^[<]string name=\"app_name\"[>].*^<string name=\"app_name\">$AppName</string>^" > \
../../res/$F
mkdir -p ../../res/`dirname $F`
cat $F | \
sed "s^[<]string name=\"app_name\"[>].*^<string name=\"app_name\">$AppName</string>^" > \
../../res/$F
done
cd ../../..
SDK_DIR=`grep '^sdk.dir' project/local.properties | sed 's/.*=//'`
[ -z "$SDK_DIR" ] && SDK_DIR=`which android | sed 's@/tools/android$@@'`
mkdir -p project/libs

View File

@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Replace com.test.game with the identifier of your game below, e.g.
com.gamemaker.game
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.libsdl.app"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="auto">
<!-- OpenGL ES 2.0 -->
<uses-feature android:glEsVersion="0x00020000" />
<!-- Touchscreen support -->
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<!-- Game controller support -->
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
<uses-feature
android:name="android.hardware.gamepad"
android:required="false" />
<uses-feature
android:name="android.hardware.usb.host"
android:required="false" />
<!-- External mouse input events -->
<uses-feature
android:name="android.hardware.type.pc"
android:required="false" />
<!-- Audio recording support -->
<!-- if you want to capture audio, uncomment this. -->
<!-- <uses-feature
android:name="android.hardware.microphone"
android:required="false" /> -->
<!-- Allow writing to external storage -->
<!--
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-->
<!-- Allow access to Bluetooth devices -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- Allow access to the vibrator -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- ==INTERNET== --> <uses-permission android:name="android.permission.INTERNET" />
<!-- ==EXTERNAL_STORAGE== --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- ==NOT_EXTERNAL_STORAGE== --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<!-- ==NOT_EXTERNAL_STORAGE== --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" /> <!-- App has write access to it's own dir on SD card without this permission on Android 4.4 and above -->
<!-- ==READ_OBB== --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<!-- ==READ_OBB== --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="23" /> <!-- OBB file requires explicit permission before Marshmallow -->
<!-- ==RECORD_AUDIO== --> <uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- ==ADMOB== --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- ==FOREGROUND_SERVICE== --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- if you want to capture audio, uncomment this. -->
<!-- <uses-permission android:name="android.permission.RECORD_AUDIO" /> -->
<!-- Create a Java class extending SDLActivity and place it in a
directory under app/src/main/java matching the package, e.g. app/src/main/java/com/gamemaker/game/MyGame.java
then replace "SDLActivity" with the name of your class (e.g. "MyGame")
in the XML below.
An example Java class can be found in README-android.md
-->
<application android:label="@string/app_name"
android:icon="@drawable/icon"
android:allowBackup="true"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:hardwareAccelerated="true" >
<!-- Example of setting SDL hints from AndroidManifest.xml:
<meta-data android:name="SDL_ENV.SDL_ACCELEROMETER_AS_JOYSTICK" android:value="0"/>
-->
<activity android:name="SDLActivity"
android:label="@string/app_name"
android:alwaysRetainTaskState="true"
android:launchMode="singleInstance"
android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Drop file event -->
<!--
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
-->
</activity>
</application>
</manifest>

View File

@@ -1,129 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.os.Vibrator;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.util.Log;
import android.widget.TextView;
class AccelerometerReader implements SensorEventListener
{
private SensorManager _manager = null;
public boolean openedBySDL = false;
public static final GyroscopeListener gyro = new GyroscopeListener();
public AccelerometerReader(Activity context)
{
_manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
}
public synchronized void stop()
{
if( _manager != null )
{
Log.i("SDL", "libSDL: stopping accelerometer/gyroscope");
_manager.unregisterListener(this);
_manager.unregisterListener(gyro);
}
}
public synchronized void start()
{
if( (Globals.UseAccelerometerAsArrowKeys || Globals.AppUsesAccelerometer) &&
_manager != null && _manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null )
{
Log.i("SDL", "libSDL: starting accelerometer");
_manager.registerListener(this, _manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
if( Globals.AppUsesGyroscope && _manager != null && _manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null )
{
Log.i("SDL", "libSDL: starting gyroscope");
_manager.registerListener(gyro, _manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
}
}
public void onSensorChanged(SensorEvent event)
{
if( Globals.HorizontalOrientation )
nativeAccelerometer(event.values[1], -event.values[0], event.values[2]);
else
nativeAccelerometer(event.values[0], event.values[1], event.values[2]); // TODO: not tested!
}
public void onAccuracyChanged(Sensor s, int a)
{
}
static class GyroscopeListener implements SensorEventListener
{
public float x1, x2, xc, y1, y2, yc, z1, z2, zc;
public GyroscopeListener()
{
}
public void onSensorChanged(SensorEvent event)
{
// TODO: vertical orientation
//if( Globals.HorizontalOrientation )
if( event.values[0] < x1 || event.values[0] > x2 ||
event.values[1] < y1 || event.values[1] > y2 ||
event.values[2] < z1 || event.values[2] > z2 )
nativeGyroscope(event.values[0] - xc, event.values[1] - yc, event.values[2] - zc);
}
public void onAccuracyChanged(Sensor s, int a)
{
}
public boolean available(Activity context)
{
SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
return ( manager != null && manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null );
}
public void registerListener(Activity context, SensorEventListener l)
{
SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
if ( manager == null && manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) == null )
return;
manager.registerListener(l, manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
}
public void unregisterListener(Activity context,SensorEventListener l)
{
SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
if ( manager == null )
return;
manager.unregisterListener(l);
}
}
private static native void nativeAccelerometer(float accX, float accY, float accZ);
private static native void nativeGyroscope(float X, float Y, float Z);
}

View File

@@ -1,50 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.view.View;
class Advertisement
{
MainActivity parent;
public Advertisement(MainActivity p)
{
parent = p;
}
public View getView()
{
return null;
}
public void requestNewAd()
{
}
}

View File

@@ -1,307 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.media.AudioTrack;
import android.media.AudioManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import java.io.*;
import android.util.Log;
import java.util.concurrent.Semaphore;
class AudioThread
{
private MainActivity mParent;
private AudioTrack mAudio;
private byte[] mAudioBuffer;
private int mVirtualBufSize;
public AudioThread(MainActivity parent)
{
mParent = parent;
mAudio = null;
mAudioBuffer = null;
//nativeAudioInitJavaCallbacks();
}
public int fillBuffer()
{
if( mParent.isPaused() )
{
try{
Thread.sleep(500);
} catch (InterruptedException e) {}
}
else
{
//if( Globals.AudioBufferConfig == 0 ) // Gives too much spam to logcat, makes things worse
// mAudio.flush();
mAudio.write( mAudioBuffer, 0, mVirtualBufSize );
}
return 1;
}
public int initAudio(int rate, int channels, int encoding, int bufSize)
{
if( mAudio == null )
{
channels = ( channels == 1 ) ? AudioFormat.CHANNEL_CONFIGURATION_MONO :
AudioFormat.CHANNEL_CONFIGURATION_STEREO;
encoding = ( encoding == 1 ) ? AudioFormat.ENCODING_PCM_16BIT :
AudioFormat.ENCODING_PCM_8BIT;
mVirtualBufSize = bufSize;
if( AudioTrack.getMinBufferSize( rate, channels, encoding ) > bufSize )
bufSize = AudioTrack.getMinBufferSize( rate, channels, encoding );
if(Globals.AudioBufferConfig != 0) { // application's choice - use minimal buffer
bufSize = (int)((float)bufSize * (((float)(Globals.AudioBufferConfig - 1) * 2.5f) + 1.0f));
mVirtualBufSize = bufSize;
}
mAudioBuffer = new byte[bufSize];
mAudio = new AudioTrack(AudioManager.STREAM_MUSIC,
rate,
channels,
encoding,
bufSize,
AudioTrack.MODE_STREAM );
mAudio.play();
}
return mVirtualBufSize;
}
public byte[] getBuffer()
{
return mAudioBuffer;
}
public int deinitAudio()
{
if( mAudio != null )
{
mAudio.stop();
mAudio.release();
mAudio = null;
}
mAudioBuffer = null;
return 1;
}
public int initAudioThread()
{
// Make audio thread priority higher so audio thread won't get underrun
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
return 1;
}
public int pauseAudioPlayback()
{
if( mAudio != null )
{
mAudio.pause();
}
if( mRecordThread != null )
{
mRecordThread.pauseRecording();
}
return 1;
}
public int resumeAudioPlayback()
{
if( mAudio != null )
{
mAudio.play();
}
if( mRecordThread != null )
{
mRecordThread.resumeRecording();
}
return 1;
}
private native int nativeAudioInitJavaCallbacks();
// ----- Audio recording -----
private RecordingThread mRecordThread = null;
private AudioRecord mRecorder = null;
private int mRecorderBufferSize = 0;
private byte[] startRecording(int rate, int channels, int encoding, int bufsize)
{
if( mRecordThread == null )
{
mRecordThread = new RecordingThread();
mRecordThread.start();
}
if( !mRecordThread.isStopped() )
{
Log.i("SDL", "SDL: error: application already opened audio recording device");
return null;
}
mRecordThread.init(bufsize);
int channelConfig = ( channels == 1 ) ? AudioFormat.CHANNEL_IN_MONO :
AudioFormat.CHANNEL_IN_STEREO;
int encodingConfig = ( encoding == 1 ) ? AudioFormat.ENCODING_PCM_16BIT :
AudioFormat.ENCODING_PCM_8BIT;
int minBufDevice = AudioRecord.getMinBufferSize(rate, channelConfig, encodingConfig);
int minBufferSize = Math.max(bufsize * 8, minBufDevice + (bufsize - (minBufDevice % bufsize)));
Log.i("SDL", "SDL: app opened recording device, rate " + rate + " channels " + channels + " sample size " + (encoding+1) + " bufsize " + bufsize + " internal bufsize " + minBufferSize);
if( mRecorder == null || mRecorder.getSampleRate() != rate ||
mRecorder.getChannelCount() != channels ||
mRecorder.getAudioFormat() != encodingConfig ||
mRecorderBufferSize != minBufferSize )
{
if( mRecorder != null )
mRecorder.release();
mRecorder = null;
try {
mRecorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, encodingConfig, minBufferSize);
mRecorderBufferSize = minBufferSize;
} catch (IllegalArgumentException e) {
Log.i("SDL", "SDL: error: failed to open recording device!");
return null;
}
}
else
{
Log.i("SDL", "SDL: reusing old recording device");
}
mRecordThread.startRecording();
return mRecordThread.mRecordBuffer;
}
private void stopRecording()
{
if( mRecordThread == null || mRecordThread.isStopped() )
{
Log.i("SDL", "SDL: error: application already closed audio recording device");
return;
}
mRecordThread.stopRecording();
Log.i("SDL", "SDL: app closed recording device");
}
private class RecordingThread extends Thread
{
private boolean stopped = true;
byte[] mRecordBuffer;
private Semaphore waitStarted = new Semaphore(0);
private boolean sleep = false;
RecordingThread()
{
super();
}
void init(int bufsize)
{
if( mRecordBuffer == null || mRecordBuffer.length != bufsize )
mRecordBuffer = new byte[bufsize];
}
public void run()
{
while( true )
{
waitStarted.acquireUninterruptibly();
waitStarted.drainPermits();
stopped = false;
sleep = false;
while( !sleep )
{
int got = mRecorder.read(mRecordBuffer, 0, mRecordBuffer.length);
if( got != mRecordBuffer.length )
{
// Audio is stopped here, sleep a bit.
try{
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
else
{
//Log.i("SDL", "SDL: nativeAudioRecordCallback with len " + mRecordBuffer.length);
nativeAudioRecordCallback();
//Log.i("SDL", "SDL: nativeAudioRecordCallback returned");
}
}
stopped = true;
mRecorder.stop();
}
}
public void startRecording()
{
mRecorder.startRecording();
waitStarted.release();
}
public void stopRecording()
{
sleep = true;
while( !stopped )
{
try{
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
public void pauseRecording()
{
if( !stopped )
mRecorder.stop();
}
public void resumeRecording()
{
if( !stopped )
mRecorder.startRecording();
}
public boolean isStopped()
{
return stopped;
}
}
private native void nativeAudioRecordCallback();
}

View File

@@ -1,758 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.os.Environment;
import android.widget.TextView;
import org.apache.http.client.methods.*;
import org.apache.http.*;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.conn.*;
import org.apache.http.conn.params.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.security.cert.*;
import java.security.SecureRandom;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.util.zip.*;
import java.io.*;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.res.Resources;
import java.lang.String;
import android.text.SpannedString;
import android.app.AlertDialog;
import android.content.DialogInterface;
class CountingInputStream extends BufferedInputStream
{
private long bytesReadMark = 0;
private long bytesRead = 0;
public CountingInputStream(InputStream in, int size) {
super(in, size);
}
public CountingInputStream(InputStream in) {
super(in);
}
public long getBytesRead() {
return bytesRead;
}
public synchronized int read() throws IOException {
int read = super.read();
if (read >= 0) {
bytesRead++;
}
return read;
}
public synchronized int read(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read >= 0) {
bytesRead += read;
}
return read;
}
public synchronized long skip(long n) throws IOException {
long skipped = super.skip(n);
if (skipped >= 0) {
bytesRead += skipped;
}
return skipped;
}
public synchronized void mark(int readlimit) {
super.mark(readlimit);
bytesReadMark = bytesRead;
}
public synchronized void reset() throws IOException {
super.reset();
bytesRead = bytesReadMark;
}
}
class DataDownloader extends Thread
{
public static final String DOWNLOAD_FLAG_FILENAME = "libsdl-DownloadFinished-";
class StatusWriter
{
private TextView Status;
private MainActivity Parent;
private SpannedString oldText = new SpannedString("");
public StatusWriter( TextView _Status, MainActivity _Parent )
{
Status = _Status;
Parent = _Parent;
}
public void setParent( TextView _Status, MainActivity _Parent )
{
synchronized(DataDownloader.this) {
Status = _Status;
Parent = _Parent;
setText( oldText.toString() );
}
}
public void setText(final String str)
{
class Callback implements Runnable
{
public TextView Status;
public SpannedString text;
public void run()
{
Status.setText(text);
}
}
synchronized(DataDownloader.this) {
Callback cb = new Callback();
oldText = new SpannedString(str);
cb.text = new SpannedString(str);
cb.Status = Status;
if( Parent != null && Status != null )
Parent.runOnUiThread(cb);
}
}
}
public DataDownloader( MainActivity _Parent, TextView _Status )
{
Parent = _Parent;
Status = new StatusWriter( _Status, _Parent );
//Status.setText( "Connecting to " + Globals.DataDownloadUrl );
outFilesDir = Globals.DataDir;
DownloadComplete = false;
this.start();
}
public void setStatusField(TextView _Status)
{
synchronized(this) {
Status.setParent( _Status, Parent );
}
}
@Override
public void run()
{
Parent.keyListener = new BackKeyListener(Parent);
String [] downloadFiles = Globals.DataDownloadUrl;
int total = 0;
int count = 0;
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].length() > 0 &&
( Globals.OptionalDataDownload.length > i && Globals.OptionalDataDownload[i] ) ||
( Globals.OptionalDataDownload.length <= i && downloadFiles[i].indexOf("!") == 0 ) )
total += 1;
}
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].length() > 0 &&
( Globals.OptionalDataDownload.length > i && Globals.OptionalDataDownload[i] ) ||
( Globals.OptionalDataDownload.length <= i && downloadFiles[i].indexOf("!") == 0 ) )
{
if( ! DownloadDataFile(downloadFiles[i], DOWNLOAD_FLAG_FILENAME + String.valueOf(i) + ".flag", count+1, total, i) )
{
DownloadFailed = true;
return;
}
count += 1;
}
}
DownloadComplete = true;
Parent.keyListener = null;
initParent();
}
public boolean DownloadDataFile(final String DataDownloadUrl, final String DownloadFlagFileName, int downloadCount, int downloadTotal, int downloadIndex)
{
DownloadCanBeResumed = false;
Resources res = Parent.getResources();
String [] downloadUrls = DataDownloadUrl.split("[|]");
if( downloadUrls.length < 2 )
{
Log.i("SDL", "Error: download string invalid: '" + DataDownloadUrl + "', your AndroidAppSettigns.cfg is broken");
Status.setText( res.getString(R.string.error_dl_from, DataDownloadUrl) );
return false;
}
boolean forceOverwrite = false;
String path = getOutFilePath(DownloadFlagFileName);
InputStream checkFile = null;
try {
checkFile = new FileInputStream( path );
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) { };
if( checkFile != null )
{
try {
byte b[] = new byte[ Globals.DataDownloadUrl[downloadIndex].getBytes("UTF-8").length + 1 ];
int readed = checkFile.read(b);
String compare = "";
if( readed > 0 )
compare = new String( b, 0, readed, "UTF-8" );
boolean matched = false;
//Log.i("SDL", "Read URL: '" + compare + "'");
for( int i = 1; i < downloadUrls.length; i++ )
{
//Log.i("SDL", "Comparing: '" + downloadUrls[i] + "'");
if( compare.compareTo(downloadUrls[i]) == 0 )
matched = true;
}
//Log.i("SDL", "Matched: " + String.valueOf(matched));
if( ! matched )
throw new IOException();
Status.setText( res.getString(R.string.download_unneeded) );
return true;
} catch ( IOException e ) {
forceOverwrite = true;
new File(path).delete();
}
}
checkFile = null;
// Create output directory (not necessary for phone storage)
Log.i("SDL", "Downloading data to: '" + outFilesDir + "'");
try {
File outDir = new File( outFilesDir );
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
OutputStream out = new FileOutputStream( getOutFilePath(".nomedia") );
out.flush();
out.close();
}
catch( SecurityException e ) {}
catch( FileNotFoundException e ) {}
catch( IOException e ) {};
HttpResponse response = null, responseError = null;
HttpGet request;
long totalLen = 0;
CountingInputStream stream;
byte[] buf = new byte[16384];
boolean DoNotUnzip = false;
boolean FileInAssets = false;
String url = "";
long partialDownloadLen = 0;
int downloadUrlIndex = 1;
while( downloadUrlIndex < downloadUrls.length )
{
Log.i("SDL", "Processing download " + downloadUrls[downloadUrlIndex]);
url = new String(downloadUrls[downloadUrlIndex]);
DoNotUnzip = false;
if(url.indexOf(":") == 0)
{
path = getOutFilePath(url.substring( 1, url.indexOf(":", 1) ));
url = url.substring( url.indexOf(":", 1) + 1 );
DoNotUnzip = true;
DownloadCanBeResumed = true;
File partialDownload = new File( path );
if( partialDownload.exists() && !partialDownload.isDirectory() && !forceOverwrite )
partialDownloadLen = partialDownload.length();
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.connecting_to, url) );
if( url.indexOf("http://") == -1 && url.indexOf("https://") == -1 ) // File inside assets
{
InputStream stream1 = null;
try {
stream1 = Parent.getAssets().open(url);
stream1.close();
} catch( Exception e ) {
try {
stream1 = Parent.getAssets().open(url + "000");
stream1.close();
} catch( Exception ee ) {
Log.i("SDL", "Failed to open file in assets: " + url);
downloadUrlIndex++;
continue;
}
}
FileInAssets = true;
Log.i("SDL", "Fetching file from assets: " + url);
break;
}
else
{
Log.i("SDL", "Connecting to: " + url);
request = new HttpGet(url);
request.addHeader("Accept", "*/*");
if( partialDownloadLen > 0 ) {
request.addHeader("Range", "bytes=" + partialDownloadLen + "-");
Log.i("SDL", "Trying to resume download at pos " + partialDownloadLen);
}
try {
DefaultHttpClient client = HttpWithDisabledSslCertCheck();
client.getParams().setBooleanParameter("http.protocol.handle-redirects", true);
response = client.execute(request);
} catch (IOException e) {
Log.i("SDL", "Failed to connect to " + url);
downloadUrlIndex++;
};
if( response != null )
{
if( response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206 )
{
Log.i("SDL", "Failed to connect to " + url + " with error " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
responseError = response;
response = null;
downloadUrlIndex++;
}
else
break;
}
}
}
if( FileInAssets )
{
int multipartCounter = 0;
InputStream multipart = null;
while( true )
{
try {
// Make string ".zip000", ".zip001" etc for multipart archives
String url1 = url + String.format("%03d", multipartCounter);
CountingInputStream stream1 = new CountingInputStream(Parent.getAssets().open(url1), 8192);
while( stream1.skip(65536) > 0 ) { };
totalLen += stream1.getBytesRead();
stream1.close();
InputStream s = Parent.getAssets().open(url1);
if( multipart == null )
multipart = s;
else
multipart = new SequenceInputStream(multipart, s);
Log.i("SDL", "Multipart archive found: " + url1);
} catch( IOException e ) {
break;
}
multipartCounter += 1;
}
if( multipart != null )
stream = new CountingInputStream(multipart, 8192);
else
{
try {
stream = new CountingInputStream(Parent.getAssets().open(url), 8192);
while( stream.skip(65536) > 0 ) { };
totalLen += stream.getBytesRead();
stream.close();
stream = new CountingInputStream(Parent.getAssets().open(url), 8192);
} catch( IOException e ) {
Log.i("SDL", "Unpacking from assets '" + url + "' - error: " + e.toString());
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
}
else
{
if( response == null )
{
Log.i("SDL", "Error connecting to " + url);
Status.setText( res.getString(R.string.failed_connecting_to, url) + (responseError == null ? "" : ": " + responseError.getStatusLine().getStatusCode() + " " + responseError.getStatusLine().getReasonPhrase()) );
return false;
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_from, url) );
totalLen = response.getEntity().getContentLength();
try {
stream = new CountingInputStream(response.getEntity().getContent(), 8192);
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
long updateStatusTime = 0;
if(DoNotUnzip)
{
Log.i("SDL", "Saving file '" + path + "'");
OutputStream out = null;
try {
try {
File outDir = new File( path.substring(0, path.lastIndexOf("/") ));
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
if( partialDownloadLen > 0 )
{
try {
Header[] range = response.getHeaders("Content-Range");
if( range.length > 0 && range[0].getValue().indexOf("bytes") == 0 )
{
//Log.i("SDL", "Resuming download of file '" + path + "': Content-Range: " + range[0].getValue());
String[] skippedBytes = range[0].getValue().split("/")[0].split("-")[0].split(" ");
if( skippedBytes.length >= 2 && Long.parseLong(skippedBytes[1]) == partialDownloadLen )
{
out = new FileOutputStream( path, true );
Log.i("SDL", "Resuming download of file '" + path + "' at pos " + partialDownloadLen);
}
}
else
Log.i("SDL", "Server does not support partial downloads. " + (range.length == 0 ? "" : range[0].getValue()));
} catch (Exception e) { }
}
if( out == null )
{
out = new FileOutputStream( path );
partialDownloadLen = 0;
}
} catch( FileNotFoundException e ) {
Log.i("SDL", "Saving file '" + path + "' - error creating output file: " + e.toString());
} catch( SecurityException e ) {
Log.i("SDL", "Saving file '" + path + "' - error creating output file: " + e.toString());
};
if( out == null )
{
Status.setText( res.getString(R.string.error_write, path) );
Log.i("SDL", "Saving file '" + path + "' - error creating output file");
return false;
}
try {
int len = stream.read(buf);
while (len >= 0)
{
if(len > 0)
out.write(buf, 0, len);
len = stream.read(buf);
float percent = 0.0f;
if( totalLen > 0 )
percent = (stream.getBytesRead() + partialDownloadLen) * 100.0f / (totalLen + partialDownloadLen);
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
}
out.flush();
out.close();
out = null;
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
Log.i("SDL", "Saving file '" + path + "' - error writing: " + e.toString());
return false;
}
Log.i("SDL", "Saving file '" + path + "' done");
}
else
{
Log.i("SDL", "Reading from zip file '" + url + "'");
ZipInputStream zip = new ZipInputStream(stream);
while(true)
{
ZipEntry entry = null;
try {
entry = zip.getNextEntry();
if( entry != null )
Log.i("SDL", "Reading from zip file '" + url + "' entry '" + entry.getName() + "'");
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
Log.i("SDL", "Error reading from zip file '" + url + "': " + e.toString());
return false;
}
if( entry == null )
{
Log.i("SDL", "Reading from zip file '" + url + "' finished");
break;
}
if( entry.isDirectory() )
{
Log.i("SDL", "Creating dir '" + getOutFilePath(entry.getName()) + "'");
try {
File outDir = new File( getOutFilePath(entry.getName()) );
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
continue;
}
OutputStream out = null;
path = getOutFilePath(entry.getName());
float percent = 0.0f;
Log.i("SDL", "Saving file '" + path + "'");
try {
File outDir = new File( path.substring(0, path.lastIndexOf("/") ));
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
try {
CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() );
while( check.read(buf, 0, buf.length) >= 0 ) {};
check.close();
if( check.getChecksum().getValue() != entry.getCrc() )
{
File ff = new File(path);
ff.delete();
throw new Exception();
}
Log.i("SDL", "File '" + path + "' exists and passed CRC check - not overwriting it");
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
continue;
} catch( Exception e ) { }
try {
out = new FileOutputStream( path );
} catch( FileNotFoundException e ) {
Log.i("SDL", "Saving file '" + path + "' - cannot create file: " + e.toString());
} catch( SecurityException e ) {
Log.i("SDL", "Saving file '" + path + "' - cannot create file: " + e.toString());
};
if( out == null )
{
Status.setText( res.getString(R.string.error_write, path) );
Log.i("SDL", "Saving file '" + path + "' - cannot create file");
return false;
}
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
try {
int len = zip.read(buf);
while (len >= 0)
{
if(len > 0)
out.write(buf, 0, len);
len = zip.read(buf);
percent = 0.0f;
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
}
out.flush();
out.close();
out = null;
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
Log.i("SDL", "Saving file '" + path + "' - error writing or downloading: " + e.toString());
return false;
}
try {
long count = 0, ret = 0;
CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() );
while( ret >= 0 )
{
count += ret;
ret = check.read(buf, 0, buf.length);
}
check.close();
if( check.getChecksum().getValue() != entry.getCrc() || count != entry.getSize() )
{
File ff = new File(path);
ff.delete();
Log.i("SDL", "Saving file '" + path + "' - CRC check failed, ZIP: " +
String.format("%x", entry.getCrc()) + " actual file: " + String.format("%x", check.getChecksum().getValue()) +
" file size in ZIP: " + entry.getSize() + " actual size " + count );
throw new Exception();
}
} catch( Exception e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
return false;
}
Log.i("SDL", "Saving file '" + path + "' done");
}
};
OutputStream out = null;
path = getOutFilePath(DownloadFlagFileName);
try {
out = new FileOutputStream( path );
out.write(downloadUrls[downloadUrlIndex].getBytes("UTF-8"));
out.flush();
out.close();
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) {
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
return false;
};
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_finished) );
try {
stream.close();
} catch( java.io.IOException e ) {
};
return true;
};
private void initParent()
{
class Callback implements Runnable
{
public MainActivity Parent;
public void run()
{
Parent.initSDL();
}
}
Callback cb = new Callback();
synchronized(this) {
cb.Parent = Parent;
if(Parent != null)
Parent.runOnUiThread(cb);
}
}
private String getOutFilePath(final String filename)
{
return outFilesDir + "/" + filename;
};
private static DefaultHttpClient HttpWithDisabledSslCertCheck()
{
return new DefaultHttpClient();
// This code does not work
/*
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
return http;
*/
}
public class BackKeyListener implements MainActivity.KeyEventsListener
{
MainActivity p;
public BackKeyListener(MainActivity _p)
{
p = _p;
}
public void onKeyEvent(final int keyCode)
{
if( DownloadFailed )
System.exit(1);
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.cancel_download));
builder.setMessage(p.getResources().getString(R.string.cancel_download) + (DownloadCanBeResumed ? " " + p.getResources().getString(R.string.cancel_download_resume) : ""));
builder.setPositiveButton(p.getResources().getString(R.string.yes), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
System.exit(1);
dialog.dismiss();
}
});
builder.setNegativeButton(p.getResources().getString(R.string.no), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
public StatusWriter Status;
public boolean DownloadComplete = false;
public boolean DownloadFailed = false;
public boolean DownloadCanBeResumed = false;
private MainActivity Parent;
private String outFilesDir = null;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,126 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
/*import android.app.Activity;
import android.content.Context;
import java.util.Vector;*/
import android.view.KeyEvent;
class Globals
{
// These config options are modified by ChangeAppsettings.sh script - see the detailed descriptions there
public static String ApplicationName = "CommanderGenius";
public static String AppLibraries[] = { "sdl-1.2", };
public static String AppMainLibraries[] = { "application", "sdl_main" };
public static final boolean Using_SDL_1_3 = false;
public static final boolean Using_SDL_2_0 = false;
public static String[] DataDownloadUrl = { "Data files are 2 Mb|https://sourceforge.net/projects/libsdl-android/files/CommanderGenius/commandergenius-data.zip/download", "High-quality GFX and music - 40 Mb|https://sourceforge.net/projects/libsdl-android/files/CommanderGenius/commandergenius-hqp.zip/download" };
public static int VideoDepthBpp = 16;
public static boolean SwVideoMode = false;
public static boolean NeedDepthBuffer = false;
public static boolean NeedStencilBuffer = false;
public static boolean NeedGles2 = false;
public static boolean CompatibilityHacksVideo = false;
public static boolean CompatibilityHacksStaticInit = false;
public static boolean CompatibilityHacksTextInputEmulatesHwKeyboard = false;
public static boolean HorizontalOrientation = true;
public static boolean KeepAspectRatioDefaultSetting = false;
public static boolean InhibitSuspend = false;
public static String ReadmeText = "^You may press \"Home\" now - the data will be downloaded in background".replace("^","\n");
public static String CommandLine = "";
public static boolean AppUsesMouse = false;
public static boolean AppNeedsTwoButtonMouse = false;
public static boolean ForceRelativeMouseMode = false; // If both on-screen keyboard and mouse are needed, this will only set the default setting, user may override it later
public static boolean ShowMouseCursor = false;
public static boolean AppNeedsArrowKeys = true;
public static boolean AppNeedsTextInput = true;
public static boolean AppUsesJoystick = false;
public static boolean AppUsesSecondJoystick = false;
public static boolean AppUsesAccelerometer = false;
public static boolean AppUsesGyroscope = false;
public static boolean AppUsesMultitouch = false;
public static boolean NonBlockingSwapBuffers = false;
public static boolean ResetSdlConfigForThisVersion = false;
public static String DeleteFilesOnUpgrade = "";
public static int AppTouchscreenKeyboardKeysAmount = 4;
public static int AppTouchscreenKeyboardKeysAmountAutoFire = 1;
public static String[] AppTouchscreenKeyboardKeysNames = "Fire Shoot Switch_weapon Jump Run Hide/Seek".split(" ");
public static int StartupMenuButtonTimeout = 3000;
public static int AppMinimumRAM = 0;
public static SettingsMenu.Menu HiddenMenuOptions [] = {}; // If you see error here - update HiddenMenuOptions in your AndroidAppSettings.cfg: change OptionalDownloadConfig to SettingsMenuMisc.OptionalDownloadConfig etc.
public static SettingsMenu.Menu FirstStartMenuOptions [] = { new SettingsMenuMisc.ShowReadme(), (AppUsesMouse && ! ForceRelativeMouseMode ? new SettingsMenuMouse.DisplaySizeConfig() : new SettingsMenu.DummyMenu()), new SettingsMenuMisc.OptionalDownloadConfig(), new SettingsMenuMisc.GyroscopeCalibration() };
public static String AdmobPublisherId = "";
public static String AdmobTestDeviceId = "";
public static String AdmobBannerSize = "";
// Phone-specific config, modified by user in "Change phone config" startup dialog, TODO: move this to settings
public static boolean DownloadToSdcard = true;
public static boolean PhoneHasTrackball = false;
public static boolean PhoneHasArrowKeys = false;
public static boolean UseAccelerometerAsArrowKeys = false;
public static boolean UseTouchscreenKeyboard = true;
public static int TouchscreenKeyboardSize = 1;
public static final int TOUCHSCREEN_KEYBOARD_CUSTOM = 4;
public static int TouchscreenKeyboardDrawSize = 1;
public static int TouchscreenKeyboardTheme = 2;
public static int TouchscreenKeyboardTransparency = 2;
public static int AccelerometerSensitivity = 2;
public static int AccelerometerCenterPos = 2;
public static int TrackballDampening = 0;
public static int AudioBufferConfig = 0;
public static boolean OptionalDataDownload[] = null;
public static int LeftClickMethod = Mouse.LEFT_CLICK_NORMAL;
public static int LeftClickKey = KeyEvent.KEYCODE_DPAD_CENTER;
public static int LeftClickTimeout = 3;
public static int RightClickTimeout = 4;
public static int RightClickMethod = AppNeedsTwoButtonMouse ? Mouse.RIGHT_CLICK_WITH_MULTITOUCH : Mouse.RIGHT_CLICK_NONE;
public static int RightClickKey = KeyEvent.KEYCODE_MENU;
public static boolean MoveMouseWithJoystick = false;
public static int MoveMouseWithJoystickSpeed = 0;
public static int MoveMouseWithJoystickAccel = 0;
public static boolean ClickMouseWithDpad = false;
public static boolean RelativeMouseMovement = ForceRelativeMouseMode; // Laptop touchpad mode
public static int RelativeMouseMovementSpeed = 2;
public static int RelativeMouseMovementAccel = 0;
public static int ShowScreenUnderFinger = Mouse.ZOOM_NONE;
public static boolean KeepAspectRatio = KeepAspectRatioDefaultSetting;
public static int ClickScreenPressure = 0;
public static int ClickScreenTouchspotSize = 0;
public static int RemapHwKeycode[] = new int[SDL_Keys.JAVA_KEYCODE_LAST];
public static int RemapScreenKbKeycode[] = new int[6];
public static int ScreenKbControlsLayout[][] = AppUsesSecondJoystick ? // Values for 800x480 resolution
new int[][] { { 0, 303, 177, 480 }, { 0, 0, 48, 48 }, { 400, 392, 488, 480 }, { 312, 392, 400, 480 }, { 400, 304, 488, 392 }, { 312, 304, 400, 392 }, { 400, 216, 488, 304 }, { 312, 216, 400, 304 }, { 623, 303, 800, 480 } } :
new int[][] { { 0, 303, 177, 480 }, { 0, 0, 48, 48 }, { 712, 392, 800, 480 }, { 624, 392, 712, 480 }, { 712, 304, 800, 392 }, { 624, 304, 712, 392 }, { 712, 216, 800, 304 }, { 624, 216, 712, 304 } };
public static boolean ScreenKbControlsShown[] = new boolean[ScreenKbControlsLayout.length]; // Also joystick and text input button added
public static int RemapMultitouchGestureKeycode[] = new int[4];
public static boolean MultitouchGesturesUsed[] = new boolean[4];
public static int MultitouchGestureSensitivity = 1;
public static int TouchscreenCalibration[] = new int[4];
public static String DataDir = new String("");
public static boolean VideoLinearFilter = true;
public static boolean MultiThreadedVideo = false;
public static boolean BrokenLibCMessageShown = false;
// Gyroscope calibration
public static float gyro_x1, gyro_x2, gyro_xc, gyro_y1, gyro_y2, gyro_yc, gyro_z1, gyro_z2, gyro_zc;
public static boolean OuyaEmulation = false; // For debugging
}

View File

@@ -0,0 +1,22 @@
package org.libsdl.app;
import android.hardware.usb.UsbDevice;
interface HIDDevice
{
public int getId();
public int getVendorId();
public int getProductId();
public String getSerialNumber();
public int getVersion();
public String getManufacturerName();
public String getProductName();
public UsbDevice getDevice();
public boolean open();
public int sendFeatureReport(byte[] report);
public int sendOutputReport(byte[] report);
public boolean getFeatureReport(byte[] report);
public void setFrozen(boolean frozen);
public void close();
public void shutdown();
}

View File

@@ -0,0 +1,650 @@
package org.libsdl.app;
import android.content.Context;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothGattService;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.os.*;
//import com.android.internal.util.HexDump;
import java.lang.Runnable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.UUID;
class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDevice {
private static final String TAG = "hidapi";
private HIDDeviceManager mManager;
private BluetoothDevice mDevice;
private int mDeviceId;
private BluetoothGatt mGatt;
private boolean mIsRegistered = false;
private boolean mIsConnected = false;
private boolean mIsChromebook = false;
private boolean mIsReconnecting = false;
private boolean mFrozen = false;
private LinkedList<GattOperation> mOperations;
GattOperation mCurrentOperation = null;
private Handler mHandler;
private static final int TRANSPORT_AUTO = 0;
private static final int TRANSPORT_BREDR = 1;
private static final int TRANSPORT_LE = 2;
private static final int CHROMEBOOK_CONNECTION_CHECK_INTERVAL = 10000;
static public final UUID steamControllerService = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3");
static public final UUID inputCharacteristic = UUID.fromString("100F6C33-1735-4313-B402-38567131E5F3");
static public final UUID reportCharacteristic = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3");
static private final byte[] enterValveMode = new byte[] { (byte)0xC0, (byte)0x87, 0x03, 0x08, 0x07, 0x00 };
static class GattOperation {
private enum Operation {
CHR_READ,
CHR_WRITE,
ENABLE_NOTIFICATION
}
Operation mOp;
UUID mUuid;
byte[] mValue;
BluetoothGatt mGatt;
boolean mResult = true;
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid) {
mGatt = gatt;
mOp = operation;
mUuid = uuid;
}
private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value) {
mGatt = gatt;
mOp = operation;
mUuid = uuid;
mValue = value;
}
public void run() {
// This is executed in main thread
BluetoothGattCharacteristic chr;
switch (mOp) {
case CHR_READ:
chr = getCharacteristic(mUuid);
//Log.v(TAG, "Reading characteristic " + chr.getUuid());
if (!mGatt.readCharacteristic(chr)) {
Log.e(TAG, "Unable to read characteristic " + mUuid.toString());
mResult = false;
break;
}
mResult = true;
break;
case CHR_WRITE:
chr = getCharacteristic(mUuid);
//Log.v(TAG, "Writing characteristic " + chr.getUuid() + " value=" + HexDump.toHexString(value));
chr.setValue(mValue);
if (!mGatt.writeCharacteristic(chr)) {
Log.e(TAG, "Unable to write characteristic " + mUuid.toString());
mResult = false;
break;
}
mResult = true;
break;
case ENABLE_NOTIFICATION:
chr = getCharacteristic(mUuid);
//Log.v(TAG, "Writing descriptor of " + chr.getUuid());
if (chr != null) {
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (cccd != null) {
int properties = chr.getProperties();
byte[] value;
if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
} else if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == BluetoothGattCharacteristic.PROPERTY_INDICATE) {
value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
} else {
Log.e(TAG, "Unable to start notifications on input characteristic");
mResult = false;
return;
}
mGatt.setCharacteristicNotification(chr, true);
cccd.setValue(value);
if (!mGatt.writeDescriptor(cccd)) {
Log.e(TAG, "Unable to write descriptor " + mUuid.toString());
mResult = false;
return;
}
mResult = true;
}
}
}
}
public boolean finish() {
return mResult;
}
private BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
BluetoothGattService valveService = mGatt.getService(steamControllerService);
if (valveService == null)
return null;
return valveService.getCharacteristic(uuid);
}
static public GattOperation readCharacteristic(BluetoothGatt gatt, UUID uuid) {
return new GattOperation(gatt, Operation.CHR_READ, uuid);
}
static public GattOperation writeCharacteristic(BluetoothGatt gatt, UUID uuid, byte[] value) {
return new GattOperation(gatt, Operation.CHR_WRITE, uuid, value);
}
static public GattOperation enableNotification(BluetoothGatt gatt, UUID uuid) {
return new GattOperation(gatt, Operation.ENABLE_NOTIFICATION, uuid);
}
}
public HIDDeviceBLESteamController(HIDDeviceManager manager, BluetoothDevice device) {
mManager = manager;
mDevice = device;
mDeviceId = mManager.getDeviceIDForIdentifier(getIdentifier());
mIsRegistered = false;
mIsChromebook = mManager.getContext().getPackageManager().hasSystemFeature("org.chromium.arc.device_management");
mOperations = new LinkedList<GattOperation>();
mHandler = new Handler(Looper.getMainLooper());
mGatt = connectGatt();
// final HIDDeviceBLESteamController finalThis = this;
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// finalThis.checkConnectionForChromebookIssue();
// }
// }, CHROMEBOOK_CONNECTION_CHECK_INTERVAL);
}
public String getIdentifier() {
return String.format("SteamController.%s", mDevice.getAddress());
}
public BluetoothGatt getGatt() {
return mGatt;
}
// Because on Chromebooks we show up as a dual-mode device, it will attempt to connect TRANSPORT_AUTO, which will use TRANSPORT_BREDR instead
// of TRANSPORT_LE. Let's force ourselves to connect low energy.
private BluetoothGatt connectGatt(boolean managed) {
if (Build.VERSION.SDK_INT >= 23) {
try {
return mDevice.connectGatt(mManager.getContext(), managed, this, TRANSPORT_LE);
} catch (Exception e) {
return mDevice.connectGatt(mManager.getContext(), managed, this);
}
} else {
return mDevice.connectGatt(mManager.getContext(), managed, this);
}
}
private BluetoothGatt connectGatt() {
return connectGatt(false);
}
protected int getConnectionState() {
Context context = mManager.getContext();
if (context == null) {
// We are lacking any context to get our Bluetooth information. We'll just assume disconnected.
return BluetoothProfile.STATE_DISCONNECTED;
}
BluetoothManager btManager = (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
if (btManager == null) {
// This device doesn't support Bluetooth. We should never be here, because how did
// we instantiate a device to start with?
return BluetoothProfile.STATE_DISCONNECTED;
}
return btManager.getConnectionState(mDevice, BluetoothProfile.GATT);
}
public void reconnect() {
if (getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
mGatt.disconnect();
mGatt = connectGatt();
}
}
protected void checkConnectionForChromebookIssue() {
if (!mIsChromebook) {
// We only do this on Chromebooks, because otherwise it's really annoying to just attempt
// over and over.
return;
}
int connectionState = getConnectionState();
switch (connectionState) {
case BluetoothProfile.STATE_CONNECTED:
if (!mIsConnected) {
// We are in the Bad Chromebook Place. We can force a disconnect
// to try to recover.
Log.v(TAG, "Chromebook: We are in a very bad state; the controller shows as connected in the underlying Bluetooth layer, but we never received a callback. Forcing a reconnect.");
mIsReconnecting = true;
mGatt.disconnect();
mGatt = connectGatt(false);
break;
}
else if (!isRegistered()) {
if (mGatt.getServices().size() > 0) {
Log.v(TAG, "Chromebook: We are connected to a controller, but never got our registration. Trying to recover.");
probeService(this);
}
else {
Log.v(TAG, "Chromebook: We are connected to a controller, but never discovered services. Trying to recover.");
mIsReconnecting = true;
mGatt.disconnect();
mGatt = connectGatt(false);
break;
}
}
else {
Log.v(TAG, "Chromebook: We are connected, and registered. Everything's good!");
return;
}
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.v(TAG, "Chromebook: We have either been disconnected, or the Chromebook BtGatt.ContextMap bug has bitten us. Attempting a disconnect/reconnect, but we may not be able to recover.");
mIsReconnecting = true;
mGatt.disconnect();
mGatt = connectGatt(false);
break;
case BluetoothProfile.STATE_CONNECTING:
Log.v(TAG, "Chromebook: We're still trying to connect. Waiting a bit longer.");
break;
}
final HIDDeviceBLESteamController finalThis = this;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
finalThis.checkConnectionForChromebookIssue();
}
}, CHROMEBOOK_CONNECTION_CHECK_INTERVAL);
}
private boolean isRegistered() {
return mIsRegistered;
}
private void setRegistered() {
mIsRegistered = true;
}
private boolean probeService(HIDDeviceBLESteamController controller) {
if (isRegistered()) {
return true;
}
if (!mIsConnected) {
return false;
}
Log.v(TAG, "probeService controller=" + controller);
for (BluetoothGattService service : mGatt.getServices()) {
if (service.getUuid().equals(steamControllerService)) {
Log.v(TAG, "Found Valve steam controller service " + service.getUuid());
for (BluetoothGattCharacteristic chr : service.getCharacteristics()) {
if (chr.getUuid().equals(inputCharacteristic)) {
Log.v(TAG, "Found input characteristic");
// Start notifications
BluetoothGattDescriptor cccd = chr.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (cccd != null) {
enableNotification(chr.getUuid());
}
}
}
return true;
}
}
if ((mGatt.getServices().size() == 0) && mIsChromebook && !mIsReconnecting) {
Log.e(TAG, "Chromebook: Discovered services were empty; this almost certainly means the BtGatt.ContextMap bug has bitten us.");
mIsConnected = false;
mIsReconnecting = true;
mGatt.disconnect();
mGatt = connectGatt(false);
}
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
private void finishCurrentGattOperation() {
GattOperation op = null;
synchronized (mOperations) {
if (mCurrentOperation != null) {
op = mCurrentOperation;
mCurrentOperation = null;
}
}
if (op != null) {
boolean result = op.finish(); // TODO: Maybe in main thread as well?
// Our operation failed, let's add it back to the beginning of our queue.
if (!result) {
mOperations.addFirst(op);
}
}
executeNextGattOperation();
}
private void executeNextGattOperation() {
synchronized (mOperations) {
if (mCurrentOperation != null)
return;
if (mOperations.isEmpty())
return;
mCurrentOperation = mOperations.removeFirst();
}
// Run in main thread
mHandler.post(new Runnable() {
@Override
public void run() {
synchronized (mOperations) {
if (mCurrentOperation == null) {
Log.e(TAG, "Current operation null in executor?");
return;
}
mCurrentOperation.run();
// now wait for the GATT callback and when it comes, finish this operation
}
}
});
}
private void queueGattOperation(GattOperation op) {
synchronized (mOperations) {
mOperations.add(op);
}
executeNextGattOperation();
}
private void enableNotification(UUID chrUuid) {
GattOperation op = HIDDeviceBLESteamController.GattOperation.enableNotification(mGatt, chrUuid);
queueGattOperation(op);
}
public void writeCharacteristic(UUID uuid, byte[] value) {
GattOperation op = HIDDeviceBLESteamController.GattOperation.writeCharacteristic(mGatt, uuid, value);
queueGattOperation(op);
}
public void readCharacteristic(UUID uuid) {
GattOperation op = HIDDeviceBLESteamController.GattOperation.readCharacteristic(mGatt, uuid);
queueGattOperation(op);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////// BluetoothGattCallback overridden methods
//////////////////////////////////////////////////////////////////////////////////////////////////////
public void onConnectionStateChange(BluetoothGatt g, int status, int newState) {
//Log.v(TAG, "onConnectionStateChange status=" + status + " newState=" + newState);
mIsReconnecting = false;
if (newState == 2) {
mIsConnected = true;
// Run directly, without GattOperation
if (!isRegistered()) {
mHandler.post(new Runnable() {
@Override
public void run() {
mGatt.discoverServices();
}
});
}
}
else if (newState == 0) {
mIsConnected = false;
}
// Disconnection is handled in SteamLink using the ACTION_ACL_DISCONNECTED Intent.
}
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//Log.v(TAG, "onServicesDiscovered status=" + status);
if (status == 0) {
if (gatt.getServices().size() == 0) {
Log.v(TAG, "onServicesDiscovered returned zero services; something has gone horribly wrong down in Android's Bluetooth stack.");
mIsReconnecting = true;
mIsConnected = false;
gatt.disconnect();
mGatt = connectGatt(false);
}
else {
probeService(this);
}
}
}
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Log.v(TAG, "onCharacteristicRead status=" + status + " uuid=" + characteristic.getUuid());
if (characteristic.getUuid().equals(reportCharacteristic) && !mFrozen) {
mManager.HIDDeviceFeatureReport(getId(), characteristic.getValue());
}
finishCurrentGattOperation();
}
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Log.v(TAG, "onCharacteristicWrite status=" + status + " uuid=" + characteristic.getUuid());
if (characteristic.getUuid().equals(reportCharacteristic)) {
// Only register controller with the native side once it has been fully configured
if (!isRegistered()) {
Log.v(TAG, "Registering Steam Controller with ID: " + getId());
mManager.HIDDeviceConnected(getId(), getIdentifier(), getVendorId(), getProductId(), getSerialNumber(), getVersion(), getManufacturerName(), getProductName(), 0, 0, 0, 0);
setRegistered();
}
}
finishCurrentGattOperation();
}
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
// Enable this for verbose logging of controller input reports
//Log.v(TAG, "onCharacteristicChanged uuid=" + characteristic.getUuid() + " data=" + HexDump.dumpHexString(characteristic.getValue()));
if (characteristic.getUuid().equals(inputCharacteristic) && !mFrozen) {
mManager.HIDDeviceInputReport(getId(), characteristic.getValue());
}
}
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
//Log.v(TAG, "onDescriptorRead status=" + status);
}
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
BluetoothGattCharacteristic chr = descriptor.getCharacteristic();
//Log.v(TAG, "onDescriptorWrite status=" + status + " uuid=" + chr.getUuid() + " descriptor=" + descriptor.getUuid());
if (chr.getUuid().equals(inputCharacteristic)) {
boolean hasWrittenInputDescriptor = true;
BluetoothGattCharacteristic reportChr = chr.getService().getCharacteristic(reportCharacteristic);
if (reportChr != null) {
Log.v(TAG, "Writing report characteristic to enter valve mode");
reportChr.setValue(enterValveMode);
gatt.writeCharacteristic(reportChr);
}
}
finishCurrentGattOperation();
}
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
//Log.v(TAG, "onReliableWriteCompleted status=" + status);
}
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
//Log.v(TAG, "onReadRemoteRssi status=" + status);
}
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
//Log.v(TAG, "onMtuChanged status=" + status);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////// Public API
//////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public int getId() {
return mDeviceId;
}
@Override
public int getVendorId() {
// Valve Corporation
final int VALVE_USB_VID = 0x28DE;
return VALVE_USB_VID;
}
@Override
public int getProductId() {
// We don't have an easy way to query from the Bluetooth device, but we know what it is
final int D0G_BLE2_PID = 0x1106;
return D0G_BLE2_PID;
}
@Override
public String getSerialNumber() {
// This will be read later via feature report by Steam
return "12345";
}
@Override
public int getVersion() {
return 0;
}
@Override
public String getManufacturerName() {
return "Valve Corporation";
}
@Override
public String getProductName() {
return "Steam Controller";
}
@Override
public UsbDevice getDevice() {
return null;
}
@Override
public boolean open() {
return true;
}
@Override
public int sendFeatureReport(byte[] report) {
if (!isRegistered()) {
Log.e(TAG, "Attempted sendFeatureReport before Steam Controller is registered!");
if (mIsConnected) {
probeService(this);
}
return -1;
}
// We need to skip the first byte, as that doesn't go over the air
byte[] actual_report = Arrays.copyOfRange(report, 1, report.length - 1);
//Log.v(TAG, "sendFeatureReport " + HexDump.dumpHexString(actual_report));
writeCharacteristic(reportCharacteristic, actual_report);
return report.length;
}
@Override
public int sendOutputReport(byte[] report) {
if (!isRegistered()) {
Log.e(TAG, "Attempted sendOutputReport before Steam Controller is registered!");
if (mIsConnected) {
probeService(this);
}
return -1;
}
//Log.v(TAG, "sendFeatureReport " + HexDump.dumpHexString(report));
writeCharacteristic(reportCharacteristic, report);
return report.length;
}
@Override
public boolean getFeatureReport(byte[] report) {
if (!isRegistered()) {
Log.e(TAG, "Attempted getFeatureReport before Steam Controller is registered!");
if (mIsConnected) {
probeService(this);
}
return false;
}
//Log.v(TAG, "getFeatureReport");
readCharacteristic(reportCharacteristic);
return true;
}
@Override
public void close() {
}
@Override
public void setFrozen(boolean frozen) {
mFrozen = frozen;
}
@Override
public void shutdown() {
close();
BluetoothGatt g = mGatt;
if (g != null) {
g.disconnect();
g.close();
mGatt = null;
}
mManager = null;
mIsRegistered = false;
mIsConnected = false;
mOperations.clear();
}
}

View File

@@ -0,0 +1,685 @@
package org.libsdl.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.util.Log;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.usb.*;
import android.os.Handler;
import android.os.Looper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class HIDDeviceManager {
private static final String TAG = "hidapi";
private static final String ACTION_USB_PERMISSION = "org.libsdl.app.USB_PERMISSION";
private static HIDDeviceManager sManager;
private static int sManagerRefCount = 0;
public static HIDDeviceManager acquire(Context context) {
if (sManagerRefCount == 0) {
sManager = new HIDDeviceManager(context);
}
++sManagerRefCount;
return sManager;
}
public static void release(HIDDeviceManager manager) {
if (manager == sManager) {
--sManagerRefCount;
if (sManagerRefCount == 0) {
sManager.close();
sManager = null;
}
}
}
private Context mContext;
private HashMap<Integer, HIDDevice> mDevicesById = new HashMap<Integer, HIDDevice>();
private HashMap<BluetoothDevice, HIDDeviceBLESteamController> mBluetoothDevices = new HashMap<BluetoothDevice, HIDDeviceBLESteamController>();
private int mNextDeviceId = 0;
private SharedPreferences mSharedPreferences = null;
private boolean mIsChromebook = false;
private UsbManager mUsbManager;
private Handler mHandler;
private BluetoothManager mBluetoothManager;
private List<BluetoothDevice> mLastBluetoothDevices;
private final BroadcastReceiver mUsbBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
handleUsbDeviceAttached(usbDevice);
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
handleUsbDeviceDetached(usbDevice);
} else if (action.equals(HIDDeviceManager.ACTION_USB_PERMISSION)) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
handleUsbDevicePermission(usbDevice, intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false));
}
}
};
private final BroadcastReceiver mBluetoothBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Bluetooth device was connected. If it was a Steam Controller, handle it
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "Bluetooth device connected: " + device);
if (isSteamController(device)) {
connectBluetoothDevice(device);
}
}
// Bluetooth device was disconnected, remove from controller manager (if any)
if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "Bluetooth device disconnected: " + device);
disconnectBluetoothDevice(device);
}
}
};
private HIDDeviceManager(final Context context) {
mContext = context;
// Make sure we have the HIDAPI library loaded with the native functions
try {
SDL.loadLibrary("hidapi");
} catch (Throwable e) {
Log.w(TAG, "Couldn't load hidapi: " + e.toString());
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("SDL HIDAPI Error");
builder.setMessage("Please report the following error to the SDL maintainers: " + e.getMessage());
builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
// If our context is an activity, exit rather than crashing when we can't
// call our native functions.
Activity activity = (Activity)context;
activity.finish();
}
catch (ClassCastException cce) {
// Context wasn't an activity, there's nothing we can do. Give up and return.
}
}
});
builder.show();
return;
}
HIDDeviceRegisterCallback();
mSharedPreferences = mContext.getSharedPreferences("hidapi", Context.MODE_PRIVATE);
mIsChromebook = mContext.getPackageManager().hasSystemFeature("org.chromium.arc.device_management");
// if (shouldClear) {
// SharedPreferences.Editor spedit = mSharedPreferences.edit();
// spedit.clear();
// spedit.commit();
// }
// else
{
mNextDeviceId = mSharedPreferences.getInt("next_device_id", 0);
}
initializeUSB();
initializeBluetooth();
}
public Context getContext() {
return mContext;
}
public int getDeviceIDForIdentifier(String identifier) {
SharedPreferences.Editor spedit = mSharedPreferences.edit();
int result = mSharedPreferences.getInt(identifier, 0);
if (result == 0) {
result = mNextDeviceId++;
spedit.putInt("next_device_id", mNextDeviceId);
}
spedit.putInt(identifier, result);
spedit.commit();
return result;
}
private void initializeUSB() {
mUsbManager = (UsbManager)mContext.getSystemService(Context.USB_SERVICE);
/*
// Logging
for (UsbDevice device : mUsbManager.getDeviceList().values()) {
Log.i(TAG,"Path: " + device.getDeviceName());
Log.i(TAG,"Manufacturer: " + device.getManufacturerName());
Log.i(TAG,"Product: " + device.getProductName());
Log.i(TAG,"ID: " + device.getDeviceId());
Log.i(TAG,"Class: " + device.getDeviceClass());
Log.i(TAG,"Protocol: " + device.getDeviceProtocol());
Log.i(TAG,"Vendor ID " + device.getVendorId());
Log.i(TAG,"Product ID: " + device.getProductId());
Log.i(TAG,"Interface count: " + device.getInterfaceCount());
Log.i(TAG,"---------------------------------------");
// Get interface details
for (int index = 0; index < device.getInterfaceCount(); index++) {
UsbInterface mUsbInterface = device.getInterface(index);
Log.i(TAG," ***** *****");
Log.i(TAG," Interface index: " + index);
Log.i(TAG," Interface ID: " + mUsbInterface.getId());
Log.i(TAG," Interface class: " + mUsbInterface.getInterfaceClass());
Log.i(TAG," Interface subclass: " + mUsbInterface.getInterfaceSubclass());
Log.i(TAG," Interface protocol: " + mUsbInterface.getInterfaceProtocol());
Log.i(TAG," Endpoint count: " + mUsbInterface.getEndpointCount());
// Get endpoint details
for (int epi = 0; epi < mUsbInterface.getEndpointCount(); epi++)
{
UsbEndpoint mEndpoint = mUsbInterface.getEndpoint(epi);
Log.i(TAG," ++++ ++++ ++++");
Log.i(TAG," Endpoint index: " + epi);
Log.i(TAG," Attributes: " + mEndpoint.getAttributes());
Log.i(TAG," Direction: " + mEndpoint.getDirection());
Log.i(TAG," Number: " + mEndpoint.getEndpointNumber());
Log.i(TAG," Interval: " + mEndpoint.getInterval());
Log.i(TAG," Packet size: " + mEndpoint.getMaxPacketSize());
Log.i(TAG," Type: " + mEndpoint.getType());
}
}
}
Log.i(TAG," No more devices connected.");
*/
// Register for USB broadcasts and permission completions
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(HIDDeviceManager.ACTION_USB_PERMISSION);
mContext.registerReceiver(mUsbBroadcast, filter);
for (UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
handleUsbDeviceAttached(usbDevice);
}
}
UsbManager getUSBManager() {
return mUsbManager;
}
private void shutdownUSB() {
try {
mContext.unregisterReceiver(mUsbBroadcast);
} catch (Exception e) {
// We may not have registered, that's okay
}
}
private boolean isHIDDeviceInterface(UsbDevice usbDevice, UsbInterface usbInterface) {
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_HID) {
return true;
}
if (isXbox360Controller(usbDevice, usbInterface) || isXboxOneController(usbDevice, usbInterface)) {
return true;
}
return false;
}
private boolean isXbox360Controller(UsbDevice usbDevice, UsbInterface usbInterface) {
final int XB360_IFACE_SUBCLASS = 93;
final int XB360_IFACE_PROTOCOL = 1; // Wired
final int XB360W_IFACE_PROTOCOL = 129; // Wireless
final int[] SUPPORTED_VENDORS = {
0x0079, // GPD Win 2
0x044f, // Thrustmaster
0x045e, // Microsoft
0x046d, // Logitech
0x056e, // Elecom
0x06a3, // Saitek
0x0738, // Mad Catz
0x07ff, // Mad Catz
0x0e6f, // PDP
0x0f0d, // Hori
0x1038, // SteelSeries
0x11c9, // Nacon
0x12ab, // Unknown
0x1430, // RedOctane
0x146b, // BigBen
0x1532, // Razer Sabertooth
0x15e4, // Numark
0x162e, // Joytech
0x1689, // Razer Onza
0x1bad, // Harmonix
0x24c6, // PowerA
};
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC &&
usbInterface.getInterfaceSubclass() == XB360_IFACE_SUBCLASS &&
(usbInterface.getInterfaceProtocol() == XB360_IFACE_PROTOCOL ||
usbInterface.getInterfaceProtocol() == XB360W_IFACE_PROTOCOL)) {
int vendor_id = usbDevice.getVendorId();
for (int supportedVid : SUPPORTED_VENDORS) {
if (vendor_id == supportedVid) {
return true;
}
}
}
return false;
}
private boolean isXboxOneController(UsbDevice usbDevice, UsbInterface usbInterface) {
final int XB1_IFACE_SUBCLASS = 71;
final int XB1_IFACE_PROTOCOL = 208;
final int[] SUPPORTED_VENDORS = {
0x045e, // Microsoft
0x0738, // Mad Catz
0x0e6f, // PDP
0x0f0d, // Hori
0x1532, // Razer Wildcat
0x24c6, // PowerA
0x2e24, // Hyperkin
};
if (usbInterface.getId() == 0 &&
usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_VENDOR_SPEC &&
usbInterface.getInterfaceSubclass() == XB1_IFACE_SUBCLASS &&
usbInterface.getInterfaceProtocol() == XB1_IFACE_PROTOCOL) {
int vendor_id = usbDevice.getVendorId();
for (int supportedVid : SUPPORTED_VENDORS) {
if (vendor_id == supportedVid) {
return true;
}
}
}
return false;
}
private void handleUsbDeviceAttached(UsbDevice usbDevice) {
connectHIDDeviceUSB(usbDevice);
}
private void handleUsbDeviceDetached(UsbDevice usbDevice) {
List<Integer> devices = new ArrayList<Integer>();
for (HIDDevice device : mDevicesById.values()) {
if (usbDevice.equals(device.getDevice())) {
devices.add(device.getId());
}
}
for (int id : devices) {
HIDDevice device = mDevicesById.get(id);
mDevicesById.remove(id);
device.shutdown();
HIDDeviceDisconnected(id);
}
}
private void handleUsbDevicePermission(UsbDevice usbDevice, boolean permission_granted) {
for (HIDDevice device : mDevicesById.values()) {
if (usbDevice.equals(device.getDevice())) {
boolean opened = false;
if (permission_granted) {
opened = device.open();
}
HIDDeviceOpenResult(device.getId(), opened);
}
}
}
private void connectHIDDeviceUSB(UsbDevice usbDevice) {
synchronized (this) {
for (int interface_index = 0; interface_index < usbDevice.getInterfaceCount(); interface_index++) {
UsbInterface usbInterface = usbDevice.getInterface(interface_index);
if (isHIDDeviceInterface(usbDevice, usbInterface)) {
HIDDeviceUSB device = new HIDDeviceUSB(this, usbDevice, interface_index);
int id = device.getId();
mDevicesById.put(id, device);
if (usbDevice != null && !mUsbManager.hasPermission(usbDevice))
{
HIDDeviceOpenPending(id);
try
{
mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(HIDDeviceManager.ACTION_USB_PERMISSION), 0));
}
catch (Exception e)
{
Log.v(TAG, "Couldn't request permission for USB device " + usbDevice);
HIDDeviceOpenResult(id, false);
return;
}
}
HIDDeviceConnected(id, device.getIdentifier(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getVersion(), device.getManufacturerName(), device.getProductName(), usbInterface.getId(), usbInterface.getInterfaceClass(), usbInterface.getInterfaceSubclass(), usbInterface.getInterfaceProtocol());
}
}
}
}
private void initializeBluetooth() {
Log.d(TAG, "Initializing Bluetooth");
if (mContext.getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH, mContext.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Couldn't initialize Bluetooth, missing android.permission.BLUETOOTH");
return;
}
// Find bonded bluetooth controllers and create SteamControllers for them
mBluetoothManager = (BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
// This device doesn't support Bluetooth.
return;
}
BluetoothAdapter btAdapter = mBluetoothManager.getAdapter();
if (btAdapter == null) {
// This device has Bluetooth support in the codebase, but has no available adapters.
return;
}
// Get our bonded devices.
for (BluetoothDevice device : btAdapter.getBondedDevices()) {
Log.d(TAG, "Bluetooth device available: " + device);
if (isSteamController(device)) {
connectBluetoothDevice(device);
}
}
// NOTE: These don't work on Chromebooks, to my undying dismay.
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
mContext.registerReceiver(mBluetoothBroadcast, filter);
if (mIsChromebook) {
mHandler = new Handler(Looper.getMainLooper());
mLastBluetoothDevices = new ArrayList<BluetoothDevice>();
// final HIDDeviceManager finalThis = this;
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// finalThis.chromebookConnectionHandler();
// }
// }, 5000);
}
}
private void shutdownBluetooth() {
try {
mContext.unregisterReceiver(mBluetoothBroadcast);
} catch (Exception e) {
// We may not have registered, that's okay
}
}
// Chromebooks do not pass along ACTION_ACL_CONNECTED / ACTION_ACL_DISCONNECTED properly.
// This function provides a sort of dummy version of that, watching for changes in the
// connected devices and attempting to add controllers as things change.
public void chromebookConnectionHandler() {
if (!mIsChromebook) {
return;
}
ArrayList<BluetoothDevice> disconnected = new ArrayList<BluetoothDevice>();
ArrayList<BluetoothDevice> connected = new ArrayList<BluetoothDevice>();
List<BluetoothDevice> currentConnected = mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
for (BluetoothDevice bluetoothDevice : currentConnected) {
if (!mLastBluetoothDevices.contains(bluetoothDevice)) {
connected.add(bluetoothDevice);
}
}
for (BluetoothDevice bluetoothDevice : mLastBluetoothDevices) {
if (!currentConnected.contains(bluetoothDevice)) {
disconnected.add(bluetoothDevice);
}
}
mLastBluetoothDevices = currentConnected;
for (BluetoothDevice bluetoothDevice : disconnected) {
disconnectBluetoothDevice(bluetoothDevice);
}
for (BluetoothDevice bluetoothDevice : connected) {
connectBluetoothDevice(bluetoothDevice);
}
final HIDDeviceManager finalThis = this;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
finalThis.chromebookConnectionHandler();
}
}, 10000);
}
public boolean connectBluetoothDevice(BluetoothDevice bluetoothDevice) {
Log.v(TAG, "connectBluetoothDevice device=" + bluetoothDevice);
synchronized (this) {
if (mBluetoothDevices.containsKey(bluetoothDevice)) {
Log.v(TAG, "Steam controller with address " + bluetoothDevice + " already exists, attempting reconnect");
HIDDeviceBLESteamController device = mBluetoothDevices.get(bluetoothDevice);
device.reconnect();
return false;
}
HIDDeviceBLESteamController device = new HIDDeviceBLESteamController(this, bluetoothDevice);
int id = device.getId();
mBluetoothDevices.put(bluetoothDevice, device);
mDevicesById.put(id, device);
// The Steam Controller will mark itself connected once initialization is complete
}
return true;
}
public void disconnectBluetoothDevice(BluetoothDevice bluetoothDevice) {
synchronized (this) {
HIDDeviceBLESteamController device = mBluetoothDevices.get(bluetoothDevice);
if (device == null)
return;
int id = device.getId();
mBluetoothDevices.remove(bluetoothDevice);
mDevicesById.remove(id);
device.shutdown();
HIDDeviceDisconnected(id);
}
}
public boolean isSteamController(BluetoothDevice bluetoothDevice) {
// Sanity check. If you pass in a null device, by definition it is never a Steam Controller.
if (bluetoothDevice == null) {
return false;
}
// If the device has no local name, we really don't want to try an equality check against it.
if (bluetoothDevice.getName() == null) {
return false;
}
return bluetoothDevice.getName().equals("SteamController") && ((bluetoothDevice.getType() & BluetoothDevice.DEVICE_TYPE_LE) != 0);
}
private void close() {
shutdownUSB();
shutdownBluetooth();
synchronized (this) {
for (HIDDevice device : mDevicesById.values()) {
device.shutdown();
}
mDevicesById.clear();
mBluetoothDevices.clear();
HIDDeviceReleaseCallback();
}
}
public void setFrozen(boolean frozen) {
synchronized (this) {
for (HIDDevice device : mDevicesById.values()) {
device.setFrozen(frozen);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
private HIDDevice getDevice(int id) {
synchronized (this) {
HIDDevice result = mDevicesById.get(id);
if (result == null) {
Log.v(TAG, "No device for id: " + id);
Log.v(TAG, "Available devices: " + mDevicesById.keySet());
}
return result;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////// JNI interface functions
//////////////////////////////////////////////////////////////////////////////////////////////////////
public boolean openDevice(int deviceID) {
Log.v(TAG, "openDevice deviceID=" + deviceID);
HIDDevice device = getDevice(deviceID);
if (device == null) {
HIDDeviceDisconnected(deviceID);
return false;
}
// Look to see if this is a USB device and we have permission to access it
UsbDevice usbDevice = device.getDevice();
if (usbDevice != null && !mUsbManager.hasPermission(usbDevice)) {
HIDDeviceOpenPending(deviceID);
try {
mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(HIDDeviceManager.ACTION_USB_PERMISSION), 0));
} catch (Exception e) {
Log.v(TAG, "Couldn't request permission for USB device " + usbDevice);
HIDDeviceOpenResult(deviceID, false);
}
return false;
}
try {
return device.open();
} catch (Exception e) {
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
}
return false;
}
public int sendOutputReport(int deviceID, byte[] report) {
try {
//Log.v(TAG, "sendOutputReport deviceID=" + deviceID + " length=" + report.length);
HIDDevice device;
device = getDevice(deviceID);
if (device == null) {
HIDDeviceDisconnected(deviceID);
return -1;
}
return device.sendOutputReport(report);
} catch (Exception e) {
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
}
return -1;
}
public int sendFeatureReport(int deviceID, byte[] report) {
try {
//Log.v(TAG, "sendFeatureReport deviceID=" + deviceID + " length=" + report.length);
HIDDevice device;
device = getDevice(deviceID);
if (device == null) {
HIDDeviceDisconnected(deviceID);
return -1;
}
return device.sendFeatureReport(report);
} catch (Exception e) {
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
}
return -1;
}
public boolean getFeatureReport(int deviceID, byte[] report) {
try {
//Log.v(TAG, "getFeatureReport deviceID=" + deviceID);
HIDDevice device;
device = getDevice(deviceID);
if (device == null) {
HIDDeviceDisconnected(deviceID);
return false;
}
return device.getFeatureReport(report);
} catch (Exception e) {
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
}
return false;
}
public void closeDevice(int deviceID) {
try {
Log.v(TAG, "closeDevice deviceID=" + deviceID);
HIDDevice device;
device = getDevice(deviceID);
if (device == null) {
HIDDeviceDisconnected(deviceID);
return;
}
device.close();
} catch (Exception e) {
Log.e(TAG, "Got exception: " + Log.getStackTraceString(e));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////// Native methods
//////////////////////////////////////////////////////////////////////////////////////////////////////
private native void HIDDeviceRegisterCallback();
private native void HIDDeviceReleaseCallback();
native void HIDDeviceConnected(int deviceID, String identifier, int vendorId, int productId, String serial_number, int release_number, String manufacturer_string, String product_string, int interface_number, int interface_class, int interface_subclass, int interface_protocol);
native void HIDDeviceOpenPending(int deviceID);
native void HIDDeviceOpenResult(int deviceID, boolean opened);
native void HIDDeviceDisconnected(int deviceID);
native void HIDDeviceInputReport(int deviceID, byte[] report);
native void HIDDeviceFeatureReport(int deviceID, byte[] report);
}

View File

@@ -0,0 +1,304 @@
package org.libsdl.app;
import android.hardware.usb.*;
import android.os.Build;
import android.util.Log;
import java.util.Arrays;
class HIDDeviceUSB implements HIDDevice {
private static final String TAG = "hidapi";
protected HIDDeviceManager mManager;
protected UsbDevice mDevice;
protected int mInterfaceIndex;
protected int mInterface;
protected int mDeviceId;
protected UsbDeviceConnection mConnection;
protected UsbEndpoint mInputEndpoint;
protected UsbEndpoint mOutputEndpoint;
protected InputThread mInputThread;
protected boolean mRunning;
protected boolean mFrozen;
public HIDDeviceUSB(HIDDeviceManager manager, UsbDevice usbDevice, int interface_index) {
mManager = manager;
mDevice = usbDevice;
mInterfaceIndex = interface_index;
mInterface = mDevice.getInterface(mInterfaceIndex).getId();
mDeviceId = manager.getDeviceIDForIdentifier(getIdentifier());
mRunning = false;
}
public String getIdentifier() {
return String.format("%s/%x/%x/%d", mDevice.getDeviceName(), mDevice.getVendorId(), mDevice.getProductId(), mInterfaceIndex);
}
@Override
public int getId() {
return mDeviceId;
}
@Override
public int getVendorId() {
return mDevice.getVendorId();
}
@Override
public int getProductId() {
return mDevice.getProductId();
}
@Override
public String getSerialNumber() {
String result = null;
if (Build.VERSION.SDK_INT >= 21) {
result = mDevice.getSerialNumber();
}
if (result == null) {
result = "";
}
return result;
}
@Override
public int getVersion() {
return 0;
}
@Override
public String getManufacturerName() {
String result = null;
if (Build.VERSION.SDK_INT >= 21) {
result = mDevice.getManufacturerName();
}
if (result == null) {
result = String.format("%x", getVendorId());
}
return result;
}
@Override
public String getProductName() {
String result = null;
if (Build.VERSION.SDK_INT >= 21) {
result = mDevice.getProductName();
}
if (result == null) {
result = String.format("%x", getProductId());
}
return result;
}
@Override
public UsbDevice getDevice() {
return mDevice;
}
public String getDeviceName() {
return getManufacturerName() + " " + getProductName() + "(0x" + String.format("%x", getVendorId()) + "/0x" + String.format("%x", getProductId()) + ")";
}
@Override
public boolean open() {
mConnection = mManager.getUSBManager().openDevice(mDevice);
if (mConnection == null) {
Log.w(TAG, "Unable to open USB device " + getDeviceName());
return false;
}
// Force claim our interface
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
if (!mConnection.claimInterface(iface, true)) {
Log.w(TAG, "Failed to claim interfaces on USB device " + getDeviceName());
close();
return false;
}
// Find the endpoints
for (int j = 0; j < iface.getEndpointCount(); j++) {
UsbEndpoint endpt = iface.getEndpoint(j);
switch (endpt.getDirection()) {
case UsbConstants.USB_DIR_IN:
if (mInputEndpoint == null) {
mInputEndpoint = endpt;
}
break;
case UsbConstants.USB_DIR_OUT:
if (mOutputEndpoint == null) {
mOutputEndpoint = endpt;
}
break;
}
}
// Make sure the required endpoints were present
if (mInputEndpoint == null || mOutputEndpoint == null) {
Log.w(TAG, "Missing required endpoint on USB device " + getDeviceName());
close();
return false;
}
// Start listening for input
mRunning = true;
mInputThread = new InputThread();
mInputThread.start();
return true;
}
@Override
public int sendFeatureReport(byte[] report) {
int res = -1;
int offset = 0;
int length = report.length;
boolean skipped_report_id = false;
byte report_number = report[0];
if (report_number == 0x0) {
++offset;
--length;
skipped_report_id = true;
}
res = mConnection.controlTransfer(
UsbConstants.USB_TYPE_CLASS | 0x01 /*RECIPIENT_INTERFACE*/ | UsbConstants.USB_DIR_OUT,
0x09/*HID set_report*/,
(3/*HID feature*/ << 8) | report_number,
mInterface,
report, offset, length,
1000/*timeout millis*/);
if (res < 0) {
Log.w(TAG, "sendFeatureReport() returned " + res + " on device " + getDeviceName());
return -1;
}
if (skipped_report_id) {
++length;
}
return length;
}
@Override
public int sendOutputReport(byte[] report) {
int r = mConnection.bulkTransfer(mOutputEndpoint, report, report.length, 1000);
if (r != report.length) {
Log.w(TAG, "sendOutputReport() returned " + r + " on device " + getDeviceName());
}
return r;
}
@Override
public boolean getFeatureReport(byte[] report) {
int res = -1;
int offset = 0;
int length = report.length;
boolean skipped_report_id = false;
byte report_number = report[0];
if (report_number == 0x0) {
/* Offset the return buffer by 1, so that the report ID
will remain in byte 0. */
++offset;
--length;
skipped_report_id = true;
}
res = mConnection.controlTransfer(
UsbConstants.USB_TYPE_CLASS | 0x01 /*RECIPIENT_INTERFACE*/ | UsbConstants.USB_DIR_IN,
0x01/*HID get_report*/,
(3/*HID feature*/ << 8) | report_number,
mInterface,
report, offset, length,
1000/*timeout millis*/);
if (res < 0) {
Log.w(TAG, "getFeatureReport() returned " + res + " on device " + getDeviceName());
return false;
}
if (skipped_report_id) {
++res;
++length;
}
byte[] data;
if (res == length) {
data = report;
} else {
data = Arrays.copyOfRange(report, 0, res);
}
mManager.HIDDeviceFeatureReport(mDeviceId, data);
return true;
}
@Override
public void close() {
mRunning = false;
if (mInputThread != null) {
while (mInputThread.isAlive()) {
mInputThread.interrupt();
try {
mInputThread.join();
} catch (InterruptedException e) {
// Keep trying until we're done
}
}
mInputThread = null;
}
if (mConnection != null) {
UsbInterface iface = mDevice.getInterface(mInterfaceIndex);
mConnection.releaseInterface(iface);
mConnection.close();
mConnection = null;
}
}
@Override
public void shutdown() {
close();
mManager = null;
}
@Override
public void setFrozen(boolean frozen) {
mFrozen = frozen;
}
protected class InputThread extends Thread {
@Override
public void run() {
int packetSize = mInputEndpoint.getMaxPacketSize();
byte[] packet = new byte[packetSize];
while (mRunning) {
int r;
try
{
r = mConnection.bulkTransfer(mInputEndpoint, packet, packetSize, 1000);
}
catch (Exception e)
{
Log.v(TAG, "Exception in UsbDeviceConnection bulktransfer: " + e);
break;
}
if (r < 0) {
// Could be a timeout or an I/O error
}
if (r > 0) {
byte[] data;
if (r == packetSize) {
data = packet;
} else {
data = Arrays.copyOfRange(packet, 0, r);
}
if (!mFrozen) {
mManager.HIDDeviceInputReport(mDeviceId, data);
}
}
}
}
}
}

View File

@@ -1,592 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import java.lang.String;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.reflect.Field;
// Autogenerated by hand with a command:
// grep 'SDLK_' SDL_keysym.h | sed 's/SDLK_\([a-zA-Z0-9_]\+\).*[=] \([0-9]\+\).*/public static final int SDLK_\1 = \2;/' >> Keycodes.java
class SDL_1_2_Keycodes
{
public static final int SDLK_UNKNOWN = 0;
public static final int SDLK_BACKSPACE = 8;
public static final int SDLK_TAB = 9;
public static final int SDLK_CLEAR = 12;
public static final int SDLK_RETURN = 13;
public static final int SDLK_PAUSE = 19;
public static final int SDLK_ESCAPE = 27;
public static final int SDLK_SPACE = 32;
public static final int SDLK_EXCLAIM = 33;
public static final int SDLK_QUOTEDBL = 34;
public static final int SDLK_HASH = 35;
public static final int SDLK_DOLLAR = 36;
public static final int SDLK_AMPERSAND = 38;
public static final int SDLK_QUOTE = 39;
public static final int SDLK_LEFTPAREN = 40;
public static final int SDLK_RIGHTPAREN = 41;
public static final int SDLK_ASTERISK = 42;
public static final int SDLK_PLUS = 43;
public static final int SDLK_COMMA = 44;
public static final int SDLK_MINUS = 45;
public static final int SDLK_PERIOD = 46;
public static final int SDLK_SLASH = 47;
public static final int SDLK_0 = 48;
public static final int SDLK_1 = 49;
public static final int SDLK_2 = 50;
public static final int SDLK_3 = 51;
public static final int SDLK_4 = 52;
public static final int SDLK_5 = 53;
public static final int SDLK_6 = 54;
public static final int SDLK_7 = 55;
public static final int SDLK_8 = 56;
public static final int SDLK_9 = 57;
public static final int SDLK_COLON = 58;
public static final int SDLK_SEMICOLON = 59;
public static final int SDLK_LESS = 60;
public static final int SDLK_EQUALS = 61;
public static final int SDLK_GREATER = 62;
public static final int SDLK_QUESTION = 63;
public static final int SDLK_AT = 64;
public static final int SDLK_LEFTBRACKET = 91;
public static final int SDLK_BACKSLASH = 92;
public static final int SDLK_RIGHTBRACKET = 93;
public static final int SDLK_CARET = 94;
public static final int SDLK_UNDERSCORE = 95;
public static final int SDLK_BACKQUOTE = 96;
public static final int SDLK_a = 97;
public static final int SDLK_b = 98;
public static final int SDLK_c = 99;
public static final int SDLK_d = 100;
public static final int SDLK_e = 101;
public static final int SDLK_f = 102;
public static final int SDLK_g = 103;
public static final int SDLK_h = 104;
public static final int SDLK_i = 105;
public static final int SDLK_j = 106;
public static final int SDLK_k = 107;
public static final int SDLK_l = 108;
public static final int SDLK_m = 109;
public static final int SDLK_n = 110;
public static final int SDLK_o = 111;
public static final int SDLK_p = 112;
public static final int SDLK_q = 113;
public static final int SDLK_r = 114;
public static final int SDLK_s = 115;
public static final int SDLK_t = 116;
public static final int SDLK_u = 117;
public static final int SDLK_v = 118;
public static final int SDLK_w = 119;
public static final int SDLK_x = 120;
public static final int SDLK_y = 121;
public static final int SDLK_z = 122;
public static final int SDLK_DELETE = 127;
public static final int SDLK_WORLD_0 = 160;
public static final int SDLK_WORLD_1 = 161;
public static final int SDLK_WORLD_2 = 162;
public static final int SDLK_WORLD_3 = 163;
public static final int SDLK_WORLD_4 = 164;
public static final int SDLK_WORLD_5 = 165;
public static final int SDLK_WORLD_6 = 166;
public static final int SDLK_WORLD_7 = 167;
public static final int SDLK_WORLD_8 = 168;
public static final int SDLK_WORLD_9 = 169;
public static final int SDLK_WORLD_10 = 170;
public static final int SDLK_WORLD_11 = 171;
public static final int SDLK_WORLD_12 = 172;
public static final int SDLK_WORLD_13 = 173;
public static final int SDLK_WORLD_14 = 174;
public static final int SDLK_WORLD_15 = 175;
public static final int SDLK_WORLD_16 = 176;
public static final int SDLK_WORLD_17 = 177;
public static final int SDLK_WORLD_18 = 178;
public static final int SDLK_WORLD_19 = 179;
public static final int SDLK_WORLD_20 = 180;
public static final int SDLK_WORLD_21 = 181;
public static final int SDLK_WORLD_22 = 182;
public static final int SDLK_WORLD_23 = 183;
public static final int SDLK_WORLD_24 = 184;
public static final int SDLK_WORLD_25 = 185;
public static final int SDLK_WORLD_26 = 186;
public static final int SDLK_WORLD_27 = 187;
public static final int SDLK_WORLD_28 = 188;
public static final int SDLK_WORLD_29 = 189;
public static final int SDLK_WORLD_30 = 190;
public static final int SDLK_WORLD_31 = 191;
public static final int SDLK_WORLD_32 = 192;
public static final int SDLK_WORLD_33 = 193;
public static final int SDLK_WORLD_34 = 194;
public static final int SDLK_WORLD_35 = 195;
public static final int SDLK_WORLD_36 = 196;
public static final int SDLK_WORLD_37 = 197;
public static final int SDLK_WORLD_38 = 198;
public static final int SDLK_WORLD_39 = 199;
public static final int SDLK_WORLD_40 = 200;
public static final int SDLK_WORLD_41 = 201;
public static final int SDLK_WORLD_42 = 202;
public static final int SDLK_WORLD_43 = 203;
public static final int SDLK_WORLD_44 = 204;
public static final int SDLK_WORLD_45 = 205;
public static final int SDLK_WORLD_46 = 206;
public static final int SDLK_WORLD_47 = 207;
public static final int SDLK_WORLD_48 = 208;
public static final int SDLK_WORLD_49 = 209;
public static final int SDLK_WORLD_50 = 210;
public static final int SDLK_WORLD_51 = 211;
public static final int SDLK_WORLD_52 = 212;
public static final int SDLK_WORLD_53 = 213;
public static final int SDLK_WORLD_54 = 214;
public static final int SDLK_WORLD_55 = 215;
public static final int SDLK_WORLD_56 = 216;
public static final int SDLK_WORLD_57 = 217;
public static final int SDLK_WORLD_58 = 218;
public static final int SDLK_WORLD_59 = 219;
public static final int SDLK_WORLD_60 = 220;
public static final int SDLK_WORLD_61 = 221;
public static final int SDLK_WORLD_62 = 222;
public static final int SDLK_WORLD_63 = 223;
public static final int SDLK_WORLD_64 = 224;
public static final int SDLK_WORLD_65 = 225;
public static final int SDLK_WORLD_66 = 226;
public static final int SDLK_WORLD_67 = 227;
public static final int SDLK_WORLD_68 = 228;
public static final int SDLK_WORLD_69 = 229;
public static final int SDLK_WORLD_70 = 230;
public static final int SDLK_WORLD_71 = 231;
public static final int SDLK_WORLD_72 = 232;
public static final int SDLK_WORLD_73 = 233;
public static final int SDLK_WORLD_74 = 234;
public static final int SDLK_WORLD_75 = 235;
public static final int SDLK_WORLD_76 = 236;
public static final int SDLK_WORLD_77 = 237;
public static final int SDLK_WORLD_78 = 238;
public static final int SDLK_WORLD_79 = 239;
public static final int SDLK_WORLD_80 = 240;
public static final int SDLK_WORLD_81 = 241;
public static final int SDLK_WORLD_82 = 242;
public static final int SDLK_WORLD_83 = 243;
public static final int SDLK_WORLD_84 = 244;
public static final int SDLK_WORLD_85 = 245;
public static final int SDLK_WORLD_86 = 246;
public static final int SDLK_WORLD_87 = 247;
public static final int SDLK_WORLD_88 = 248;
public static final int SDLK_WORLD_89 = 249;
public static final int SDLK_WORLD_90 = 250;
public static final int SDLK_WORLD_91 = 251;
public static final int SDLK_WORLD_92 = 252;
public static final int SDLK_WORLD_93 = 253;
public static final int SDLK_WORLD_94 = 254;
public static final int SDLK_WORLD_95 = 255;
public static final int SDLK_KP0 = 256;
public static final int SDLK_KP1 = 257;
public static final int SDLK_KP2 = 258;
public static final int SDLK_KP3 = 259;
public static final int SDLK_KP4 = 260;
public static final int SDLK_KP5 = 261;
public static final int SDLK_KP6 = 262;
public static final int SDLK_KP7 = 263;
public static final int SDLK_KP8 = 264;
public static final int SDLK_KP9 = 265;
public static final int SDLK_KP_PERIOD = 266;
public static final int SDLK_KP_DIVIDE = 267;
public static final int SDLK_KP_MULTIPLY = 268;
public static final int SDLK_KP_MINUS = 269;
public static final int SDLK_KP_PLUS = 270;
public static final int SDLK_KP_ENTER = 271;
public static final int SDLK_KP_EQUALS = 272;
public static final int SDLK_UP = 273;
public static final int SDLK_DOWN = 274;
public static final int SDLK_RIGHT = 275;
public static final int SDLK_LEFT = 276;
public static final int SDLK_INSERT = 277;
public static final int SDLK_HOME = 278;
public static final int SDLK_END = 279;
public static final int SDLK_PAGEUP = 280;
public static final int SDLK_PAGEDOWN = 281;
public static final int SDLK_F1 = 282;
public static final int SDLK_F2 = 283;
public static final int SDLK_F3 = 284;
public static final int SDLK_F4 = 285;
public static final int SDLK_F5 = 286;
public static final int SDLK_F6 = 287;
public static final int SDLK_F7 = 288;
public static final int SDLK_F8 = 289;
public static final int SDLK_F9 = 290;
public static final int SDLK_F10 = 291;
public static final int SDLK_F11 = 292;
public static final int SDLK_F12 = 293;
public static final int SDLK_F13 = 294;
public static final int SDLK_F14 = 295;
public static final int SDLK_F15 = 296;
public static final int SDLK_NUMLOCK = 300;
public static final int SDLK_CAPSLOCK = 301;
public static final int SDLK_SCROLLOCK = 302;
public static final int SDLK_RSHIFT = 303;
public static final int SDLK_LSHIFT = 304;
public static final int SDLK_RCTRL = 305;
public static final int SDLK_LCTRL = 306;
public static final int SDLK_RALT = 307;
public static final int SDLK_LALT = 308;
public static final int SDLK_RMETA = 309;
public static final int SDLK_LMETA = 310;
public static final int SDLK_LSUPER = 311;
public static final int SDLK_RSUPER = 312;
public static final int SDLK_MODE = 313;
public static final int SDLK_COMPOSE = 314;
public static final int SDLK_HELP = 315;
public static final int SDLK_PRINT = 316;
public static final int SDLK_SYSREQ = 317;
public static final int SDLK_BREAK = 318;
public static final int SDLK_MENU = 319;
public static final int SDLK_POWER = 320;
public static final int SDLK_EURO = 321;
public static final int SDLK_UNDO = 322;
public static final int SDLK_NO_REMAP = 512;
}
// Autogenerated by hand with a command:
// grep 'SDL_SCANCODE_' SDL_scancode.h | sed 's/SDL_SCANCODE_\([a-zA-Z0-9_]\+\).*[=] \([0-9]\+\).*/public static final int SDLK_\1 = \2;/' >> Keycodes.java
class SDL_1_3_Keycodes
{
public static final int SDLK_UNKNOWN = 0;
public static final int SDLK_A = 4;
public static final int SDLK_B = 5;
public static final int SDLK_C = 6;
public static final int SDLK_D = 7;
public static final int SDLK_E = 8;
public static final int SDLK_F = 9;
public static final int SDLK_G = 10;
public static final int SDLK_H = 11;
public static final int SDLK_I = 12;
public static final int SDLK_J = 13;
public static final int SDLK_K = 14;
public static final int SDLK_L = 15;
public static final int SDLK_M = 16;
public static final int SDLK_N = 17;
public static final int SDLK_O = 18;
public static final int SDLK_P = 19;
public static final int SDLK_Q = 20;
public static final int SDLK_R = 21;
public static final int SDLK_S = 22;
public static final int SDLK_T = 23;
public static final int SDLK_U = 24;
public static final int SDLK_V = 25;
public static final int SDLK_W = 26;
public static final int SDLK_X = 27;
public static final int SDLK_Y = 28;
public static final int SDLK_Z = 29;
public static final int SDLK_1 = 30;
public static final int SDLK_2 = 31;
public static final int SDLK_3 = 32;
public static final int SDLK_4 = 33;
public static final int SDLK_5 = 34;
public static final int SDLK_6 = 35;
public static final int SDLK_7 = 36;
public static final int SDLK_8 = 37;
public static final int SDLK_9 = 38;
public static final int SDLK_0 = 39;
public static final int SDLK_RETURN = 40;
public static final int SDLK_ESCAPE = 41;
public static final int SDLK_BACKSPACE = 42;
public static final int SDLK_TAB = 43;
public static final int SDLK_SPACE = 44;
public static final int SDLK_MINUS = 45;
public static final int SDLK_EQUALS = 46;
public static final int SDLK_LEFTBRACKET = 47;
public static final int SDLK_RIGHTBRACKET = 48;
public static final int SDLK_BACKSLASH = 49;
public static final int SDLK_NONUSHASH = 50;
public static final int SDLK_SEMICOLON = 51;
public static final int SDLK_APOSTROPHE = 52;
public static final int SDLK_GRAVE = 53;
public static final int SDLK_COMMA = 54;
public static final int SDLK_PERIOD = 55;
public static final int SDLK_SLASH = 56;
public static final int SDLK_CAPSLOCK = 57;
public static final int SDLK_F1 = 58;
public static final int SDLK_F2 = 59;
public static final int SDLK_F3 = 60;
public static final int SDLK_F4 = 61;
public static final int SDLK_F5 = 62;
public static final int SDLK_F6 = 63;
public static final int SDLK_F7 = 64;
public static final int SDLK_F8 = 65;
public static final int SDLK_F9 = 66;
public static final int SDLK_F10 = 67;
public static final int SDLK_F11 = 68;
public static final int SDLK_F12 = 69;
public static final int SDLK_PRINTSCREEN = 70;
public static final int SDLK_SCROLLLOCK = 71;
public static final int SDLK_PAUSE = 72;
public static final int SDLK_INSERT = 73;
public static final int SDLK_HOME = 74;
public static final int SDLK_PAGEUP = 75;
public static final int SDLK_DELETE = 76;
public static final int SDLK_END = 77;
public static final int SDLK_PAGEDOWN = 78;
public static final int SDLK_RIGHT = 79;
public static final int SDLK_LEFT = 80;
public static final int SDLK_DOWN = 81;
public static final int SDLK_UP = 82;
public static final int SDLK_NUMLOCKCLEAR = 83;
public static final int SDLK_KP_DIVIDE = 84;
public static final int SDLK_KP_MULTIPLY = 85;
public static final int SDLK_KP_MINUS = 86;
public static final int SDLK_KP_PLUS = 87;
public static final int SDLK_KP_ENTER = 88;
public static final int SDLK_KP_1 = 89;
public static final int SDLK_KP_2 = 90;
public static final int SDLK_KP_3 = 91;
public static final int SDLK_KP_4 = 92;
public static final int SDLK_KP_5 = 93;
public static final int SDLK_KP_6 = 94;
public static final int SDLK_KP_7 = 95;
public static final int SDLK_KP_8 = 96;
public static final int SDLK_KP_9 = 97;
public static final int SDLK_KP_0 = 98;
public static final int SDLK_KP_PERIOD = 99;
public static final int SDLK_NONUSBACKSLASH = 100;
public static final int SDLK_APPLICATION = 101;
public static final int SDLK_POWER = 102;
public static final int SDLK_KP_EQUALS = 103;
public static final int SDLK_F13 = 104;
public static final int SDLK_F14 = 105;
public static final int SDLK_F15 = 106;
public static final int SDLK_F16 = 107;
public static final int SDLK_F17 = 108;
public static final int SDLK_F18 = 109;
public static final int SDLK_F19 = 110;
public static final int SDLK_F20 = 111;
public static final int SDLK_F21 = 112;
public static final int SDLK_F22 = 113;
public static final int SDLK_F23 = 114;
public static final int SDLK_F24 = 115;
public static final int SDLK_EXECUTE = 116;
public static final int SDLK_HELP = 117;
public static final int SDLK_MENU = 118;
public static final int SDLK_SELECT = 119;
public static final int SDLK_STOP = 120;
public static final int SDLK_AGAIN = 121;
public static final int SDLK_UNDO = 122;
public static final int SDLK_CUT = 123;
public static final int SDLK_COPY = 124;
public static final int SDLK_PASTE = 125;
public static final int SDLK_FIND = 126;
public static final int SDLK_MUTE = 127;
public static final int SDLK_VOLUMEUP = 128;
public static final int SDLK_VOLUMEDOWN = 129;
public static final int SDLK_KP_COMMA = 133;
public static final int SDLK_KP_EQUALSAS400 = 134;
public static final int SDLK_INTERNATIONAL1 = 135;
public static final int SDLK_INTERNATIONAL2 = 136;
public static final int SDLK_INTERNATIONAL3 = 137;
public static final int SDLK_INTERNATIONAL4 = 138;
public static final int SDLK_INTERNATIONAL5 = 139;
public static final int SDLK_INTERNATIONAL6 = 140;
public static final int SDLK_INTERNATIONAL7 = 141;
public static final int SDLK_INTERNATIONAL8 = 142;
public static final int SDLK_INTERNATIONAL9 = 143;
public static final int SDLK_LANG1 = 144;
public static final int SDLK_LANG2 = 145;
public static final int SDLK_LANG3 = 146;
public static final int SDLK_LANG4 = 147;
public static final int SDLK_LANG5 = 148;
public static final int SDLK_LANG6 = 149;
public static final int SDLK_LANG7 = 150;
public static final int SDLK_LANG8 = 151;
public static final int SDLK_LANG9 = 152;
public static final int SDLK_ALTERASE = 153;
public static final int SDLK_SYSREQ = 154;
public static final int SDLK_CANCEL = 155;
public static final int SDLK_CLEAR = 156;
public static final int SDLK_PRIOR = 157;
public static final int SDLK_RETURN2 = 158;
public static final int SDLK_SEPARATOR = 159;
public static final int SDLK_OUT = 160;
public static final int SDLK_OPER = 161;
public static final int SDLK_CLEARAGAIN = 162;
public static final int SDLK_CRSEL = 163;
public static final int SDLK_EXSEL = 164;
public static final int SDLK_KP_00 = 176;
public static final int SDLK_KP_000 = 177;
public static final int SDLK_THOUSANDSSEPARATOR = 178;
public static final int SDLK_DECIMALSEPARATOR = 179;
public static final int SDLK_CURRENCYUNIT = 180;
public static final int SDLK_CURRENCYSUBUNIT = 181;
public static final int SDLK_KP_LEFTPAREN = 182;
public static final int SDLK_KP_RIGHTPAREN = 183;
public static final int SDLK_KP_LEFTBRACE = 184;
public static final int SDLK_KP_RIGHTBRACE = 185;
public static final int SDLK_KP_TAB = 186;
public static final int SDLK_KP_BACKSPACE = 187;
public static final int SDLK_KP_A = 188;
public static final int SDLK_KP_B = 189;
public static final int SDLK_KP_C = 190;
public static final int SDLK_KP_D = 191;
public static final int SDLK_KP_E = 192;
public static final int SDLK_KP_F = 193;
public static final int SDLK_KP_XOR = 194;
public static final int SDLK_KP_POWER = 195;
public static final int SDLK_KP_PERCENT = 196;
public static final int SDLK_KP_LESS = 197;
public static final int SDLK_KP_GREATER = 198;
public static final int SDLK_KP_AMPERSAND = 199;
public static final int SDLK_KP_DBLAMPERSAND = 200;
public static final int SDLK_KP_VERTICALBAR = 201;
public static final int SDLK_KP_DBLVERTICALBAR = 202;
public static final int SDLK_KP_COLON = 203;
public static final int SDLK_KP_HASH = 204;
public static final int SDLK_KP_SPACE = 205;
public static final int SDLK_KP_AT = 206;
public static final int SDLK_KP_EXCLAM = 207;
public static final int SDLK_KP_MEMSTORE = 208;
public static final int SDLK_KP_MEMRECALL = 209;
public static final int SDLK_KP_MEMCLEAR = 210;
public static final int SDLK_KP_MEMADD = 211;
public static final int SDLK_KP_MEMSUBTRACT = 212;
public static final int SDLK_KP_MEMMULTIPLY = 213;
public static final int SDLK_KP_MEMDIVIDE = 214;
public static final int SDLK_KP_PLUSMINUS = 215;
public static final int SDLK_KP_CLEAR = 216;
public static final int SDLK_KP_CLEARENTRY = 217;
public static final int SDLK_KP_BINARY = 218;
public static final int SDLK_KP_OCTAL = 219;
public static final int SDLK_KP_DECIMAL = 220;
public static final int SDLK_KP_HEXADECIMAL = 221;
public static final int SDLK_LCTRL = 224;
public static final int SDLK_LSHIFT = 225;
public static final int SDLK_LALT = 226;
public static final int SDLK_LGUI = 227;
public static final int SDLK_RCTRL = 228;
public static final int SDLK_RSHIFT = 229;
public static final int SDLK_RALT = 230;
public static final int SDLK_RGUI = 231;
public static final int SDLK_MODE = 257;
public static final int SDLK_AUDIONEXT = 258;
public static final int SDLK_AUDIOPREV = 259;
public static final int SDLK_AUDIOSTOP = 260;
public static final int SDLK_AUDIOPLAY = 261;
public static final int SDLK_AUDIOMUTE = 262;
public static final int SDLK_MEDIASELECT = 263;
public static final int SDLK_WWW = 264;
public static final int SDLK_MAIL = 265;
public static final int SDLK_CALCULATOR = 266;
public static final int SDLK_COMPUTER = 267;
public static final int SDLK_AC_SEARCH = 268;
public static final int SDLK_AC_HOME = 269;
public static final int SDLK_AC_BACK = 270;
public static final int SDLK_AC_FORWARD = 271;
public static final int SDLK_AC_STOP = 272;
public static final int SDLK_AC_REFRESH = 273;
public static final int SDLK_AC_BOOKMARKS = 274;
public static final int SDLK_BRIGHTNESSDOWN = 275;
public static final int SDLK_BRIGHTNESSUP = 276;
public static final int SDLK_DISPLAYSWITCH = 277;
public static final int SDLK_KBDILLUMTOGGLE = 278;
public static final int SDLK_KBDILLUMDOWN = 279;
public static final int SDLK_KBDILLUMUP = 280;
public static final int SDLK_EJECT = 281;
public static final int SDLK_SLEEP = 282;
public static final int SDLK_NO_REMAP = 512;
}
class SDL_Keys
{
public static String [] names = null;
public static Integer [] values = null;
public static String [] namesSorted = null;
public static Integer [] namesSortedIdx = null;
public static Integer [] namesSortedBackIdx = null;
static final int JAVA_KEYCODE_LAST = 255; // Android 2.3 added several new gaming keys, Android 3.1 added even more - keep in sync with javakeycodes.h
static String getName(int v)
{
for( int f = 0; f < values.length; f++ )
{
if( values[f] == v )
return names[f];
}
return names[0];
}
static
{
ArrayList<String> Names = new ArrayList<String> ();
ArrayList<Integer> Values = new ArrayList<Integer> ();
Field [] fields = SDL_1_2_Keycodes.class.getDeclaredFields();
if( Globals.Using_SDL_1_3 )
{
fields = SDL_1_3_Keycodes.class.getDeclaredFields();
}
try {
for(Field f: fields)
{
Values.add(f.getInt(null));
Names.add(f.getName().substring(5).toUpperCase());
}
} catch(IllegalAccessException e) {};
// Sort by value
for( int i = 0; i < Values.size(); i++ )
{
for( int j = i; j < Values.size(); j++ )
{
if( Values.get(i) > Values.get(j) )
{
int x = Values.get(i);
Values.set(i, Values.get(j));
Values.set(j, x);
String s = Names.get(i);
Names.set(i, Names.get(j));
Names.set(j, s);
}
}
}
names = Names.toArray(new String[0]);
values = Values.toArray(new Integer[0]);
namesSorted = Names.toArray(new String[0]);
namesSortedIdx = new Integer[values.length];
namesSortedBackIdx = new Integer[values.length];
Arrays.sort(namesSorted);
for( int i = 0; i < namesSorted.length; i++ )
{
for( int j = 0; j < namesSorted.length; j++ )
{
if( namesSorted[i].equals( names[j] ) )
{
namesSortedIdx[i] = j;
namesSortedBackIdx[j] = i;
break;
}
}
}
}
}

File diff suppressed because it is too large Load Diff

84
project/javaSDL2/SDL.java Normal file
View File

@@ -0,0 +1,84 @@
package org.libsdl.app;
import android.content.Context;
import java.lang.reflect.*;
/**
SDL library initialization
*/
public class SDL {
// This function should be called first and sets up the native code
// so it can call into the Java classes
public static void setupJNI() {
SDLActivity.nativeSetupJNI();
SDLAudioManager.nativeSetupJNI();
SDLControllerManager.nativeSetupJNI();
}
// This function should be called each time the activity is started
public static void initialize() {
setContext(null);
SDLActivity.initialize();
SDLAudioManager.initialize();
SDLControllerManager.initialize();
}
// This function stores the current activity (SDL or not)
public static void setContext(Context context) {
mContext = context;
}
public static Context getContext() {
return mContext;
}
public static void loadLibrary(String libraryName) throws UnsatisfiedLinkError, SecurityException, NullPointerException {
if (libraryName == null) {
throw new NullPointerException("No library name provided.");
}
try {
// Let's see if we have ReLinker available in the project. This is necessary for
// some projects that have huge numbers of local libraries bundled, and thus may
// trip a bug in Android's native library loader which ReLinker works around. (If
// loadLibrary works properly, ReLinker will simply use the normal Android method
// internally.)
//
// To use ReLinker, just add it as a dependency. For more information, see
// https://github.com/KeepSafe/ReLinker for ReLinker's repository.
//
Class relinkClass = mContext.getClassLoader().loadClass("com.getkeepsafe.relinker.ReLinker");
Class relinkListenerClass = mContext.getClassLoader().loadClass("com.getkeepsafe.relinker.ReLinker$LoadListener");
Class contextClass = mContext.getClassLoader().loadClass("android.content.Context");
Class stringClass = mContext.getClassLoader().loadClass("java.lang.String");
// Get a 'force' instance of the ReLinker, so we can ensure libraries are reinstalled if
// they've changed during updates.
Method forceMethod = relinkClass.getDeclaredMethod("force");
Object relinkInstance = forceMethod.invoke(null);
Class relinkInstanceClass = relinkInstance.getClass();
// Actually load the library!
Method loadMethod = relinkInstanceClass.getDeclaredMethod("loadLibrary", contextClass, stringClass, stringClass, relinkListenerClass);
loadMethod.invoke(relinkInstance, mContext, libraryName, null, null);
}
catch (final Throwable e) {
// Fall back
try {
System.loadLibrary(libraryName);
}
catch (final UnsatisfiedLinkError ule) {
throw ule;
}
catch (final SecurityException se) {
throw se;
}
}
}
protected static Context mContext;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,387 @@
package org.libsdl.app;
import android.media.*;
import android.os.Build;
import android.util.Log;
public class SDLAudioManager
{
protected static final String TAG = "SDLAudio";
protected static AudioTrack mAudioTrack;
protected static AudioRecord mAudioRecord;
public static void initialize() {
mAudioTrack = null;
mAudioRecord = null;
}
// Audio
protected static String getAudioFormatString(int audioFormat) {
switch (audioFormat) {
case AudioFormat.ENCODING_PCM_8BIT:
return "8-bit";
case AudioFormat.ENCODING_PCM_16BIT:
return "16-bit";
case AudioFormat.ENCODING_PCM_FLOAT:
return "float";
default:
return Integer.toString(audioFormat);
}
}
protected static int[] open(boolean isCapture, int sampleRate, int audioFormat, int desiredChannels, int desiredFrames) {
int channelConfig;
int sampleSize;
int frameSize;
Log.v(TAG, "Opening " + (isCapture ? "capture" : "playback") + ", requested " + desiredFrames + " frames of " + desiredChannels + " channel " + getAudioFormatString(audioFormat) + " audio at " + sampleRate + " Hz");
/* On older devices let's use known good settings */
if (Build.VERSION.SDK_INT < 21) {
if (desiredChannels > 2) {
desiredChannels = 2;
}
if (sampleRate < 8000) {
sampleRate = 8000;
} else if (sampleRate > 48000) {
sampleRate = 48000;
}
}
if (audioFormat == AudioFormat.ENCODING_PCM_FLOAT) {
int minSDKVersion = (isCapture ? 23 : 21);
if (Build.VERSION.SDK_INT < minSDKVersion) {
audioFormat = AudioFormat.ENCODING_PCM_16BIT;
}
}
switch (audioFormat)
{
case AudioFormat.ENCODING_PCM_8BIT:
sampleSize = 1;
break;
case AudioFormat.ENCODING_PCM_16BIT:
sampleSize = 2;
break;
case AudioFormat.ENCODING_PCM_FLOAT:
sampleSize = 4;
break;
default:
Log.v(TAG, "Requested format " + audioFormat + ", getting ENCODING_PCM_16BIT");
audioFormat = AudioFormat.ENCODING_PCM_16BIT;
sampleSize = 2;
break;
}
if (isCapture) {
switch (desiredChannels) {
case 1:
channelConfig = AudioFormat.CHANNEL_IN_MONO;
break;
case 2:
channelConfig = AudioFormat.CHANNEL_IN_STEREO;
break;
default:
Log.v(TAG, "Requested " + desiredChannels + " channels, getting stereo");
desiredChannels = 2;
channelConfig = AudioFormat.CHANNEL_IN_STEREO;
break;
}
} else {
switch (desiredChannels) {
case 1:
channelConfig = AudioFormat.CHANNEL_OUT_MONO;
break;
case 2:
channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
break;
case 3:
channelConfig = AudioFormat.CHANNEL_OUT_STEREO | AudioFormat.CHANNEL_OUT_FRONT_CENTER;
break;
case 4:
channelConfig = AudioFormat.CHANNEL_OUT_QUAD;
break;
case 5:
channelConfig = AudioFormat.CHANNEL_OUT_QUAD | AudioFormat.CHANNEL_OUT_FRONT_CENTER;
break;
case 6:
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1;
break;
case 7:
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1 | AudioFormat.CHANNEL_OUT_BACK_CENTER;
break;
case 8:
if (Build.VERSION.SDK_INT >= 23) {
channelConfig = AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;
} else {
Log.v(TAG, "Requested " + desiredChannels + " channels, getting 5.1 surround");
desiredChannels = 6;
channelConfig = AudioFormat.CHANNEL_OUT_5POINT1;
}
break;
default:
Log.v(TAG, "Requested " + desiredChannels + " channels, getting stereo");
desiredChannels = 2;
channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
break;
}
/*
Log.v(TAG, "Speaker configuration (and order of channels):");
if ((channelConfig & 0x00000004) != 0) {
Log.v(TAG, " CHANNEL_OUT_FRONT_LEFT");
}
if ((channelConfig & 0x00000008) != 0) {
Log.v(TAG, " CHANNEL_OUT_FRONT_RIGHT");
}
if ((channelConfig & 0x00000010) != 0) {
Log.v(TAG, " CHANNEL_OUT_FRONT_CENTER");
}
if ((channelConfig & 0x00000020) != 0) {
Log.v(TAG, " CHANNEL_OUT_LOW_FREQUENCY");
}
if ((channelConfig & 0x00000040) != 0) {
Log.v(TAG, " CHANNEL_OUT_BACK_LEFT");
}
if ((channelConfig & 0x00000080) != 0) {
Log.v(TAG, " CHANNEL_OUT_BACK_RIGHT");
}
if ((channelConfig & 0x00000100) != 0) {
Log.v(TAG, " CHANNEL_OUT_FRONT_LEFT_OF_CENTER");
}
if ((channelConfig & 0x00000200) != 0) {
Log.v(TAG, " CHANNEL_OUT_FRONT_RIGHT_OF_CENTER");
}
if ((channelConfig & 0x00000400) != 0) {
Log.v(TAG, " CHANNEL_OUT_BACK_CENTER");
}
if ((channelConfig & 0x00000800) != 0) {
Log.v(TAG, " CHANNEL_OUT_SIDE_LEFT");
}
if ((channelConfig & 0x00001000) != 0) {
Log.v(TAG, " CHANNEL_OUT_SIDE_RIGHT");
}
*/
}
frameSize = (sampleSize * desiredChannels);
// Let the user pick a larger buffer if they really want -- but ye
// gods they probably shouldn't, the minimums are horrifyingly high
// latency already
int minBufferSize;
if (isCapture) {
minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
} else {
minBufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat);
}
desiredFrames = Math.max(desiredFrames, (minBufferSize + frameSize - 1) / frameSize);
int[] results = new int[4];
if (isCapture) {
if (mAudioRecord == null) {
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, sampleRate,
channelConfig, audioFormat, desiredFrames * frameSize);
// see notes about AudioTrack state in audioOpen(), above. Probably also applies here.
if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG, "Failed during initialization of AudioRecord");
mAudioRecord.release();
mAudioRecord = null;
return null;
}
mAudioRecord.startRecording();
}
results[0] = mAudioRecord.getSampleRate();
results[1] = mAudioRecord.getAudioFormat();
results[2] = mAudioRecord.getChannelCount();
results[3] = desiredFrames;
} else {
if (mAudioTrack == null) {
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
// Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
// Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
// Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
/* Try again, with safer values */
Log.e(TAG, "Failed during initialization of Audio Track");
mAudioTrack.release();
mAudioTrack = null;
return null;
}
mAudioTrack.play();
}
results[0] = mAudioTrack.getSampleRate();
results[1] = mAudioTrack.getAudioFormat();
results[2] = mAudioTrack.getChannelCount();
results[3] = desiredFrames;
}
Log.v(TAG, "Opening " + (isCapture ? "capture" : "playback") + ", got " + results[3] + " frames of " + results[2] + " channel " + getAudioFormatString(results[1]) + " audio at " + results[0] + " Hz");
return results;
}
/**
* This method is called by SDL using JNI.
*/
public static int[] audioOpen(int sampleRate, int audioFormat, int desiredChannels, int desiredFrames) {
return open(false, sampleRate, audioFormat, desiredChannels, desiredFrames);
}
/**
* This method is called by SDL using JNI.
*/
public static void audioWriteFloatBuffer(float[] buffer) {
if (mAudioTrack == null) {
Log.e(TAG, "Attempted to make audio call with uninitialized audio!");
return;
}
for (int i = 0; i < buffer.length;) {
int result = mAudioTrack.write(buffer, i, buffer.length - i, AudioTrack.WRITE_BLOCKING);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w(TAG, "SDL audio: error return from write(float)");
return;
}
}
}
/**
* This method is called by SDL using JNI.
*/
public static void audioWriteShortBuffer(short[] buffer) {
if (mAudioTrack == null) {
Log.e(TAG, "Attempted to make audio call with uninitialized audio!");
return;
}
for (int i = 0; i < buffer.length;) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w(TAG, "SDL audio: error return from write(short)");
return;
}
}
}
/**
* This method is called by SDL using JNI.
*/
public static void audioWriteByteBuffer(byte[] buffer) {
if (mAudioTrack == null) {
Log.e(TAG, "Attempted to make audio call with uninitialized audio!");
return;
}
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w(TAG, "SDL audio: error return from write(byte)");
return;
}
}
}
/**
* This method is called by SDL using JNI.
*/
public static int[] captureOpen(int sampleRate, int audioFormat, int desiredChannels, int desiredFrames) {
return open(true, sampleRate, audioFormat, desiredChannels, desiredFrames);
}
/** This method is called by SDL using JNI. */
public static int captureReadFloatBuffer(float[] buffer, boolean blocking) {
return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
}
/** This method is called by SDL using JNI. */
public static int captureReadShortBuffer(short[] buffer, boolean blocking) {
if (Build.VERSION.SDK_INT < 23) {
return mAudioRecord.read(buffer, 0, buffer.length);
} else {
return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
}
}
/** This method is called by SDL using JNI. */
public static int captureReadByteBuffer(byte[] buffer, boolean blocking) {
if (Build.VERSION.SDK_INT < 23) {
return mAudioRecord.read(buffer, 0, buffer.length);
} else {
return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
}
}
/** This method is called by SDL using JNI. */
public static void audioClose() {
if (mAudioTrack != null) {
mAudioTrack.stop();
mAudioTrack.release();
mAudioTrack = null;
}
}
/** This method is called by SDL using JNI. */
public static void captureClose() {
if (mAudioRecord != null) {
mAudioRecord.stop();
mAudioRecord.release();
mAudioRecord = null;
}
}
/** This method is called by SDL using JNI. */
public static void audioSetThreadPriority(boolean iscapture, int device_id) {
try {
/* Set thread name */
if (iscapture) {
Thread.currentThread().setName("SDLAudioC" + device_id);
} else {
Thread.currentThread().setName("SDLAudioP" + device_id);
}
/* Set thread priority */
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
} catch (Exception e) {
Log.v(TAG, "modify thread properties failed " + e.toString());
}
}
public static native int nativeSetupJNI();
}

View File

@@ -0,0 +1,788 @@
package org.libsdl.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.content.Context;
import android.os.*;
import android.view.*;
import android.util.Log;
public class SDLControllerManager
{
public static native int nativeSetupJNI();
public static native int nativeAddJoystick(int device_id, String name, String desc,
int vendor_id, int product_id,
boolean is_accelerometer, int button_mask,
int naxes, int nhats, int nballs);
public static native int nativeRemoveJoystick(int device_id);
public static native int nativeAddHaptic(int device_id, String name);
public static native int nativeRemoveHaptic(int device_id);
public static native int onNativePadDown(int device_id, int keycode);
public static native int onNativePadUp(int device_id, int keycode);
public static native void onNativeJoy(int device_id, int axis,
float value);
public static native void onNativeHat(int device_id, int hat_id,
int x, int y);
protected static SDLJoystickHandler mJoystickHandler;
protected static SDLHapticHandler mHapticHandler;
private static final String TAG = "SDLControllerManager";
public static void initialize() {
if (mJoystickHandler == null) {
if (Build.VERSION.SDK_INT >= 19) {
mJoystickHandler = new SDLJoystickHandler_API19();
} else {
mJoystickHandler = new SDLJoystickHandler_API16();
}
}
if (mHapticHandler == null) {
if (Build.VERSION.SDK_INT >= 26) {
mHapticHandler = new SDLHapticHandler_API26();
} else {
mHapticHandler = new SDLHapticHandler();
}
}
}
// Joystick glue code, just a series of stubs that redirect to the SDLJoystickHandler instance
public static boolean handleJoystickMotionEvent(MotionEvent event) {
return mJoystickHandler.handleMotionEvent(event);
}
/**
* This method is called by SDL using JNI.
*/
public static void pollInputDevices() {
mJoystickHandler.pollInputDevices();
}
/**
* This method is called by SDL using JNI.
*/
public static void pollHapticDevices() {
mHapticHandler.pollHapticDevices();
}
/**
* This method is called by SDL using JNI.
*/
public static void hapticRun(int device_id, float intensity, int length) {
mHapticHandler.run(device_id, intensity, length);
}
/**
* This method is called by SDL using JNI.
*/
public static void hapticStop(int device_id)
{
mHapticHandler.stop(device_id);
}
// Check if a given device is considered a possible SDL joystick
public static boolean isDeviceSDLJoystick(int deviceId) {
InputDevice device = InputDevice.getDevice(deviceId);
// We cannot use InputDevice.isVirtual before API 16, so let's accept
// only nonnegative device ids (VIRTUAL_KEYBOARD equals -1)
if ((device == null) || (deviceId < 0)) {
return false;
}
int sources = device.getSources();
/* This is called for every button press, so let's not spam the logs */
/**
if ((sources & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
Log.v(TAG, "Input device " + device.getName() + " has class joystick.");
}
if ((sources & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) {
Log.v(TAG, "Input device " + device.getName() + " is a dpad.");
}
if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) {
Log.v(TAG, "Input device " + device.getName() + " is a gamepad.");
}
**/
return ((sources & InputDevice.SOURCE_CLASS_JOYSTICK) != 0 ||
((sources & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) ||
((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
);
}
}
class SDLJoystickHandler {
/**
* Handles given MotionEvent.
* @param event the event to be handled.
* @return if given event was processed.
*/
public boolean handleMotionEvent(MotionEvent event) {
return false;
}
/**
* Handles adding and removing of input devices.
*/
public void pollInputDevices() {
}
}
/* Actual joystick functionality available for API >= 12 devices */
class SDLJoystickHandler_API16 extends SDLJoystickHandler {
static class SDLJoystick {
public int device_id;
public String name;
public String desc;
public ArrayList<InputDevice.MotionRange> axes;
public ArrayList<InputDevice.MotionRange> hats;
}
static class RangeComparator implements Comparator<InputDevice.MotionRange> {
@Override
public int compare(InputDevice.MotionRange arg0, InputDevice.MotionRange arg1) {
// Some controllers, like the Moga Pro 2, return AXIS_GAS (22) for right trigger and AXIS_BRAKE (23) for left trigger - swap them so they're sorted in the right order for SDL
int arg0Axis = arg0.getAxis();
int arg1Axis = arg1.getAxis();
if (arg0Axis == MotionEvent.AXIS_GAS) {
arg0Axis = MotionEvent.AXIS_BRAKE;
} else if (arg0Axis == MotionEvent.AXIS_BRAKE) {
arg0Axis = MotionEvent.AXIS_GAS;
}
if (arg1Axis == MotionEvent.AXIS_GAS) {
arg1Axis = MotionEvent.AXIS_BRAKE;
} else if (arg1Axis == MotionEvent.AXIS_BRAKE) {
arg1Axis = MotionEvent.AXIS_GAS;
}
return arg0Axis - arg1Axis;
}
}
private ArrayList<SDLJoystick> mJoysticks;
public SDLJoystickHandler_API16() {
mJoysticks = new ArrayList<SDLJoystick>();
}
@Override
public void pollInputDevices() {
int[] deviceIds = InputDevice.getDeviceIds();
for(int i=0; i < deviceIds.length; ++i) {
SDLJoystick joystick = getJoystick(deviceIds[i]);
if (joystick == null) {
joystick = new SDLJoystick();
InputDevice joystickDevice = InputDevice.getDevice(deviceIds[i]);
if (SDLControllerManager.isDeviceSDLJoystick(deviceIds[i])) {
joystick.device_id = deviceIds[i];
joystick.name = joystickDevice.getName();
joystick.desc = getJoystickDescriptor(joystickDevice);
joystick.axes = new ArrayList<InputDevice.MotionRange>();
joystick.hats = new ArrayList<InputDevice.MotionRange>();
List<InputDevice.MotionRange> ranges = joystickDevice.getMotionRanges();
Collections.sort(ranges, new RangeComparator());
for (InputDevice.MotionRange range : ranges ) {
if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
if (range.getAxis() == MotionEvent.AXIS_HAT_X ||
range.getAxis() == MotionEvent.AXIS_HAT_Y) {
joystick.hats.add(range);
}
else {
joystick.axes.add(range);
}
}
}
mJoysticks.add(joystick);
SDLControllerManager.nativeAddJoystick(joystick.device_id, joystick.name, joystick.desc, getVendorId(joystickDevice), getProductId(joystickDevice), false, getButtonMask(joystickDevice), joystick.axes.size(), joystick.hats.size()/2, 0);
}
}
}
/* Check removed devices */
ArrayList<Integer> removedDevices = new ArrayList<Integer>();
for(int i=0; i < mJoysticks.size(); i++) {
int device_id = mJoysticks.get(i).device_id;
int j;
for (j=0; j < deviceIds.length; j++) {
if (device_id == deviceIds[j]) break;
}
if (j == deviceIds.length) {
removedDevices.add(Integer.valueOf(device_id));
}
}
for(int i=0; i < removedDevices.size(); i++) {
int device_id = removedDevices.get(i).intValue();
SDLControllerManager.nativeRemoveJoystick(device_id);
for (int j=0; j < mJoysticks.size(); j++) {
if (mJoysticks.get(j).device_id == device_id) {
mJoysticks.remove(j);
break;
}
}
}
}
protected SDLJoystick getJoystick(int device_id) {
for(int i=0; i < mJoysticks.size(); i++) {
if (mJoysticks.get(i).device_id == device_id) {
return mJoysticks.get(i);
}
}
return null;
}
@Override
public boolean handleMotionEvent(MotionEvent event) {
if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
int actionPointerIndex = event.getActionIndex();
int action = event.getActionMasked();
switch(action) {
case MotionEvent.ACTION_MOVE:
SDLJoystick joystick = getJoystick(event.getDeviceId());
if ( joystick != null ) {
for (int i = 0; i < joystick.axes.size(); i++) {
InputDevice.MotionRange range = joystick.axes.get(i);
/* Normalize the value to -1...1 */
float value = ( event.getAxisValue( range.getAxis(), actionPointerIndex) - range.getMin() ) / range.getRange() * 2.0f - 1.0f;
SDLControllerManager.onNativeJoy(joystick.device_id, i, value );
}
for (int i = 0; i < joystick.hats.size(); i+=2) {
int hatX = Math.round(event.getAxisValue( joystick.hats.get(i).getAxis(), actionPointerIndex ) );
int hatY = Math.round(event.getAxisValue( joystick.hats.get(i+1).getAxis(), actionPointerIndex ) );
SDLControllerManager.onNativeHat(joystick.device_id, i/2, hatX, hatY );
}
}
break;
default:
break;
}
}
return true;
}
public String getJoystickDescriptor(InputDevice joystickDevice) {
String desc = joystickDevice.getDescriptor();
if (desc != null && !desc.isEmpty()) {
return desc;
}
return joystickDevice.getName();
}
public int getProductId(InputDevice joystickDevice) {
return 0;
}
public int getVendorId(InputDevice joystickDevice) {
return 0;
}
public int getButtonMask(InputDevice joystickDevice) {
return -1;
}
}
class SDLJoystickHandler_API19 extends SDLJoystickHandler_API16 {
@Override
public int getProductId(InputDevice joystickDevice) {
return joystickDevice.getProductId();
}
@Override
public int getVendorId(InputDevice joystickDevice) {
return joystickDevice.getVendorId();
}
@Override
public int getButtonMask(InputDevice joystickDevice) {
int button_mask = 0;
int[] keys = new int[] {
KeyEvent.KEYCODE_BUTTON_A,
KeyEvent.KEYCODE_BUTTON_B,
KeyEvent.KEYCODE_BUTTON_X,
KeyEvent.KEYCODE_BUTTON_Y,
KeyEvent.KEYCODE_BACK,
KeyEvent.KEYCODE_BUTTON_MODE,
KeyEvent.KEYCODE_BUTTON_START,
KeyEvent.KEYCODE_BUTTON_THUMBL,
KeyEvent.KEYCODE_BUTTON_THUMBR,
KeyEvent.KEYCODE_BUTTON_L1,
KeyEvent.KEYCODE_BUTTON_R1,
KeyEvent.KEYCODE_DPAD_UP,
KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT,
KeyEvent.KEYCODE_BUTTON_SELECT,
KeyEvent.KEYCODE_DPAD_CENTER,
// These don't map into any SDL controller buttons directly
KeyEvent.KEYCODE_BUTTON_L2,
KeyEvent.KEYCODE_BUTTON_R2,
KeyEvent.KEYCODE_BUTTON_C,
KeyEvent.KEYCODE_BUTTON_Z,
KeyEvent.KEYCODE_BUTTON_1,
KeyEvent.KEYCODE_BUTTON_2,
KeyEvent.KEYCODE_BUTTON_3,
KeyEvent.KEYCODE_BUTTON_4,
KeyEvent.KEYCODE_BUTTON_5,
KeyEvent.KEYCODE_BUTTON_6,
KeyEvent.KEYCODE_BUTTON_7,
KeyEvent.KEYCODE_BUTTON_8,
KeyEvent.KEYCODE_BUTTON_9,
KeyEvent.KEYCODE_BUTTON_10,
KeyEvent.KEYCODE_BUTTON_11,
KeyEvent.KEYCODE_BUTTON_12,
KeyEvent.KEYCODE_BUTTON_13,
KeyEvent.KEYCODE_BUTTON_14,
KeyEvent.KEYCODE_BUTTON_15,
KeyEvent.KEYCODE_BUTTON_16,
};
int[] masks = new int[] {
(1 << 0), // A -> A
(1 << 1), // B -> B
(1 << 2), // X -> X
(1 << 3), // Y -> Y
(1 << 4), // BACK -> BACK
(1 << 5), // MODE -> GUIDE
(1 << 6), // START -> START
(1 << 7), // THUMBL -> LEFTSTICK
(1 << 8), // THUMBR -> RIGHTSTICK
(1 << 9), // L1 -> LEFTSHOULDER
(1 << 10), // R1 -> RIGHTSHOULDER
(1 << 11), // DPAD_UP -> DPAD_UP
(1 << 12), // DPAD_DOWN -> DPAD_DOWN
(1 << 13), // DPAD_LEFT -> DPAD_LEFT
(1 << 14), // DPAD_RIGHT -> DPAD_RIGHT
(1 << 4), // SELECT -> BACK
(1 << 0), // DPAD_CENTER -> A
(1 << 15), // L2 -> ??
(1 << 16), // R2 -> ??
(1 << 17), // C -> ??
(1 << 18), // Z -> ??
(1 << 20), // 1 -> ??
(1 << 21), // 2 -> ??
(1 << 22), // 3 -> ??
(1 << 23), // 4 -> ??
(1 << 24), // 5 -> ??
(1 << 25), // 6 -> ??
(1 << 26), // 7 -> ??
(1 << 27), // 8 -> ??
(1 << 28), // 9 -> ??
(1 << 29), // 10 -> ??
(1 << 30), // 11 -> ??
(1 << 31), // 12 -> ??
// We're out of room...
0xFFFFFFFF, // 13 -> ??
0xFFFFFFFF, // 14 -> ??
0xFFFFFFFF, // 15 -> ??
0xFFFFFFFF, // 16 -> ??
};
boolean[] has_keys = joystickDevice.hasKeys(keys);
for (int i = 0; i < keys.length; ++i) {
if (has_keys[i]) {
button_mask |= masks[i];
}
}
return button_mask;
}
}
class SDLHapticHandler_API26 extends SDLHapticHandler {
@Override
public void run(int device_id, float intensity, int length) {
SDLHaptic haptic = getHaptic(device_id);
if (haptic != null) {
Log.d("SDL", "Rtest: Vibe with intensity " + intensity + " for " + length);
if (intensity == 0.0f) {
stop(device_id);
return;
}
int vibeValue = Math.round(intensity * 255);
if (vibeValue > 255) {
vibeValue = 255;
}
if (vibeValue < 1) {
stop(device_id);
return;
}
try {
haptic.vib.vibrate(VibrationEffect.createOneShot(length, vibeValue));
}
catch (Exception e) {
// Fall back to the generic method, which uses DEFAULT_AMPLITUDE, but works even if
// something went horribly wrong with the Android 8.0 APIs.
haptic.vib.vibrate(length);
}
}
}
}
class SDLHapticHandler {
class SDLHaptic {
public int device_id;
public String name;
public Vibrator vib;
}
private ArrayList<SDLHaptic> mHaptics;
public SDLHapticHandler() {
mHaptics = new ArrayList<SDLHaptic>();
}
public void run(int device_id, float intensity, int length) {
SDLHaptic haptic = getHaptic(device_id);
if (haptic != null) {
haptic.vib.vibrate(length);
}
}
public void stop(int device_id) {
SDLHaptic haptic = getHaptic(device_id);
if (haptic != null) {
haptic.vib.cancel();
}
}
public void pollHapticDevices() {
final int deviceId_VIBRATOR_SERVICE = 999999;
boolean hasVibratorService = false;
int[] deviceIds = InputDevice.getDeviceIds();
// It helps processing the device ids in reverse order
// For example, in the case of the XBox 360 wireless dongle,
// so the first controller seen by SDL matches what the receiver
// considers to be the first controller
for (int i = deviceIds.length - 1; i > -1; i--) {
SDLHaptic haptic = getHaptic(deviceIds[i]);
if (haptic == null) {
InputDevice device = InputDevice.getDevice(deviceIds[i]);
Vibrator vib = device.getVibrator();
if (vib.hasVibrator()) {
haptic = new SDLHaptic();
haptic.device_id = deviceIds[i];
haptic.name = device.getName();
haptic.vib = vib;
mHaptics.add(haptic);
SDLControllerManager.nativeAddHaptic(haptic.device_id, haptic.name);
}
}
}
/* Check VIBRATOR_SERVICE */
Vibrator vib = (Vibrator) SDL.getContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vib != null) {
hasVibratorService = vib.hasVibrator();
if (hasVibratorService) {
SDLHaptic haptic = getHaptic(deviceId_VIBRATOR_SERVICE);
if (haptic == null) {
haptic = new SDLHaptic();
haptic.device_id = deviceId_VIBRATOR_SERVICE;
haptic.name = "VIBRATOR_SERVICE";
haptic.vib = vib;
mHaptics.add(haptic);
SDLControllerManager.nativeAddHaptic(haptic.device_id, haptic.name);
}
}
}
/* Check removed devices */
ArrayList<Integer> removedDevices = new ArrayList<Integer>();
for(int i=0; i < mHaptics.size(); i++) {
int device_id = mHaptics.get(i).device_id;
int j;
for (j=0; j < deviceIds.length; j++) {
if (device_id == deviceIds[j]) break;
}
if (device_id == deviceId_VIBRATOR_SERVICE && hasVibratorService) {
// don't remove the vibrator if it is still present
} else if (j == deviceIds.length) {
removedDevices.add(device_id);
}
}
for(int i=0; i < removedDevices.size(); i++) {
int device_id = removedDevices.get(i);
SDLControllerManager.nativeRemoveHaptic(device_id);
for (int j=0; j < mHaptics.size(); j++) {
if (mHaptics.get(j).device_id == device_id) {
mHaptics.remove(j);
break;
}
}
}
}
protected SDLHaptic getHaptic(int device_id) {
for(int i=0; i < mHaptics.size(); i++) {
if (mHaptics.get(i).device_id == device_id) {
return mHaptics.get(i);
}
}
return null;
}
}
class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener {
// Generic Motion (mouse hover, joystick...) events go here
@Override
public boolean onGenericMotion(View v, MotionEvent event) {
float x, y;
int action;
switch ( event.getSource() ) {
case InputDevice.SOURCE_JOYSTICK:
case InputDevice.SOURCE_GAMEPAD:
case InputDevice.SOURCE_DPAD:
return SDLControllerManager.handleJoystickMotionEvent(event);
case InputDevice.SOURCE_MOUSE:
action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_SCROLL:
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
SDLActivity.onNativeMouse(0, action, x, y, false);
return true;
case MotionEvent.ACTION_HOVER_MOVE:
x = event.getX(0);
y = event.getY(0);
SDLActivity.onNativeMouse(0, action, x, y, false);
return true;
default:
break;
}
break;
default:
break;
}
// Event was not managed
return false;
}
public boolean supportsRelativeMouse() {
return false;
}
public boolean inRelativeMode() {
return false;
}
public boolean setRelativeMouseEnabled(boolean enabled) {
return false;
}
public void reclaimRelativeMouseModeIfNeeded()
{
}
public float getEventX(MotionEvent event) {
return event.getX(0);
}
public float getEventY(MotionEvent event) {
return event.getY(0);
}
}
class SDLGenericMotionListener_API24 extends SDLGenericMotionListener_API12 {
// Generic Motion (mouse hover, joystick...) events go here
private boolean mRelativeModeEnabled;
@Override
public boolean onGenericMotion(View v, MotionEvent event) {
// Handle relative mouse mode
if (mRelativeModeEnabled) {
if (event.getSource() == InputDevice.SOURCE_MOUSE) {
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_HOVER_MOVE) {
float x = event.getAxisValue(MotionEvent.AXIS_RELATIVE_X);
float y = event.getAxisValue(MotionEvent.AXIS_RELATIVE_Y);
SDLActivity.onNativeMouse(0, action, x, y, true);
return true;
}
}
}
// Event was not managed, call SDLGenericMotionListener_API12 method
return super.onGenericMotion(v, event);
}
@Override
public boolean supportsRelativeMouse() {
return true;
}
@Override
public boolean inRelativeMode() {
return mRelativeModeEnabled;
}
@Override
public boolean setRelativeMouseEnabled(boolean enabled) {
mRelativeModeEnabled = enabled;
return true;
}
@Override
public float getEventX(MotionEvent event) {
if (mRelativeModeEnabled) {
return event.getAxisValue(MotionEvent.AXIS_RELATIVE_X);
}
else {
return event.getX(0);
}
}
@Override
public float getEventY(MotionEvent event) {
if (mRelativeModeEnabled) {
return event.getAxisValue(MotionEvent.AXIS_RELATIVE_Y);
}
else {
return event.getY(0);
}
}
}
class SDLGenericMotionListener_API26 extends SDLGenericMotionListener_API24 {
// Generic Motion (mouse hover, joystick...) events go here
private boolean mRelativeModeEnabled;
@Override
public boolean onGenericMotion(View v, MotionEvent event) {
float x, y;
int action;
switch ( event.getSource() ) {
case InputDevice.SOURCE_JOYSTICK:
case InputDevice.SOURCE_GAMEPAD:
case InputDevice.SOURCE_DPAD:
return SDLControllerManager.handleJoystickMotionEvent(event);
case InputDevice.SOURCE_MOUSE:
// DeX desktop mouse cursor is a separate non-standard input type.
case InputDevice.SOURCE_MOUSE | InputDevice.SOURCE_TOUCHSCREEN:
action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_SCROLL:
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
SDLActivity.onNativeMouse(0, action, x, y, false);
return true;
case MotionEvent.ACTION_HOVER_MOVE:
x = event.getX(0);
y = event.getY(0);
SDLActivity.onNativeMouse(0, action, x, y, false);
return true;
default:
break;
}
break;
case InputDevice.SOURCE_MOUSE_RELATIVE:
action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_SCROLL:
x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
SDLActivity.onNativeMouse(0, action, x, y, false);
return true;
case MotionEvent.ACTION_HOVER_MOVE:
x = event.getX(0);
y = event.getY(0);
SDLActivity.onNativeMouse(0, action, x, y, true);
return true;
default:
break;
}
break;
default:
break;
}
// Event was not managed
return false;
}
@Override
public boolean supportsRelativeMouse() {
return (!SDLActivity.isDeXMode() || (Build.VERSION.SDK_INT >= 27));
}
@Override
public boolean inRelativeMode() {
return mRelativeModeEnabled;
}
@Override
public boolean setRelativeMouseEnabled(boolean enabled) {
if (!SDLActivity.isDeXMode() || (Build.VERSION.SDK_INT >= 27)) {
if (enabled) {
SDLActivity.getContentView().requestPointerCapture();
}
else {
SDLActivity.getContentView().releasePointerCapture();
}
mRelativeModeEnabled = enabled;
return true;
}
else
{
return false;
}
}
@Override
public void reclaimRelativeMouseModeIfNeeded()
{
if (mRelativeModeEnabled && !SDLActivity.isDeXMode()) {
SDLActivity.getContentView().requestPointerCapture();
}
}
@Override
public float getEventX(MotionEvent event) {
// Relative mouse in capture mode will only have relative for X/Y
return event.getX(0);
}
@Override
public float getEventY(MotionEvent event) {
// Relative mouse in capture mode will only have relative for X/Y
return event.getY(0);
}
}

View File

@@ -1,782 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.util.Log;
import java.io.*;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.StatFs;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.Collections;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import java.lang.String;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Button;
import android.view.View;
import android.widget.LinearLayout;
import android.text.Editable;
import android.text.SpannedString;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.util.DisplayMetrics;
import android.net.Uri;
import java.util.concurrent.Semaphore;
import java.util.Arrays;
import android.graphics.Color;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import android.widget.Toast;
// TODO: too much code here, split into multiple files, possibly auto-generated menus?
class Settings
{
static String SettingsFileName = "libsdl-settings.cfg";
static boolean settingsLoaded = false;
static boolean settingsChanged = false;
static final int SETTINGS_FILE_VERSION = 5;
static void Save(final MainActivity p)
{
try {
ObjectOutputStream out = new ObjectOutputStream(p.openFileOutput( SettingsFileName, p.MODE_WORLD_READABLE ));
out.writeInt(SETTINGS_FILE_VERSION);
out.writeBoolean(Globals.DownloadToSdcard);
out.writeBoolean(Globals.PhoneHasArrowKeys);
out.writeBoolean(Globals.PhoneHasTrackball);
out.writeBoolean(Globals.UseAccelerometerAsArrowKeys);
out.writeBoolean(Globals.UseTouchscreenKeyboard);
out.writeInt(Globals.TouchscreenKeyboardSize);
out.writeInt(Globals.AccelerometerSensitivity);
out.writeInt(Globals.AccelerometerCenterPos);
out.writeInt(Globals.TrackballDampening);
out.writeInt(Globals.AudioBufferConfig);
out.writeInt(Globals.TouchscreenKeyboardTheme);
out.writeInt(Globals.RightClickMethod);
out.writeInt(Globals.ShowScreenUnderFinger);
out.writeInt(Globals.LeftClickMethod);
out.writeBoolean(Globals.MoveMouseWithJoystick);
out.writeBoolean(Globals.ClickMouseWithDpad);
out.writeInt(Globals.ClickScreenPressure);
out.writeInt(Globals.ClickScreenTouchspotSize);
out.writeBoolean(Globals.KeepAspectRatio);
out.writeInt(Globals.MoveMouseWithJoystickSpeed);
out.writeInt(Globals.MoveMouseWithJoystickAccel);
out.writeInt(SDL_Keys.JAVA_KEYCODE_LAST);
for( int i = 0; i < SDL_Keys.JAVA_KEYCODE_LAST; i++ )
{
out.writeInt(Globals.RemapHwKeycode[i]);
}
out.writeInt(Globals.RemapScreenKbKeycode.length);
for( int i = 0; i < Globals.RemapScreenKbKeycode.length; i++ )
{
out.writeInt(Globals.RemapScreenKbKeycode[i]);
}
out.writeInt(Globals.ScreenKbControlsShown.length);
for( int i = 0; i < Globals.ScreenKbControlsShown.length; i++ )
{
out.writeBoolean(Globals.ScreenKbControlsShown[i]);
}
out.writeInt(Globals.TouchscreenKeyboardTransparency);
out.writeInt(Globals.RemapMultitouchGestureKeycode.length);
for( int i = 0; i < Globals.RemapMultitouchGestureKeycode.length; i++ )
{
out.writeInt(Globals.RemapMultitouchGestureKeycode[i]);
out.writeBoolean(Globals.MultitouchGesturesUsed[i]);
}
out.writeInt(Globals.MultitouchGestureSensitivity);
for( int i = 0; i < Globals.TouchscreenCalibration.length; i++ )
out.writeInt(Globals.TouchscreenCalibration[i]);
out.writeInt(Globals.DataDir.length());
for( int i = 0; i < Globals.DataDir.length(); i++ )
out.writeChar(Globals.DataDir.charAt(i));
out.writeInt(Globals.CommandLine.length());
for( int i = 0; i < Globals.CommandLine.length(); i++ )
out.writeChar(Globals.CommandLine.charAt(i));
out.writeInt(Globals.ScreenKbControlsLayout.length);
for( int i = 0; i < Globals.ScreenKbControlsLayout.length; i++ )
for( int ii = 0; ii < 4; ii++ )
out.writeInt(Globals.ScreenKbControlsLayout[i][ii]);
out.writeInt(Globals.LeftClickKey);
out.writeInt(Globals.RightClickKey);
out.writeBoolean(Globals.VideoLinearFilter);
out.writeInt(Globals.LeftClickTimeout);
out.writeInt(Globals.RightClickTimeout);
out.writeBoolean(Globals.RelativeMouseMovement);
out.writeInt(Globals.RelativeMouseMovementSpeed);
out.writeInt(Globals.RelativeMouseMovementAccel);
out.writeBoolean(Globals.MultiThreadedVideo);
out.writeInt(Globals.OptionalDataDownload.length);
for(int i = 0; i < Globals.OptionalDataDownload.length; i++)
out.writeBoolean(Globals.OptionalDataDownload[i]);
out.writeBoolean(Globals.BrokenLibCMessageShown);
out.writeInt(Globals.TouchscreenKeyboardDrawSize);
out.writeInt(p.getApplicationVersion());
out.writeFloat(Globals.gyro_x1);
out.writeFloat(Globals.gyro_x2);
out.writeFloat(Globals.gyro_xc);
out.writeFloat(Globals.gyro_y1);
out.writeFloat(Globals.gyro_y2);
out.writeFloat(Globals.gyro_yc);
out.writeFloat(Globals.gyro_z1);
out.writeFloat(Globals.gyro_z2);
out.writeFloat(Globals.gyro_zc);
out.writeBoolean(Globals.OuyaEmulation);
out.close();
settingsLoaded = true;
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) {
} catch ( IOException e ) {};
}
static void Load( final MainActivity p )
{
if(settingsLoaded) // Prevent starting twice
{
return;
}
Log.i("SDL", "libSDL: Settings.Load(): enter");
/*nativeInitKeymap(); // TODO: Disabled in SDL2
if( p.isRunningOnOUYA() )
nativeSetKeymapKey(KeyEvent.KEYCODE_MENU, nativeGetKeymapKey(KeyEvent.KEYCODE_BACK)); // Ouya does not have Back key, only Menu, so remap Back keycode to Menu
for( int i = 0; i < SDL_Keys.JAVA_KEYCODE_LAST; i++ )
{
int sdlKey = nativeGetKeymapKey(i);
int idx = 0;
for(int ii = 0; ii < SDL_Keys.values.length; ii++)
if(SDL_Keys.values[ii] == sdlKey)
idx = ii;
Globals.RemapHwKeycode[i] = idx;
}
for( int i = 0; i < Globals.RemapScreenKbKeycode.length; i++ )
{
int sdlKey = nativeGetKeymapKeyScreenKb(i);
int idx = 0;
for(int ii = 0; ii < SDL_Keys.values.length; ii++)
if(SDL_Keys.values[ii] == sdlKey)
idx = ii;
Globals.RemapScreenKbKeycode[i] = idx;
}*/
Globals.ScreenKbControlsShown[0] = (Globals.AppNeedsArrowKeys || Globals.AppUsesJoystick);
Globals.ScreenKbControlsShown[1] = Globals.AppNeedsTextInput;
for( int i = 2; i < Globals.ScreenKbControlsShown.length; i++ )
Globals.ScreenKbControlsShown[i] = ( i - 2 < Globals.AppTouchscreenKeyboardKeysAmount );
if( Globals.AppUsesSecondJoystick )
Globals.ScreenKbControlsShown[8] = true;
/*for( int i = 0; i < Globals.RemapMultitouchGestureKeycode.length; i++ )
{
int sdlKey = nativeGetKeymapKeyMultitouchGesture(i);
int idx = 0;
for(int ii = 0; ii < SDL_Keys.values.length; ii++)
if(SDL_Keys.values[ii] == sdlKey)
idx = ii;
Globals.RemapMultitouchGestureKeycode[i] = idx;
}*/
for( int i = 0; i < Globals.MultitouchGesturesUsed.length; i++ )
Globals.MultitouchGesturesUsed[i] = true;
// Adjust coordinates of on-screen buttons from 800x480
int displayX = 800;
int displayY = 480;
try {
DisplayMetrics dm = new DisplayMetrics();
p.getWindowManager().getDefaultDisplay().getMetrics(dm);
displayX = dm.widthPixels;
displayY = dm.heightPixels;
} catch (Exception eeeee) {}
for( int i = 0; i < Globals.ScreenKbControlsLayout.length; i++ )
{
Globals.ScreenKbControlsLayout[i][0] *= (float)displayX / 800.0f;
Globals.ScreenKbControlsLayout[i][2] *= (float)displayX / 800.0f;
Globals.ScreenKbControlsLayout[i][1] *= (float)displayY / 480.0f;
Globals.ScreenKbControlsLayout[i][3] *= (float)displayY / 480.0f;
// Make them square
int wh = Math.min( Globals.ScreenKbControlsLayout[i][2] - Globals.ScreenKbControlsLayout[i][0], Globals.ScreenKbControlsLayout[i][3] - Globals.ScreenKbControlsLayout[i][1] );
Globals.ScreenKbControlsLayout[i][2] = Globals.ScreenKbControlsLayout[i][0] + wh;
Globals.ScreenKbControlsLayout[i][3] = Globals.ScreenKbControlsLayout[i][1] + wh;
}
Log.i("SDL", "android.os.Build.MODEL: " + android.os.Build.MODEL);
if( (android.os.Build.MODEL.equals("GT-N7000") || android.os.Build.MODEL.equals("SGH-I717"))
&& android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.GINGERBREAD_MR1 )
{
// Samsung Galaxy Note generates a keypress when you hover a stylus over the screen, and that messes up OpenTTD dialogs
// ICS update sends events in a proper way
Globals.RemapHwKeycode[112] = SDL_1_2_Keycodes.SDLK_UNKNOWN;
}
try {
ObjectInputStream settingsFile = new ObjectInputStream(new FileInputStream( p.getFilesDir().getAbsolutePath() + "/" + SettingsFileName ));
if( settingsFile.readInt() != SETTINGS_FILE_VERSION )
throw new IOException();
Globals.DownloadToSdcard = settingsFile.readBoolean();
Globals.PhoneHasArrowKeys = settingsFile.readBoolean();
Globals.PhoneHasTrackball = settingsFile.readBoolean();
Globals.UseAccelerometerAsArrowKeys = settingsFile.readBoolean();
Globals.UseTouchscreenKeyboard = settingsFile.readBoolean();
Globals.TouchscreenKeyboardSize = settingsFile.readInt();
Globals.AccelerometerSensitivity = settingsFile.readInt();
Globals.AccelerometerCenterPos = settingsFile.readInt();
Globals.TrackballDampening = settingsFile.readInt();
Globals.AudioBufferConfig = settingsFile.readInt();
Globals.TouchscreenKeyboardTheme = settingsFile.readInt();
Globals.RightClickMethod = settingsFile.readInt();
Globals.ShowScreenUnderFinger = settingsFile.readInt();
Globals.LeftClickMethod = settingsFile.readInt();
Globals.MoveMouseWithJoystick = settingsFile.readBoolean();
Globals.ClickMouseWithDpad = settingsFile.readBoolean();
Globals.ClickScreenPressure = settingsFile.readInt();
Globals.ClickScreenTouchspotSize = settingsFile.readInt();
Globals.KeepAspectRatio = settingsFile.readBoolean();
Globals.MoveMouseWithJoystickSpeed = settingsFile.readInt();
Globals.MoveMouseWithJoystickAccel = settingsFile.readInt();
int readKeys = settingsFile.readInt();
for( int i = 0; i < readKeys; i++ )
{
Globals.RemapHwKeycode[i] = settingsFile.readInt();
}
if( settingsFile.readInt() != Globals.RemapScreenKbKeycode.length )
throw new IOException();
for( int i = 0; i < Globals.RemapScreenKbKeycode.length; i++ )
{
Globals.RemapScreenKbKeycode[i] = settingsFile.readInt();
}
if( settingsFile.readInt() != Globals.ScreenKbControlsShown.length )
throw new IOException();
for( int i = 0; i < Globals.ScreenKbControlsShown.length; i++ )
{
Globals.ScreenKbControlsShown[i] = settingsFile.readBoolean();
}
Globals.TouchscreenKeyboardTransparency = settingsFile.readInt();
if( settingsFile.readInt() != Globals.RemapMultitouchGestureKeycode.length )
throw new IOException();
for( int i = 0; i < Globals.RemapMultitouchGestureKeycode.length; i++ )
{
Globals.RemapMultitouchGestureKeycode[i] = settingsFile.readInt();
Globals.MultitouchGesturesUsed[i] = settingsFile.readBoolean();
}
Globals.MultitouchGestureSensitivity = settingsFile.readInt();
for( int i = 0; i < Globals.TouchscreenCalibration.length; i++ )
Globals.TouchscreenCalibration[i] = settingsFile.readInt();
StringBuilder b = new StringBuilder();
int len = settingsFile.readInt();
for( int i = 0; i < len; i++ )
b.append( settingsFile.readChar() );
Globals.DataDir = b.toString();
b = new StringBuilder();
len = settingsFile.readInt();
for( int i = 0; i < len; i++ )
b.append( settingsFile.readChar() );
Globals.CommandLine = b.toString();
if( settingsFile.readInt() != Globals.ScreenKbControlsLayout.length )
throw new IOException();
for( int i = 0; i < Globals.ScreenKbControlsLayout.length; i++ )
for( int ii = 0; ii < 4; ii++ )
Globals.ScreenKbControlsLayout[i][ii] = settingsFile.readInt();
Globals.LeftClickKey = settingsFile.readInt();
Globals.RightClickKey = settingsFile.readInt();
Globals.VideoLinearFilter = settingsFile.readBoolean();
Globals.LeftClickTimeout = settingsFile.readInt();
Globals.RightClickTimeout = settingsFile.readInt();
Globals.RelativeMouseMovement = settingsFile.readBoolean();
Globals.RelativeMouseMovementSpeed = settingsFile.readInt();
Globals.RelativeMouseMovementAccel = settingsFile.readInt();
Globals.MultiThreadedVideo = settingsFile.readBoolean();
Globals.OptionalDataDownload = new boolean[settingsFile.readInt()];
for(int i = 0; i < Globals.OptionalDataDownload.length; i++)
Globals.OptionalDataDownload[i] = settingsFile.readBoolean();
Globals.BrokenLibCMessageShown = settingsFile.readBoolean();
Globals.TouchscreenKeyboardDrawSize = settingsFile.readInt();
int cfgVersion = settingsFile.readInt();
Globals.gyro_x1 = settingsFile.readFloat();
Globals.gyro_x2 = settingsFile.readFloat();
Globals.gyro_xc = settingsFile.readFloat();
Globals.gyro_y1 = settingsFile.readFloat();
Globals.gyro_y2 = settingsFile.readFloat();
Globals.gyro_yc = settingsFile.readFloat();
Globals.gyro_z1 = settingsFile.readFloat();
Globals.gyro_z2 = settingsFile.readFloat();
Globals.gyro_zc = settingsFile.readFloat();
Globals.OuyaEmulation = settingsFile.readBoolean();
settingsLoaded = true;
Log.i("SDL", "libSDL: Settings.Load(): loaded settings successfully");
settingsFile.close();
Log.i("SDL", "libSDL: old cfg version " + cfgVersion + ", our version " + p.getApplicationVersion());
if( cfgVersion != p.getApplicationVersion() )
{
DeleteFilesOnUpgrade(p);
if( Globals.ResetSdlConfigForThisVersion )
{
Log.i("SDL", "libSDL: old cfg version " + cfgVersion + ", our version " + p.getApplicationVersion() + " and we need to clean up config file");
// Delete settings file, and restart the application
DeleteSdlConfigOnUpgradeAndRestart(p);
}
Save(p);
}
return;
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) {
} catch ( IOException e ) {
DeleteFilesOnUpgrade(p);
if( Globals.ResetSdlConfigForThisVersion )
{
Log.i("SDL", "libSDL: old cfg version unknown or too old, our version " + p.getApplicationVersion() + " and we need to clean up config file");
DeleteSdlConfigOnUpgradeAndRestart(p);
}
};
if( Globals.DataDir.length() == 0 )
{
if( !Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) )
{
Log.i("SDL", "libSDL: SD card or external storage is not mounted (state " + Environment.getExternalStorageState() + "), switching to the internal storage.");
Globals.DownloadToSdcard = false;
}
Globals.DataDir = Globals.DownloadToSdcard ?
SdcardAppPath.getPath(p) :
p.getFilesDir().getAbsolutePath();
if( Globals.DownloadToSdcard )
{
// Check if data already installed into deprecated location at /sdcard/app-data/<package-name>
String[] fileList = new File(SdcardAppPath.deprecatedPath(p)).list();
if( fileList != null )
for( String s: fileList )
if( s.toUpperCase().startsWith(DataDownloader.DOWNLOAD_FLAG_FILENAME.toUpperCase()) )
Globals.DataDir = SdcardAppPath.deprecatedPath(p);
}
}
Log.i("SDL", "libSDL: Settings.Load(): loading settings failed, running config dialog");
p.setUpStatusLabel();
if( checkRamSize(p) )
SettingsMenu.showConfig(p, true);
}
// ===============================================================================================
public static boolean deleteRecursively(File dir)
{
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++)
{
boolean success = deleteRecursively(new File(dir, children[i]));
if (!success)
return false;
}
}
return dir.delete();
}
public static boolean deleteRecursivelyAndLog(File dir)
{
Log.v("SDL", "Deleting old file: " + dir.getAbsolutePath() + " exists " + dir.exists());
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++)
{
boolean success = deleteRecursively(new File(dir, children[i]));
if (!success)
return false;
}
}
return dir.delete();
}
public static void DeleteFilesOnUpgrade(final MainActivity p)
{
String [] files = Globals.DeleteFilesOnUpgrade.split(" ");
for(String path: files)
{
if( path.equals("") )
continue;
deleteRecursivelyAndLog(new File( SdcardAppPath.getPath(p) + "/" + path ));
deleteRecursivelyAndLog(new File( p.getFilesDir().getAbsolutePath() + "/" + path ));
deleteRecursivelyAndLog(new File( SdcardAppPath.deprecatedPath(p) + "/" + path ));
}
}
public static void DeleteSdlConfigOnUpgradeAndRestart(final MainActivity p)
{
try {
ObjectOutputStream out = new ObjectOutputStream(p.openFileOutput( SettingsFileName, p.MODE_WORLD_READABLE ));
out.writeInt(-1);
out.close();
} catch( FileNotFoundException e ) {
} catch ( IOException e ) { }
new File( p.getFilesDir() + "/" + SettingsFileName ).delete();
PendingIntent intent = PendingIntent.getActivity(p, 0, new Intent(p.getIntent()), p.getIntent().getFlags());
AlarmManager mgr = (AlarmManager) p.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, intent);
System.exit(0);
}
// ===============================================================================================
static void Apply(MainActivity p)
{
/*nativeSetVideoDepth(Globals.VideoDepthBpp, Globals.NeedGles2 ? 1 : 0);
if(Globals.VideoLinearFilter)
nativeSetVideoLinearFilter();
if( Globals.CompatibilityHacksVideo )
{
Globals.MultiThreadedVideo = true;
Globals.SwVideoMode = true;
nativeSetCompatibilityHacks();
}
if( Globals.SwVideoMode )
nativeSetVideoForceSoftwareMode();
if( Globals.SwVideoMode && Globals.MultiThreadedVideo )
nativeSetVideoMultithreaded();
if( Globals.PhoneHasTrackball )
nativeSetTrackballUsed();
if( Globals.AppUsesMouse )
nativeSetMouseUsed( Globals.RightClickMethod,
Globals.ShowScreenUnderFinger,
Globals.LeftClickMethod,
Globals.MoveMouseWithJoystick ? 1 : 0,
Globals.ClickMouseWithDpad ? 1 : 0,
Globals.ClickScreenPressure,
Globals.ClickScreenTouchspotSize,
Globals.MoveMouseWithJoystickSpeed,
Globals.MoveMouseWithJoystickAccel,
Globals.LeftClickKey,
Globals.RightClickKey,
Globals.LeftClickTimeout,
Globals.RightClickTimeout,
Globals.RelativeMouseMovement ? 1 : 0,
Globals.RelativeMouseMovementSpeed,
Globals.RelativeMouseMovementAccel,
Globals.ShowMouseCursor ? 1 : 0 );
nativeSetJoystickUsed(Globals.AppUsesJoystick ? 1 : 0, Globals.AppUsesSecondJoystick ? 1 : 0);
if( Globals.AppUsesAccelerometer )
nativeSetAccelerometerUsed();
if( Globals.AppUsesMultitouch )
nativeSetMultitouchUsed();
nativeSetAccelerometerSettings(Globals.AccelerometerSensitivity, Globals.AccelerometerCenterPos);
nativeSetTrackballDampening(Globals.TrackballDampening);
if( Globals.UseTouchscreenKeyboard )
{
boolean screenKbReallyUsed = false;
for( int i = 0; i < Globals.ScreenKbControlsShown.length; i++ )
if( Globals.ScreenKbControlsShown[i] )
screenKbReallyUsed = true;
if( p.isRunningOnOUYA() )
screenKbReallyUsed = false;
if( screenKbReallyUsed )
{
nativeSetTouchscreenKeyboardUsed();
nativeSetupScreenKeyboard( Globals.TouchscreenKeyboardSize,
Globals.TouchscreenKeyboardDrawSize,
Globals.TouchscreenKeyboardTheme,
Globals.AppTouchscreenKeyboardKeysAmountAutoFire,
Globals.TouchscreenKeyboardTransparency );
SetupTouchscreenKeyboardGraphics(p);
for( int i = 0; i < Globals.RemapScreenKbKeycode.length; i++ )
nativeSetKeymapKeyScreenKb(i, SDL_Keys.values[Globals.RemapScreenKbKeycode[i]]);
if( Globals.TouchscreenKeyboardSize == Globals.TOUCHSCREEN_KEYBOARD_CUSTOM )
{
for( int i = 0; i < Globals.ScreenKbControlsLayout.length; i++ )
if( Globals.ScreenKbControlsLayout[i][0] < Globals.ScreenKbControlsLayout[i][2] )
nativeSetScreenKbKeyLayout( i, Globals.ScreenKbControlsLayout[i][0], Globals.ScreenKbControlsLayout[i][1],
Globals.ScreenKbControlsLayout[i][2], Globals.ScreenKbControlsLayout[i][3]);
}
for( int i = 0; i < Globals.ScreenKbControlsShown.length; i++ )
nativeSetScreenKbKeyUsed(i, Globals.ScreenKbControlsShown[i] ? 1 : 0);
}
else
Globals.UseTouchscreenKeyboard = false;
}
for( int i = 0; i < SDL_Keys.JAVA_KEYCODE_LAST; i++ )
nativeSetKeymapKey(i, SDL_Keys.values[Globals.RemapHwKeycode[i]]);
for( int i = 0; i < Globals.RemapMultitouchGestureKeycode.length; i++ )
nativeSetKeymapKeyMultitouchGesture(i, Globals.MultitouchGesturesUsed[i] ? SDL_Keys.values[Globals.RemapMultitouchGestureKeycode[i]] : 0);
nativeSetMultitouchGestureSensitivity(Globals.MultitouchGestureSensitivity);
if( Globals.TouchscreenCalibration[2] > Globals.TouchscreenCalibration[0] )
nativeSetTouchscreenCalibration(Globals.TouchscreenCalibration[0], Globals.TouchscreenCalibration[1],
Globals.TouchscreenCalibration[2], Globals.TouchscreenCalibration[3]);*/
String lang = new String(Locale.getDefault().getLanguage());
if( Locale.getDefault().getCountry().length() > 0 )
lang = lang + "_" + Locale.getDefault().getCountry();
Log.i("SDL", "libSDL: setting envvar LANGUAGE to '" + lang + "'");
nativeSetEnv( "LANG", lang );
nativeSetEnv( "LANGUAGE", lang );
// TODO: get current user name and set envvar USER, the API is not availalbe on Android 1.6 so I don't bother with this
nativeSetEnv( "APPDIR", p.getFilesDir().getAbsolutePath() );
nativeSetEnv( "SECURE_STORAGE_DIR", p.getFilesDir().getAbsolutePath() );
nativeSetEnv( "DATADIR", Globals.DataDir );
nativeSetEnv( "UNSECURE_STORAGE_DIR", Globals.DataDir );
nativeSetEnv( "HOME", Globals.DataDir );
nativeSetEnv( "ANDROID_VERSION", String.valueOf(android.os.Build.VERSION.SDK_INT) );
Log.d("SDL", "libSDL: Is running on OUYA: " + p.isRunningOnOUYA());
if( p.isRunningOnOUYA() )
nativeSetEnv( "OUYA", "1" );
try {
DisplayMetrics dm = new DisplayMetrics();
p.getWindowManager().getDefaultDisplay().getMetrics(dm);
float xx = dm.widthPixels/dm.xdpi;
float yy = dm.heightPixels/dm.ydpi;
float x = Math.max(xx, yy);
float y = Math.min(xx, yy);
float displayInches = (float)Math.sqrt( x*x + y*y );
nativeSetEnv( "DISPLAY_SIZE", String.valueOf(displayInches) );
nativeSetEnv( "DISPLAY_SIZE_MM", String.valueOf((int)(displayInches*25.4f)) );
nativeSetEnv( "DISPLAY_WIDTH", String.valueOf(x) );
nativeSetEnv( "DISPLAY_HEIGHT", String.valueOf(y) );
nativeSetEnv( "DISPLAY_WIDTH_MM", String.valueOf((int)(x*25.4f)) );
nativeSetEnv( "DISPLAY_HEIGHT_MM", String.valueOf((int)(y*25.4f)) );
nativeSetEnv( "DISPLAY_RESOLUTION_WIDTH", String.valueOf(Math.max(dm.widthPixels, dm.heightPixels)) );
nativeSetEnv( "DISPLAY_RESOLUTION_HEIGHT", String.valueOf(Math.min(dm.widthPixels, dm.heightPixels)) );
} catch (Exception eeeee) {}
}
static byte [] loadRaw(Activity p, int res)
{
byte [] buf = new byte[65536 * 2];
byte [] a = new byte[65536 * 4 * 10]; // We need 2363516 bytes for the Sun theme
int written = 0;
try{
InputStream is = new GZIPInputStream(p.getResources().openRawResource(res));
int readed = 0;
while( (readed = is.read(buf)) >= 0 )
{
if( written + readed > a.length )
{
byte [] b = new byte [written + readed];
System.arraycopy(a, 0, b, 0, written);
a = b;
}
System.arraycopy(buf, 0, a, written, readed);
written += readed;
}
} catch(Exception e) {};
byte [] b = new byte [written];
System.arraycopy(a, 0, b, 0, written);
return b;
}
static void SetupTouchscreenKeyboardGraphics(Activity p)
{
if( Globals.UseTouchscreenKeyboard )
{
if(Globals.TouchscreenKeyboardTheme < 0)
Globals.TouchscreenKeyboardTheme = 0;
if(Globals.TouchscreenKeyboardTheme > 3)
Globals.TouchscreenKeyboardTheme = 3;
if( Globals.TouchscreenKeyboardTheme == 0 )
{
nativeSetupScreenKeyboardButtons(loadRaw(p, R.raw.ultimatedroid));
}
if( Globals.TouchscreenKeyboardTheme == 1 )
{
nativeSetupScreenKeyboardButtons(loadRaw(p, R.raw.simpletheme));
}
if( Globals.TouchscreenKeyboardTheme == 2 )
{
nativeSetupScreenKeyboardButtons(loadRaw(p, R.raw.sun));
}
if( Globals.TouchscreenKeyboardTheme == 3 )
{
nativeSetupScreenKeyboardButtons(loadRaw(p, R.raw.keen));
}
}
}
abstract static class SdcardAppPath
{
private static SdcardAppPath get()
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO)
return Froyo.Holder.sInstance;
else
return Dummy.Holder.sInstance;
}
public abstract String path(final Context p);
public static String deprecatedPath(final Context p)
{
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/app-data/" + p.getPackageName();
}
public static String getPath(final Context p)
{
try {
return get().path(p);
} catch(Exception e) { }
return Dummy.Holder.sInstance.path(p);
}
private static class Froyo extends SdcardAppPath
{
private static class Holder
{
private static final Froyo sInstance = new Froyo();
}
public String path(final Context p)
{
return p.getExternalFilesDir(null).getAbsolutePath();
}
}
private static class Dummy extends SdcardAppPath
{
private static class Holder
{
private static final Dummy sInstance = new Dummy();
}
public String path(final Context p)
{
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + p.getPackageName() + "/files";
}
}
}
static boolean checkRamSize(final MainActivity p)
{
try {
BufferedReader reader = new BufferedReader(new FileReader("/proc/meminfo"));
String line = null;
while( ( line = reader.readLine() ) != null )
{
if( line.indexOf("MemTotal:") == 0 )
{
String[] fields = line.split("[ \t]+");
Long size = Long.parseLong(fields[1]);
Log.i("SDL", "Device RAM size: " + size / 1024 + " Mb, required minimum RAM: " + Globals.AppMinimumRAM + " Mb" );
if( size / 1024 < Globals.AppMinimumRAM )
{
settingsChanged = true;
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.not_enough_ram);
builder.setMessage(p.getResources().getString( R.string.not_enough_ram_size, Globals.AppMinimumRAM, (int)(size / 1024)) );
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
p.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + p.getPackageName())));
System.exit(0);
}
});
builder.setNegativeButton(p.getResources().getString(R.string.ignore), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
SettingsMenu.showConfig(p, true);
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
p.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + p.getPackageName())));
System.exit(0);
}
});
final AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
return false;
}
}
}
} catch ( Exception e ) {
Log.i("SDL", "Error: cannot parse /proc/meminfo: " + e.toString());
}
return true;
}
private static native void nativeSetTrackballUsed();
private static native void nativeSetTrackballDampening(int value);
private static native void nativeSetAccelerometerSettings(int sensitivity, int centerPos);
private static native void nativeSetMouseUsed(int RightClickMethod, int ShowScreenUnderFinger, int LeftClickMethod,
int MoveMouseWithJoystick, int ClickMouseWithDpad, int MaxForce, int MaxRadius,
int MoveMouseWithJoystickSpeed, int MoveMouseWithJoystickAccel,
int leftClickKeycode, int rightClickKeycode,
int leftClickTimeout, int rightClickTimeout,
int relativeMovement, int relativeMovementSpeed,
int relativeMovementAccel, int showMouseCursor);
private static native void nativeSetJoystickUsed(int firstJoystickUsed, int secondJoystickUsed);
private static native void nativeSetAccelerometerUsed();
private static native void nativeSetMultitouchUsed();
private static native void nativeSetTouchscreenKeyboardUsed();
private static native void nativeSetVideoLinearFilter();
private static native void nativeSetVideoDepth(int bpp, int gles2);
private static native void nativeSetCompatibilityHacks();
private static native void nativeSetVideoMultithreaded();
private static native void nativeSetVideoForceSoftwareMode();
private static native void nativeSetupScreenKeyboard(int size, int drawsize, int theme, int nbuttonsAutoFire, int transparency);
private static native void nativeSetupScreenKeyboardButtons(byte[] img);
private static native void nativeInitKeymap();
private static native int nativeGetKeymapKey(int key);
private static native void nativeSetKeymapKey(int javakey, int key);
private static native int nativeGetKeymapKeyScreenKb(int keynum);
private static native void nativeSetKeymapKeyScreenKb(int keynum, int key);
private static native void nativeSetScreenKbKeyUsed(int keynum, int used);
private static native void nativeSetScreenKbKeyLayout(int keynum, int x1, int y1, int x2, int y2);
private static native int nativeGetKeymapKeyMultitouchGesture(int keynum);
private static native void nativeSetKeymapKeyMultitouchGesture(int keynum, int key);
private static native void nativeSetMultitouchGestureSensitivity(int sensitivity);
private static native void nativeSetTouchscreenCalibration(int x1, int y1, int x2, int y2);
public static native void nativeSetEnv(final String name, final String value);
public static native int nativeChmod(final String name, int mode);
public static native void nativeChdir(final String dir);
}

View File

@@ -1,257 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.util.Log;
import java.io.*;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.StatFs;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.Collections;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import java.lang.String;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Button;
import android.view.View;
import android.widget.LinearLayout;
import android.text.Editable;
import android.text.SpannedString;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.util.DisplayMetrics;
import android.net.Uri;
import java.util.concurrent.Semaphore;
import java.util.Arrays;
import android.graphics.Color;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import android.widget.Toast;
class SettingsMenu
{
public static abstract class Menu
{
// Should be overridden by children
abstract void run(final MainActivity p);
abstract String title(final MainActivity p);
boolean enabled()
{
return true;
}
// Should not be overridden
boolean enabledOrHidden()
{
for( Menu m: Globals.HiddenMenuOptions )
{
if( m.getClass().getName().equals( this.getClass().getName() ) )
return false;
}
return enabled();
}
void showMenuOptionsList(final MainActivity p, final Menu[] list)
{
menuStack.add(this);
ArrayList<CharSequence> items = new ArrayList<CharSequence> ();
for( Menu m: list )
{
if(m.enabledOrHidden())
items.add(m.title(p));
}
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(title(p));
builder.setItems(items.toArray(new CharSequence[0]), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
int selected = 0;
for( Menu m: list )
{
if(m.enabledOrHidden())
{
if( selected == item )
{
m.run(p);
return;
}
selected ++;
}
}
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBackOuterMenu(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static ArrayList<Menu> menuStack = new ArrayList<Menu> ();
public static void showConfig(final MainActivity p, final boolean firstStart)
{
Settings.settingsChanged = true;
if( Globals.OptionalDataDownload == null )
{
String downloads[] = Globals.DataDownloadUrl;
Globals.OptionalDataDownload = new boolean[downloads.length];
boolean oldFormat = true;
for( int i = 0; i < downloads.length; i++ )
{
if( downloads[i].indexOf("!") == 0 )
{
Globals.OptionalDataDownload[i] = true;
oldFormat = false;
}
}
if( oldFormat )
Globals.OptionalDataDownload[0] = true;
}
if(!firstStart)
new MainMenu().run(p);
else
{
if( Globals.StartupMenuButtonTimeout > 0 ) // If we did not disable startup menu altogether
{
for( Menu m: Globals.FirstStartMenuOptions )
{
boolean hidden = false;
for( Menu m1: Globals.HiddenMenuOptions )
{
if( m1.getClass().getName().equals( m.getClass().getName() ) )
hidden = true;
}
if( ! hidden )
menuStack.add(0, m);
}
}
goBack(p);
}
}
static void goBack(final MainActivity p)
{
if(menuStack.isEmpty())
{
Settings.Save(p);
p.startDownloader();
}
else
{
Menu c = menuStack.remove(menuStack.size() - 1);
c.run(p);
}
}
static void goBackOuterMenu(final MainActivity p)
{
if(!menuStack.isEmpty())
menuStack.remove(menuStack.size() - 1);
goBack(p);
}
static class OkButton extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.ok);
}
void run (final MainActivity p)
{
goBackOuterMenu(p);
}
}
static class DummyMenu extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.ok);
}
void run (final MainActivity p)
{
goBack(p);
}
}
static class MainMenu extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.device_config);
}
void run (final MainActivity p)
{
Menu options[] =
{
new SettingsMenuMisc.DownloadConfig(),
new SettingsMenuMisc.OptionalDownloadConfig(false),
new SettingsMenuKeyboard.KeyboardConfigMainMenu(),
new SettingsMenuMouse.MouseConfigMainMenu(),
new SettingsMenuMisc.GyroscopeCalibration(),
new SettingsMenuMisc.AudioConfig(),
new SettingsMenuKeyboard.RemapHwKeysConfig(),
new SettingsMenuKeyboard.ScreenGesturesConfig(),
new SettingsMenuMisc.VideoSettingsConfig(),
new SettingsMenuMisc.ResetToDefaultsConfig(),
new OkButton(),
};
showMenuOptionsList(p, options);
}
}
}

View File

@@ -1,843 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.util.Log;
import java.io.*;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.StatFs;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.Collections;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import java.lang.String;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Button;
import android.view.View;
import android.widget.LinearLayout;
import android.text.Editable;
import android.text.SpannedString;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.util.DisplayMetrics;
import android.net.Uri;
import java.util.concurrent.Semaphore;
import java.util.Arrays;
import android.graphics.Color;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import android.widget.Toast;
class SettingsMenuKeyboard extends SettingsMenu
{
static class KeyboardConfigMainMenu extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.controls_screenkb);
}
boolean enabled()
{
return Globals.UseTouchscreenKeyboard;
}
void run (final MainActivity p)
{
Menu options[] =
{
new ScreenKeyboardThemeConfig(),
new ScreenKeyboardSizeConfig(),
new ScreenKeyboardDrawSizeConfig(),
new ScreenKeyboardTransparencyConfig(),
new RemapScreenKbConfig(),
new CustomizeScreenKbLayout(),
new OkButton(),
};
showMenuOptionsList(p, options);
}
}
static class ScreenKeyboardSizeConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.controls_screenkb_size);
}
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.controls_screenkb_large),
p.getResources().getString(R.string.controls_screenkb_medium),
p.getResources().getString(R.string.controls_screenkb_small),
p.getResources().getString(R.string.controls_screenkb_tiny),
p.getResources().getString(R.string.controls_screenkb_custom) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.controls_screenkb_size));
builder.setSingleChoiceItems(items, Globals.TouchscreenKeyboardSize, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.TouchscreenKeyboardSize = item;
dialog.dismiss();
if( Globals.TouchscreenKeyboardSize == Globals.TOUCHSCREEN_KEYBOARD_CUSTOM )
new CustomizeScreenKbLayout().run(p);
else
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class ScreenKeyboardDrawSizeConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.controls_screenkb_drawsize);
}
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.controls_screenkb_large),
p.getResources().getString(R.string.controls_screenkb_medium),
p.getResources().getString(R.string.controls_screenkb_small),
p.getResources().getString(R.string.controls_screenkb_tiny) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.controls_screenkb_drawsize));
builder.setSingleChoiceItems(items, Globals.TouchscreenKeyboardDrawSize, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.TouchscreenKeyboardDrawSize = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class ScreenKeyboardThemeConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.controls_screenkb_theme);
}
void run (final MainActivity p)
{
final CharSequence[] items = {
p.getResources().getString(R.string.controls_screenkb_by, "Ultimate Droid", "Sean Stieber"),
p.getResources().getString(R.string.controls_screenkb_by, "Simple Theme", "Beholder"),
p.getResources().getString(R.string.controls_screenkb_by, "Sun", "Sirea"),
p.getResources().getString(R.string.controls_screenkb_by, "Keen", "Gerstrong")
};
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.controls_screenkb_theme));
builder.setSingleChoiceItems(items, Globals.TouchscreenKeyboardTheme, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.TouchscreenKeyboardTheme = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class ScreenKeyboardTransparencyConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.controls_screenkb_transparency);
}
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.controls_screenkb_trans_0),
p.getResources().getString(R.string.controls_screenkb_trans_1),
p.getResources().getString(R.string.controls_screenkb_trans_2),
p.getResources().getString(R.string.controls_screenkb_trans_3),
p.getResources().getString(R.string.controls_screenkb_trans_4) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.controls_screenkb_transparency));
builder.setSingleChoiceItems(items, Globals.TouchscreenKeyboardTransparency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.TouchscreenKeyboardTransparency = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class RemapHwKeysConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.remap_hwkeys);
}
void run (final MainActivity p)
{
p.setText(p.getResources().getString(R.string.remap_hwkeys_press));
p.keyListener = new KeyRemapTool(p);
}
public static class KeyRemapTool implements MainActivity.KeyEventsListener
{
MainActivity p;
public KeyRemapTool(MainActivity _p)
{
p = _p;
}
public void onKeyEvent(final int keyCode)
{
p.keyListener = null;
int keyIndex = keyCode;
if( keyIndex < 0 )
keyIndex = 0;
if( keyIndex > SDL_Keys.JAVA_KEYCODE_LAST )
keyIndex = 0;
final int KeyIndexFinal = keyIndex;
CharSequence[] items = {
SDL_Keys.names[Globals.RemapScreenKbKeycode[0]],
SDL_Keys.names[Globals.RemapScreenKbKeycode[1]],
SDL_Keys.names[Globals.RemapScreenKbKeycode[2]],
SDL_Keys.names[Globals.RemapScreenKbKeycode[3]],
SDL_Keys.names[Globals.RemapScreenKbKeycode[4]],
SDL_Keys.names[Globals.RemapScreenKbKeycode[5]],
p.getResources().getString(R.string.remap_hwkeys_select_more_keys),
};
for( int i = 0; i < Math.min(6, Globals.AppTouchscreenKeyboardKeysNames.length); i++ )
items[i] = Globals.AppTouchscreenKeyboardKeysNames[i].replace("_", " ");
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.remap_hwkeys_select_simple);
builder.setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
if( item >= 6 )
ShowAllKeys(KeyIndexFinal);
else
{
Globals.RemapHwKeycode[KeyIndexFinal] = Globals.RemapScreenKbKeycode[item];
goBack(p);
}
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
public void ShowAllKeys(final int KeyIndex)
{
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.remap_hwkeys_select);
builder.setSingleChoiceItems(SDL_Keys.namesSorted, SDL_Keys.namesSortedBackIdx[Globals.RemapHwKeycode[KeyIndex]], new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RemapHwKeycode[KeyIndex] = SDL_Keys.namesSortedIdx[item];
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
}
static class RemapScreenKbConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.remap_screenkb);
}
//boolean enabled() { return true; };
void run (final MainActivity p)
{
CharSequence[] items = {
p.getResources().getString(R.string.remap_screenkb_joystick),
p.getResources().getString(R.string.remap_screenkb_button_text),
p.getResources().getString(R.string.remap_screenkb_button) + " 1",
p.getResources().getString(R.string.remap_screenkb_button) + " 2",
p.getResources().getString(R.string.remap_screenkb_button) + " 3",
p.getResources().getString(R.string.remap_screenkb_button) + " 4",
p.getResources().getString(R.string.remap_screenkb_button) + " 5",
p.getResources().getString(R.string.remap_screenkb_button) + " 6",
};
boolean defaults[] = Arrays.copyOf(Globals.ScreenKbControlsShown, Globals.ScreenKbControlsShown.length);
if( Globals.AppUsesSecondJoystick )
{
items = Arrays.copyOf(items, items.length + 1);
items[items.length - 1] = p.getResources().getString(R.string.remap_screenkb_joystick) + " 2";
defaults = Arrays.copyOf(defaults, defaults.length + 1);
defaults[defaults.length - 1] = true;
}
for( int i = 0; i < Math.min(6, Globals.AppTouchscreenKeyboardKeysNames.length); i++ )
items[i+2] = items[i+2] + " - " + Globals.AppTouchscreenKeyboardKeysNames[i].replace("_", " ");
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.remap_screenkb));
builder.setMultiChoiceItems(items, defaults, new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog, int item, boolean isChecked)
{
Globals.ScreenKbControlsShown[item] = isChecked;
}
});
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
showRemapScreenKbConfig2(p, 0);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showRemapScreenKbConfig2(final MainActivity p, final int currentButton)
{
CharSequence[] items = {
p.getResources().getString(R.string.remap_screenkb_button) + " 1",
p.getResources().getString(R.string.remap_screenkb_button) + " 2",
p.getResources().getString(R.string.remap_screenkb_button) + " 3",
p.getResources().getString(R.string.remap_screenkb_button) + " 4",
p.getResources().getString(R.string.remap_screenkb_button) + " 5",
p.getResources().getString(R.string.remap_screenkb_button) + " 6",
};
for( int i = 0; i < Math.min(6, Globals.AppTouchscreenKeyboardKeysNames.length); i++ )
items[i] = items[i] + " - " + Globals.AppTouchscreenKeyboardKeysNames[i].replace("_", " ");
if( currentButton >= Globals.RemapScreenKbKeycode.length )
{
goBack(p);
return;
}
if( ! Globals.ScreenKbControlsShown[currentButton + 2] )
{
showRemapScreenKbConfig2(p, currentButton + 1);
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(items[currentButton]);
builder.setSingleChoiceItems(SDL_Keys.namesSorted, SDL_Keys.namesSortedBackIdx[Globals.RemapScreenKbKeycode[currentButton]], new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RemapScreenKbKeycode[currentButton] = SDL_Keys.namesSortedIdx[item];
dialog.dismiss();
showRemapScreenKbConfig2(p, currentButton + 1);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class ScreenGesturesConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.remap_screenkb_button_gestures);
}
//boolean enabled() { return true; };
void run (final MainActivity p)
{
CharSequence[] items = {
p.getResources().getString(R.string.remap_screenkb_button_zoomin),
p.getResources().getString(R.string.remap_screenkb_button_zoomout),
p.getResources().getString(R.string.remap_screenkb_button_rotateleft),
p.getResources().getString(R.string.remap_screenkb_button_rotateright),
};
boolean defaults[] = {
Globals.MultitouchGesturesUsed[0],
Globals.MultitouchGesturesUsed[1],
Globals.MultitouchGesturesUsed[2],
Globals.MultitouchGesturesUsed[3],
};
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.remap_screenkb_button_gestures));
builder.setMultiChoiceItems(items, defaults, new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog, int item, boolean isChecked)
{
Globals.MultitouchGesturesUsed[item] = isChecked;
}
});
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
showScreenGesturesConfig2(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showScreenGesturesConfig2(final MainActivity p)
{
final CharSequence[] items = {
p.getResources().getString(R.string.accel_slow),
p.getResources().getString(R.string.accel_medium),
p.getResources().getString(R.string.accel_fast),
p.getResources().getString(R.string.accel_veryfast)
};
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.remap_screenkb_button_gestures_sensitivity);
builder.setSingleChoiceItems(items, Globals.MultitouchGestureSensitivity, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.MultitouchGestureSensitivity = item;
dialog.dismiss();
showScreenGesturesConfig3(p, 0);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showScreenGesturesConfig3(final MainActivity p, final int currentButton)
{
CharSequence[] items = {
p.getResources().getString(R.string.remap_screenkb_button_zoomin),
p.getResources().getString(R.string.remap_screenkb_button_zoomout),
p.getResources().getString(R.string.remap_screenkb_button_rotateleft),
p.getResources().getString(R.string.remap_screenkb_button_rotateright),
};
if( currentButton >= Globals.RemapMultitouchGestureKeycode.length )
{
goBack(p);
return;
}
if( ! Globals.MultitouchGesturesUsed[currentButton] )
{
showScreenGesturesConfig3(p, currentButton + 1);
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(items[currentButton]);
builder.setSingleChoiceItems(SDL_Keys.namesSorted, SDL_Keys.namesSortedBackIdx[Globals.RemapMultitouchGestureKeycode[currentButton]], new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RemapMultitouchGestureKeycode[currentButton] = SDL_Keys.namesSortedIdx[item];
dialog.dismiss();
showScreenGesturesConfig3(p, currentButton + 1);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class CustomizeScreenKbLayout extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.screenkb_custom_layout);
}
//boolean enabled() { return true; };
void run (final MainActivity p)
{
p.setText(p.getResources().getString(R.string.screenkb_custom_layout_help));
CustomizeScreenKbLayoutTool tool = new CustomizeScreenKbLayoutTool(p);
p.touchListener = tool;
p.keyListener = tool;
Globals.TouchscreenKeyboardSize = Globals.TOUCHSCREEN_KEYBOARD_CUSTOM;
}
static class CustomizeScreenKbLayoutTool implements MainActivity.TouchEventsListener, MainActivity.KeyEventsListener
{
MainActivity p;
FrameLayout layout = null;
ImageView imgs[] = new ImageView[Globals.ScreenKbControlsLayout.length];
Bitmap bmps[] = new Bitmap[Globals.ScreenKbControlsLayout.length];
ImageView boundary = null;
Bitmap boundaryBmp = null;
int currentButton = 0;
int buttons[] = {
R.drawable.dpad,
R.drawable.keyboard,
R.drawable.b1,
R.drawable.b2,
R.drawable.b3,
R.drawable.b4,
R.drawable.b5,
R.drawable.b6,
R.drawable.dpad
};
int oldX = 0, oldY = 0;
boolean resizing = false;
public CustomizeScreenKbLayoutTool(MainActivity _p)
{
p = _p;
layout = new FrameLayout(p);
p.getVideoLayout().addView(layout);
boundary = new ImageView(p);
boundary.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
boundary.setScaleType(ImageView.ScaleType.MATRIX);
boundaryBmp = BitmapFactory.decodeResource( p.getResources(), R.drawable.rectangle );
boundary.setImageBitmap(boundaryBmp);
layout.addView(boundary);
currentButton = -1;
if( Globals.TouchscreenKeyboardTheme == 2 )
{
buttons = new int[] {
R.drawable.sun_dpad,
R.drawable.sun_keyboard,
R.drawable.sun_b1,
R.drawable.sun_b2,
R.drawable.sun_b3,
R.drawable.sun_b4,
R.drawable.sun_b5,
R.drawable.sun_b6,
R.drawable.sun_dpad
};
}
int displayX = 800;
int displayY = 480;
try {
DisplayMetrics dm = new DisplayMetrics();
p.getWindowManager().getDefaultDisplay().getMetrics(dm);
displayX = dm.widthPixels;
displayY = dm.heightPixels;
} catch (Exception eeeee) {}
for( int i = 0; i < Globals.ScreenKbControlsLayout.length; i++ )
{
if( ! Globals.ScreenKbControlsShown[i] )
continue;
if( currentButton == -1 )
currentButton = i;
//Log.i("SDL", "Screen kb button " + i + " coords " + Globals.ScreenKbControlsLayout[i][0] + ":" + Globals.ScreenKbControlsLayout[i][1] + ":" + Globals.ScreenKbControlsLayout[i][2] + ":" + Globals.ScreenKbControlsLayout[i][3] );
// Check if the button is off screen edge or shrunk to zero
if( Globals.ScreenKbControlsLayout[i][0] > Globals.ScreenKbControlsLayout[i][2] - displayY/12 )
Globals.ScreenKbControlsLayout[i][0] = Globals.ScreenKbControlsLayout[i][2] - displayY/12;
if( Globals.ScreenKbControlsLayout[i][1] > Globals.ScreenKbControlsLayout[i][3] - displayY/12 )
Globals.ScreenKbControlsLayout[i][1] = Globals.ScreenKbControlsLayout[i][3] - displayY/12;
if( Globals.ScreenKbControlsLayout[i][0] < Globals.ScreenKbControlsLayout[i][2] - displayY*2/3 )
Globals.ScreenKbControlsLayout[i][0] = Globals.ScreenKbControlsLayout[i][2] - displayY*2/3;
if( Globals.ScreenKbControlsLayout[i][1] < Globals.ScreenKbControlsLayout[i][3] - displayY*2/3 )
Globals.ScreenKbControlsLayout[i][1] = Globals.ScreenKbControlsLayout[i][3] - displayY*2/3;
if( Globals.ScreenKbControlsLayout[i][0] < 0 )
{
Globals.ScreenKbControlsLayout[i][2] += -Globals.ScreenKbControlsLayout[i][0];
Globals.ScreenKbControlsLayout[i][0] = 0;
}
if( Globals.ScreenKbControlsLayout[i][2] > displayX )
{
Globals.ScreenKbControlsLayout[i][0] -= Globals.ScreenKbControlsLayout[i][2] - displayX;
Globals.ScreenKbControlsLayout[i][2] = displayX;
}
if( Globals.ScreenKbControlsLayout[i][1] < 0 )
{
Globals.ScreenKbControlsLayout[i][3] += -Globals.ScreenKbControlsLayout[i][1];
Globals.ScreenKbControlsLayout[i][1] = 0;
}
if( Globals.ScreenKbControlsLayout[i][3] > displayY )
{
Globals.ScreenKbControlsLayout[i][1] -= Globals.ScreenKbControlsLayout[i][3] - displayY;
Globals.ScreenKbControlsLayout[i][3] = displayY;
}
//Log.i("SDL", "After bounds check coords " + Globals.ScreenKbControlsLayout[i][0] + ":" + Globals.ScreenKbControlsLayout[i][1] + ":" + Globals.ScreenKbControlsLayout[i][2] + ":" + Globals.ScreenKbControlsLayout[i][3] );
imgs[i] = new ImageView(p);
imgs[i].setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
imgs[i].setScaleType(ImageView.ScaleType.MATRIX);
bmps[i] = BitmapFactory.decodeResource( p.getResources(), buttons[i] );
imgs[i].setImageBitmap(bmps[i]);
imgs[i].setAlpha(128);
layout.addView(imgs[i]);
Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmps[i].getWidth(), bmps[i].getHeight());
RectF dst = new RectF(Globals.ScreenKbControlsLayout[i][0], Globals.ScreenKbControlsLayout[i][1],
Globals.ScreenKbControlsLayout[i][2], Globals.ScreenKbControlsLayout[i][3]);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
imgs[i].setImageMatrix(m);
}
boundary.bringToFront();
if( currentButton == -1 )
onKeyEvent( KeyEvent.KEYCODE_BACK ); // All buttons disabled - do not show anything
else
setupButton(currentButton);
}
void setupButton(int i)
{
Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmps[i].getWidth(), bmps[i].getHeight());
RectF dst = new RectF(Globals.ScreenKbControlsLayout[i][0], Globals.ScreenKbControlsLayout[i][1],
Globals.ScreenKbControlsLayout[i][2], Globals.ScreenKbControlsLayout[i][3]);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
imgs[i].setImageMatrix(m);
m = new Matrix();
src = new RectF(0, 0, boundaryBmp.getWidth(), boundaryBmp.getHeight());
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
boundary.setImageMatrix(m);
String buttonText = "";
if( i >= 2 && i <= 7 )
buttonText = p.getResources().getString(R.string.remap_screenkb_button) + (i - 2);
if( i >= 2 && i - 2 < Globals.AppTouchscreenKeyboardKeysNames.length )
buttonText = Globals.AppTouchscreenKeyboardKeysNames[i - 2].replace("_", " ");
if( i == 0 )
buttonText = "Joystick";
if( i == 1 )
buttonText = "Text input";
if( i == 8 )
buttonText = "Joystick 2";
p.setText(p.getResources().getString(R.string.screenkb_custom_layout_help) + "\n" + buttonText);
}
public void onTouchEvent(final MotionEvent ev)
{
if( ev.getAction() == MotionEvent.ACTION_DOWN )
{
oldX = (int)ev.getX();
oldY = (int)ev.getY();
resizing = true;
for( int i = 0; i < Globals.ScreenKbControlsLayout.length; i++ )
{
if( ! Globals.ScreenKbControlsShown[i] )
continue;
if( Globals.ScreenKbControlsLayout[i][0] <= oldX &&
Globals.ScreenKbControlsLayout[i][2] >= oldX &&
Globals.ScreenKbControlsLayout[i][1] <= oldY &&
Globals.ScreenKbControlsLayout[i][3] >= oldY )
{
currentButton = i;
setupButton(currentButton);
resizing = false;
break;
}
}
}
if( ev.getAction() == MotionEvent.ACTION_MOVE )
{
int dx = (int)ev.getX() - oldX;
int dy = (int)ev.getY() - oldY;
if( resizing )
{
// Resize slowly, with 1/3 of movement speed
dx /= 6;
dy /= 6;
if( Globals.ScreenKbControlsLayout[currentButton][0] <= Globals.ScreenKbControlsLayout[currentButton][2] + dx*2 )
{
Globals.ScreenKbControlsLayout[currentButton][0] -= dx;
Globals.ScreenKbControlsLayout[currentButton][2] += dx;
}
if( Globals.ScreenKbControlsLayout[currentButton][1] <= Globals.ScreenKbControlsLayout[currentButton][3] + dy*2 )
{
Globals.ScreenKbControlsLayout[currentButton][1] += dy;
Globals.ScreenKbControlsLayout[currentButton][3] -= dy;
}
dx *= 6;
dy *= 6;
}
else
{
Globals.ScreenKbControlsLayout[currentButton][0] += dx;
Globals.ScreenKbControlsLayout[currentButton][2] += dx;
Globals.ScreenKbControlsLayout[currentButton][1] += dy;
Globals.ScreenKbControlsLayout[currentButton][3] += dy;
}
oldX += dx;
oldY += dy;
Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmps[currentButton].getWidth(), bmps[currentButton].getHeight());
RectF dst = new RectF(Globals.ScreenKbControlsLayout[currentButton][0], Globals.ScreenKbControlsLayout[currentButton][1],
Globals.ScreenKbControlsLayout[currentButton][2], Globals.ScreenKbControlsLayout[currentButton][3]);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
imgs[currentButton].setImageMatrix(m);
m = new Matrix();
src = new RectF(0, 0, boundaryBmp.getWidth(), boundaryBmp.getHeight());
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
boundary.setImageMatrix(m);
}
}
public void onKeyEvent(final int keyCode)
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
p.getVideoLayout().removeView(layout);
layout = null;
p.touchListener = null;
p.keyListener = null;
goBack(p);
}
}
}
}
}

View File

@@ -1,755 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.util.Log;
import java.io.*;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.StatFs;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.Collections;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import java.lang.String;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Button;
import android.widget.Scroller;
import android.view.View;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.text.Editable;
import android.text.SpannedString;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.util.DisplayMetrics;
import android.net.Uri;
import java.util.concurrent.Semaphore;
import java.util.Arrays;
import android.graphics.Color;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import android.widget.Toast;
class SettingsMenuMisc extends SettingsMenu
{
static class DownloadConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.storage_question);
}
void run (final MainActivity p)
{
long freeSdcard = 0;
long freePhone = 0;
try
{
StatFs sdcard = new StatFs(Environment.getExternalStorageDirectory().getPath());
StatFs phone = new StatFs(Environment.getDataDirectory().getPath());
freeSdcard = (long)sdcard.getAvailableBlocks() * sdcard.getBlockSize() / 1024 / 1024;
freePhone = (long)phone.getAvailableBlocks() * phone.getBlockSize() / 1024 / 1024;
}
catch(Exception e) {}
final CharSequence[] items = { p.getResources().getString(R.string.storage_phone, freePhone),
p.getResources().getString(R.string.storage_sd, freeSdcard),
p.getResources().getString(R.string.storage_custom) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.storage_question));
builder.setSingleChoiceItems(items, Globals.DownloadToSdcard ? 1 : 0, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
if( item == 2 )
showCustomDownloadDirConfig(p);
else
{
Globals.DownloadToSdcard = (item != 0);
Globals.DataDir = Globals.DownloadToSdcard ?
Settings.SdcardAppPath.getPath(p) :
p.getFilesDir().getAbsolutePath();
goBack(p);
}
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showCustomDownloadDirConfig(final MainActivity p)
{
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.storage_custom));
final EditText edit = new EditText(p);
edit.setFocusableInTouchMode(true);
edit.setFocusable(true);
edit.setText(Globals.DataDir);
builder.setView(edit);
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.DataDir = edit.getText().toString();
dialog.dismiss();
showCommandLineConfig(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showCommandLineConfig(final MainActivity p)
{
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.storage_commandline));
final EditText edit = new EditText(p);
edit.setFocusableInTouchMode(true);
edit.setFocusable(true);
edit.setText(Globals.CommandLine);
builder.setView(edit);
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.CommandLine = edit.getText().toString();
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class OptionalDownloadConfig extends Menu
{
boolean firstStart = false;
OptionalDownloadConfig()
{
firstStart = true;
}
OptionalDownloadConfig(boolean firstStart)
{
this.firstStart = firstStart;
}
String title(final MainActivity p)
{
return p.getResources().getString(R.string.downloads);
}
void run (final MainActivity p)
{
String [] downloadFiles = Globals.DataDownloadUrl;
final boolean [] mandatory = new boolean[downloadFiles.length];
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.downloads));
CharSequence[] items = new CharSequence[downloadFiles.length];
for(int i = 0; i < downloadFiles.length; i++ )
{
items[i] = new String(downloadFiles[i].split("[|]")[0]);
if( items[i].toString().indexOf("!") == 0 )
items[i] = items[i].toString().substring(1);
if( items[i].toString().indexOf("!") == 0 )
{
items[i] = items[i].toString().substring(1);
mandatory[i] = true;
}
}
if( Globals.OptionalDataDownload == null || Globals.OptionalDataDownload.length != items.length )
{
Globals.OptionalDataDownload = new boolean[downloadFiles.length];
boolean oldFormat = true;
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].indexOf("!") == 0 )
{
Globals.OptionalDataDownload[i] = true;
oldFormat = false;
}
}
if( oldFormat )
{
Globals.OptionalDataDownload[0] = true;
mandatory[0] = true;
}
}
builder.setMultiChoiceItems(items, Globals.OptionalDataDownload, new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog, int item, boolean isChecked)
{
Globals.OptionalDataDownload[item] = isChecked;
if( mandatory[item] && !isChecked )
{
Globals.OptionalDataDownload[item] = true;
((AlertDialog)dialog).getListView().setItemChecked(item, true);
}
}
});
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
goBack(p);
}
});
if( firstStart )
{
builder.setNegativeButton(p.getResources().getString(R.string.show_more_options), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
menuStack.clear();
new MainMenu().run(p);
}
});
}
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class AudioConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.audiobuf_question);
}
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.audiobuf_verysmall),
p.getResources().getString(R.string.audiobuf_small),
p.getResources().getString(R.string.audiobuf_medium),
p.getResources().getString(R.string.audiobuf_large) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.audiobuf_question);
builder.setSingleChoiceItems(items, Globals.AudioBufferConfig, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.AudioBufferConfig = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class VideoSettingsConfig extends Menu
{
static int debugMenuShowCount = 0;
String title(final MainActivity p)
{
return p.getResources().getString(R.string.video);
}
//boolean enabled() { return true; };
void run (final MainActivity p)
{
debugMenuShowCount++;
CharSequence[] items = {
p.getResources().getString(R.string.pointandclick_keepaspectratio),
p.getResources().getString(R.string.video_smooth)
};
boolean defaults[] = {
Globals.KeepAspectRatio,
Globals.VideoLinearFilter
};
if(Globals.SwVideoMode && !Globals.CompatibilityHacksVideo)
{
CharSequence[] items2 = {
p.getResources().getString(R.string.pointandclick_keepaspectratio),
p.getResources().getString(R.string.video_smooth),
p.getResources().getString(R.string.video_separatethread),
};
boolean defaults2[] = {
Globals.KeepAspectRatio,
Globals.VideoLinearFilter,
Globals.MultiThreadedVideo
};
items = items2;
defaults = defaults2;
}
if(Globals.Using_SDL_1_3)
{
CharSequence[] items2 = {
p.getResources().getString(R.string.pointandclick_keepaspectratio),
};
boolean defaults2[] = {
Globals.KeepAspectRatio,
};
items = items2;
defaults = defaults2;
}
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.video));
builder.setMultiChoiceItems(items, defaults, new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog, int item, boolean isChecked)
{
if( item == 0 )
Globals.KeepAspectRatio = isChecked;
if( item == 1 )
Globals.VideoLinearFilter = isChecked;
if( item == 2 )
Globals.MultiThreadedVideo = isChecked;
}
});
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
if( debugMenuShowCount > 5 || Globals.OuyaEmulation )
showDebugMenu(p);
else
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
void showDebugMenu (final MainActivity p)
{
CharSequence[] items = {
"OUYA emulation"
};
boolean defaults[] = {
Globals.OuyaEmulation,
};
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle("Debug settings");
builder.setMultiChoiceItems(items, defaults, new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog, int item, boolean isChecked)
{
if( item == 0 )
Globals.OuyaEmulation = isChecked;
}
});
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class ShowReadme extends Menu
{
String title(final MainActivity p)
{
return "Readme";
}
boolean enabled()
{
return true;
}
void run (final MainActivity p)
{
String readmes[] = Globals.ReadmeText.split("\\^");
String lang = new String(Locale.getDefault().getLanguage()) + ":";
if( p.isRunningOnOUYA() )
lang = "ouya:";
String readme = readmes[0];
String buttonName = "", buttonUrl = "";
for( String r: readmes )
{
if( r.startsWith(lang) )
readme = r.substring(lang.length());
if( r.startsWith("button:") )
{
buttonName = r.substring("button:".length());
if( buttonName.indexOf(":") != -1 )
{
buttonUrl = buttonName.substring(buttonName.indexOf(":") + 1);
buttonName = buttonName.substring(0, buttonName.indexOf(":"));
}
}
}
readme = readme.trim();
if( readme.length() <= 2 )
{
goBack(p);
return;
}
TextView text = new TextView(p);
text.setMaxLines(100);
//text.setScroller(new Scroller(p));
//text.setVerticalScrollBarEnabled(true);
text.setText(readme);
text.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
text.setPadding(0, 5, 0, 20);
text.setTextSize(20.0f);
text.setGravity(Gravity.CENTER);
AlertDialog.Builder builder = new AlertDialog.Builder(p);
ScrollView scroll = new ScrollView(p);
scroll.addView(text, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button ok = new Button(p);
final AlertDialog alertDismiss[] = new AlertDialog[1];
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
alertDismiss[0].cancel();
}
});
ok.setText(R.string.ok);
LinearLayout layout = new LinearLayout(p);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(scroll);
//layout.addView(text);
layout.addView(ok);
if( buttonName.length() > 0 )
{
Button cancel = new Button(p);
cancel.setText(buttonName);
final String url = buttonUrl;
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if( url.length() > 0 )
{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
p.startActivity(i);
}
alertDismiss[0].cancel();
System.exit(0);
}
});
layout.addView(cancel);
}
builder.setView(layout);
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alertDismiss[0] = alert;
alert.setOwnerActivity(p);
alert.show();
}
}
static class GyroscopeCalibration extends Menu implements SensorEventListener
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.calibrate_gyroscope);
}
boolean enabled()
{
return Globals.AppUsesGyroscope;
}
void run (final MainActivity p)
{
if( !Globals.AppUsesGyroscope || !AccelerometerReader.gyro.available(p) )
{
if( Globals.AppUsesGyroscope )
{
Toast toast = Toast.makeText(p, p.getResources().getString(R.string.calibrate_gyroscope_not_supported), Toast.LENGTH_LONG);
toast.show();
}
goBack(p);
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.calibrate_gyroscope));
builder.setMessage(p.getResources().getString(R.string.calibrate_gyroscope_text));
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
startCalibration(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
ImageView img;
Bitmap bmp;
int numEvents;
MainActivity p;
void startCalibration(final MainActivity _p)
{
p = _p;
img = new ImageView(p);
img.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
img.setScaleType(ImageView.ScaleType.MATRIX);
bmp = BitmapFactory.decodeResource( p.getResources(), R.drawable.calibrate );
img.setImageBitmap(bmp);
Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmp.getWidth(), bmp.getHeight());
RectF dst = new RectF( p.getVideoLayout().getWidth()/2 - 50, p.getVideoLayout().getHeight()/2 - 50,
p.getVideoLayout().getWidth()/2 + 50, p.getVideoLayout().getHeight()/2 + 50);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
img.setImageMatrix(m);
p.getVideoLayout().addView(img);
numEvents = 0;
AccelerometerReader.gyro.x1 = 100;
AccelerometerReader.gyro.x2 = -100;
AccelerometerReader.gyro.xc = 0;
AccelerometerReader.gyro.y1 = 100;
AccelerometerReader.gyro.y2 = -100;
AccelerometerReader.gyro.yc = 0;
AccelerometerReader.gyro.z1 = 100;
AccelerometerReader.gyro.z2 = -100;
AccelerometerReader.gyro.zc = 0;
AccelerometerReader.gyro.registerListener(p, this);
(new Thread(new Runnable()
{
public void run()
{
for(int count = 1; count < 10; count++)
{
p.setText("" + count + "0% ...");
try {
Thread.sleep(500);
} catch( Exception e ) {}
}
finishCalibration(p);
}
}
)).start();
}
public void onSensorChanged(SensorEvent event)
{
gyroscopeEvent(event.values[0], event.values[1], event.values[2]);
}
public void onAccuracyChanged(Sensor s, int a)
{
}
void gyroscopeEvent(float x, float y, float z)
{
numEvents++;
AccelerometerReader.gyro.xc += x;
AccelerometerReader.gyro.yc += y;
AccelerometerReader.gyro.zc += z;
AccelerometerReader.gyro.x1 = Math.min(AccelerometerReader.gyro.x1, x * 1.1f); // Small safety bound coefficient
AccelerometerReader.gyro.x2 = Math.max(AccelerometerReader.gyro.x2, x * 1.1f);
AccelerometerReader.gyro.y1 = Math.min(AccelerometerReader.gyro.y1, y * 1.1f);
AccelerometerReader.gyro.y2 = Math.max(AccelerometerReader.gyro.y2, y * 1.1f);
AccelerometerReader.gyro.z1 = Math.min(AccelerometerReader.gyro.z1, z * 1.1f);
AccelerometerReader.gyro.z2 = Math.max(AccelerometerReader.gyro.z2, z * 1.1f);
final Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmp.getWidth(), bmp.getHeight());
RectF dst = new RectF( x * 5000 + p.getVideoLayout().getWidth()/2 - 50, y * 5000 + p.getVideoLayout().getHeight()/2 - 50,
x * 5000 + p.getVideoLayout().getWidth()/2 + 50, y * 5000 + p.getVideoLayout().getHeight()/2 + 50);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
p.runOnUiThread(new Runnable()
{
public void run()
{
img.setImageMatrix(m);
}
});
}
void finishCalibration(final MainActivity p)
{
AccelerometerReader.gyro.unregisterListener(p, this);
try {
Thread.sleep(200); // Just in case we have pending events
} catch( Exception e ) {}
if( numEvents > 5 )
{
AccelerometerReader.gyro.xc /= (float)numEvents;
AccelerometerReader.gyro.yc /= (float)numEvents;
AccelerometerReader.gyro.zc /= (float)numEvents;
}
p.runOnUiThread(new Runnable()
{
public void run()
{
p.getVideoLayout().removeView(img);
goBack(p);
}
});
}
}
static class ResetToDefaultsConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.reset_config);
}
boolean enabled()
{
return true;
}
void run (final MainActivity p)
{
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.reset_config_ask));
builder.setMessage(p.getResources().getString(R.string.reset_config_ask));
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Settings.DeleteSdlConfigOnUpgradeAndRestart(p); // Never returns
dialog.dismiss();
goBack(p);
}
});
builder.setNegativeButton(p.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
}

View File

@@ -1,771 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.util.Log;
import java.io.*;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.StatFs;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.Collections;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import java.lang.String;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Button;
import android.view.View;
import android.widget.LinearLayout;
import android.text.Editable;
import android.text.SpannedString;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.util.DisplayMetrics;
import android.net.Uri;
import java.util.concurrent.Semaphore;
import java.util.Arrays;
import android.graphics.Color;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import android.widget.Toast;
class SettingsMenuMouse extends SettingsMenu
{
static class MouseConfigMainMenu extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.mouse_emulation);
}
boolean enabled()
{
return Globals.AppUsesMouse;
}
void run (final MainActivity p)
{
Menu options[] =
{
new DisplaySizeConfig(false),
new LeftClickConfig(),
new RightClickConfig(),
new AdditionalMouseConfig(),
new JoystickMouseConfig(),
new TouchPressureMeasurementTool(),
new CalibrateTouchscreenMenu(),
new OkButton(),
};
showMenuOptionsList(p, options);
}
}
static class DisplaySizeConfig extends Menu
{
boolean firstStart = false;
DisplaySizeConfig()
{
this.firstStart = true;
}
DisplaySizeConfig(boolean firstStart)
{
this.firstStart = firstStart;
}
String title(final MainActivity p)
{
return p.getResources().getString(R.string.display_size_mouse);
}
void run (final MainActivity p)
{
CharSequence[] items = {
p.getResources().getString(R.string.display_size_tiny_touchpad),
p.getResources().getString(R.string.display_size_tiny),
p.getResources().getString(R.string.display_size_small),
p.getResources().getString(R.string.display_size_small_touchpad),
p.getResources().getString(R.string.display_size_large),
};
int _size_tiny_touchpad = 0;
int _size_tiny = 1;
int _size_small = 2;
int _size_small_touchpad = 3;
int _size_large = 4;
int _more_options = 5;
if( ! Globals.SwVideoMode )
{
CharSequence[] items2 = {
p.getResources().getString(R.string.display_size_small_touchpad),
p.getResources().getString(R.string.display_size_large),
};
items = items2;
_size_small_touchpad = 0;
_size_large = 1;
_size_tiny_touchpad = _size_tiny = _size_small = 1000;
}
if( firstStart )
{
CharSequence[] items2 = {
p.getResources().getString(R.string.display_size_tiny_touchpad),
p.getResources().getString(R.string.display_size_tiny),
p.getResources().getString(R.string.display_size_small),
p.getResources().getString(R.string.display_size_small_touchpad),
p.getResources().getString(R.string.display_size_large),
p.getResources().getString(R.string.show_more_options),
};
items = items2;
if( ! Globals.SwVideoMode )
{
CharSequence[] items3 = {
p.getResources().getString(R.string.display_size_small_touchpad),
p.getResources().getString(R.string.display_size_large),
p.getResources().getString(R.string.show_more_options),
};
items = items3;
_more_options = 3;
}
}
// Java is so damn worse than C++11
final int size_tiny_touchpad = _size_tiny_touchpad;
final int size_tiny = _size_tiny;
final int size_small = _size_small;
final int size_small_touchpad = _size_small_touchpad;
final int size_large = _size_large;
final int more_options = _more_options;
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.display_size);
class ClickListener implements DialogInterface.OnClickListener
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
if( item == size_large )
{
Globals.LeftClickMethod = Mouse.LEFT_CLICK_NORMAL;
Globals.RelativeMouseMovement = false;
Globals.ShowScreenUnderFinger = Mouse.ZOOM_NONE;
}
if( item == size_small )
{
Globals.LeftClickMethod = Mouse.LEFT_CLICK_NEAR_CURSOR;
Globals.RelativeMouseMovement = false;
Globals.ShowScreenUnderFinger = Mouse.ZOOM_MAGNIFIER;
}
if( item == size_small_touchpad )
{
Globals.LeftClickMethod = Mouse.LEFT_CLICK_WITH_TAP_OR_TIMEOUT;
Globals.RelativeMouseMovement = true;
Globals.ShowScreenUnderFinger = Mouse.ZOOM_NONE;
}
if( item == size_tiny )
{
Globals.LeftClickMethod = Mouse.LEFT_CLICK_NEAR_CURSOR;
Globals.RelativeMouseMovement = false;
Globals.ShowScreenUnderFinger = Mouse.ZOOM_SCREEN_TRANSFORM;
}
if( item == size_tiny_touchpad )
{
Globals.LeftClickMethod = Mouse.LEFT_CLICK_WITH_TAP_OR_TIMEOUT;
Globals.RelativeMouseMovement = true;
Globals.ShowScreenUnderFinger = Mouse.ZOOM_FULLSCREEN_MAGNIFIER;
}
if( item == more_options )
{
menuStack.clear();
new MainMenu().run(p);
return;
}
goBack(p);
}
}
builder.setItems(items, new ClickListener());
/*
else
builder.setSingleChoiceItems(items,
Globals.ShowScreenUnderFinger == Mouse.ZOOM_NONE ?
( Globals.RelativeMouseMovement ? Globals.SwVideoMode ? 2 : 1 : 0 ) :
( Globals.ShowScreenUnderFinger == Mouse.ZOOM_MAGNIFIER && Globals.SwVideoMode ) ? 1 :
Globals.ShowScreenUnderFinger + 1,
new ClickListener());
*/
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class LeftClickConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.leftclick_question);
}
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.leftclick_normal),
p.getResources().getString(R.string.leftclick_near_cursor),
p.getResources().getString(R.string.leftclick_multitouch),
p.getResources().getString(R.string.leftclick_pressure),
p.getResources().getString(R.string.rightclick_key),
p.getResources().getString(R.string.leftclick_timeout),
p.getResources().getString(R.string.leftclick_tap),
p.getResources().getString(R.string.leftclick_tap_or_timeout) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.leftclick_question);
builder.setSingleChoiceItems(items, Globals.LeftClickMethod, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
Globals.LeftClickMethod = item;
if( item == Mouse.LEFT_CLICK_WITH_KEY )
p.keyListener = new KeyRemapToolMouseClick(p, true);
else if( item == Mouse.LEFT_CLICK_WITH_TIMEOUT || item == Mouse.LEFT_CLICK_WITH_TAP_OR_TIMEOUT )
showLeftClickTimeoutConfig(p);
else
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showLeftClickTimeoutConfig(final MainActivity p) {
final CharSequence[] items = { p.getResources().getString(R.string.leftclick_timeout_time_0),
p.getResources().getString(R.string.leftclick_timeout_time_1),
p.getResources().getString(R.string.leftclick_timeout_time_2),
p.getResources().getString(R.string.leftclick_timeout_time_3),
p.getResources().getString(R.string.leftclick_timeout_time_4) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.leftclick_timeout_time);
builder.setSingleChoiceItems(items, Globals.LeftClickTimeout, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.LeftClickTimeout = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class RightClickConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.rightclick_question);
}
boolean enabled()
{
return Globals.AppNeedsTwoButtonMouse;
}
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.rightclick_none),
p.getResources().getString(R.string.rightclick_multitouch),
p.getResources().getString(R.string.rightclick_pressure),
p.getResources().getString(R.string.rightclick_key),
p.getResources().getString(R.string.leftclick_timeout) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.rightclick_question);
builder.setSingleChoiceItems(items, Globals.RightClickMethod, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RightClickMethod = item;
dialog.dismiss();
if( item == Mouse.RIGHT_CLICK_WITH_KEY )
p.keyListener = new KeyRemapToolMouseClick(p, false);
else if( item == Mouse.RIGHT_CLICK_WITH_TIMEOUT )
showRightClickTimeoutConfig(p);
else
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showRightClickTimeoutConfig(final MainActivity p) {
final CharSequence[] items = { p.getResources().getString(R.string.leftclick_timeout_time_0),
p.getResources().getString(R.string.leftclick_timeout_time_1),
p.getResources().getString(R.string.leftclick_timeout_time_2),
p.getResources().getString(R.string.leftclick_timeout_time_3),
p.getResources().getString(R.string.leftclick_timeout_time_4) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.leftclick_timeout_time);
builder.setSingleChoiceItems(items, Globals.RightClickTimeout, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RightClickTimeout = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
public static class KeyRemapToolMouseClick implements MainActivity.KeyEventsListener
{
MainActivity p;
boolean leftClick;
public KeyRemapToolMouseClick(MainActivity _p, boolean leftClick)
{
p = _p;
p.setText(p.getResources().getString(R.string.remap_hwkeys_press));
this.leftClick = leftClick;
}
public void onKeyEvent(final int keyCode)
{
p.keyListener = null;
int keyIndex = keyCode;
if( keyIndex < 0 )
keyIndex = 0;
if( keyIndex > SDL_Keys.JAVA_KEYCODE_LAST )
keyIndex = 0;
if( leftClick )
Globals.LeftClickKey = keyIndex;
else
Globals.RightClickKey = keyIndex;
goBack(p);
}
}
static class AdditionalMouseConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.pointandclick_question);
}
void run (final MainActivity p)
{
CharSequence[] items = {
p.getResources().getString(R.string.pointandclick_joystickmouse),
p.getResources().getString(R.string.click_with_dpadcenter),
p.getResources().getString(R.string.pointandclick_relative)
};
boolean defaults[] = {
Globals.MoveMouseWithJoystick,
Globals.ClickMouseWithDpad,
Globals.RelativeMouseMovement
};
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.pointandclick_question));
builder.setMultiChoiceItems(items, defaults, new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog, int item, boolean isChecked)
{
if( item == 0 )
Globals.MoveMouseWithJoystick = isChecked;
if( item == 1 )
Globals.ClickMouseWithDpad = isChecked;
if( item == 2 )
Globals.RelativeMouseMovement = isChecked;
}
});
builder.setPositiveButton(p.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
if( Globals.RelativeMouseMovement )
showRelativeMouseMovementConfig(p);
else
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showRelativeMouseMovementConfig(final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.accel_veryslow),
p.getResources().getString(R.string.accel_slow),
p.getResources().getString(R.string.accel_medium),
p.getResources().getString(R.string.accel_fast),
p.getResources().getString(R.string.accel_veryfast) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.pointandclick_relative_speed);
builder.setSingleChoiceItems(items, Globals.RelativeMouseMovementSpeed, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RelativeMouseMovementSpeed = item;
dialog.dismiss();
showRelativeMouseMovementConfig1(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showRelativeMouseMovementConfig1(final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.none),
p.getResources().getString(R.string.accel_slow),
p.getResources().getString(R.string.accel_medium),
p.getResources().getString(R.string.accel_fast) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.pointandclick_relative_accel);
builder.setSingleChoiceItems(items, Globals.RelativeMouseMovementAccel, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.RelativeMouseMovementAccel = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class JoystickMouseConfig extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.pointandclick_joystickmousespeed);
}
boolean enabled()
{
return Globals.MoveMouseWithJoystick;
};
void run (final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.accel_slow),
p.getResources().getString(R.string.accel_medium),
p.getResources().getString(R.string.accel_fast) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.pointandclick_joystickmousespeed);
builder.setSingleChoiceItems(items, Globals.MoveMouseWithJoystickSpeed, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.MoveMouseWithJoystickSpeed = item;
dialog.dismiss();
showJoystickMouseAccelConfig(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
static void showJoystickMouseAccelConfig(final MainActivity p)
{
final CharSequence[] items = { p.getResources().getString(R.string.none),
p.getResources().getString(R.string.accel_slow),
p.getResources().getString(R.string.accel_medium),
p.getResources().getString(R.string.accel_fast) };
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(R.string.pointandclick_joystickmouseaccel);
builder.setSingleChoiceItems(items, Globals.MoveMouseWithJoystickAccel, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Globals.MoveMouseWithJoystickAccel = item;
dialog.dismiss();
goBack(p);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
goBack(p);
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
static class TouchPressureMeasurementTool extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.measurepressure);
}
boolean enabled()
{
return Globals.RightClickMethod == Mouse.RIGHT_CLICK_WITH_PRESSURE ||
Globals.LeftClickMethod == Mouse.LEFT_CLICK_WITH_PRESSURE;
};
void run (final MainActivity p)
{
p.setText(p.getResources().getString(R.string.measurepressure_touchplease));
p.touchListener = new TouchMeasurementTool(p);
}
public static class TouchMeasurementTool implements MainActivity.TouchEventsListener
{
MainActivity p;
ArrayList<Integer> force = new ArrayList<Integer>();
ArrayList<Integer> radius = new ArrayList<Integer>();
static final int maxEventAmount = 100;
public TouchMeasurementTool(MainActivity _p)
{
p = _p;
}
public void onTouchEvent(final MotionEvent ev)
{
force.add(new Integer((int)(ev.getPressure() * 1000.0)));
radius.add(new Integer((int)(ev.getSize() * 1000.0)));
p.setText(p.getResources().getString(R.string.measurepressure_response, force.get(force.size()-1), radius.get(radius.size()-1)));
try {
Thread.sleep(10L);
} catch (InterruptedException e) { }
if( force.size() >= maxEventAmount )
{
p.touchListener = null;
Globals.ClickScreenPressure = getAverageForce();
Globals.ClickScreenTouchspotSize = getAverageRadius();
Log.i("SDL", "SDL: measured average force " + Globals.ClickScreenPressure + " radius " + Globals.ClickScreenTouchspotSize);
goBack(p);
}
}
int getAverageForce()
{
int avg = 0;
for(Integer f: force)
{
avg += f;
}
return avg / force.size();
}
int getAverageRadius()
{
int avg = 0;
for(Integer r: radius)
{
avg += r;
}
return avg / radius.size();
}
}
}
static class CalibrateTouchscreenMenu extends Menu
{
String title(final MainActivity p)
{
return p.getResources().getString(R.string.calibrate_touchscreen);
}
//boolean enabled() { return true; };
void run (final MainActivity p)
{
p.setText(p.getResources().getString(R.string.calibrate_touchscreen_touch));
Globals.TouchscreenCalibration[0] = 0;
Globals.TouchscreenCalibration[1] = 0;
Globals.TouchscreenCalibration[2] = 0;
Globals.TouchscreenCalibration[3] = 0;
ScreenEdgesCalibrationTool tool = new ScreenEdgesCalibrationTool(p);
p.touchListener = tool;
p.keyListener = tool;
}
static class ScreenEdgesCalibrationTool implements MainActivity.TouchEventsListener, MainActivity.KeyEventsListener
{
MainActivity p;
ImageView img;
Bitmap bmp;
public ScreenEdgesCalibrationTool(MainActivity _p)
{
p = _p;
img = new ImageView(p);
img.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
img.setScaleType(ImageView.ScaleType.MATRIX);
bmp = BitmapFactory.decodeResource( p.getResources(), R.drawable.calibrate );
img.setImageBitmap(bmp);
Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmp.getWidth(), bmp.getHeight());
RectF dst = new RectF(Globals.TouchscreenCalibration[0], Globals.TouchscreenCalibration[1],
Globals.TouchscreenCalibration[2], Globals.TouchscreenCalibration[3]);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
img.setImageMatrix(m);
p.getVideoLayout().addView(img);
}
public void onTouchEvent(final MotionEvent ev)
{
if( Globals.TouchscreenCalibration[0] == Globals.TouchscreenCalibration[1] &&
Globals.TouchscreenCalibration[1] == Globals.TouchscreenCalibration[2] &&
Globals.TouchscreenCalibration[2] == Globals.TouchscreenCalibration[3] )
{
Globals.TouchscreenCalibration[0] = (int)ev.getX();
Globals.TouchscreenCalibration[1] = (int)ev.getY();
Globals.TouchscreenCalibration[2] = (int)ev.getX();
Globals.TouchscreenCalibration[3] = (int)ev.getY();
}
if( ev.getX() < Globals.TouchscreenCalibration[0] )
Globals.TouchscreenCalibration[0] = (int)ev.getX();
if( ev.getY() < Globals.TouchscreenCalibration[1] )
Globals.TouchscreenCalibration[1] = (int)ev.getY();
if( ev.getX() > Globals.TouchscreenCalibration[2] )
Globals.TouchscreenCalibration[2] = (int)ev.getX();
if( ev.getY() > Globals.TouchscreenCalibration[3] )
Globals.TouchscreenCalibration[3] = (int)ev.getY();
Matrix m = new Matrix();
RectF src = new RectF(0, 0, bmp.getWidth(), bmp.getHeight());
RectF dst = new RectF(Globals.TouchscreenCalibration[0], Globals.TouchscreenCalibration[1],
Globals.TouchscreenCalibration[2], Globals.TouchscreenCalibration[3]);
m.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
img.setImageMatrix(m);
}
public void onKeyEvent(final int keyCode)
{
p.touchListener = null;
p.keyListener = null;
p.getVideoLayout().removeView(img);
goBack(p);
}
}
}
}

View File

@@ -1,846 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.InputDevice;
import android.view.Window;
import android.view.WindowManager;
import android.os.Environment;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.content.res.Resources;
import android.content.res.AssetManager;
import android.widget.Toast;
import android.util.Log;
import android.widget.TextView;
import java.lang.Thread;
import java.util.concurrent.locks.ReentrantLock;
import android.os.Build;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
class Mouse
{
public static final int LEFT_CLICK_NORMAL = 0;
public static final int LEFT_CLICK_NEAR_CURSOR = 1;
public static final int LEFT_CLICK_WITH_MULTITOUCH = 2;
public static final int LEFT_CLICK_WITH_PRESSURE = 3;
public static final int LEFT_CLICK_WITH_KEY = 4;
public static final int LEFT_CLICK_WITH_TIMEOUT = 5;
public static final int LEFT_CLICK_WITH_TAP = 6;
public static final int LEFT_CLICK_WITH_TAP_OR_TIMEOUT = 7;
public static final int RIGHT_CLICK_NONE = 0;
public static final int RIGHT_CLICK_WITH_MULTITOUCH = 1;
public static final int RIGHT_CLICK_WITH_PRESSURE = 2;
public static final int RIGHT_CLICK_WITH_KEY = 3;
public static final int RIGHT_CLICK_WITH_TIMEOUT = 4;
public static final int SDL_FINGER_DOWN = 0;
public static final int SDL_FINGER_UP = 1;
public static final int SDL_FINGER_MOVE = 2;
public static final int SDL_FINGER_HOVER = 3;
public static final int ZOOM_NONE = 0;
public static final int ZOOM_MAGNIFIER = 1;
public static final int ZOOM_SCREEN_TRANSFORM = 2;
public static final int ZOOM_FULLSCREEN_MAGNIFIER = 3;
}
abstract class DifferentTouchInput
{
public abstract void process(final MotionEvent event);
public abstract void processGenericEvent(final MotionEvent event);
public static boolean ExternalMouseDetected = false;
public static DifferentTouchInput getInstance()
{
boolean multiTouchAvailable1 = false;
boolean multiTouchAvailable2 = false;
// Not checking for getX(int), getY(int) etc 'cause I'm lazy
Method methods [] = MotionEvent.class.getDeclaredMethods();
for(Method m: methods)
{
if( m.getName().equals("getPointerCount") )
multiTouchAvailable1 = true;
if( m.getName().equals("getPointerId") )
multiTouchAvailable2 = true;
}
try {
Log.i("SDL", "Device model: " + android.os.Build.MODEL);
if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH )
{
if( DetectCrappyDragonRiseDatexGamepad() )
return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance;
return IcsTouchInput.Holder.sInstance;
}
if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD )
return GingerbreadTouchInput.Holder.sInstance;
if (multiTouchAvailable1 && multiTouchAvailable2)
return MultiTouchInput.Holder.sInstance;
else
return SingleTouchInput.Holder.sInstance;
} catch( Exception e ) {
try {
if (multiTouchAvailable1 && multiTouchAvailable2)
return MultiTouchInput.Holder.sInstance;
else
return SingleTouchInput.Holder.sInstance;
} catch( Exception ee ) {
return SingleTouchInput.Holder.sInstance;
}
}
}
private static boolean DetectCrappyDragonRiseDatexGamepad()
{
if( CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance == null )
return false;
return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance.detect();
}
private static class SingleTouchInput extends DifferentTouchInput
{
private static class Holder
{
private static final SingleTouchInput sInstance = new SingleTouchInput();
}
@Override
public void processGenericEvent(final MotionEvent event)
{
process(event);
}
public void process(final MotionEvent event)
{
int action = -1;
if( event.getAction() == MotionEvent.ACTION_DOWN )
action = Mouse.SDL_FINGER_DOWN;
if( event.getAction() == MotionEvent.ACTION_UP )
action = Mouse.SDL_FINGER_UP;
if( event.getAction() == MotionEvent.ACTION_MOVE )
action = Mouse.SDL_FINGER_MOVE;
if ( action >= 0 )
DemoGLSurfaceView.nativeMotionEvent( (int)event.getX(), (int)event.getY(), action, 0,
(int)(event.getPressure() * 1000.0),
(int)(event.getSize() * 1000.0) );
}
}
private static class MultiTouchInput extends DifferentTouchInput
{
public static final int TOUCH_EVENTS_MAX = 16; // Max multitouch pointers
private class touchEvent
{
public boolean down = false;
public int x = 0;
public int y = 0;
public int pressure = 0;
public int size = 0;
}
protected touchEvent touchEvents[];
MultiTouchInput()
{
touchEvents = new touchEvent[TOUCH_EVENTS_MAX];
for( int i = 0; i < TOUCH_EVENTS_MAX; i++ )
touchEvents[i] = new touchEvent();
}
private static class Holder
{
private static final MultiTouchInput sInstance = new MultiTouchInput();
}
public void processGenericEvent(final MotionEvent event)
{
process(event);
}
public void process(final MotionEvent event)
{
int action = -1;
//Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY());
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP ||
(event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_CANCEL )
{
action = Mouse.SDL_FINGER_UP;
for( int i = 0; i < TOUCH_EVENTS_MAX; i++ )
{
if( touchEvents[i].down )
{
touchEvents[i].down = false;
DemoGLSurfaceView.nativeMotionEvent( touchEvents[i].x, touchEvents[i].y, action, i, touchEvents[i].pressure, touchEvents[i].size );
}
}
}
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN )
{
action = Mouse.SDL_FINGER_DOWN;
for( int i = 0; i < event.getPointerCount(); i++ )
{
int id = event.getPointerId(i);
if( id >= TOUCH_EVENTS_MAX )
id = TOUCH_EVENTS_MAX - 1;
touchEvents[id].down = true;
touchEvents[id].x = (int)event.getX(i);
touchEvents[id].y = (int)event.getY(i);
touchEvents[id].pressure = (int)(event.getPressure(i) * 1000.0);
touchEvents[id].size = (int)(event.getSize(i) * 1000.0);
DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size );
}
}
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE ||
(event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN ||
(event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP )
{
/*
String s = "MOVE: ptrs " + event.getPointerCount();
for( int i = 0 ; i < event.getPointerCount(); i++ )
{
s += " p" + event.getPointerId(i) + "=" + (int)event.getX(i) + ":" + (int)event.getY(i);
}
Log.i("SDL", s);
*/
int pointerReleased = -1;
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP )
pointerReleased = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
for( int id = 0; id < TOUCH_EVENTS_MAX; id++ )
{
int ii;
for( ii = 0; ii < event.getPointerCount(); ii++ )
{
if( id == event.getPointerId(ii) )
break;
}
if( ii >= event.getPointerCount() )
{
// Up event
if( touchEvents[id].down )
{
action = Mouse.SDL_FINGER_UP;
touchEvents[id].down = false;
DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size );
}
}
else
{
if( pointerReleased == id && touchEvents[pointerReleased].down )
{
action = Mouse.SDL_FINGER_UP;
touchEvents[id].down = false;
}
else if( touchEvents[id].down )
{
action = Mouse.SDL_FINGER_MOVE;
}
else
{
action = Mouse.SDL_FINGER_DOWN;
touchEvents[id].down = true;
}
touchEvents[id].x = (int)event.getX(ii);
touchEvents[id].y = (int)event.getY(ii);
touchEvents[id].pressure = (int)(event.getPressure(ii) * 1000.0);
touchEvents[id].size = (int)(event.getSize(ii) * 1000.0);
DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size );
}
}
}
if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_HOVER_MOVE ) // Support bluetooth/USB mouse - available since Android 3.1
{
// TODO: it is possible that multiple pointers return that event, but we're handling only pointer #0
if( touchEvents[0].down )
action = Mouse.SDL_FINGER_UP;
else
action = Mouse.SDL_FINGER_HOVER;
touchEvents[0].down = false;
touchEvents[0].x = (int)event.getX();
touchEvents[0].y = (int)event.getY();
touchEvents[0].pressure = 0;
touchEvents[0].size = 0;
DemoGLSurfaceView.nativeMotionEvent( touchEvents[0].x, touchEvents[0].y, action, 0, touchEvents[0].pressure, touchEvents[0].size );
}
}
}
private static class GingerbreadTouchInput extends MultiTouchInput
{
private static class Holder
{
private static final GingerbreadTouchInput sInstance = new GingerbreadTouchInput();
}
GingerbreadTouchInput()
{
super();
}
public void process(final MotionEvent event)
{
boolean hwMouseEvent = ( (event.getSource() & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE ||
(event.getSource() & InputDevice.SOURCE_STYLUS) == InputDevice.SOURCE_STYLUS ||
(event.getMetaState() & KeyEvent.FLAG_TRACKING) != 0 ); // Hack to recognize Galaxy Note Gingerbread stylus
if( ExternalMouseDetected != hwMouseEvent )
{
ExternalMouseDetected = hwMouseEvent;
DemoGLSurfaceView.nativeHardwareMouseDetected(hwMouseEvent ? 1 : 0);
}
super.process(event);
}
public void processGenericEvent(final MotionEvent event)
{
process(event);
}
}
private static class IcsTouchInput extends GingerbreadTouchInput
{
private static class Holder
{
private static final IcsTouchInput sInstance = new IcsTouchInput();
}
private int buttonState = 0;
public void process(final MotionEvent event)
{
//Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY() + " buttons " + buttonState + " source " + event.getSource());
int buttonStateNew = event.getButtonState();
if( buttonStateNew != buttonState )
{
for( int i = 1; i <= MotionEvent.BUTTON_FORWARD; i *= 2 )
{
if( (buttonStateNew & i) != (buttonState & i) )
DemoGLSurfaceView.nativeMouseButtonsPressed(i, ((buttonStateNew & i) == 0) ? 0 : 1);
}
buttonState = buttonStateNew;
}
super.process(event); // Push mouse coordinate first
}
public void processGenericEvent(final MotionEvent event)
{
// Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it
if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK )
{
DemoGLSurfaceView.nativeGamepadAnalogJoystickInput(
event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y),
event.getAxisValue(MotionEvent.AXIS_Z), event.getAxisValue(MotionEvent.AXIS_RZ),
event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_LTRIGGER) );
return;
}
// Process mousewheel
if( event.getAction() == MotionEvent.ACTION_SCROLL )
{
int scrollX = Math.round(event.getAxisValue(MotionEvent.AXIS_HSCROLL));
int scrollY = Math.round(event.getAxisValue(MotionEvent.AXIS_VSCROLL));
DemoGLSurfaceView.nativeMouseWheel(scrollX, scrollY);
return;
}
super.processGenericEvent(event);
}
}
private static class CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad extends IcsTouchInput
{
private static class Holder
{
private static final CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad sInstance = new CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad();
}
float hatX = 0.0f, hatY = 0.0f;
public void processGenericEvent(final MotionEvent event)
{
// Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it
if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK )
{
// event.getAxisValue(AXIS_HAT_X) and event.getAxisValue(AXIS_HAT_Y) are joystick arrow keys, they also send keyboard events
DemoGLSurfaceView.nativeGamepadAnalogJoystickInput(
event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y),
event.getAxisValue(MotionEvent.AXIS_RX), event.getAxisValue(MotionEvent.AXIS_RZ),
0, 0);
if( event.getAxisValue(MotionEvent.AXIS_HAT_X) != hatX )
{
hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
if( hatX == 0.0f )
{
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_LEFT, 0);
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_RIGHT, 0);
}
else
DemoGLSurfaceView.nativeKey(hatX < 0.0f ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT, 1);
}
if( event.getAxisValue(MotionEvent.AXIS_HAT_Y) != hatY )
{
hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
if( hatY == 0.0f )
{
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_UP, 0);
DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_DOWN, 0);
}
else
DemoGLSurfaceView.nativeKey(hatY < 0.0f ? KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN, 1);
}
return;
}
super.processGenericEvent(event);
}
public boolean detect()
{
int[] devIds = InputDevice.getDeviceIds();
for( int id : devIds )
{
InputDevice device = InputDevice.getDevice(id);
if( device == null )
continue;
System.out.println("libSDL: input device ID " + id + " type " + device.getSources() + " name " + device.getName() );
if( (device.getSources() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD &&
(device.getSources() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK &&
device.getName().indexOf("DragonRise Inc") == 0 )
{
System.out.println("libSDL: Detected crappy DragonRise gamepad, enabling special hack for it. Please press button labeled 'Analog', otherwise it won't work, because it's cheap and crappy");
return true;
}
}
return false;
}
}
}
class DemoRenderer extends GLSurfaceView_SDL.Renderer
{
public DemoRenderer(MainActivity _context)
{
context = _context;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.i("SDL", "libSDL: DemoRenderer.onSurfaceCreated(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart );
mGlSurfaceCreated = true;
mGl = gl;
/*if( ! mPaused && ! mFirstTimeStart )
nativeGlContextRecreated();*/
mFirstTimeStart = false;
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
Log.i("SDL", "libSDL: DemoRenderer.onSurfaceChanged(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart + " w " + w + " h " + h);
if( w < h && Globals.HorizontalOrientation )
{
// Sometimes when Android awakes from lockscreen, portrait orientation is kept
int x = w;
w = h;
h = x;
}
mWidth = w;
mHeight = h;
mGl = gl;
//nativeResize(w, h, Globals.KeepAspectRatio ? 1 : 0);
}
public void onSurfaceDestroyed() {
Log.i("SDL", "libSDL: DemoRenderer.onSurfaceDestroyed(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart );
mGlSurfaceCreated = false;
mGlContextLost = true;
//nativeGlContextLost();
};
public void onDrawFrame(GL10 gl) {
mGl = gl;
DrawLogo(mGl);
SwapBuffers();
//nativeInitJavaCallbacks();
// Make main thread priority lower so audio thread won't get underrun
// Thread.currentThread().setPriority((Thread.currentThread().getPriority() + Thread.MIN_PRIORITY)/2);
mGlContextLost = false;
if(Globals.CompatibilityHacksStaticInit)
MainActivity.LoadApplicationLibrary(context);
Settings.Apply(context);
accelerometer = new AccelerometerReader(context);
// Tweak video thread priority, if user selected big audio buffer
if(Globals.AudioBufferConfig >= 2)
Thread.currentThread().setPriority( (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2 ); // Lower than normal
// Calls main() and never returns, hehe - we'll call eglSwapBuffers() from native code
/*nativeInit( Globals.DataDir,
Globals.CommandLine,
( (Globals.SwVideoMode && Globals.MultiThreadedVideo) || Globals.CompatibilityHacksVideo ) ? 1 : 0,
android.os.Debug.isDebuggerConnected() ? 1 : 0 );*/
//System.exit(0); // The main() returns here - I don't bother with deinit stuff, just terminate process
}
public int swapBuffers() // Called from native code
{
if( ! super.SwapBuffers() && Globals.NonBlockingSwapBuffers )
{
if(mRatelimitTouchEvents)
{
synchronized(this)
{
this.notify();
}
}
return 0;
}
if(mGlContextLost) {
mGlContextLost = false;
Settings.SetupTouchscreenKeyboardGraphics(context); // Reload on-screen buttons graphics
DrawLogo(mGl);
super.SwapBuffers();
}
// Unblock event processing thread only after we've finished rendering
if(mRatelimitTouchEvents)
{
synchronized(this)
{
this.notify();
}
}
/*if( context.isScreenKeyboardShown() )
{
try {
Thread.sleep(50); // Give some time to the keyboard input thread
} catch(Exception e) { };
}*/
return 1;
}
public void showScreenKeyboardWithoutTextInputField() // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public void run()
{
parent.showScreenKeyboardWithoutTextInputField();
}
}
Callback cb = new Callback();
cb.parent = context;
context.runOnUiThread(cb);
}
public void showScreenKeyboard(final String oldText, int sendBackspace) // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public String oldText;
public boolean sendBackspace;
public void run()
{
parent.showScreenKeyboard(oldText, sendBackspace);
}
}
Callback cb = new Callback();
cb.parent = context;
cb.oldText = oldText;
cb.sendBackspace = (sendBackspace != 0);
context.runOnUiThread(cb);
}
public void hideScreenKeyboard() // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public void run()
{
//parent.hideScreenKeyboard();
}
}
Callback cb = new Callback();
cb.parent = context;
context.runOnUiThread(cb);
}
public int isScreenKeyboardShown() // Called from native code
{
//return context.isScreenKeyboardShown() ? 1 : 0;
return 0;
}
public void setScreenKeyboardHintMessage(String s)
{
//context.setScreenKeyboardHintMessage(s);
}
public void startAccelerometerGyroscope(int started)
{
accelerometer.openedBySDL = (started != 0);
if( accelerometer.openedBySDL && !mPaused )
accelerometer.start();
else
accelerometer.stop();
}
public void exitApp()
{
//nativeDone();
}
public void getAdvertisementParams(int params[])
{
//context.getAdvertisementParams(params);
}
public void setAdvertisementVisible(int visible)
{
//context.setAdvertisementVisible(visible);
}
public void setAdvertisementPosition(int left, int top)
{
//context.setAdvertisementPosition(left, top);
}
public void requestNewAdvertisement()
{
//context.requestNewAdvertisement();
}
private int PowerOf2(int i)
{
int value = 1;
while (value < i)
value <<= 1;
return value;
}
public void DrawLogo(GL10 gl)
{
/*
// TODO: this not quite works, as it seems
BitmapDrawable bmp = null;
try
{
bmp = new BitmapDrawable(context.getAssets().open("logo.png"));
}
catch(Exception e)
{
bmp = new BitmapDrawable(context.getResources().openRawResource(R.drawable.publisherlogo));
}
int width = bmp.getBitmap().getWidth();
int height = bmp.getBitmap().getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * width * height);
//byteBuffer.order(ByteOrder.BIG_ENDIAN);
bmp.getBitmap().copyPixelsToBuffer(byteBuffer);
byteBuffer.position(0);
gl.glViewport(0, 0, mWidth, mHeight);
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1);
gl.glEnable(GL10.GL_TEXTURE_2D);
int textureName = -1;
int mTextureNameWorkspace[] = new int[1];
int mCropWorkspace[] = new int[4];
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
gl.glActiveTexture(textureName);
gl.glClientActiveTexture(textureName);
gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA,
PowerOf2(width), PowerOf2(height), 0,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, null);
gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0,
width, height,
GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, byteBuffer);
mCropWorkspace[0] = 0; // u
mCropWorkspace[1] = height; // v
mCropWorkspace[2] = width;
mCropWorkspace[3] = -height;
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
((GL11Ext) gl).glDrawTexiOES(0, -mHeight, 0, mWidth, mHeight);
gl.glActiveTexture(0);
gl.glClientActiveTexture(0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
gl.glDeleteTextures(1, mTextureNameWorkspace, 0);
gl.glFlush();
*/
}
//private native void nativeInitJavaCallbacks();
//private native void nativeInit(String CurrentPath, String CommandLine, int multiThreadedVideo, int isDebuggerConnected);
//private native void nativeResize(int w, int h, int keepAspectRatio);
//private native void nativeDone();
//private native void nativeGlContextLost();
//public native void nativeGlContextRecreated();
//public native void nativeGlContextLostAsyncEvent();
//public static native void nativeTextInput( int ascii, int unicode );
//public static native void nativeTextInputFinished();
private MainActivity context = null;
public AccelerometerReader accelerometer = null;
private GL10 mGl = null;
private EGL10 mEgl = null;
private EGLDisplay mEglDisplay = null;
private EGLSurface mEglSurface = null;
//private EGLContext mEglContext = null;
private boolean mGlContextLost = false;
public boolean mGlSurfaceCreated = false;
public boolean mPaused = false;
private boolean mFirstTimeStart = true;
public int mWidth = 0;
public int mHeight = 0;
public static final boolean mRatelimitTouchEvents = true; //(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO);
}
class DemoGLSurfaceView extends GLSurfaceView_SDL {
public DemoGLSurfaceView(MainActivity context) {
super(context);
mParent = context;
touchInput = DifferentTouchInput.getInstance();
setEGLConfigChooser(Globals.VideoDepthBpp, Globals.NeedDepthBuffer, Globals.NeedStencilBuffer, Globals.NeedGles2);
mRenderer = new DemoRenderer(context);
setRenderer(mRenderer);
}
@Override
public boolean onTouchEvent(final MotionEvent event)
{
touchInput.process(event);
if( DemoRenderer.mRatelimitTouchEvents )
{
limitEventRate(event);
}
return true;
};
@Override
public boolean onGenericMotionEvent (final MotionEvent event)
{
touchInput.processGenericEvent(event);
if( DemoRenderer.mRatelimitTouchEvents )
{
limitEventRate(event);
}
return true;
}
public void limitEventRate(final MotionEvent event)
{
// Wait a bit, and try to synchronize to app framerate, or event thread will eat all CPU and we'll lose FPS
// With Froyo the rate of touch events seems to be limited by OS, but they are arriving faster then we're redrawing anyway
if((event.getAction() == MotionEvent.ACTION_MOVE ||
event.getAction() == MotionEvent.ACTION_HOVER_MOVE))
{
synchronized(mRenderer)
{
try
{
mRenderer.wait(300L); // And sometimes the app decides not to render at all, so this timeout should not be big.
} catch (InterruptedException e) { }
}
}
}
public void exitApp() {
mRenderer.exitApp();
};
@Override
public void onPause() {
if(mRenderer.mPaused)
return;
mRenderer.mPaused = true;
//mRenderer.nativeGlContextLostAsyncEvent();
if( mRenderer.accelerometer != null ) // For some reason it crashes here often - are we getting this event before initialization?
mRenderer.accelerometer.stop();
super.onPause();
};
public boolean isPaused() {
return mRenderer.mPaused;
}
@Override
public void onResume() {
if(!mRenderer.mPaused)
return;
mRenderer.mPaused = false;
super.onResume();
Log.i("SDL", "libSDL: DemoGLSurfaceView.onResume(): mRenderer.mGlSurfaceCreated " + mRenderer.mGlSurfaceCreated + " mRenderer.mPaused " + mRenderer.mPaused);
/*if( mRenderer.mGlSurfaceCreated && ! mRenderer.mPaused || Globals.NonBlockingSwapBuffers )
mRenderer.nativeGlContextRecreated();*/
if( mRenderer.accelerometer != null && mRenderer.accelerometer.openedBySDL ) // For some reason it crashes here often - are we getting this event before initialization?
mRenderer.accelerometer.start();
};
// This seems like redundant code - it handled in MainActivity.java
@Override
public boolean onKeyDown(int keyCode, final KeyEvent event) {
//Log.i("SDL", "Got key down event, id " + keyCode + " meta " + event.getMetaState() + " event " + event.toString());
if( nativeKey( keyCode, 1 ) == 0 )
return super.onKeyDown(keyCode, event);
return true;
}
@Override
public boolean onKeyUp(int keyCode, final KeyEvent event) {
//Log.i("SDL", "Got key up event, id " + keyCode + " meta " + event.getMetaState());
if( nativeKey( keyCode, 0 ) == 0 )
return super.onKeyUp(keyCode, event);
return true;
}
DemoRenderer mRenderer;
MainActivity mParent;
DifferentTouchInput touchInput = null;
public static native void nativeMotionEvent( int x, int y, int action, int pointerId, int pressure, int radius );
public static native int nativeKey( int keyCode, int down );
public static native void nativeTouchpad( int x, int y, int down, int multitouch );
public static native void initJavaCallbacks();
public static native void nativeHardwareMouseDetected( int detected );
public static native void nativeMouseButtonsPressed( int buttonId, int pressedState );
public static native void nativeMouseWheel( int scrollX, int scrollY );
public static native void nativeGamepadAnalogJoystickInput( float stick1x, float stick1y, float stick2x, float stick2y, float rtrigger, float ltrigger );
}

View File

@@ -1,75 +0,0 @@
/*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.view.View;
import com.google.ads.*; // Copy GoogleAdMobAdsSdk.jar to the directory project/libs
class Advertisement
{
private AdView ad;
MainActivity parent;
public Advertisement(MainActivity p)
{
parent = p;
AdSize adSize = AdSize.BANNER;
if( Globals.AdmobBannerSize.equals("BANNER") )
adSize = AdSize.BANNER;
else if( Globals.AdmobBannerSize.equals("IAB_BANNER") )
adSize = AdSize.IAB_BANNER;
else if( Globals.AdmobBannerSize.equals("IAB_LEADERBOARD") )
adSize = AdSize.IAB_LEADERBOARD;
else if( Globals.AdmobBannerSize.equals("IAB_MRECT") )
adSize = AdSize.IAB_MRECT;
else if( Globals.AdmobBannerSize.equals("IAB_WIDE_SKYSCRAPER") )
adSize = AdSize.IAB_WIDE_SKYSCRAPER;
else if( Globals.AdmobBannerSize.equals("SMART_BANNER") )
adSize = AdSize.SMART_BANNER;
ad = new AdView(parent, adSize, Globals.AdmobPublisherId);
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(AdRequest.TEST_EMULATOR); // Copy GoogleAdMobAdsSdk.jar to the directory project/libs
adRequest.addTestDevice(Globals.AdmobTestDeviceId);
ad.loadAd(adRequest);
}
public View getView()
{
return ad;
}
public void requestNewAd()
{
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(AdRequest.TEST_EMULATOR); // Copy GoogleAdMobAdsSdk.jar to the directory project/libs
adRequest.addTestDevice(Globals.AdmobTestDeviceId);
ad.loadAd(adRequest);
}
}

View File

@@ -2,6 +2,8 @@
grep '<string name=' values/strings.xml | while read str; do
if echo "$str" | grep 'translatable="false"' ; then continue; fi
var=`echo $str | sed 's/<string name=["]\([^"]*\).*/\1/'`
text=`echo $str | sed 's/<string name=["][^"]*["]>\([^<]*\).*/\1/'`
if [ "$var" = "app_name" ]; then

View File

@@ -1,3 +1,3 @@
I''ve tired of using Google Translate to create random gibberish in the languages I don't know,
I've tired of using Google Translate to create random gibberish in the languages I don't know,
so from now on the only supported languages are English, Russian, Ukrainian, and French with some community support,
If you wish to maintain a translation - contact me, but I will want a continuous support, not just one-time translation.

View File

@@ -62,9 +62,9 @@
<string name="rightclick_menu">Menütaste</string>
<string name="rightclick_multitouch">Touch-Screen mit dem zweiten Finger</string>
<string name="rightclick_pressure">Touchscreen mit Kraft</string>
<string name="pointandclick_question">Erweiterte Funktionen</string>
<string name="pointandclick_keepaspectratio">Halten 4:3-Bildschirm Seitenverhältnis</string>
<string name="pointandclick_showcreenunderfinger">Show-Bildschirm unter dem Finger in einem separaten Fenster</string>
<string name="advanced">Erweiterte Funktionen</string>
<string name="mouse_keepaspectratio">Halten 4:3-Bildschirm Seitenverhältnis</string>
<string name="mouse_showcreenunderfinger">Show-Bildschirm unter dem Finger in einem separaten Fenster</string>
<string name="measurepressure_touchplease">Bitte schieben Sie den Finger über den Bildschirm für zwei Sekunden</string>
<string name="rightclick_none">Deaktivieren der rechten Maustaste</string>
<string name="leftclick_question">Linke Maustaste</string>
@@ -73,11 +73,11 @@
<string name="leftclick_multitouch">Touch-Screen mit dem zweiten Finger</string>
<string name="leftclick_pressure">Touchscreen mit Kraft</string>
<string name="leftclick_dpadcenter">Trackball klicken Select-Taste</string>
<string name="pointandclick_joystickmouse">Bewegen Sie die Maus mit Joystick oder Trackball</string>
<string name="mouse_joystickmouse">Bewegen Sie die Maus mit Joystick oder Trackball</string>
<string name="measurepressure_response">Pressure %1$03d Radius %2$03d</string>
<string name="click_with_dpadcenter">Linker Mausklick mit Trackball / Joystick Zentrum</string>
<string name="pointandclick_joystickmousespeed">Bewegen Sie die Maus mit Joystick-Geschwindigkeit</string>
<string name="pointandclick_joystickmouseaccel">Bewegen Sie die Maus mit Joystick-Beschleunigung</string>
<string name="mouse_joystickmousespeed">Bewegen Sie die Maus mit Joystick-Geschwindigkeit</string>
<string name="mouse_joystickmouseaccel">Bewegen Sie die Maus mit Joystick-Beschleunigung</string>
<string name="none">Keine</string>
<string name="controls_screenkb_transparency">On-Screen-Tastatur Transparenz</string>
<string name="controls_screenkb_trans_0">Nicht sichtbar</string>
@@ -108,7 +108,7 @@
<string name="screenkb_custom_layout">Passen Sie auf dem Bildschirm Tastatur-Layout</string>
<string name="screenkb_custom_layout_help">Slide-Bildschirm hinzufügen Taste, drücken Sie Menü zum letzten Knopf rückgängig machen</string>
<string name="rightclick_key">Physikalische Schlüssel</string>
<string name="pointandclick_showcreenunderfinger2">On-Screen-Lupe</string>
<string name="mouse_showcreenunderfinger2">On-Screen-Lupe</string>
<string name="video">Video-Einstellungen</string>
<string name="video_smooth">Glatte Video</string>
<string name="accel_veryslow">Sehr langsam</string>
@@ -121,9 +121,9 @@
<string name="leftclick_timeout_time_2">0,7 Sek.</string>
<string name="leftclick_timeout_time_3">1 Sek.</string>
<string name="leftclick_timeout_time_4">1,5 Sek.</string>
<string name="pointandclick_relative">Relative Bewegung der Maus (Laptop-Modus)</string>
<string name="pointandclick_relative_speed">Relative Maus Bewegungsgeschwindigkeit</string>
<string name="pointandclick_relative_accel">Relative Bewegung der Maus Beschleunigung</string>
<string name="mouse_relative">Relative Bewegung der Maus (Laptop-Modus)</string>
<string name="mouse_relative_speed">Relative Maus Bewegungsgeschwindigkeit</string>
<string name="mouse_relative_accel">Relative Bewegung der Maus Beschleunigung</string>
<string name="downloads">Downloads</string>
<string name="video_separatethread">Separaten Thread für Video, FPS bei einigen Geräten zu erhöhen</string>
<string name="text_edit_click_here">Tippen Sie auf der Eingabe beginnen, drücken Sie Zurück, wenn Sie fertig</string>
@@ -134,4 +134,24 @@
<string name="display_size_tiny">Uberklein (Xperia Mini)</string>
<string name="show_more_options">Weitere Optionen</string>
<string name="controls_screenkb_drawsize">Größe der Schaltfläche Bilder</string>
<string name="cancel">Cancel</string>
<string name="controls_screenkb_custom">Custom</string>
<string name="mouse_hover_jitter_filter">Filter jitter for stylus/finger hover</string>
<string name="remap_hwkeys_select_simple">Select action</string>
<string name="remap_hwkeys_select_more_keys">Show all keycodes</string>
<string name="display_size_small_touchpad">Small, touchpad mode</string>
<string name="display_size_tiny_touchpad">Tiny, touchpad mode</string>
<string name="hardware_mouse_detected">Hardware mouse detected, disabling mouse emulation</string>
<string name="not_enough_ram">Not enough RAM</string>
<string name="not_enough_ram_size">This app needs %1$d Mb RAM, your device has %2$d Mb</string>
<string name="ignore">Ignore</string>
<string name="calibrate_gyroscope">Calibrate gyroscope</string>
<string name="calibrate_gyroscope_text">Put your device on a flat surface</string>
<string name="calibrate_gyroscope_not_supported">Your device does not have gyroscope</string>
<string name="reset_config">Reset config to defaults</string>
<string name="reset_config_ask">Reset all options to default values?</string>
<string name="cancel_download">Cancel data downloading?</string>
<string name="cancel_download_resume">You can resume it later, the data will not be downloaded twice.</string>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>

View File

@@ -62,9 +62,9 @@
<string name="rightclick_menu">Valikkonäppäin</string>
<string name="rightclick_multitouch">Kosketusnäyttö on toinen sormi</string>
<string name="rightclick_pressure">Kosketusnäyttö voimalla</string>
<string name="pointandclick_question">Lisäominaisuudet</string>
<string name="pointandclick_keepaspectratio">Pidä 04:03 kuvasuhde</string>
<string name="pointandclick_showcreenunderfinger">Näytä näytön alle sormi erillisessä ikkunassa</string>
<string name="advanced">Lisäominaisuudet</string>
<string name="mouse_keepaspectratio">Pidä 04:03 kuvasuhde</string>
<string name="mouse_showcreenunderfinger">Näytä näytön alle sormi erillisessä ikkunassa</string>
<string name="measurepressure_touchplease">Ole hyvä ja liu\u0026#39;uttamalla sormea näytöllä kaksi sekuntia</string>
<string name="rightclick_none">Poista oikealla hiiren klikkauksella</string>
<string name="leftclick_question">Vasen hiiren nappi</string>
@@ -73,11 +73,11 @@
<string name="leftclick_multitouch">Kosketusnäyttö on toinen sormi</string>
<string name="leftclick_pressure">Kosketusnäyttö voimalla</string>
<string name="leftclick_dpadcenter">Trackball Valitse / Select-näppäintä</string>
<string name="pointandclick_joystickmouse">Siirrä hiiren ohjaimella tai trackball</string>
<string name="mouse_joystickmouse">Siirrä hiiren ohjaimella tai trackball</string>
<string name="measurepressure_response">Paine %1$03d säde %2$03d</string>
<string name="click_with_dpadcenter">Vasen hiiren klikkaus trackball-ohjaimella keskusta</string>
<string name="pointandclick_joystickmousespeed">Siirrä hiiri ohjainta nopeasti</string>
<string name="pointandclick_joystickmouseaccel">Siirrä hiiri ohjainta kiihtyvyys</string>
<string name="mouse_joystickmousespeed">Siirrä hiiri ohjainta nopeasti</string>
<string name="mouse_joystickmouseaccel">Siirrä hiiri ohjainta kiihtyvyys</string>
<string name="none">Ei</string>
<string name="controls_screenkb_transparency">Näyttönäppäimistöllä avoimuutta</string>
<string name="controls_screenkb_trans_0">Näkymätön</string>
@@ -108,7 +108,7 @@
<string name="screenkb_custom_layout">Mukauta-ruudun näppäimistö</string>
<string name="screenkb_custom_layout_help">Työnnä näytön lisätä painikkeen, paina Menu kumota viimeksi painike</string>
<string name="rightclick_key">Fyysinen avain</string>
<string name="pointandclick_showcreenunderfinger2">Näytöllä suurennuslasi</string>
<string name="mouse_showcreenunderfinger2">Näytöllä suurennuslasi</string>
<string name="video">Videon asetukset</string>
<string name="video_smooth">Tasainen video</string>
<string name="accel_veryslow">Erittäin hidas</string>
@@ -121,9 +121,9 @@
<string name="leftclick_timeout_time_2">0,7 sekuntia</string>
<string name="leftclick_timeout_time_3">1 sek</string>
<string name="leftclick_timeout_time_4">1,5 sek</string>
<string name="pointandclick_relative">Suhteellinen hiiren liikkeet (kannettavan tietokoneen tilassa)</string>
<string name="pointandclick_relative_speed">Suhteellinen hiiren liikkeen nopeus</string>
<string name="pointandclick_relative_accel">Suhteellinen hiiren liikkeen kiihtyvyys</string>
<string name="mouse_relative">Suhteellinen hiiren liikkeet (kannettavan tietokoneen tilassa)</string>
<string name="mouse_relative_speed">Suhteellinen hiiren liikkeen nopeus</string>
<string name="mouse_relative_accel">Suhteellinen hiiren liikkeen kiihtyvyys</string>
<string name="downloads">Downloads</string>
<string name="video_separatethread">Erillisessä säikeessä video, kasvaa FPS joissakin laitteissa</string>
<string name="text_edit_click_here">Napauta aloittaa kirjoittamisen, paina Takaisin, kun olet valmis</string>
@@ -134,4 +134,24 @@
<string name="display_size_tiny">Tiny (Xperia Mini)</string>
<string name="show_more_options">Näytä enemmän vaihtoehtoja</string>
<string name="controls_screenkb_drawsize">Koko painike kuvia</string>
<string name="cancel">Cancel</string>
<string name="controls_screenkb_custom">Custom</string>
<string name="mouse_hover_jitter_filter">Filter jitter for stylus/finger hover</string>
<string name="remap_hwkeys_select_simple">Select action</string>
<string name="remap_hwkeys_select_more_keys">Show all keycodes</string>
<string name="display_size_small_touchpad">Small, touchpad mode</string>
<string name="display_size_tiny_touchpad">Tiny, touchpad mode</string>
<string name="hardware_mouse_detected">Hardware mouse detected, disabling mouse emulation</string>
<string name="not_enough_ram">Not enough RAM</string>
<string name="not_enough_ram_size">This app needs %1$d Mb RAM, your device has %2$d Mb</string>
<string name="ignore">Ignore</string>
<string name="calibrate_gyroscope">Calibrate gyroscope</string>
<string name="calibrate_gyroscope_text">Put your device on a flat surface</string>
<string name="calibrate_gyroscope_not_supported">Your device does not have gyroscope</string>
<string name="reset_config">Reset config to defaults</string>
<string name="reset_config_ask">Reset all options to default values?</string>
<string name="cancel_download">Cancel data downloading?</string>
<string name="cancel_download_resume">You can resume it later, the data will not be downloaded twice.</string>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>

View File

@@ -0,0 +1,196 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- values-es/string.xml string resource in spanish languaje -->
<resources>
<string name="init">Inicializando</string>
<string name="please_wait">Por favor espere mientras se descargan los datos</string>
<string name="device_config">Configuración del dispositivo</string>
<string name="device_change_cfg">Cambiar la configuración del dispositivo</string>
<string name="download_unneeded">No se necesita descarga</string>
<string name="connecting_to">Conectándose a %s</string>
<string name="failed_connecting_to">Fallo al conectarse a %s</string>
<string name="error_connecting_to">Error al conectarse a %s</string>
<string name="dl_from">Descargándose datos desde %s</string>
<string name="error_dl_from">Error al descargarse los datos desde %s</string>
<string name="error_write">Error al escribir en %s</string>
<string name="dl_progress">%1$.0f%% hecho: archivo %2$s</string>
<string name="dl_finished">Finalizado</string>
<string name="storage_phone">Almacenamiento interno - %d MB libres</string>
<string name="storage_sd">Almacenamiento SD card - %d MB libres</string>
<string name="storage_custom">Especifique el directorio</string>
<string name="storage_commandline">Especifique los parámetros de la línea de comandos, one argument per line</string>
<string name="storage_question">Lugar donde guardar los datos de la instalación</string>
<string name="optional_downloads">Descargas</string>
<string name="downloads">Descargas</string>
<string name="ok">Aceptar</string>
<string name="cancel">Cancelar</string>
<string name="controls_arrows">Flechas / Joystick / Cruceta mando video consola</string>
<string name="controls_trackball">Bola de control (Trackball)</string>
<string name="controls_accel">Acelerómetro</string>
<string name="controls_touch">Sólo Tocando la pantalla</string>
<string name="controls_question">¿ Qué clase de teclas de navegación tiene su dispositivo ?</string>
<string name="controls_additional">Controles adicionales</string>
<string name="controls_screenkb">Teclado virtual en pantalla</string>
<string name="controls_accelnav">Acelerómetro</string>
<string name="controls_screenkb_size">Tamaño del teclado virtual en pantalla</string>
<string name="controls_screenkb_drawsize">Tamaño de las imágenes de los botones</string>
<string name="controls_screenkb_large">Grande</string>
<string name="controls_screenkb_medium">Mediano</string>
<string name="controls_screenkb_small">Pequeño</string>
<string name="controls_screenkb_tiny">Diminuto</string>
<string name="controls_screenkb_custom">Personalizado</string>
<string name="controls_screenkb_theme">Tema del teclado virtual en pantalla</string>
<string name="controls_screenkb_by">%1$s x %2$s</string>
<string name="controls_screenkb_transparency">Teclado virtual en pantalla transparente</string>
<string name="controls_screenkb_trans_0">Invisible</string>
<string name="controls_screenkb_trans_1">Semi invisible</string>
<string name="controls_screenkb_trans_2">Transparente</string>
<string name="controls_screenkb_trans_3">Semi transparente</string>
<string name="controls_screenkb_trans_4">Opaco</string>
<string name="trackball_no_dampening">Sin retardo (muy rápido)</string>
<string name="trackball_fast">Rápido</string>
<string name="trackball_medium">Mediano</string>
<string name="trackball_slow">Lento</string>
<string name="trackball_question">Retardo de la Bola control(Trackball)</string>
<string name="accel_veryfast">Muy rápido</string>
<string name="accel_fast">Rápido</string>
<string name="accel_medium">Mediano</string>
<string name="accel_slow">Lento</string>
<string name="accel_veryslow">Muy lento</string>
<string name="accel_question">Determinar velocidad accelerómetro</string>
<string name="accel_floating">Flotante</string>
<string name="accel_fixed_start">Fijo cuando la aplicación comienza</string>
<string name="accel_fixed_horiz">Fijar la orientación de la tablet</string>
<string name="accel_question_center">Centrar la posición del acelerómetro</string>
<string name="mouse_emulation">Emulación del ratón</string>
<string name="rightclick_question">Botón derecho del ratón</string>
<string name="rightclick_menu">Tecla de menú</string>
<string name="rightclick_key">Tecla física</string>
<string name="rightclick_multitouch">Tocar la pantalla con un segundo dedo</string>
<string name="rightclick_pressure">Tocar la pantalla durante un tiempo prolongado</string>
<string name="rightclick_none">Desabilitar el botón derecho del ratón</string>
<string name="leftclick_question">Botón izquierdo del ratón</string>
<string name="leftclick_normal">Normal</string>
<string name="leftclick_near_cursor">Tocar cerca del cursor del ratón</string>
<string name="leftclick_multitouch">Tocar la pantalla con un segundo dedo</string>
<string name="leftclick_pressure">Tocar la pantalla durante un tiempo prolongado</string>
<string name="leftclick_dpadcenter">Botón del Trackball / centrar joystick</string>
<string name="leftclick_timeout">Dejar de tocar y tocar la pantalla durante ...</string>
<string name="leftclick_tap">Un toque rápido (no tocar, tocar, y no tocar)</string>
<string name="leftclick_tap_or_timeout">Tocar o dejar de tocar</string>
<string name="leftclick_timeout_time">Mantener toque durante ...</string>
<string name="leftclick_timeout_time_0">0.3 sec</string>
<string name="leftclick_timeout_time_1">0.5 sec</string>
<string name="leftclick_timeout_time_2">0.7 sec</string>
<string name="leftclick_timeout_time_3">1 sec</string>
<string name="leftclick_timeout_time_4">1.5 sec</string>
<string name="click_with_dpadcenter">Botón izquierdo del ratón mediante: Bola(trackball)/centrar joystick</string>
<string name="advanced">Características avanzadas</string>
<string name="mouse_keepaspectratio">Mantenr proporción de la pantalla 4:3</string>
<string name="mouse_showcreenunderfinger">Mostrar la pantalla debajo del dedo en una ventana por separado</string>
<string name="mouse_showcreenunderfinger2">Mostrar lente de aumento sobre la pantalla</string>
<string name="mouse_joystickmouse">Mover el ratón mediante joystick o bola(trackball)</string>
<string name="mouse_joystickmousespeed">Mover el ratón mediante un joystick de velocidad</string>
<string name="mouse_joystickmouseaccel">Mover el ratón mediante un joystick de aceleración</string>
<string name="mouse_relative">Movimiento relativo del ratón (laptop mode)</string>
<string name="mouse_relative_speed">Velocidad relativa del movimiento del ratón</string>
<string name="mouse_relative_accel">Aceleración relativa del movimiento del ratón</string>
<string name="mouse_hover_jitter_filter">Filtro elimina nerviosismo al escribir/dedo flotante</string>
<string name="mouse_gyroscope_mouse">Controlar el ratón mediante el giroscopio</string>
<string name="mouse_gyroscope_mouse_sensitivity">Sensibilidad del giroscopio</string>
<string name="mouse_finger_hover">Dedo flotante deslizante</string>
<string name="mouse_subframe_touch_events">Múltiples eventos de toque por fotograma</string>
<string name="none">Nada</string>
<string name="measurepressure">Calibrar la presión del toque</string>
<string name="measurepressure_touchplease">Por favor deslice el dedo por la pantalla durante dos segundos</string>
<string name="measurepressure_response">Presión %1$03d radio %2$03d</string>
<string name="audiobuf_verysmall">Muy pequeña (dispositivos rápidos, menos retraso)</string>
<string name="audiobuf_small">Pequeña</string>
<string name="audiobuf_medium">Media</string>
<string name="audiobuf_large">Grande (dispositivos antiguos, si el sonido se entrecorta)</string>
<string name="audiobuf_question">Tamaño de la memoria de almacenamiento de audio</string>
<string name="remap_hwkeys">Cambiar teclas físicas</string>
<string name="remap_hwkeys_press">Presione una tecla excepto Botón central(HOME) y Botón encendido, puede usar las teclas de volumen</string>
<string name="remap_hwkeys_select">Seleccionar código de la tecla SDL</string>
<string name="remap_hwkeys_select_simple">Seleccionar acción</string>
<string name="remap_hwkeys_select_more_keys">Mostrar todos los códigos de teclas</string>
<string name="remap_screenkb">Cambiar controles de pulsación pantalla</string>
<string name="remap_screenkb_joystick">Joystick</string>
<string name="remap_screenkb_button">Botón</string>
<string name="remap_screenkb_button_text">Bótón para introducir texto</string>
<string name="remap_screenkb_button_gestures">Gestos con dos dedos</string>
<string name="remap_screenkb_button_gestures_sensitivity">Sensibilidad de gestos con dos dedos</string>
<string name="remap_screenkb_button_zoomin">Gesto para Zoom de aumento con dos dedos</string>
<string name="remap_screenkb_button_zoomout">Gesto prara Zoom de disminución con dos dedos</string>
<string name="remap_screenkb_button_rotateleft">Gesto para rotar a la izquierda con dos dedos</string>
<string name="remap_screenkb_button_rotateright">Gesto para rotar a la derecha con dos dedos</string>
<string name="screenkb_custom_layout">Pesonalizar la presentación del teclado virtual en pantalla</string>
<string name="screenkb_custom_layout_help">Presione botón Atras para finalizar. Cambiar tamaño botones deslizando sobre el espacio vacío.</string>
<string name="screenkb_floating_joystick">Joystick flotante</string>
<string name="calibrate_touchscreen">Calibrar el toque sobre la pantalla</string>
<string name="calibrate_touchscreen_touch">Toque todas las esquinas de la pantalla, puse botón Atras para finalizar</string>
<string name="video">Configuración de Video</string>
<string name="video_smooth">Filtro de lineas</string>
<string name="video_separatethread">Hebra/proceso separado para video, puede incrementar FPS, puede colgar la APP</string>
<string name="video_orientation_vertical">Orientación Horizontal/Vertical de la pantalla</string>
<string name="video_bpp_24">24 bits profundidad del color</string>
<string name="video_immersive">Ocultar botones de navegación(botones pantalla) / modo inmersión</string>
<string name="text_edit_click_here">Toque y suelte para empezar a teclear, presione botón Atras para finalizar</string>
<string name="display_size_mouse">Modo de emulación del ratón</string>
<string name="display_size">Tamaño de la pantalla para la emulación del ratón</string>
<string name="display_size_large">Grande (tablets)</string>
<string name="display_size_small">Pequeña, lupa de aumento</string>
<string name="display_size_small_touchpad">Pequeña, modo touchpad</string>
<string name="display_size_tiny">Diminuta</string>
<string name="display_size_tiny_touchpad">Diminuta, modo touchpad</string>
<string name="show_more_options">Mostrar más opciones</string>
<string name="hardware_mouse_detected">Detección del ratón real, desabilita emulación del ratón</string>
<string name="not_enough_ram">No hay suficiente memoria RAM</string>
<string name="not_enough_ram_size">Esta APP necesita %1$d Mb RAM, su dispositivo tiene %2$d Mb</string>
<string name="ignore">Ignorar</string>
<string name="calibrate_gyroscope">Calibrar giroscopio</string>
<string name="calibrate_gyroscope_text">Mantenga quieta la pantalla en una superficie plana, que no vibre</string>
<string name="calibrate_gyroscope_not_supported">Su dispositivo no tiene giroscopio</string>
<string name="reset_config">Resetear configuración a valores por defecto</string>
<string name="reset_config_ask">¿ Resetear todas las opciones a valores por defecto ?</string>
<string name="cancel_download">¿ Cancelar descarga de datos ?</string>
<string name="cancel_download_resume">Usted puede continuar después, los datos ya guardados no se descargarán otra vez.</string>
<string name="yes">Si</string>
<string name="no">No</string>
<!-- Play Game Services strings -->
<string name="gamehelper_sign_in_failed">Fallo al conectarse a la cuenta. Por favor chequee la conexión de la red e inténtelo de nuevo.</string>
<string name="gamehelper_app_misconfigured">La aplicacion esta incorrectamente configurada. Chequee que el nombre del paquete y certificado coincide con el ID de cliente creado en la Consola de Desarrollo. También, si la aplicación no esta todavía publicada, chequee que la cuenta que usted esta intentando acceder esta listada como cuenta de testeador. Vea registro de errores(logs) para más información.</string>
<string name="gamehelper_license_failed">Chequeo de licencia fallido.</string>
<string name="gamehelper_unknown_error">Error desconocido.</string>
<string name="accessing_network">Accediendo a la red, por favor espere</string>
</resources>

View File

@@ -19,7 +19,7 @@
<string name="storage_phone">Stockage interne - %d Mo de libre</string>
<string name="storage_sd">Carte SD - %d Mo de libre</string>
<string name="storage_custom">Choisir le répertoire</string>
<string name="storage_commandline">Choisir les paramètres de la ligne de commande</string>
<string name="storage_commandline">Choisir les paramètres de la ligne de commande, one argument per line</string>
<string name="storage_question">Où télécharger les données</string>
<string name="optional_downloads">Téléchargements</string>
<string name="downloads">Téléchargements</string>
@@ -98,16 +98,16 @@
<string name="leftclick_timeout_time_4">1,5 sec</string>
<string name="click_with_dpadcenter">Cliquez gauche de la souris avec le Trackball / centre du joystick </string>
<string name="pointandclick_question">Fonctionnalités avancées</string>
<string name="pointandclick_keepaspectratio">Gardez le format 4:3 écran</string>
<string name="pointandclick_showcreenunderfinger">Afficher l\'écran sous le doigt dans une fenêtre séparée</string>
<string name="pointandclick_showcreenunderfinger2">Loupe à l\'écran</string>
<string name="pointandclick_joystickmouse">Déplacez la souris avec un trackball ou le joystick</string>
<string name="pointandclick_joystickmousespeed">Déplacez la souris avec la vitesse du joystick</string>
<string name="pointandclick_joystickmouseaccel">Déplacez la souris avec l\'accélération du joystick</string>
<string name="pointandclick_relative">Mouvement relatif de la souris (mode portable)</string>
<string name="pointandclick_relative_speed">Vitesse relative de la souris</string>
<string name="pointandclick_relative_accel">Accélération relative de la souris</string>
<string name="advanced">Fonctionnalités avancées</string>
<string name="mouse_keepaspectratio">Gardez le format 4:3 écran</string>
<string name="mouse_showcreenunderfinger">Afficher l\'écran sous le doigt dans une fenêtre séparée</string>
<string name="mouse_showcreenunderfinger2">Loupe à l\'écran</string>
<string name="mouse_joystickmouse">Déplacez la souris avec un trackball ou le joystick</string>
<string name="mouse_joystickmousespeed">Déplacez la souris avec la vitesse du joystick</string>
<string name="mouse_joystickmouseaccel">Déplacez la souris avec l\'accélération du joystick</string>
<string name="mouse_relative">Mouvement relatif de la souris (mode portable)</string>
<string name="mouse_relative_speed">Vitesse relative de la souris</string>
<string name="mouse_relative_accel">Accélération relative de la souris</string>
<string name="none">Aucun</string>
@@ -173,4 +173,20 @@
<string name="no">No</string>
<string name="screenkb_custom_layout_help">Press BACK when done. Resize buttons by sliding on empty space.</string>
<string name="controls_screenkb_custom">Custom</string>
<string name="mouse_hover_jitter_filter">Filter jitter for stylus/finger hover</string>
<string name="remap_hwkeys_select_simple">Select action</string>
<string name="remap_hwkeys_select_more_keys">Show all keycodes</string>
<string name="mouse_gyroscope_mouse">Control mouse with gyroscope</string>
<string name="mouse_gyroscope_mouse_sensitivity">Gyroscope sensitivity</string>
<string name="mouse_finger_hover">Finger hover</string>
<string name="mouse_subframe_touch_events">Multiple touch events per video frame</string>
<string name="screenkb_floating_joystick">Floating joystick</string>
<string name="video_orientation_vertical">Portrait/vertical screen orientation</string>
<string name="video_bpp_24">24 bpp screen color depth</string>
<string name="video_immersive">Hide system navigation buttons / immersive mode</string>
<string name="gamehelper_sign_in_failed">Failed to sign in. Please check your network connection and try again.</string>
<string name="gamehelper_app_misconfigured">The application is incorrectly configured. Check that the package name and signing certificate match the client ID created in Developer Console. Also, if the application is not yet published, check that the account you are trying to sign in with is listed as a tester account. See logs for more information.</string>
<string name="gamehelper_license_failed">License check failed.</string>
<string name="gamehelper_unknown_error">Unknown error.</string>
<string name="accessing_network">Accessing network, please wait</string>
</resources>

View File

@@ -16,13 +16,14 @@
<string name="storage_phone">Внутреннее хранение - %d Мб</string>
<string name="storage_sd">SD карта - %d Мб</string>
<string name="storage_question">Куда сохранять данные приложения</string>
<string name="storage_access">Разрешение на запись на SD карту</string>
<string name="optional_downloads">Дополнительные загрузки</string>
<string name="ok">Продолжить</string>
<string name="controls_arrows">Стрелки / джойстик / Dpad</string>
<string name="controls_trackball">Трекбол</string>
<string name="controls_accel">Акселерометр</string>
<string name="controls_touch">Только сенсорный экран</string>
<string name="controls_question">Какие на телефоне клавиши навигации?</string>
<string name="controls_question">Какие на телефоне кнопки навигации?</string>
<string name="controls_additional">Дополнительные элементы управления</string>
<string name="controls_screenkb">Экранная клавиатура</string>
<string name="controls_accelnav">Акселерометр</string>
@@ -43,12 +44,12 @@
<string name="accel_slow">Медленно</string>
<string name="accel_question">Чувствительность акселерометра</string>
<string name="rightclick_question">Правая кнопка мыши</string>
<string name="rightclick_menu">Клавиша меню</string>
<string name="rightclick_menu">Кнопка меню</string>
<string name="rightclick_multitouch">Касание экрана вторым пальцем</string>
<string name="rightclick_pressure">Нажатие на экран с силой</string>
<string name="pointandclick_question">Расширенные функции</string>
<string name="pointandclick_keepaspectratio">Сохранять соотношение сторон 4:3 на экране</string>
<string name="pointandclick_showcreenunderfinger">Экранная лупа</string>
<string name="advanced">Расширенные функции</string>
<string name="mouse_keepaspectratio">Сохранять соотношение сторон 4:3 на экране</string>
<string name="mouse_showcreenunderfinger">Экранная лупа</string>
<string name="measurepressure_touchplease">Пожалуйста, проведите пальцем по экрану в течение двух секунд</string>
<string name="measurepressure_response">Давление %1$03d радиус %2$03d </string>
<string name="audiobuf_verysmall">Очень мало (быстрые устройства)</string>
@@ -67,10 +68,10 @@
<string name="leftclick_multitouch">Касание двумя пальцами</string>
<string name="leftclick_pressure">Нажатие с силой</string>
<string name="leftclick_dpadcenter">Нажатие на трекбол / центр джойстика</string>
<string name="pointandclick_joystickmouse">Перемещение мыши при помощи джойстика или трекбола</string>
<string name="mouse_joystickmouse">Перемещение мыши при помощи джойстика или трекбола</string>
<string name="click_with_dpadcenter">Левый клик мыши при помощи трекбола / центра джойстика</string>
<string name="pointandclick_joystickmousespeed">Перемещение мыши джойстиком - скорость</string>
<string name="pointandclick_joystickmouseaccel">Перемещение мыши джойстиком - ускорение</string>
<string name="mouse_joystickmousespeed">Перемещение мыши джойстиком - скорость</string>
<string name="mouse_joystickmouseaccel">Перемещение мыши джойстиком - ускорение</string>
<string name="none">Нет</string>
<string name="controls_screenkb_transparency">Прозрачность клавиатуры</string>
<string name="controls_screenkb_trans_0">Невидимый</string>
@@ -80,8 +81,8 @@
<string name="controls_screenkb_trans_4">Непрозрачные</string>
<string name="mouse_emulation">Эмуляции мыши</string>
<string name="measurepressure">Калибровка сенсорного давления</string>
<string name="remap_hwkeys">Переназначение физических клавиш</string>
<string name="remap_hwkeys_press">Нажмите любую клавишу, кроме HOME и POWER, вы можете использовать клавиши регулировки громкости</string>
<string name="remap_hwkeys">Переназначение физических кнопок</string>
<string name="remap_hwkeys_press">Нажмите любую клавишу, кроме HOME и POWER, вы можете использовать кнопки регулировки громкости</string>
<string name="remap_hwkeys_select">Выберите код кнопки SDL</string>
<string name="remap_screenkb">Переназначение экранных кнопок</string>
<string name="remap_screenkb_joystick">Экранный джойстик</string>
@@ -95,13 +96,13 @@
<string name="accel_veryfast">Очень быстро</string>
<string name="remap_screenkb_button_gestures_sensitivity">Чувствительность жеста двумя пальцами по экрану</string>
<string name="storage_custom">Укажите каталог</string>
<string name="storage_commandline">Укажите параметры командной строки</string>
<string name="storage_commandline">Параметры командной строки, каждый аргумент на отдельной строке</string>
<string name="calibrate_touchscreen">Калибровка сенсорного экрана</string>
<string name="calibrate_touchscreen_touch">Дотроньтесь до всех краев экрана, потом нажмите Назад/BACK</string>
<string name="screenkb_custom_layout">Настройка расположения кнопок</string>
<string name="screenkb_custom_layout_help">Нажмите клавишу Назад/BACK для завершения. Проведите по пустому месту, чтобы изменить размер кнопки</string>
<string name="screenkb_custom_layout_help">Нажмите кнопку Назад/BACK для завершения. Проведите по пустому месту, чтобы изменить размер кнопки</string>
<string name="rightclick_key">Физическая кнопка</string>
<string name="pointandclick_showcreenunderfinger2">Наэкранная лупа</string>
<string name="mouse_showcreenunderfinger2">Наэкранная лупа</string>
<string name="video">Настройки видео</string>
<string name="video_smooth">Линейное сглаживание видео</string>
<string name="accel_veryslow">Очень медленно</string>
@@ -114,9 +115,9 @@
<string name="leftclick_timeout_time_2">0,7 сек</string>
<string name="leftclick_timeout_time_3">1 сек</string>
<string name="leftclick_timeout_time_4">1,5 сек</string>
<string name="pointandclick_relative">Относительное движение мыши (режим ноутбука)</string>
<string name="pointandclick_relative_speed">Скорость движения мыши</string>
<string name="pointandclick_relative_accel">Ускорение движения мыши</string>
<string name="mouse_relative">Относительное движение мыши (режим ноутбука)</string>
<string name="mouse_relative_speed">Скорость движения мыши</string>
<string name="mouse_relative_accel">Ускорение движения мыши</string>
<string name="downloads">Загрузки</string>
<string name="video_separatethread">Отдельный поток для видео, увеличит FPS на некоторых устройствах</string>
<string name="text_edit_click_here">Нажмите, чтобы ввести текст, нажмите Назад, когда закончите</string>
@@ -146,4 +147,20 @@
<string name="yes">Да</string>
<string name="no">Нет</string>
<string name="controls_screenkb_custom">Пользовательские настройки</string>
<string name="mouse_hover_jitter_filter">Фильтровать дрожание при поднесении стилуса/пальца к экрану</string>
<string name="remap_hwkeys_select_simple">Выберите действие</string>
<string name="remap_hwkeys_select_more_keys">Показать все коды кнопок</string>
<string name="mouse_gyroscope_mouse">Control mouse with gyroscope</string>
<string name="mouse_gyroscope_mouse_sensitivity">Gyroscope sensitivity</string>
<string name="mouse_finger_hover">Finger hover</string>
<string name="mouse_subframe_touch_events">Multiple touch events per video frame</string>
<string name="screenkb_floating_joystick">Floating joystick</string>
<string name="video_orientation_vertical">Portrait/vertical screen orientation</string>
<string name="video_bpp_24">24 bpp screen color depth</string>
<string name="video_immersive">Hide system navigation buttons / immersive mode</string>
<string name="gamehelper_sign_in_failed">Failed to sign in. Please check your network connection and try again.</string>
<string name="gamehelper_app_misconfigured">The application is incorrectly configured. Check that the package name and signing certificate match the client ID created in Developer Console. Also, if the application is not yet published, check that the account you are trying to sign in with is listed as a tester account. See logs for more information.</string>
<string name="gamehelper_license_failed">License check failed.</string>
<string name="gamehelper_unknown_error">Unknown error.</string>
<string name="accessing_network">Accessing network, please wait</string>
</resources>

View File

@@ -16,6 +16,7 @@
<string name="storage_phone">Внутрішнє зберігання - %d Мб</string>
<string name="storage_sd">SD карта - %d Мб</string>
<string name="storage_question">Куди зберігати дані програми</string>
<string name="storage_access">Дозвіл на запис на SD карту</string>
<string name="optional_downloads">Додаткові завантаження</string>
<string name="ok">ОК</string>
<string name="controls_arrows">Стрілки / джойстік / Dpad</string>
@@ -46,9 +47,9 @@
<string name="rightclick_menu">Кнопка меню</string>
<string name="rightclick_multitouch">Торкання екрана другим пальцем</string>
<string name="rightclick_pressure">Натиск на екран силою</string>
<string name="pointandclick_question">Розширені функції</string>
<string name="pointandclick_keepaspectratio">Зберігати співвідношення сторін 4:3 на екрані</string>
<string name="pointandclick_showcreenunderfinger">Наекранна лупа</string>
<string name="advanced">Розширені функції</string>
<string name="mouse_keepaspectratio">Зберігати співвідношення сторін 4:3 на екрані</string>
<string name="mouse_showcreenunderfinger">Наекранна лупа</string>
<string name="measurepressure_touchplease">Будь-ласка, проведіть пальцем по екрану на протязі двох секунд</string>
<string name="measurepressure_response">Тиск %1$03d радіус %2$03d </string>
<string name="audiobuf_verysmall">Дуже мало (швидкі пристрої)</string>
@@ -67,10 +68,10 @@
<string name="leftclick_multitouch">Натиск на екран другим пальцем</string>
<string name="leftclick_pressure">>Натиск на екран з силою</string>
<string name="leftclick_dpadcenter">Натиск на трекбол / центр джойстику</string>
<string name="pointandclick_joystickmouse">Переміщення миші за допомогою джойстика або трекбола</string>
<string name="mouse_joystickmouse">Переміщення миші за допомогою джойстика або трекбола</string>
<string name="click_with_dpadcenter">Лівий клік миші за допомогою трекбола / центра джойстика</string>
<string name="pointandclick_joystickmousespeed">Переміщення миші джойстиком - швидкiсть</string>
<string name="pointandclick_joystickmouseaccel">Переміщення миші джойстиком - прискорення</string>
<string name="mouse_joystickmousespeed">Переміщення миші джойстиком - швидкiсть</string>
<string name="mouse_joystickmouseaccel">Переміщення миші джойстиком - прискорення</string>
<string name="none">Немає</string>
<string name="controls_screenkb_transparency">Прозорість клавіатури</string>
<string name="controls_screenkb_trans_0">Невидимий</string>
@@ -95,13 +96,13 @@
<string name="accel_veryfast">Дуже швидко</string>
<string name="remap_screenkb_button_gestures_sensitivity">Чутливість жесту двома пальцями по екрану</string>
<string name="storage_custom">Вкажіть каталог</string>
<string name="storage_commandline">Вкажіть параметри командного рядка</string>
<string name="storage_commandline">Вкажіть параметри командного рядка, кожен аргумент на окремому рядку</string>
<string name="calibrate_touchscreen">Калібрування сенсорного екрану</string>
<string name="calibrate_touchscreen_touch">Доторкнiться до всіх країв екрану, потiм натисніть Назад/BACK</string>
<string name="screenkb_custom_layout">Налаштування положення кнопок</string>
<string name="screenkb_custom_layout_help">Натисніть Назад/BACK для завершення. Проведiть по екрану, щоб змінити розмір кнопки</string>
<string name="rightclick_key">Фізична кнопка</string>
<string name="pointandclick_showcreenunderfinger2">Наекранна лупа</string>
<string name="mouse_showcreenunderfinger2">Наекранна лупа</string>
<string name="video">Налаштування відео</string>
<string name="video_smooth">Лінійне сглажування відео</string>
<string name="accel_veryslow">Дуже повільно</string>
@@ -114,9 +115,9 @@
<string name="leftclick_timeout_time_2">0,7 секунд</string>
<string name="leftclick_timeout_time_3">1 сек</string>
<string name="leftclick_timeout_time_4">1,5 сек</string>
<string name="pointandclick_relative">Відносний рух миші (режим ноутбука)</string>
<string name="pointandclick_relative_speed">Швидкість руху миші</string>
<string name="pointandclick_relative_accel">Прискорення руху миші</string>
<string name="mouse_relative">Відносний рух миші (режим ноутбука)</string>
<string name="mouse_relative_speed">Швидкість руху миші</string>
<string name="mouse_relative_accel">Прискорення руху миші</string>
<string name="downloads">Завантаження</string>
<string name="video_separatethread">Окремий потік для відео, збільшить FPS на деяких пристроях</string>
<string name="text_edit_click_here">Натисніть, щоб ввести текст, натисніть Назад, коли закiнчете</string>
@@ -145,4 +146,20 @@
<string name="yes">Так</string>
<string name="no">Ні</string>
<string name="controls_screenkb_custom">Налаштування користувача</string>
<string name="mouse_hover_jitter_filter">Фільтрувати тремтіння при піднесенні стилуса/пальця до екрану</string>
<string name="remap_hwkeys_select_simple">Виберіть дію</string>
<string name="remap_hwkeys_select_more_keys">Показати всі коди кнопок</string>
<string name="mouse_gyroscope_mouse">Control mouse with gyroscope</string>
<string name="mouse_gyroscope_mouse_sensitivity">Gyroscope sensitivity</string>
<string name="mouse_finger_hover">Finger hover</string>
<string name="mouse_subframe_touch_events">Multiple touch events per video frame</string>
<string name="screenkb_floating_joystick">Floating joystick</string>
<string name="video_orientation_vertical">Portrait/vertical screen orientation</string>
<string name="video_bpp_24">24 bpp screen color depth</string>
<string name="video_immersive">Hide system navigation buttons / immersive mode</string>
<string name="gamehelper_sign_in_failed">Failed to sign in. Please check your network connection and try again.</string>
<string name="gamehelper_app_misconfigured">The application is incorrectly configured. Check that the package name and signing certificate match the client ID created in Developer Console. Also, if the application is not yet published, check that the account you are trying to sign in with is listed as a tester account. See logs for more information.</string>
<string name="gamehelper_license_failed">License check failed.</string>
<string name="gamehelper_unknown_error">Unknown error.</string>
<string name="accessing_network">Accessing network, please wait</string>
</resources>

View File

@@ -0,0 +1,205 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Commander Genius</string>
<string name="init">初始化中</string>
<string name="please_wait">正在下载数据,请稍候</string>
<string name="device_config">设备配置</string>
<string name="device_change_cfg">更改设备配置</string>
<string name="download_unneeded">没有需要下载的内容</string>
<string name="connecting_to">正在连接到 %s</string>
<string name="failed_connecting_to">连接到 %s 失败</string>
<string name="error_connecting_to"> %s 连接出错</string>
<string name="dl_from">正在从 %s 下载数据</string>
<string name="error_dl_from">从 %s 下载数据时出错</string>
<string name="error_write">写入到 %s 时出错</string>
<string name="dl_progress">%1$.0f%% 已完成: 文件 %2$s</string>
<string name="dl_finished">已完成</string>
<string name="storage_phone">内部储存 - %d MB 空闲</string>
<string name="storage_sd">SD卡储存 - %d MB 空闲</string>
<string name="storage_custom">自定义目录</string>
<string name="storage_commandline">命令行参数,每行一个参数</string>
<string name="storage_question">数据文件安装位置</string>
<string name="optional_downloads">下载</string>
<string name="downloads">下载</string>
<string name="ok">完成</string>
<string name="cancel">取消</string>
<string name="controls_arrows">箭头 / 操纵杆 / 方向键</string>
<string name="controls_trackball">轨迹球</string>
<string name="controls_accel">加速度计</string>
<string name="controls_touch">只使用触屏</string>
<string name="controls_question">您的设备有哪些导航键?</string>
<string name="controls_additional">附加控制</string>
<string name="controls_screenkb">屏幕键盘</string>
<string name="controls_accelnav">加速度计</string>
<string name="controls_screenkb_size">屏幕键盘大小</string>
<string name="controls_screenkb_drawsize">按钮大小</string>
<string name="controls_screenkb_large"></string>
<string name="controls_screenkb_medium"></string>
<string name="controls_screenkb_small"></string>
<string name="controls_screenkb_tiny">微小</string>
<string name="controls_screenkb_custom">自定义</string>
<string name="controls_screenkb_theme">屏幕键盘主题</string>
<string name="controls_screenkb_by">%1$s by %2$s</string>
<string name="controls_screenkb_transparency">屏幕键盘透明度</string>
<string name="controls_screenkb_trans_0">隐形</string>
<string name="controls_screenkb_trans_1">半隐形</string>
<string name="controls_screenkb_trans_2">透明</string>
<string name="controls_screenkb_trans_3">半透明</string>
<string name="controls_screenkb_trans_4">不透明</string>
<string name="trackball_no_dampening">无阻碍</string>
<string name="trackball_fast"></string>
<string name="trackball_medium"></string>
<string name="trackball_slow"></string>
<string name="trackball_question">轨迹球阻碍</string>
<string name="accel_veryfast">非常快</string>
<string name="accel_fast"></string>
<string name="accel_medium"></string>
<string name="accel_slow"></string>
<string name="accel_veryslow">非常慢</string>
<string name="accel_question">加速度计灵敏度</string>
<string name="accel_floating">Floating</string>
<string name="accel_fixed_start">在应用程序启动时修复</string>
<string name="accel_fixed_horiz">Fixed to table desk orientation</string>
<string name="accel_question_center">加速度计中心位置</string>
<string name="mouse_emulation">鼠标模拟</string>
<string name="rightclick_question">单击鼠标右键</string>
<string name="rightclick_menu">菜单键</string>
<string name="rightclick_key">物理按键</string>
<string name="rightclick_multitouch">双指触摸</string>
<string name="rightclick_pressure">使用按压力度</string>
<string name="rightclick_none">禁用鼠标右键</string>
<string name="leftclick_question">鼠标左键单击</string>
<string name="leftclick_normal">正常</string>
<string name="leftclick_near_cursor">触摸靠近鼠标光标</string>
<string name="leftclick_multitouch">双指触摸</string>
<string name="leftclick_pressure">使用按压力度</string>
<string name="leftclick_dpadcenter">轨迹球点击 / 操纵杆中心</string>
<string name="leftclick_timeout">长按一个点</string>
<string name="leftclick_tap">点击</string>
<string name="leftclick_tap_or_timeout">点击或长按</string>
<string name="leftclick_timeout_time">长按超时</string>
<string name="leftclick_timeout_time_0">0.3 秒</string>
<string name="leftclick_timeout_time_1">0.5 秒</string>
<string name="leftclick_timeout_time_2">0.7 秒</string>
<string name="leftclick_timeout_time_3">1 秒</string>
<string name="leftclick_timeout_time_4">1.5 秒</string>
<string name="click_with_dpadcenter">左键点击和轨迹球点击 / 操纵杆中心</string>
<string name="advanced">高级功能</string>
<string name="mouse_keepaspectratio">保持4:3的屏幕宽高比</string>
<string name="mouse_showcreenunderfinger">在单独的窗口中显示屏幕</string>
<string name="mouse_showcreenunderfinger2">屏幕放大镜</string>
<string name="mouse_joystickmouse">使用操纵杆或轨迹球移动鼠标</string>
<string name="mouse_joystickmousespeed">使用操纵杆移动鼠标时的速度</string>
<string name="mouse_joystickmouseaccel">使用操纵杆加速移动鼠标</string>
<string name="mouse_relative">鼠标相对移动(笔记本模式)</string>
<string name="mouse_relative_speed">鼠标相对移动速度</string>
<string name="mouse_relative_accel">鼠标相对移动加速</string>
<string name="mouse_hover_jitter_filter">过滤指针/手指的抖动</string>
<string name="mouse_gyroscope_mouse">用陀螺仪控制鼠标移动</string>
<string name="mouse_gyroscope_mouse_sensitivity">陀螺仪灵敏度</string>
<string name="mouse_finger_hover">手指抖动</string>
<string name="mouse_subframe_touch_events">每一帧的多点触摸事件</string>
<string name="none"></string>
<string name="measurepressure">校准触摸屏压力</string>
<string name="measurepressure_touchplease">请将手指滑过屏幕两秒钟</string>
<string name="measurepressure_response">压力 %1$03d 半径 %2$03d</string>
<string name="audiobuf_verysmall">非常小(较新的设备,延迟低)</string>
<string name="audiobuf_small"></string>
<string name="audiobuf_medium">中等</string>
<string name="audiobuf_large">大(较老的设备,如果声音不稳定请选此项)</string>
<string name="audiobuf_question">音频缓冲大小</string>
<string name="remap_hwkeys">映射物理按键</string>
<string name="remap_hwkeys_press">按下任意按键 除了HOME键和POWER键如音量键</string>
<string name="remap_hwkeys_select">选择SDL按键</string>
<string name="remap_hwkeys_select_simple">选择动作</string>
<string name="remap_hwkeys_select_more_keys">显示所有按键</string>
<string name="remap_screenkb">映射屏幕控件</string>
<string name="remap_screenkb_joystick">手柄</string>
<string name="remap_screenkb_button">按钮</string>
<string name="remap_screenkb_button_text">文本输入按钮</string>
<string name="remap_screenkb_button_gestures">双指手势</string>
<string name="remap_screenkb_button_gestures_sensitivity">双指手势灵敏度</string>
<string name="remap_screenkb_button_zoomin">双指放大</string>
<string name="remap_screenkb_button_zoomout">双指缩小</string>
<string name="remap_screenkb_button_rotateleft">双指向左旋转</string>
<string name="remap_screenkb_button_rotateright">双指向右旋转</string>
<string name="screenkb_custom_layout">自定义屏幕键盘布局</string>
<string name="screenkb_custom_layout_help">按返回键结束,在空白区域滑动调整按钮大小</string>
<string name="screenkb_floating_joystick">浮动操纵杆</string>
<string name="calibrate_touchscreen">校准触摸屏</string>
<string name="calibrate_touchscreen_touch">触摸屏幕的所有边缘,按返回键结束</string>
<string name="video">视频选项</string>
<string name="video_smooth">线性过滤</string>
<string name="video_separatethread">用单线程处理视频可能会提高FPS也可能使程序崩溃</string>
<string name="video_orientation_vertical">切换横屏/竖屏</string>
<string name="video_orientation_autodetect">自动检测屏幕方向</string>
<string name="video_bpp_24">24 bpp颜色深度</string>
<string name="video_immersive">隐藏系统导航按钮/沉浸模式</string>
<string name="tv_borders">电视边框</string>
<string name="text_edit_click_here">点击开始输入,按返回键结束</string>
<string name="display_size_mouse">鼠标仿真模式</string>
<string name="display_size">显示仿真鼠标的大小</string>
<string name="display_size_desktop">桌面版,无仿真</string>
<string name="display_size_large">大(适用于平板电脑)</string>
<string name="display_size_small">小,放大镜</string>
<string name="display_size_small_touchpad">小,触摸模式</string>
<string name="display_size_tiny">很小</string>
<string name="display_size_tiny_touchpad">很小,触摸模式</string>
<string name="show_more_options">显示更多选项</string>
<string name="hardware_mouse_detected">检测到鼠标硬件,禁用鼠标仿真</string>
<string name="not_enough_ram">没有足够的 RAM</string>
<string name="not_enough_ram_size">本程序需要 %1$d Mb 的RAM您的设备有 %2$d Mb</string>
<string name="ignore">忽略</string>
<string name="calibrate_gyroscope">校准陀螺仪</string>
<string name="calibrate_gyroscope_text">将您的设备放在水平表面上</string>
<string name="calibrate_gyroscope_not_supported">您的设备没有陀螺仪</string>
<string name="reset_config">将所有配置重置为默认值</string>
<string name="reset_config_ask">是否将所有选项重置为默认值?</string>
<string name="cancel_download">是否取消数据下载?</string>
<string name="cancel_download_resume">您可以稍后恢复它,数据不会被下载两次。</string>
<string name="yes"></string>
<string name="no"></string>
<!-- Play Game Services strings -->
<string name="gamehelper_sign_in_failed">无法登录,请检查您的网络连接,然后重试。</string>
<string name="gamehelper_app_misconfigured">应用程序配置不正确。请检查包名和签名证书是否与开发者控制台中创建的客户端ID一致。此外如果应用程序尚未发布请检查您的帐户是否为测试人员帐户。详细信息请参阅日志。</string>
<string name="gamehelper_license_failed">许可证检查失败。</string>
<string name="gamehelper_unknown_error">未知错误。</string>
<string name="accessing_network">正在访问网络,请稍候</string>
<string name="restarting_please_wait">重新启动中,请稍候。</string>
<string name="notification_app_is_running">%s 正在运行中</string>
<string name="notification_stop">停止</string>
</resources>

View File

@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingTranslation">
<string name="app_name">Commander Genius</string>
@@ -22,8 +24,9 @@
<string name="storage_phone">Internal storage - %d MB free</string>
<string name="storage_sd">SD card storage - %d MB free</string>
<string name="storage_custom">Specify directory</string>
<string name="storage_commandline">Specify command line parameters</string>
<string name="storage_commandline">Command line parameters, one argument per line</string>
<string name="storage_question">Data installation location</string>
<string name="storage_access">Permission to write to SD card</string>
<string name="optional_downloads">Downloads</string>
<string name="downloads">Downloads</string>
<string name="ok">OK</string>
@@ -98,16 +101,21 @@
<string name="leftclick_timeout_time_4">1.5 sec</string>
<string name="click_with_dpadcenter">Left mouse click with trackball / joystick center</string>
<string name="pointandclick_question">Advanced features</string>
<string name="pointandclick_keepaspectratio">Keep 4:3 screen aspect ratio</string>
<string name="pointandclick_showcreenunderfinger">Show screen under finger in separate window</string>
<string name="pointandclick_showcreenunderfinger2">On-screen magnifying glass</string>
<string name="pointandclick_joystickmouse">Move mouse with joystick or trackball</string>
<string name="pointandclick_joystickmousespeed">Move mouse with joystick speed</string>
<string name="pointandclick_joystickmouseaccel">Move mouse with joystick acceleration</string>
<string name="pointandclick_relative">Relative mouse movement (laptop mode)</string>
<string name="pointandclick_relative_speed">Relative mouse movement speed</string>
<string name="pointandclick_relative_accel">Relative mouse movement acceleration</string>
<string name="advanced">Advanced features</string>
<string name="mouse_keepaspectratio">Keep 4:3 screen aspect ratio</string>
<string name="mouse_showcreenunderfinger">Show screen under finger in separate window</string>
<string name="mouse_showcreenunderfinger2">On-screen magnifying glass</string>
<string name="mouse_joystickmouse">Move mouse with joystick or trackball</string>
<string name="mouse_joystickmousespeed">Move mouse with joystick speed</string>
<string name="mouse_joystickmouseaccel">Move mouse with joystick acceleration</string>
<string name="mouse_relative">Relative mouse movement (laptop mode)</string>
<string name="mouse_relative_speed">Relative mouse movement speed</string>
<string name="mouse_relative_accel">Relative mouse movement acceleration</string>
<string name="mouse_hover_jitter_filter">Filter jitter for stylus/finger hover</string>
<string name="mouse_gyroscope_mouse">Control mouse with gyroscope</string>
<string name="mouse_gyroscope_mouse_sensitivity">Gyroscope sensitivity</string>
<string name="mouse_finger_hover">Finger hover</string>
<string name="mouse_subframe_touch_events">Multiple touch events per video frame</string>
<string name="none">None</string>
@@ -140,18 +148,25 @@
<string name="screenkb_custom_layout">Customize on-screen keyboard layout</string>
<string name="screenkb_custom_layout_help">Press BACK when done. Resize buttons by sliding on empty space.</string>
<string name="screenkb_floating_joystick">Floating joystick</string>
<string name="calibrate_touchscreen">Calibrate touchscreen</string>
<string name="calibrate_touchscreen_touch">Touch all edges of the screen, press BACK when done</string>
<string name="video">Video settings</string>
<string name="video_smooth">Linear video filtering</string>
<string name="video_separatethread">Separate thread for video, will increase FPS on some devices</string>
<string name="video_separatethread">Separate thread for video, it can increase FPS, it also can crash the app</string>
<string name="video_orientation_vertical">Portrait/vertical screen orientation</string>
<string name="video_orientation_autodetect">Auto-detect screen orientation</string>
<string name="video_bpp_24">24 bpp screen color depth</string>
<string name="video_immersive">Hide system navigation buttons / immersive mode</string>
<string name="tv_borders">TV borders</string>
<string name="text_edit_click_here">Tap to start typing, press Back when done</string>
<string name="display_size_mouse">Mouse emulation mode</string>
<string name="display_size">Display size for mouse emulation</string>
<string name="display_size_desktop">Desktop, no emulation</string>
<string name="display_size_large">Large (tablets)</string>
<string name="display_size_small">Small, magnifying glass</string>
<string name="display_size_small_touchpad">Small, touchpad mode</string>
@@ -178,4 +193,18 @@
<string name="yes">Yes</string>
<string name="no">No</string>
<!-- Play Game Services strings -->
<string name="gamehelper_sign_in_failed">Failed to sign in. Please check your network connection and try again.</string>
<string name="gamehelper_app_misconfigured">The application is incorrectly configured. Check that the package name and signing certificate match the client ID created in Developer Console. Also, if the application is not yet published, check that the account you are trying to sign in with is listed as a tester account. See logs for more information.</string>
<string name="gamehelper_license_failed">License check failed.</string>
<string name="gamehelper_unknown_error">Unknown error.</string>
<string name="accessing_network">Accessing network, please wait</string>
<string name="google_play_game_services_app_id" translatable="false">==GOOGLEPLAYGAMESERVICES_APP_ID==</string>
<string name="restarting_please_wait">Restarting, please wait.</string>
<string name="notification_app_is_running">%s is running</string>
<string name="notification_stop">Stop</string>
</resources>

View File

@@ -12,4 +12,19 @@ endif
NDK_PATH := $(shell dirname $(shell which ndk-build))
include $(call all-subdir-makefiles)
NDK_SUBDIR_MAKEFILES_FULL := $(call all-subdir-makefiles)
# If you want to exclude certain subprojects from the build process.
# v.g.: SDL2_image already brings it's own implementation of png, so we exclude the bundled one
ifeq ($(SDL_VERSION),2.0)
BLACKLISTED_SUBPROJECTS := jpeg png ogg mpg123 timidity fluidsynth faad openal sdl_blitpool sdl_gfx sdl_image sdl_main sdl_mixer sdl_net sdl_sound sdl_ttf zzip freetype
else
BLACKLISTED_SUBPROJECTS := sdl2_image
endif
BLACKLISTED_MAKEFILES := $(addprefix jni/../jni/,$(BLACKLISTED_SUBPROJECTS))
BLACKLISTED_MAKEFILES := $(addsuffix /Android.mk,$(BLACKLISTED_MAKEFILES))
NDK_SUBDIR_MAKEFILES := $(filter-out $(BLACKLISTED_MAKEFILES), $(NDK_SUBDIR_MAKEFILES_FULL))
include $(NDK_SUBDIR_MAKEFILES)

View File

@@ -45,10 +45,15 @@ ifneq ($(APPLICATION_CUSTOM_BUILD_SCRIPT),)
LOCAL_SRC_FILES := dummy.c
endif
ifeq ($(SDL_VERSION),2.0)
LOCAL_SHARED_LIBRARIES := SDL2 $(filter-out $(APP_AVAILABLE_STATIC_LIBS), $(COMPILED_LIBRARIES))
else
LOCAL_SHARED_LIBRARIES := sdl-$(SDL_VERSION) $(filter-out $(APP_AVAILABLE_STATIC_LIBS), $(COMPILED_LIBRARIES))
endif
LOCAL_STATIC_LIBRARIES := $(filter $(APP_AVAILABLE_STATIC_LIBS), $(COMPILED_LIBRARIES))
LOCAL_LDLIBS := $(APPLICATION_GLES_LIBRARY) -ldl -llog -lz
LOCAL_LDFLAGS := -Lobj/local/$(TARGET_ARCH_ABI)

View File

@@ -7,10 +7,10 @@ AppName="Commander Genius"
AppFullName=net.sourceforge.clonekeenplus
# Application version code (integer)
AppVersionCode=207010
AppVersionCode=282000
# Application user-visible version name (string)
AppVersionName="2.0.7 Release"
AppVersionName="2.8.2 Release"
# Specify path to download application data in zip archive in the form 'Description|URL|MirrorURL^Description2|URL2|MirrorURL2^...'
# If you'll start Description with '!' symbol it will be enabled by default, other downloads should be selected by user from startup config menu
@@ -31,7 +31,7 @@ DeleteFilesOnUpgrade="%"
ReadmeText='^You may press "Home" now - the data will be downloaded in background'
# libSDL version to use (1.2/1.3/2.0)
LibSdlVersion=1.2
LibSdlVersion=2.0
# Specify screen orientation: (v)ertical/(p)ortrait or (h)orizontal/(l)andscape
ScreenOrientation=h
@@ -201,8 +201,9 @@ FirstStartMenuOptions=''
# Enable multi-ABI binary, with hardware FPU support - it will also work on old devices,
# but .apk size is 2x bigger (y) / (n) / (x86) / (all)
MultiABI='armeabi-v7a'
#MultiABI='y'
#MultiABI='armeabi-v7a'
#MultiABI='arm64-v8a'
MultiABI='y'
# Minimum amount of RAM application requires, in Mb, SDL will print warning to user if it's lower
AppMinimumRAM=64
@@ -210,16 +211,17 @@ AppMinimumRAM=64
# Optional shared libraries to compile - removing some of them will save space
# MP3 support by libMAD is encumbered by patents and libMAD is GPL-ed
# Available libraries: mad (GPL-ed!) sdl_mixer sdl_image sdl_ttf sdl_net sdl_blitpool sdl_gfx sdl_sound intl xml2 lua jpeg png ogg flac tremor vorbis freetype xerces curl theora fluidsynth lzma lzo2 mikmod openal timidity zzip bzip2 yaml-cpp python boost_date_time boost_filesystem boost_iostreams boost_program_options boost_regex boost_signals boost_system boost_thread glu avcodec avdevice avfilter avformat avresample avutil swscale swresample bzip2
CompiledLibraries="sdl_image sdl_mixer boost_system crypto ssl curl vorbis ogg"
#CompiledLibraries="sdl2_image sdl_mixer crypto ssl curl"
CompiledLibraries="c++_shared SDL2_mixer SDL2_image SDL2_ttf curl ssl crypto"
# Application uses custom build script AndroidBuild.sh instead of Android.mk (y) or (n)
CustomBuildScript=n
# Aditional CFLAGS for application
AppCflags='-frtti -fexceptions -finline-functions -DOGG=1 -DUSE_FILE32API -DDOWNLOADER=1 -DANDROID=1 -DREFKEEN_VER_KDREAMS -DGRMODE=EGAGR -DREFKEEN_VER_KDREAMS_ANYEGA_ALL -DIOAPI_NO_64 -DBUILD_TYPE=LINUX -DTARGET_LNX=1 -DNOTYPESAVE -Werror=strict-aliasing -Werror=cast-align -Werror=pointer-arith -Werror=address -std=c99 -Ijni/../jni/application/commandergenius/commandergenius/GsKit -Ijni/vorbis/include/vorbis -Ijni/curl/include'
AppCflags='-frtti -fexceptions -finline-functions -DFORCE_HTTPS -DOGG=1 -DLUA_USE_POSIX -DUSE_FILE32API -DDOWNLOADER=1 -DANDROID=1 -DREFKEEN_VER_KDREAMS -DGRMODE=EGAGR -DREFKEEN_VER_KDREAMS_ANYEGA_ALL -DIOAPI_NO_64 -DBUILD_TYPE=LINUX -DTARGET_LNX=1 -DNOTYPESAVE -Werror=strict-aliasing -Werror=pointer-arith -Werror=address -std=c99 -Ijni/../jni/application/commandergenius/commandergenius/GsKit -Ijni/vorbis/include/vorbis -Ijni/curl/include'
# Aditional CXXFLAGS for application
AppCppflags='-frtti -fexceptions -finline-functions -DOGG=1 -DUSE_FILE32API -DDOWNLOADER=1 -DANDROID=1 -DREFKEEN_VER_KDREAMS -DGRMODE=EGAGR -DREFKEEN_VER_KDREAMS_ANYEGA_ALL -DIOAPI_NO_64 -DBUILD_TYPE=LINUX -DTARGET_LNX=1 -DNOTYPESAVE -Werror=strict-aliasing -Werror=cast-align -Werror=pointer-arith -Werror=address -std=c++14 -Ijni/../jni/application/commandergenius/commandergenius/GsKit -Ijni/vorbis/include/vorbis -Ijni/curl/include'
AppCppflags='-frtti -fexceptions -finline-functions -DFORCE_HTTPS -DOGG=1 -DUSE_FILE32API -DUSE_VIRTUALPAD -DDOWNLOADER=1 -DANDROID=1 -DREFKEEN_VER_KDREAMS -DGRMODE=EGAGR -DREFKEEN_VER_KDREAMS_ANYEGA_ALL -DIOAPI_NO_64 -DBUILD_TYPE=LINUX -DTARGET_LNX=1 -DNOTYPESAVE -DDISABLE_HOVER -Werror=strict-aliasing -Werror=cast-align -Werror=pointer-arith -Werror=address -std=c++14 -Ijni/../jni/application/commandergenius/commandergenius/GsKit'
# Additional LDFLAGS for application
@@ -235,7 +237,7 @@ AppOverlapsSystemHeaders=
AppSubdirsBuild='commandergenius/src/* commandergenius/GsKit/*'
# Exclude these files from build
AppBuildExclude='commandergenius/src/engine/dbfusion'
AppBuildExclude=''
# Application command line parameters, including app name as 0-th param
AppCmdline=''

Binary file not shown.

Before

Width:  |  Height:  |  Size: 315 B

View File

@@ -1,12 +1,12 @@
# The application settings for Android libSDL port
AppSettingVersion=17
LibSdlVersion=1.3
LibSdlVersion=2.0
AppName="SDL sprite test"
AppFullName=net.sdl.testsprite
ScreenOrientation=h
InhibitSuspend=n
AppDataDownloadUrl="Game data is 1 Mb|ballfield2.zip"
VideoDepthBpp=16
VideoDepthBpp=32
NeedDepthBuffer=n
NeedStencilBuffer=n
NeedGles2=n
@@ -32,15 +32,16 @@ RedefinedKeysScreenKb="1 2 3 4 5 6 1 2 3 4"
StartupMenuButtonTimeout=3000
HiddenMenuOptions='OptionalDownloadConfig'
FirstStartMenuOptions=''
MultiABI=n
MultiABI=y
AppVersionCode=101
AppVersionName="1.01"
ResetSdlConfigForThisVersion=n
DeleteFilesOnUpgrade="%"
CompiledLibraries="sdl_mixer sdl_image"
CompiledLibraries="c++_shared SDL2_mixer SDL2_image"
CustomBuildScript=n
AppCflags='-O2 -finline-functions'
AppLdflags=''
AppSubdirsBuild=''
AppCmdline=''
ReadmeText='^Readme text'
AppMinimumRAM=64

View File

@@ -0,0 +1,198 @@
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "icon.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define NUM_SPRITES 100
#define MAX_SPEED 1
static SDL_Texture *sprite;
static SDL_Rect positions[NUM_SPRITES];
static SDL_Rect velocities[NUM_SPRITES];
static int sprite_w, sprite_h;
SDL_Renderer *renderer;
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
exit(rc);
}
int
LoadSprite(char *file, SDL_Renderer *renderer)
{
SDL_Surface *temp;
/* Load the sprite image */
//temp = SDL_LoadBMP(file);
SDL_RWops *rw = SDL_RWFromMem(icon_bmp, icon_bmp_len);
temp = SDL_LoadBMP_RW(rw, 1);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", file, SDL_GetError());
return (-1);
}
sprite_w = temp->w;
sprite_h = temp->h;
/* Set transparent pixel as the pixel at (0,0) */
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
/* Create textures from the image */
sprite = SDL_CreateTextureFromSurface(renderer, temp);
if (!sprite) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return (-1);
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return (0);
}
void
MoveSprites(SDL_Renderer * renderer, SDL_Texture * sprite)
{
int i;
int window_w = WINDOW_WIDTH;
int window_h = WINDOW_HEIGHT;
SDL_Rect *position, *velocity;
/* Draw a gray background */
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
/* Move the sprite, bounce at the wall, and draw */
for (i = 0; i < NUM_SPRITES; ++i) {
position = &positions[i];
velocity = &velocities[i];
position->x += velocity->x;
if ((position->x < 0) || (position->x >= (window_w - sprite_w))) {
velocity->x = -velocity->x;
position->x += velocity->x;
}
position->y += velocity->y;
if ((position->y < 0) || (position->y >= (window_h - sprite_h))) {
velocity->y = -velocity->y;
position->y += velocity->y;
}
/* Blit the sprite onto the screen */
SDL_RenderCopy(renderer, sprite, NULL, position);
}
/* Update the screen! */
SDL_RenderPresent(renderer);
}
void loop()
{
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT || event.type == SDL_KEYDOWN) {
done = 1;
}
}
MoveSprites(renderer, sprite);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
SDL_Window *window;
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_HEIGHT, 0, &window, &renderer) < 0) {
quit(2);
}
if (LoadSprite("icon.bmp", renderer) < 0) {
quit(2);
}
/* Initialize the sprite positions */
srand(time(NULL));
for (i = 0; i < NUM_SPRITES; ++i) {
positions[i].x = rand() % (WINDOW_WIDTH - sprite_w);
positions[i].y = rand() % (WINDOW_HEIGHT - sprite_h);
positions[i].w = sprite_w;
positions[i].h = sprite_h;
velocities[i].x = 0;
velocities[i].y = 0;
while (!velocities[i].x && !velocities[i].y) {
velocities[i].x = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
velocities[i].y = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
}
}
/* Main render loop */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
quit(0);
return 0; /* to prevent compiler warning */
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -82,10 +82,12 @@ LOCAL_MODULE:= libcurl
LOCAL_MODULE_FILENAME := libcurl-sdl # It clashes with system libcurl in Android 4.3 and older
LOCAL_SHARED_LIBRARIES := ssl crypto
#LOCAL_SHARED_LIBRARIES := ssl crypto
LOCAL_STATIC_LIBRARIES := ssl crypto
LOCAL_LDLIBS := -lz
include $(BUILD_SHARED_LIBRARY)
#include $(BUILD_SHARED_LIBRARY)
include $(BUILD_STATIC_LIBRARY)
endif

View File

@@ -7,20 +7,23 @@ LOCAL_MODULE := $(notdir $(LOCAL_PATH))
ifneq (openssl,$(LOCAL_MODULE))
ifneq ($(filter $(LOCAL_MODULE), $(APP_MODULES)),)
LOCAL_MODULE_FILENAME := lib$(notdir $(LOCAL_PATH)).so.sdl.1 # It clashes with system libcrypto and libssl in Android 4.3 and older
#LOCAL_MODULE_FILENAME := lib$(notdir $(LOCAL_PATH)).so.sdl.1 # It clashes with system libcrypto and libssl in Android 4.3 and older
#LOCAL_MODULE_FILENAME := lib$(notdir $(LOCAL_PATH)).a.sdl.1 # It clashes with system libcrypto and libssl in Android 4.3 and older
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := lib-$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.1.so
#LOCAL_SRC_FILES := lib-$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.1.so
LOCAL_SRC_FILES := lib-$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).a
LOCAL_BUILT_MODULE := # This fixes a bug in NDK r10d
# NDK is buggy meh
obj/local/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.1.so: $(LOCAL_PATH)/$(LOCAL_SRC_FILES)
cp -f $< $@
#obj/local/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.1.so: $(LOCAL_PATH)/$(LOCAL_SRC_FILES)
# cp -f $< $@
obj/local/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.0.so: obj/local/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.1.so
cp -f $< $@
#obj/local/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.0.so: obj/local/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so.sdl.1.so
# cp -f $< $@
include $(PREBUILT_SHARED_LIBRARY)
#include $(PREBUILT_SHARED_LIBRARY)
include $(PREBUILT_STATIC_LIBRARY)
endif
endif

View File

@@ -10,6 +10,10 @@ build() {
ARCH=$1
NO_ASM=""
if [ -d "lib-$ARCH" ]; then
exit 0
fi
case $ARCH in
armeabi-v7a)
#NO_ASM="-DOPENSSL_NO_ASM=1" # Assembler in OpenSSL is broken when using clang
@@ -35,7 +39,7 @@ build() {
mkdir -p build/$ARCH
cd build/$ARCH
tar -x -v -z -f ../../openssl-1.1.1d.tar.gz --strip=1
tar -x -v -z -f ../../openssl-1.1.1h.tar.gz --strip=1
NDK=`which ndk-build`
NDK=`dirname $NDK`
@@ -43,25 +47,25 @@ build() {
export CROSS_SYSROOT=$NDK/sysroot/usr
export ANDROID_NDK_HOME=$NDK
env LDFLAGS="-shared -landroid -llog" \
env LDFLAGS="" \
CFLAGS="$NO_ASM" \
../../setCrossEnvironment-$ARCH.sh \
sh -c 'env PATH=`dirname $CC`:$PATH \
./Configure shared zlib --prefix=`pwd`/dist --openssldir=. $CONFIGURE_ARCH -fPIC' \
./Configure no-shared --prefix=`pwd`/dist --openssldir=. $CONFIGURE_ARCH -fPIC' \
|| exit 1
sed -i.old 's/^CNF_CPPFLAGS=.*/CNF_CPPFLAGS=/' Makefile
sed -i.old 's/^CNF_CFLAGS=.*/CNF_CFLAGS=/' Makefile
sed -i.old 's/^CNF_CXXFLAGS=.*/CNF_CXXFLAGS=/' Makefile
sed -i.old 's/^CNF_LDFLAGS=.*/CNF_LDFLAGS=/' Makefile
sed -i.old 's/^SHLIB_VERSION_NUMBER=.*/SHLIB_VERSION_NUMBER=sdl.1.so/' Makefile
#sed -i.old 's/^SHLIB_VERSION_NUMBER=.*/SHLIB_VERSION_NUMBER=sdl.1.so/' Makefile
if [ "$ARCH" = armeabi-v7a ]; then
sed -i.old 's/-DPOLY1305_ASM //' Makefile
sed -i.old 's@crypto/poly1305/poly1305-armv4.S @@' Makefile
sed -i.old 's@crypto/poly1305/poly1305-armv4.o @@' Makefile
fi
env LDFLAGS="-shared -landroid -llog" \
env LDFLAGS="" \
CFLAGS="$NO_ASM" \
../../setCrossEnvironment-$ARCH.sh \
sh -c 'env PATH=`dirname $CC`:$PATH \
@@ -71,8 +75,10 @@ build() {
rm -rf lib-$ARCH
mkdir -p lib-$ARCH
cp build/$ARCH/libcrypto.so.sdl.1.so lib-${ARCH}/libcrypto.so.sdl.1.so || exit 1
cp build/$ARCH/libssl.so.sdl.1.so lib-${ARCH}/libssl.so.sdl.1.so || exit 1
# cp build/$ARCH/libcrypto.so.sdl.1.so lib-${ARCH}/libcrypto.so.sdl.1.so || exit 1
# cp build/$ARCH/libssl.so.sdl.1.so lib-${ARCH}/libssl.so.sdl.1.so || exit 1
cp build/$ARCH/libcrypto.a lib-${ARCH}/libcrypto.a || exit 1
cp build/$ARCH/libssl.a lib-${ARCH}/libssl.a || exit 1
}

View File

@@ -8,8 +8,7 @@ LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
#LOCAL_MODULE := SDL2
LOCAL_MODULE := $(lastword $(subst /, ,$(LOCAL_PATH)))
LOCAL_MODULE := SDL2
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
@@ -21,19 +20,25 @@ LOCAL_SRC_FILES := \
$(wildcard $(LOCAL_PATH)/src/audio/*.c) \
$(wildcard $(LOCAL_PATH)/src/audio/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/audio/dummy/*.c) \
$(LOCAL_PATH)/src/atomic/SDL_atomic.c \
$(wildcard $(LOCAL_PATH)/src/audio/openslES/*.c) \
$(LOCAL_PATH)/src/atomic/SDL_atomic.c.arm \
$(LOCAL_PATH)/src/atomic/SDL_spinlock.c.arm \
$(wildcard $(LOCAL_PATH)/src/core/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/cpuinfo/*.c) \
$(wildcard $(LOCAL_PATH)/src/dynapi/*.c) \
$(wildcard $(LOCAL_PATH)/src/events/*.c) \
$(wildcard $(LOCAL_PATH)/src/file/*.c) \
$(wildcard $(LOCAL_PATH)/src/haptic/*.c) \
$(wildcard $(LOCAL_PATH)/src/haptic/dummy/*.c) \
$(wildcard $(LOCAL_PATH)/src/haptic/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/joystick/*.c) \
$(wildcard $(LOCAL_PATH)/src/joystick/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/joystick/hidapi/*.c) \
$(wildcard $(LOCAL_PATH)/src/loadso/dlopen/*.c) \
$(wildcard $(LOCAL_PATH)/src/power/*.c) \
$(wildcard $(LOCAL_PATH)/src/power/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/filesystem/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/sensor/*.c) \
$(wildcard $(LOCAL_PATH)/src/sensor/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/render/*.c) \
$(wildcard $(LOCAL_PATH)/src/render/*/*.c) \
$(wildcard $(LOCAL_PATH)/src/stdlib/*.c) \
@@ -42,9 +47,90 @@ LOCAL_SRC_FILES := \
$(wildcard $(LOCAL_PATH)/src/timer/*.c) \
$(wildcard $(LOCAL_PATH)/src/timer/unix/*.c) \
$(wildcard $(LOCAL_PATH)/src/video/*.c) \
$(wildcard $(LOCAL_PATH)/src/video/android/*.c))
$(wildcard $(LOCAL_PATH)/src/video/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/video/yuv2rgb/*.c) \
$(wildcard $(LOCAL_PATH)/src/test/*.c))
LOCAL_SHARED_LIBRARIES := hidapi
LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES
LOCAL_LDLIBS := -ldl -lGLESv1_CM -lGLESv2 -llog
LOCAL_CFLAGS += \
-Wall -Wextra \
-Wdocumentation \
-Wdocumentation-unknown-command \
-Wmissing-prototypes \
-Wunreachable-code-break \
-Wunneeded-internal-declaration \
-Wmissing-variable-declarations \
-Wfloat-conversion \
-Wshorten-64-to-32 \
-Wunreachable-code-return \
-Wshift-sign-overflow \
-Wstrict-prototypes \
-Wkeyword-macro \
# Warnings we haven't fixed (yet)
LOCAL_CFLAGS += -Wno-unused-parameter -Wno-sign-compare
LOCAL_LDLIBS := -ldl -lGLESv1_CM -lGLESv2 -lOpenSLES -llog -landroid
ifeq ($(NDK_DEBUG),1)
cmd-strip :=
endif
LOCAL_STATIC_LIBRARIES := cpufeatures
include $(BUILD_SHARED_LIBRARY)
###########################
#
# SDL static library
#
###########################
LOCAL_MODULE := SDL2_static
LOCAL_MODULE_FILENAME := libSDL2
LOCAL_LDLIBS :=
LOCAL_EXPORT_LDLIBS := -ldl -lGLESv1_CM -lGLESv2 -llog -landroid
include $(BUILD_STATIC_LIBRARY)
###########################
#
# SDL main static library
#
###########################
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_MODULE := SDL2_main
LOCAL_MODULE_FILENAME := libSDL2main
include $(BUILD_STATIC_LIBRARY)
###########################
#
# hidapi library
#
###########################
include $(CLEAR_VARS)
LOCAL_CPPFLAGS += -std=c++11
LOCAL_SRC_FILES := src/hidapi/android/hid.cpp
LOCAL_MODULE := libhidapi
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
$(call import-module,android/cpufeatures)

View File

@@ -1,49 +0,0 @@
LOCAL_PATH := $(call my-dir)
###########################
#
# SDL shared library
#
###########################
include $(CLEAR_VARS)
LOCAL_MODULE := SDL2
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES)
LOCAL_SRC_FILES := \
$(subst $(LOCAL_PATH)/,, \
$(wildcard $(LOCAL_PATH)/src/*.c) \
$(wildcard $(LOCAL_PATH)/src/audio/*.c) \
$(wildcard $(LOCAL_PATH)/src/audio/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/audio/dummy/*.c) \
$(LOCAL_PATH)/src/atomic/SDL_atomic.c \
$(LOCAL_PATH)/src/atomic/SDL_spinlock.c.arm \
$(wildcard $(LOCAL_PATH)/src/core/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/cpuinfo/*.c) \
$(wildcard $(LOCAL_PATH)/src/events/*.c) \
$(wildcard $(LOCAL_PATH)/src/file/*.c) \
$(wildcard $(LOCAL_PATH)/src/haptic/*.c) \
$(wildcard $(LOCAL_PATH)/src/haptic/dummy/*.c) \
$(wildcard $(LOCAL_PATH)/src/joystick/*.c) \
$(wildcard $(LOCAL_PATH)/src/joystick/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/loadso/dlopen/*.c) \
$(wildcard $(LOCAL_PATH)/src/power/*.c) \
$(wildcard $(LOCAL_PATH)/src/power/android/*.c) \
$(wildcard $(LOCAL_PATH)/src/render/*.c) \
$(wildcard $(LOCAL_PATH)/src/render/*/*.c) \
$(wildcard $(LOCAL_PATH)/src/stdlib/*.c) \
$(wildcard $(LOCAL_PATH)/src/thread/*.c) \
$(wildcard $(LOCAL_PATH)/src/thread/pthread/*.c) \
$(wildcard $(LOCAL_PATH)/src/timer/*.c) \
$(wildcard $(LOCAL_PATH)/src/timer/unix/*.c) \
$(wildcard $(LOCAL_PATH)/src/video/*.c) \
$(wildcard $(LOCAL_PATH)/src/video/android/*.c))
LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES
LOCAL_LDLIBS := -ldl -lGLESv1_CM -lGLESv2 -llog
include $(BUILD_SHARED_LIBRARY)

View File

@@ -1,103 +0,0 @@
--- Android.mk 2013-10-08 17:46:42.381361960 +0200
+++ Android.mk 2013-10-08 15:37:33.539950000 +0200
@@ -1,46 +1,64 @@
LOCAL_PATH := $(call my-dir)
-###########################
-#
-# SDL shared library
-#
-###########################
-
include $(CLEAR_VARS)
-LOCAL_MODULE := SDL2
+LOCAL_MODULE := $(lastword $(subst /, ,$(LOCAL_PATH)))
+
+ifndef SDL_JAVA_PACKAGE_PATH
+$(error Please define SDL_JAVA_PACKAGE_PATH to the path of your Java package with dots replaced with underscores, for example "com_example_SanAngeles")
+endif
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_CFLAGS := -O3 -D__ANDROID__ -DANDROID \
+ -DSDL_JAVA_PACKAGE_PATH=$(SDL_JAVA_PACKAGE_PATH) \
+ -DSDL_CURDIR_PATH=\"$(SDL_CURDIR_PATH)\" \
+ -DSDL_TRACKBALL_KEYUP_DELAY=$(SDL_TRACKBALL_KEYUP_DELAY) \
+ -DSDL_VIDEO_RENDER_RESIZE_KEEP_ASPECT=$(SDL_VIDEO_RENDER_RESIZE_KEEP_ASPECT) \
+ -DSDL_VIDEO_RENDER_RESIZE=$(SDL_VIDEO_RENDER_RESIZE) \
+ $(SDL_ADDITIONAL_CFLAGS)
+
+
+SDL_SRCS := \
+ src/*.c \
+ src/audio/*.c \
+ src/cdrom/*.c \
+ src/cpuinfo/*.c \
+ src/events/*.c \
+ src/file/*.c \
+ src/haptic/*.c \
+ src/joystick/*.c \
+ src/stdlib/*.c \
+ src/thread/*.c \
+ src/timer/*.c \
+ src/video/*.c \
+ src/main/*.c \
+ src/power/*.c \
+ src/thread/pthread/*.c \
+ src/timer/unix/*.c \
+ src/audio/android/*.c \
+ src/cdrom/dummy/*.c \
+ src/video/android/*.c \
+ src/haptic/dummy/*.c \
+ src/loadso/dlopen/*.c \
+ src/atomic/*.c \
+ src/render/*.c \
+ src/render/opengles/*.c \
+ src/render/software/*.c
+
+
+# TODO: use libcutils for atomic operations, but it's not included in NDK
+
+# src/atomic/linux/*.c \
+# src/power/linux/*.c \
+# src/joystick/android/*.c \
+# src/haptic/android/*.c \
+# src/libm/*.c \
+
+LOCAL_CPP_EXTENSION := .cpp
-LOCAL_SRC_FILES := \
- $(subst $(LOCAL_PATH)/,, \
- $(wildcard $(LOCAL_PATH)/src/*.c) \
- $(wildcard $(LOCAL_PATH)/src/audio/*.c) \
- $(wildcard $(LOCAL_PATH)/src/audio/android/*.c) \
- $(wildcard $(LOCAL_PATH)/src/audio/dummy/*.c) \
- $(LOCAL_PATH)/src/atomic/SDL_atomic.c \
- $(LOCAL_PATH)/src/atomic/SDL_spinlock.c.arm \
- $(wildcard $(LOCAL_PATH)/src/core/android/*.cpp) \
- $(wildcard $(LOCAL_PATH)/src/cpuinfo/*.c) \
- $(wildcard $(LOCAL_PATH)/src/events/*.c) \
- $(wildcard $(LOCAL_PATH)/src/file/*.c) \
- $(wildcard $(LOCAL_PATH)/src/haptic/*.c) \
- $(wildcard $(LOCAL_PATH)/src/haptic/dummy/*.c) \
- $(wildcard $(LOCAL_PATH)/src/joystick/*.c) \
- $(wildcard $(LOCAL_PATH)/src/joystick/android/*.c) \
- $(wildcard $(LOCAL_PATH)/src/loadso/dlopen/*.c) \
- $(wildcard $(LOCAL_PATH)/src/power/*.c) \
- $(wildcard $(LOCAL_PATH)/src/render/*.c) \
- $(wildcard $(LOCAL_PATH)/src/render/*/*.c) \
- $(wildcard $(LOCAL_PATH)/src/stdlib/*.c) \
- $(wildcard $(LOCAL_PATH)/src/thread/*.c) \
- $(wildcard $(LOCAL_PATH)/src/thread/pthread/*.c) \
- $(wildcard $(LOCAL_PATH)/src/timer/*.c) \
- $(wildcard $(LOCAL_PATH)/src/timer/unix/*.c) \
- $(wildcard $(LOCAL_PATH)/src/video/*.c) \
- $(wildcard $(LOCAL_PATH)/src/video/android/*.c))
+# Note this "simple" makefile var substitution, you can find even more complex examples in different Android projects
+LOCAL_SRC_FILES := $(foreach F, $(SDL_SRCS), $(addprefix $(dir $(F)),$(notdir $(wildcard $(LOCAL_PATH)/$(F)))))
-LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES
-LOCAL_LDLIBS := -ldl -lGLESv1_CM -lGLESv2 -llog
+LOCAL_LDLIBS := -lGLESv1_CM -ldl -llog
include $(BUILD_SHARED_LIBRARY)

View File

@@ -1,18 +0,0 @@
Bugs are now managed in the SDL bug tracker, here:
http://bugzilla.libsdl.org/
You may report bugs there, and search to see if a given issue has already
been reported, discussed, and maybe even fixed.
You may also find help at the SDL mailing list. Subscription information:
http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org
Bug reports are welcome here, but we really appreciate if you use Bugzilla, as
bugs discussed on the mailing list may be forgotten or missed.

View File

@@ -1,15 +1,15 @@
Bugs are now managed in the SDL bug tracker, here:
http://bugzilla.libsdl.org/
https://bugzilla.libsdl.org/
You may report bugs there, and search to see if a given issue has already
been reported, discussed, and maybe even fixed.
You may also find help on the SDL mailing list. Subscription information:
You may also find help at the SDL forums/mailing list:
http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org
https://discourse.libsdl.org/
Bug reports are welcome here, but we really appreciate if you use Bugzilla, as
bugs discussed on the mailing list may be forgotten or missed.

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages

View File

@@ -1,73 +0,0 @@
Simple DirectMedia Layer CREDITS
Thanks to everyone who made this possible, including:
* Cliff Matthews, for giving me a reason to start this project. :)
-- Executor rocks! *grin*
* The Linux Fund, C Magazine, Educational Technology Resources Inc.,
Gareth Noyce, Jesse Pavel, Keith Kitchin, Jeremy Horvath, Thomas Nicholson,
Hans-Peter Gygax, the Eternal Lands Development Team, Lars Brubaker,
and Phoenix Kokido for financial contributions
* Edgar "bobbens" Simo for his force feedback API development during the
Google Summer of Code 2008
* Aaron Wishnick for his work on audio resampling and pitch shifting during
the Google Summer of Code 2008
* Holmes Futrell for port of SDL to the iPhone and iPod Touch during the
Google Summer of Code 2008
* Darren Alton for port of SDL to the Nintendo DS during the Google Summer
of Code 2008
* Szymon "Wilku" Wilczek for adding support for multiple mice and tablets
during the Google Summer of Code 2008
* Marty Leisner, Andrew, Will, Edgar Simo, Donny Viszneki, Andrea Mazzoleni,
Dmytro Bogovych, and Couriersud for helping find SDL 1.3 bugs in the great
SDL Bug Hunt of January 2009!
* Donny Viszneki for helping fix SDL 1.3 bugs in the great SDL Bug Hunt of
January 2009!
* Luke Benstead for OpenGL 3.0 support
* Gaëtan de Menten for writing the PHP and SQL behind the SDL website
* Tim Jones for the new look of the SDL website
* Ryan Gordon for helping everybody out and keeping the dream alive. :)
* Mattias Engdegård, for help with the Solaris port and lots of other help
* Eric Wing, Max Horn, and Darrell Walisser for unflagging work on the Mac OS X port
* David Carré, for the Pandora port
* Couriersud for the DirectFB driver
* Jon Atkins for SDL_image, SDL_mixer and SDL_net documentation
* Arne Claus, for the 2004 winning SDL logo,
and Shandy Brown, Jac, Alex Lyman, Mikkel Gjoel, #Guy, Jonas Hartmann,
Daniel Liljeberg, Ronald Sowa, DocD, Pekka Jaervinen, Patrick Avella,
Erkki Kontilla, Levon Gavalian, Hal Emerich, David Wiktorsson,
S. Schury and F. Hufsky, Ciska de Ruyver, Shredweat, Tyler Montbriand,
Martin Andersson, Merlyn Wysard, Fernando Ibanez, David Miller,
Andre Bommele, lovesby.com, Francisco Camenforte Torres, and David Igreja
for other logo entries.
* Bob Pendleton and David Olofson for being long time contributors to
the SDL mailing list.
* Everybody at Loki Software, Inc. for their great contributions!
And a big hand to everyone else who gave me appreciation, advice,
and suggestions, especially the good folks on the SDL mailing list.
THANKS! :)
-- Sam Lantinga <slouken@libsdl.org>

View File

@@ -21,6 +21,8 @@ Thanks to everyone who made this possible, including:
* Pierre-Loup Griffais for his deep knowledge of OpenGL drivers.
* Julian Winter for the SDL 2.0 website.
* Sheena Smith for many months of great work on the SDL wiki creating the API documentation and style guides.
* Paul Hunkin for his port of SDL to Android during the Google Summer of Code 2010.

View File

@@ -1,27 +0,0 @@
To compile and install SDL:
0. If you have downloaded this from the website, skip to the next step.
If you have checked this out from subversion, you'll need to run
./autogen.sh to build the configure script.
1. Run './configure; make; make install'
If you are compiling for Windows using gcc, read the FAQ at:
http://www.libsdl.org/faq.php?action=listentries&category=4#42
If you are compiling using Visual C++ on Win32, you should read
the file VisualC.html
2. Look at the example programs in ./test, and check out the HTML
documentation in ./docs to see how to use the SDL library.
3. Join the SDL developer mailing list by sending E-mail to
sdl-request@libsdl.org
and put "subscribe" in the subject of the message.
Or alternatively you can use the web interface:
http://www.libsdl.org/mailing-list.php
That's it!
Sam Lantinga <slouken@libsdl.org>

View File

@@ -5,11 +5,11 @@ To compile and install SDL:
* Read VisualC.html
Windows with gcc, either native or cross-compiling:
* Read the FAQ at http://wiki.libsdl.org/moin.fcg/FAQWindows
* Read the FAQ at https://wiki.libsdl.org/moin.fcg/FAQWindows
* Run './configure; make; make install'
Mac OS X with Xcode:
* Read README-macosx.txt
* Read docs/README-macosx.md
Mac OS X from the command line:
* Run './configure; make; make install'
@@ -18,23 +18,23 @@ To compile and install SDL:
* Run './configure; make; make install'
Android:
* Read README-android.txt
* Read docs/README-android.md
iOS:
* Read README-ios.txt
* Read docs/README-ios.md
Using Cmake:
* Read README-cmake.txt
* Read docs/README-cmake.md
2. Look at the example programs in ./test, and check out the online
documentation at http://wiki.libsdl.org/
documentation at https://wiki.libsdl.org/
3. Join the SDL developer mailing list by sending E-mail to
sdl-request@libsdl.org
and put "subscribe" in the subject of the message.
Or alternatively you can use the web interface:
http://www.libsdl.org/mailing-list.php
https://www.libsdl.org/mailing-list.php
That's it!
Sam Lantinga <slouken@libsdl.org>

View File

@@ -1,234 +0,0 @@
--- Makefile.ds 2013-10-08 17:46:42.384695327 +0200
+++ Makefile.ds 1970-01-01 01:00:00.000000000 +0100
@@ -1,231 +0,0 @@
-#---------------------------------------------------------------------------------
-.SUFFIXES:
-#---------------------------------------------------------------------------------
-
-ifeq ($(strip $(DEVKITARM)),)
-$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
-endif
-
-include $(DEVKITARM)/ds_rules
-
-#---------------------------------------------------------------------------------
-# TARGET is the name of the output
-# BUILD is the directory where object files & intermediate files will be placed
-# SOURCES is a list of directories containing source code
-# DATA is a list of directories containing data files
-# INCLUDES is a list of directories containing header files
-#---------------------------------------------------------------------------------
-TARGET := $(shell basename $(CURDIR))
-BUILD := src
-SOURCES := src
-DATA := data
-INCLUDES := include
-
-#---------------------------------------------------------------------------------
-# options for code generation
-#---------------------------------------------------------------------------------
-ARCH := -mthumb -mthumb-interwork \
- -D__NDS__ -DENABLE_NDS -DNO_SIGNAL_H -DDISABLE_THREADS -DPACKAGE=\"SDL\" \
- -DVERSION=\"2.0\" -DHAVE_ALLOCA_H=1 -DHAVE_ALLOCA=1
-
-CFLAGS := -g -Wall -Os\
- -march=armv5te -mtune=arm946e-s \
- -fomit-frame-pointer -ffast-math \
- $(ARCH)
-
-CFLAGS += $(INCLUDE) -DARM9
-CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
-
-ASFLAGS := -g $(ARCH) -march=armv5te -mtune=arm946e-s
-LDFLAGS = -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
-
-# Set to 0 to use a framer buffer, or 1 to use the GL like hardware
-# renderer. Alas, both cannot be used at the same time for lack of
-# display/texture memory.
-USE_HW_RENDERER := 1
-
-ifeq ($(USE_HW_RENDERER),1)
-CFLAGS += -DUSE_HW_RENDERER
-else
-endif
-
-#---------------------------------------------------------------------------------
-# list of directories containing libraries, this must be the top level containing
-# include and lib
-#---------------------------------------------------------------------------------
-LIBDIRS := $(LIBNDS) $(PORTLIBS)
-
-#---------------------------------------------------------------------------------
-# no real need to edit anything past this point unless you need to add additional
-# rules for different file extensions
-#---------------------------------------------------------------------------------
-ifneq ($(BUILD),$(notdir $(CURDIR)))
-#---------------------------------------------------------------------------------
-
-export OUTPUT := $(CURDIR)/lib/lib$(TARGET).a
-
-export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
- $(foreach dir,$(DATA),$(CURDIR)/$(dir))
-
-export DEPSDIR := $(CURDIR)/$(BUILD)
-
-CFILES := \
- SDL.c \
- SDL_assert.c \
- SDL_error.c \
- SDL_fatal.c \
- SDL_hints.c \
- SDL_log.c \
- atomic/SDL_atomic.c \
- atomic/SDL_spinlock.arm.c \
- audio/SDL_audio.c \
- audio/SDL_audiocvt.c \
- audio/SDL_audiodev.c \
- audio/SDL_audiotypecvt.c \
- audio/SDL_mixer.c \
- audio/SDL_wave.c \
- audio/nds/SDL_ndsaudio.c \
- cpuinfo/SDL_cpuinfo.c \
- events/SDL_events.c \
- events/SDL_keyboard.c \
- events/SDL_mouse.c \
- events/SDL_quit.c \
- events/SDL_touch.c \
- events/SDL_windowevents.c \
- events/nds/SDL_ndsgesture.c \
- file/SDL_rwops.c \
- haptic/SDL_haptic.c \
- haptic/nds/SDL_syshaptic.c \
- joystick/SDL_joystick.c \
- joystick/nds/SDL_sysjoystick.c \
- power/SDL_power.c \
- power/nds/SDL_syspower.c \
- render/SDL_render.c \
- render/SDL_yuv_sw.c \
- render/nds/SDL_ndsrender.c \
- render/nds/SDL_libgl2D.c \
- render/software/SDL_blendfillrect.c \
- render/software/SDL_blendline.c \
- render/software/SDL_blendpoint.c \
- render/software/SDL_drawline.c \
- render/software/SDL_drawpoint.c \
- render/software/SDL_render_sw.c \
- stdlib/SDL_getenv.c \
- stdlib/SDL_iconv.c \
- stdlib/SDL_malloc.c \
- stdlib/SDL_qsort.c \
- stdlib/SDL_stdlib.c \
- stdlib/SDL_string.c \
- thread/SDL_thread.c \
- thread/nds/SDL_syscond.c \
- thread/nds/SDL_sysmutex.c \
- thread/nds/SDL_syssem.c \
- thread/nds/SDL_systhread.c \
- timer/SDL_timer.c \
- timer/nds/SDL_systimer.c \
- video/SDL_RLEaccel.c \
- video/SDL_blit.c \
- video/SDL_blit_0.c \
- video/SDL_blit_1.c \
- video/SDL_blit_A.c \
- video/SDL_blit_N.c \
- video/SDL_blit_auto.c \
- video/SDL_blit_copy.c \
- video/SDL_blit_slow.c \
- video/SDL_bmp.c \
- video/SDL_clipboard.c \
- video/SDL_fillrect.c \
- video/SDL_pixels.c \
- video/SDL_rect.c \
- video/SDL_stretch.c \
- video/SDL_surface.c \
- video/SDL_video.c \
- video/nds/SDL_ndsevents.c \
- video/nds/SDL_ndsvideo.c \
- video/nds/SDL_ndswindow.c
-
-
-#CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
-#SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
-#BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
-
-#---------------------------------------------------------------------------------
-# use CXX for linking C++ projects, CC for standard C
-#---------------------------------------------------------------------------------
-ifeq ($(strip $(CPPFILES)),)
-#---------------------------------------------------------------------------------
- export LD := $(CC)
-#---------------------------------------------------------------------------------
-else
-#---------------------------------------------------------------------------------
- export LD := $(CXX)
-#---------------------------------------------------------------------------------
-endif
-#---------------------------------------------------------------------------------
-
-export OFILES := $(addsuffix .o,$(BINFILES)) \
- $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
-
-export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
- $(foreach dir,$(LIBDIRS),-I$(dir)/include) \
- -I$(CURDIR)/$(BUILD) \
- -I$(PORTLIBS)/include/SDL
-
-.PHONY: $(BUILD) clean all
-
-#---------------------------------------------------------------------------------
-all: arm_only $(BUILD) install nds_test
-
-lib:
- @[ -d $@ ] || mkdir -p $@
-
-$(BUILD): lib
- @[ -d $@ ] || mkdir -p $@
- @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile.ds -s
-
-install: $(BUILD)
- @mkdir -p $(PORTLIBS)/include/SDL/
- @rsync -a $(OUTPUT) $(PORTLIBS)/lib/
- @rsync -a include/*.h $(PORTLIBS)/include/SDL/
-
-nds_test:
- $(MAKE) -C test/nds-test-progs -s
-
-tags:
- cd $(SOURCES); etags $(CFILES)
-
-# This file must be compiled with the ARM instruction set, not
-# thumb. Use devkitpro way of doing things.
-arm_only: src/atomic/SDL_spinlock.arm.c
-src/atomic/SDL_spinlock.arm.c: src/atomic/SDL_spinlock.c
- @cp $< $@
-
-#---------------------------------------------------------------------------------
-clean:
- @echo clean ...
- @cd src; rm -fr $(OFILES) $(OFILES:.o=.d) lib
- @rm -f $(OUTPUT)
- @make -C test/nds-test-progs -s clean
-
-#---------------------------------------------------------------------------------
-else
-
-DEPENDS := $(OFILES:.o=.d)
-
-#---------------------------------------------------------------------------------
-# main targets
-#---------------------------------------------------------------------------------
-$(OUTPUT) : $(OFILES)
-
-#---------------------------------------------------------------------------------
-%.bin.o : %.bin
-#---------------------------------------------------------------------------------
- @echo $(notdir $<)
- @$(bin2o)
-
-
--include $(DEPENDS)
-
-#---------------------------------------------------------------------------------------
-endif
-#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,251 @@
# Makefile to build and install the SDL library
top_builddir = .
srcdir = @srcdir@
objects = build
gen = gen
prefix = @prefix@
exec_prefix = @exec_prefix@
bindir = @bindir@
libdir = @libdir@
includedir = @includedir@
datarootdir = @datarootdir@
datadir = @datadir@
auxdir = @ac_aux_dir@
distpath = $(srcdir)/..
distdir = SDL2-@SDL_VERSION@
distfile = $(distdir).tar.gz
@SET_MAKE@
SHELL = @SHELL@
CC = @CC@
INCLUDE = @INCLUDE@
CFLAGS = @BUILD_CFLAGS@
EXTRA_CFLAGS = @EXTRA_CFLAGS@
LDFLAGS = @BUILD_LDFLAGS@
EXTRA_LDFLAGS = @EXTRA_LDFLAGS@
LIBTOOL = @LIBTOOL@
INSTALL = @INSTALL@
AR = @AR@
RANLIB = @RANLIB@
WINDRES = @WINDRES@
TARGET = libSDL2.la
OBJECTS = @OBJECTS@
GEN_HEADERS = @GEN_HEADERS@
GEN_OBJECTS = @GEN_OBJECTS@
VERSION_OBJECTS = @VERSION_OBJECTS@
SDLMAIN_TARGET = libSDL2main.la
SDLMAIN_OBJECTS = @SDLMAIN_OBJECTS@
SDLTEST_TARGET = libSDL2_test.la
SDLTEST_OBJECTS = @SDLTEST_OBJECTS@
WAYLAND_SCANNER = @WAYLAND_SCANNER@
INSTALL_SDL2_CONFIG = @INSTALL_SDL2_CONFIG@
SRC_DIST = *.txt acinclude Android.mk autogen.sh android-project build-scripts cmake cmake_uninstall.cmake.in configure configure.ac debian docs include Makefile.* sdl2-config.cmake.in sdl2-config-version.cmake.in sdl2-config.in sdl2.m4 sdl2.pc.in SDL2.spec.in SDL2Config.cmake src test VisualC.html VisualC VisualC-WinRT Xcode Xcode-iOS wayland-protocols
GEN_DIST = SDL2.spec
ifneq ($V,1)
RUN_CMD_AR = @echo " AR " $@;
RUN_CMD_CC = @echo " CC " $@;
RUN_CMD_CXX = @echo " CXX " $@;
RUN_CMD_LTLINK = @echo " LTLINK" $@;
RUN_CMD_RANLIB = @echo " RANLIB" $@;
RUN_CMD_GEN = @echo " GEN " $@;
LIBTOOL += --quiet
endif
HDRS = \
SDL.h \
SDL_assert.h \
SDL_atomic.h \
SDL_audio.h \
SDL_bits.h \
SDL_blendmode.h \
SDL_clipboard.h \
SDL_cpuinfo.h \
SDL_egl.h \
SDL_endian.h \
SDL_error.h \
SDL_events.h \
SDL_filesystem.h \
SDL_gamecontroller.h \
SDL_gesture.h \
SDL_haptic.h \
SDL_hints.h \
SDL_joystick.h \
SDL_keyboard.h \
SDL_keycode.h \
SDL_loadso.h \
SDL_log.h \
SDL_main.h \
SDL_messagebox.h \
SDL_metal.h \
SDL_mouse.h \
SDL_mutex.h \
SDL_name.h \
SDL_opengl.h \
SDL_opengl_glext.h \
SDL_opengles.h \
SDL_opengles2_gl2ext.h \
SDL_opengles2_gl2.h \
SDL_opengles2_gl2platform.h \
SDL_opengles2.h \
SDL_opengles2_khrplatform.h \
SDL_pixels.h \
SDL_platform.h \
SDL_power.h \
SDL_quit.h \
SDL_rect.h \
SDL_render.h \
SDL_rwops.h \
SDL_scancode.h \
SDL_sensor.h \
SDL_shape.h \
SDL_stdinc.h \
SDL_surface.h \
SDL_system.h \
SDL_syswm.h \
SDL_thread.h \
SDL_timer.h \
SDL_touch.h \
SDL_types.h \
SDL_version.h \
SDL_video.h \
SDL_vulkan.h \
begin_code.h \
close_code.h
SDLTEST_HDRS = $(shell ls $(srcdir)/include | fgrep SDL_test)
LT_AGE = @LT_AGE@
LT_CURRENT = @LT_CURRENT@
LT_RELEASE = @LT_RELEASE@
LT_REVISION = @LT_REVISION@
LT_LDFLAGS = -no-undefined -rpath $(libdir) -release $(LT_RELEASE) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
all: $(srcdir)/configure Makefile $(objects)/$(TARGET) $(objects)/$(SDLMAIN_TARGET) $(objects)/$(SDLTEST_TARGET)
$(srcdir)/configure: $(srcdir)/configure.ac
@echo "Warning, configure is out of date, please re-run autogen.sh"
Makefile: $(srcdir)/Makefile.in
$(SHELL) config.status $@
Makefile.in:;
$(objects)/.created:
$(SHELL) $(auxdir)/mkinstalldirs $(objects)
touch $@
update-revision:
$(SHELL) $(auxdir)/updaterev.sh
.PHONY: all update-revision install install-bin install-hdrs install-lib install-data uninstall uninstall-bin uninstall-hdrs uninstall-lib uninstall-data clean distclean dist $(OBJECTS:.lo=.d)
$(objects)/$(TARGET): $(GEN_HEADERS) $(GEN_OBJECTS) $(OBJECTS) $(VERSION_OBJECTS)
$(RUN_CMD_LTLINK)$(LIBTOOL) --tag=CC --mode=link $(CC) -o $@ $(OBJECTS) $(GEN_OBJECTS) $(VERSION_OBJECTS) $(LDFLAGS) $(EXTRA_LDFLAGS) $(LT_LDFLAGS)
$(objects)/$(SDLMAIN_TARGET): $(SDLMAIN_OBJECTS)
$(RUN_CMD_LTLINK)$(LIBTOOL) --tag=CC --mode=link $(CC) -static -o $@ $(SDLMAIN_OBJECTS) -rpath $(libdir)
$(objects)/$(SDLTEST_TARGET): $(SDLTEST_OBJECTS)
$(RUN_CMD_LTLINK)$(LIBTOOL) --tag=CC --mode=link $(CC) -static -o $@ $(SDLTEST_OBJECTS) -rpath $(libdir)
install: all install-bin install-hdrs install-lib install-data
install-bin:
ifeq ($(INSTALL_SDL2_CONFIG),TRUE)
$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(bindir)
$(INSTALL) -m 755 sdl2-config $(DESTDIR)$(bindir)/sdl2-config
endif
install-hdrs: update-revision
$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(includedir)/SDL2
for file in $(HDRS) $(SDLTEST_HDRS); do \
$(INSTALL) -m 644 $(srcdir)/include/$$file $(DESTDIR)$(includedir)/SDL2/$$file; \
done
$(INSTALL) -m 644 include/SDL_config.h $(DESTDIR)$(includedir)/SDL2/SDL_config.h
if test -f include/SDL_revision.h; then \
$(INSTALL) -m 644 include/SDL_revision.h $(DESTDIR)$(includedir)/SDL2/SDL_revision.h; \
else \
$(INSTALL) -m 644 $(srcdir)/include/SDL_revision.h $(DESTDIR)$(includedir)/SDL2/SDL_revision.h; \
fi
install-lib: $(objects) $(objects)/$(TARGET) $(objects)/$(SDLMAIN_TARGET) $(objects)/$(SDLTEST_TARGET)
$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(libdir)
$(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(TARGET) $(DESTDIR)$(libdir)/$(TARGET)
$(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(SDLMAIN_TARGET) $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
$(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(SDLTEST_TARGET) $(DESTDIR)$(libdir)/$(SDLTEST_TARGET)
install-data:
$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(datadir)/aclocal
$(INSTALL) -m 644 $(srcdir)/sdl2.m4 $(DESTDIR)$(datadir)/aclocal/sdl2.m4
$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(libdir)/pkgconfig
$(INSTALL) -m 644 sdl2.pc $(DESTDIR)$(libdir)/pkgconfig
ifeq ($(INSTALL_SDL2_CONFIG),TRUE)
$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(libdir)/cmake/SDL2
$(INSTALL) -m 644 sdl2-config.cmake $(DESTDIR)$(libdir)/cmake/SDL2
$(INSTALL) -m 644 sdl2-config-version.cmake $(DESTDIR)$(libdir)/cmake/SDL2
endif
uninstall: uninstall-bin uninstall-hdrs uninstall-lib uninstall-data
uninstall-bin:
rm -f $(DESTDIR)$(bindir)/sdl2-config
uninstall-hdrs:
for file in $(HDRS) $(SDLTEST_HDRS); do \
rm -f $(DESTDIR)$(includedir)/SDL2/$$file; \
done
rm -f $(DESTDIR)$(includedir)/SDL2/SDL_config.h
rm -f $(DESTDIR)$(includedir)/SDL2/SDL_revision.h
-rmdir $(DESTDIR)$(includedir)/SDL2
uninstall-lib:
$(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(libdir)/$(TARGET)
rm -f $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
rm -f $(DESTDIR)$(libdir)/$(SDLTEST_TARGET)
uninstall-data:
rm -f $(DESTDIR)$(datadir)/aclocal/sdl2.m4
rm -f $(DESTDIR)$(libdir)/pkgconfig/sdl2.pc
rm -f $(DESTDIR)$(libdir)/cmake/SDL2/sdl2-config.cmake
rm -f $(DESTDIR)$(libdir)/cmake/SDL2/sdl2-config-version.cmake
clean:
rm -rf $(objects)
rm -rf $(gen)
if test -f test/Makefile; then (cd test; $(MAKE) $@); fi
distclean: clean
rm -f Makefile Makefile.rules sdl2-config
rm -f config.status config.cache config.log libtool
rm -rf $(srcdir)/autom4te*
find $(srcdir) \( \
-name '*~' -o \
-name '*.bak' -o \
-name '*.old' -o \
-name '*.rej' -o \
-name '*.orig' -o \
-name '.#*' \) \
-exec rm -f {} \;
if test -f test/Makefile; then (cd test; $(MAKE) $@); fi
dist $(distfile):
$(SHELL) $(auxdir)/mkinstalldirs $(distdir)
(cd $(srcdir); tar cf - $(SRC_DIST)) | (cd $(distdir); tar xf -)
tar cf - $(GEN_DIST) | (cd $(distdir); tar xf -)
find $(distdir) \( \
-name '*~' -o \
-name '*.bak' -o \
-name '*.old' -o \
-name '*.rej' -o \
-name '*.orig' -o \
-name '.#*' \) \
-exec rm -f {} \;
if test -f $(distdir)/test/Makefile; then (cd $(distdir)/test && make distclean); fi
(cd $(distdir); build-scripts/updaterev.sh)
tar cvf - $(distdir) | gzip --best >$(distfile)
rm -rf $(distdir)
rpm: $(distfile)
rpmbuild -ta $?

View File

@@ -1,228 +0,0 @@
--- Makefile.in 2013-10-08 17:46:42.384695327 +0200
+++ Makefile.in 1970-01-01 01:00:00.000000000 +0100
@@ -1,225 +0,0 @@
-# Makefile to build and install the SDL library
-
-top_builddir = .
-srcdir = @srcdir@
-objects = build
-prefix = @prefix@
-exec_prefix = @exec_prefix@
-bindir = @bindir@
-libdir = @libdir@
-includedir = @includedir@
-datarootdir = @datarootdir@
-datadir = @datadir@
-auxdir = @ac_aux_dir@
-distpath = $(srcdir)/..
-distdir = SDL2-@SDL_VERSION@
-distfile = $(distdir).tar.gz
-
-@SET_MAKE@
-SHELL = @SHELL@
-CC = @CC@
-INCLUDE = @INCLUDE@
-CFLAGS = @BUILD_CFLAGS@
-EXTRA_CFLAGS = @EXTRA_CFLAGS@
-LDFLAGS = @BUILD_LDFLAGS@
-EXTRA_LDFLAGS = @EXTRA_LDFLAGS@
-LIBTOOL = @LIBTOOL@
-INSTALL = @INSTALL@
-AR = @AR@
-RANLIB = @RANLIB@
-WINDRES = @WINDRES@
-
-TARGET = libSDL2.la
-OBJECTS = @OBJECTS@
-VERSION_OBJECTS = @VERSION_OBJECTS@
-
-SDLMAIN_TARGET = libSDL2main.a
-SDLMAIN_OBJECTS = @SDLMAIN_OBJECTS@
-
-SRC_DIST = acinclude Android.mk autogen.sh BUGS build-scripts configure configure.in COPYING CREDITS include INSTALL Makefile.minimal Makefile.in README* sdl2-config.in sdl2.m4 sdl2.pc.in SDL2.spec.in src test TODO VisualC.html VisualC VisualCE WhatsNew Xcode Xcode-iOS
-GEN_DIST = SDL2.spec
-
-HDRS = \
- SDL.h \
- SDL_assert.h \
- SDL_atomic.h \
- SDL_audio.h \
- SDL_blendmode.h \
- SDL_clipboard.h \
- SDL_cpuinfo.h \
- SDL_endian.h \
- SDL_error.h \
- SDL_events.h \
- SDL_gesture.h \
- SDL_haptic.h \
- SDL_hints.h \
- SDL_input.h \
- SDL_joystick.h \
- SDL_keyboard.h \
- SDL_keycode.h \
- SDL_loadso.h \
- SDL_log.h \
- SDL_main.h \
- SDL_mouse.h \
- SDL_mutex.h \
- SDL_name.h \
- SDL_opengl.h \
- SDL_opengles.h \
- SDL_opengles2.h \
- SDL_pixels.h \
- SDL_platform.h \
- SDL_power.h \
- SDL_quit.h \
- SDL_rect.h \
- SDL_render.h \
- SDL_rwops.h \
- SDL_scancode.h \
- SDL_shape.h \
- SDL_stdinc.h \
- SDL_surface.h \
- SDL_syswm.h \
- SDL_thread.h \
- SDL_timer.h \
- SDL_touch.h \
- SDL_types.h \
- SDL_version.h \
- SDL_video.h \
- begin_code.h \
- close_code.h
-
-LT_AGE = @LT_AGE@
-LT_CURRENT = @LT_CURRENT@
-LT_RELEASE = @LT_RELEASE@
-LT_REVISION = @LT_REVISION@
-LT_LDFLAGS = -no-undefined -rpath $(DESTDIR)$(libdir) -release $(LT_RELEASE) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
-
-all: $(srcdir)/configure Makefile $(objects) $(objects)/$(TARGET) $(objects)/$(SDLMAIN_TARGET)
-
-$(srcdir)/configure: $(srcdir)/configure.in
- @echo "Warning, configure.in is out of date"
- #(cd $(srcdir) && sh autogen.sh && sh configure)
- @sleep 3
-
-Makefile: $(srcdir)/Makefile.in
- $(SHELL) config.status $@
-
-Makefile.in:;
-
-$(objects):
- $(SHELL) $(auxdir)/mkinstalldirs $@
-
-update-revision:
- $(SHELL) $(auxdir)/updaterev.sh
-
-.PHONY: all update-revision install install-bin install-hdrs install-lib install-data uninstall uninstall-bin uninstall-hdrs uninstall-lib uninstall-data clean distclean dist $(OBJECTS:.lo=.d)
-
-$(objects)/$(TARGET): $(OBJECTS) $(VERSION_OBJECTS)
- $(LIBTOOL) --mode=link $(CC) -o $@ $(OBJECTS) $(VERSION_OBJECTS) $(LDFLAGS) $(EXTRA_LDFLAGS) $(LT_LDFLAGS)
-
-$(objects)/$(SDLMAIN_TARGET): $(SDLMAIN_OBJECTS)
- $(AR) cru $@ $(SDLMAIN_OBJECTS)
- $(RANLIB) $@
-
-install: all install-bin install-hdrs install-lib install-data
-install-bin:
- $(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(bindir)
- $(INSTALL) -m 755 sdl2-config $(DESTDIR)$(bindir)/sdl2-config
-install-hdrs: update-revision
- $(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(includedir)/SDL2
- for file in $(HDRS); do \
- $(INSTALL) -m 644 $(srcdir)/include/$$file $(DESTDIR)$(includedir)/SDL2/$$file; \
- done
- $(INSTALL) -m 644 include/SDL_config.h $(DESTDIR)$(includedir)/SDL2/SDL_config.h
- if test -f include/SDL_revision.h; then \
- $(INSTALL) -m 644 include/SDL_revision.h $(DESTDIR)$(includedir)/SDL2/SDL_revision.h; \
- else \
- $(INSTALL) -m 644 $(srcdir)/include/SDL_revision.h $(DESTDIR)$(includedir)/SDL2/SDL_revision.h; \
- fi
-
-install-lib: $(objects) $(objects)/$(TARGET) $(objects)/$(SDLMAIN_TARGET)
- $(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(libdir)
- $(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(TARGET) $(DESTDIR)$(libdir)/$(TARGET)
- $(INSTALL) -m 644 $(objects)/$(SDLMAIN_TARGET) $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
- $(RANLIB) $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
-install-data:
- $(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(datadir)/aclocal
- $(INSTALL) -m 644 $(srcdir)/sdl2.m4 $(DESTDIR)$(datadir)/aclocal/sdl2.m4
- $(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(libdir)/pkgconfig
- $(INSTALL) -m 644 sdl2.pc $(DESTDIR)$(libdir)/pkgconfig
-
-uninstall: uninstall-bin uninstall-hdrs uninstall-lib uninstall-data
-uninstall-bin:
- rm -f $(DESTDIR)$(bindir)/sdl2-config
-uninstall-hdrs:
- for file in $(HDRS); do \
- rm -f $(DESTDIR)$(includedir)/SDL2/$$file; \
- done
- rm -f $(DESTDIR)$(includedir)/SDL2/SDL_config.h
- rm -f $(DESTDIR)$(includedir)/SDL2/SDL_revision.h
- -rmdir $(DESTDIR)$(includedir)/SDL2
-uninstall-lib:
- $(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(libdir)/$(TARGET)
- rm -f $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
-uninstall-data:
- rm -f $(DESTDIR)$(datadir)/aclocal/sdl2.m4
- rm -f $(DESTDIR)$(libdir)/pkgconfig/sdl2.pc
-
-clean:
- rm -rf $(objects)
- if test -f test/Makefile; then (cd test; $(MAKE) $@); fi
-
-distclean: clean
- rm -f Makefile Makefile.rules sdl2-config
- rm -f config.status config.cache config.log libtool
- rm -rf $(srcdir)/autom4te*
- find $(srcdir) \( \
- -name '*~' -o \
- -name '*.bak' -o \
- -name '*.old' -o \
- -name '*.rej' -o \
- -name '*.orig' -o \
- -name '.#*' \) \
- -exec rm -f {} \;
- if test -f test/Makefile; then (cd test; $(MAKE) $@); fi
-
-dist $(distfile):
- $(SHELL) $(auxdir)/mkinstalldirs $(distdir)
- (cd $(srcdir); tar cf - $(SRC_DIST)) | (cd $(distdir); tar xf -)
- tar cf - $(GEN_DIST) | (cd $(distdir); tar xf -)
- find $(distdir) \( \
- -name '*~' -o \
- -name '*.bak' -o \
- -name '*.old' -o \
- -name '*.rej' -o \
- -name '*.orig' -o \
- -name '.#*' \) \
- -exec rm -f {} \;
- if test -f $(distdir)/test/Makefile; then (cd $(distdir)/test && make distclean); fi
- tar cvf - $(distdir) | gzip --best >$(distfile)
- rm -rf $(distdir)
-
-rpm: $(distfile)
- rpmbuild -ta $?
-
-# Run indent on the source to standardize coding style
-indent:
- @echo "Running indent... modified files:"
- @cd $(srcdir) && \
- find . \( \
- -name '*.h' -o \
- -name '*.c' -o \
- -name '*.cc' \) \
- -print | fgrep -v ./Xcode | \
- while read file; do \
- indent "$$file" -o "$$file.indent"; \
- if cmp "$$file" "$$file.indent" >/dev/null; then \
- rm -f "$$file.indent"; \
- else \
- echo "$$file"; \
- mv -f "$$file.indent" "$$file"; \
- fi; \
- done
-
-# Run indent and then commit modified files
-commit: indent
- hg commit

View File

@@ -0,0 +1,44 @@
# Makefile to build the SDL library
INCLUDE = -I./include
CFLAGS = -g -O2 $(INCLUDE)
AR = ar
RANLIB = ranlib
TARGET = libSDL.a
SOURCES = \
src/*.c \
src/audio/*.c \
src/audio/dummy/*.c \
src/cpuinfo/*.c \
src/events/*.c \
src/file/*.c \
src/haptic/*.c \
src/haptic/dummy/*.c \
src/joystick/*.c \
src/joystick/dummy/*.c \
src/loadso/dummy/*.c \
src/power/*.c \
src/filesystem/dummy/*.c \
src/render/*.c \
src/render/software/*.c \
src/sensor/*.c \
src/sensor/dummy/*.c \
src/stdlib/*.c \
src/thread/*.c \
src/thread/generic/*.c \
src/timer/*.c \
src/timer/dummy/*.c \
src/video/*.c \
src/video/dummy/*.c \
OBJECTS = $(shell echo $(SOURCES) | sed -e 's,\.c,\.o,g')
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(AR) crv $@ $^
$(RANLIB) $@
clean:
rm -f $(TARGET) $(OBJECTS)

View File

@@ -0,0 +1,140 @@
# Open Watcom makefile to build SDL2.dll for OS/2
# wmake -f Makefile.os2
LIBNAME = SDL2
VERSION = 2.0.12
DESCRIPTION = Simple DirectMedia Layer 2
LIBHOME = .
LIBPATH = $(LIBHOME)/lib
DLLFILE = $(LIBHOME)/$(LIBNAME).dll
LIBFILE = $(LIBHOME)/$(LIBNAME).lib
LNKFILE = $(LIBNAME).lnk
INCPATH = -I"$(%WATCOM)/h/os2" -I"$(%WATCOM)/h"
INCPATH+= -I"$(LIBHOME)/h"
INCPATH+= -Iinclude
LIBM = libm.lib
LIBS = mmpm2.lib libuls.lib libconv.lib $(LIBM)
CFLAGS = -bt=os2 -d0 -q -bm -5s -fp5 -fpi87 -sg -oteanbmier -ei
# max warnings:
CFLAGS+= -wx
# building dll:
CFLAGS+= -bd
# the include paths :
CFLAGS+= $(INCPATH)
# building SDL itself (for DECLSPEC):
CFLAGS+= -DBUILD_SDL
MSRCS= e_atan2.c e_exp.c e_fmod.c e_log10.c e_log.c e_pow.c e_rem_pio2.c e_sqrt.c &
k_cos.c k_rem_pio2.c k_sin.c k_tan.c &
s_atan.c s_copysign.c s_cos.c s_fabs.c s_floor.c s_scalbn.c s_sin.c s_tan.c
SRCS = SDL.c SDL_assert.c SDL_error.c SDL_log.c SDL_dataqueue.c SDL_hints.c
SRCS+= SDL_getenv.c SDL_iconv.c SDL_malloc.c SDL_qsort.c SDL_stdlib.c SDL_string.c SDL_strtokr.c
SRCS+= SDL_cpuinfo.c SDL_atomic.c SDL_spinlock.c SDL_thread.c SDL_timer.c
SRCS+= SDL_rwops.c SDL_power.c
SRCS+= SDL_audio.c SDL_audiocvt.c SDL_audiodev.c SDL_audiotypecvt.c SDL_mixer.c SDL_wave.c
SRCS+= SDL_events.c SDL_quit.c SDL_keyboard.c SDL_mouse.c SDL_windowevents.c &
SDL_clipboardevents.c SDL_dropevents.c SDL_displayevents.c SDL_gesture.c &
SDL_sensor.c SDL_touch.c
SRCS+= SDL_haptic.c SDL_gamecontroller.c SDL_joystick.c
SRCS+= SDL_render.c yuv_rgb.c SDL_yuv.c SDL_yuv_sw.c SDL_blendfillrect.c &
SDL_blendline.c SDL_blendpoint.c SDL_drawline.c SDL_drawpoint.c &
SDL_render_sw.c SDL_rotate.c
SRCS+= SDL_blit.c SDL_blit_0.c SDL_blit_1.c SDL_blit_A.c SDL_blit_auto.c &
SDL_blit_copy.c SDL_blit_N.c SDL_blit_slow.c SDL_fillrect.c SDL_bmp.c &
SDL_pixels.c SDL_rect.c SDL_RLEaccel.c SDL_shape.c SDL_stretch.c &
SDL_surface.c SDL_video.c SDL_clipboard.c SDL_vulkan_utils.c SDL_egl.c
SRCS+= SDL_syscond.c SDL_sysmutex.c SDL_syssem.c SDL_systhread.c SDL_systls.c
SRCS+= SDL_systimer.c
SRCS+= SDL_sysloadso.c
SRCS+= SDL_sysfilesystem.c
SRCS+= SDL_syshaptic.c SDL_sysjoystick.c
SRCS+= SDL_dummyaudio.c SDL_diskaudio.c
SRCS+= SDL_nullvideo.c SDL_nullframebuffer.c SDL_nullevents.c
SRCS+= SDL_dummysensor.c
SRCS+= SDL_dynapi.c
OBJS = $(SRCS:.c=.obj)
MOBJS= $(MSRCS:.c=.obj)
.extensions:
.extensions: .lib .dll .obj .c .asm
.c: ./src;./src/dynapi;./src/audio;./src/cpuinfo;./src/events;./src/file;./src/haptic;./src/joystick;./src/power;./src/render;./src/render/software;./src/sensor;./src/stdlib;./src/thread;./src/timer;./src/video;./src/video/yuv2rgb;./src/atomic;./src/audio/disk;
.c: ./src/haptic/dummy;./src/joystick/dummy;./src/audio/dummy;./src/video/dummy;./src/sensor/dummy;
.c: ./src/loadso/dummy;./src/filesystem/dummy;./src/timer/dummy;./src/thread/generic;
all: $(DLLFILE) $(LIBFILE) .symbolic
$(DLLFILE): $(OBJS) $(LIBM) $(LNKFILE)
@echo * Linking: $@
wlink @$(LNKFILE)
$(LIBFILE): $(DLLFILE)
@echo * Creating LIB file: $@
wlib -q -b -n -c -pa -s -t -zld -ii -io $* $(DLLFILE)
.c.obj:
wcc386 $(CFLAGS) -fo=$^@ $<
SDL_cpuinfo.obj: SDL_cpuinfo.c
wcc386 $(CFLAGS) -wcd=200 -fo=$^@ $<
SDL_rwops.obj: SDL_rwops.c
wcc386 $(CFLAGS) -wcd=136 -fo=$^@ $<
SDL_wave.obj: SDL_wave.c
wcc386 $(CFLAGS) -wcd=124 -fo=$^@ $<
SDL_blendfillrect.obj: SDL_blendfillrect.c
wcc386 $(CFLAGS) -wcd=200 -fo=$^@ $<
SDL_blendline.obj: SDL_blendline.c
wcc386 $(CFLAGS) -wcd=200 -fo=$^@ $<
SDL_blendpoint.obj: SDL_blendpoint.c
wcc386 $(CFLAGS) -wcd=200 -fo=$^@ $<
SDL_RLEaccel.obj: SDL_RLEaccel.c
wcc386 $(CFLAGS) -wcd=201 -fo=$^@ $<
.c: ./src/libm;
$(LIBM): $(MOBJS)
wlib -q -b -n -c -pa -s -t -zld -ii -io $@ $(MOBJS)
$(LNKFILE):
@echo * Creating linker file: $@
@%create $@
@%append $@ SYSTEM os2v2_dll INITINSTANCE TERMINSTANCE
@%append $@ NAME $(DLLFILE)
@for %i in ($(OBJS)) do @%append $@ FILE %i
@%append $@ LIBPATH $(%LIB);$(LIBPATH)
@for %i in ($(LIBS)) do @%append $@ LIB %i
@%append $@ OPTION QUIET
@%append $@ OPTION IMPF=$(LIBHOME)/$^&.exp
@%append $@ OPTION MAP=$(LIBHOME)/$^&.map
@%append $@ OPTION DESCRIPTION '@$#libsdl org:$(VERSION)$#@$(DESCRIPTION)'
@%append $@ OPTION QUIET
@%append $@ OPTION ELIMINATE
@%append $@ OPTION MANYAUTODATA
@%append $@ OPTION OSNAME='OS/2 and eComStation'
@%append $@ OPTION SHOWDEAD
clean: .SYMBOLIC
@ echo * Clean: $(LIBNAME)
@if exist *.obj rm *.obj
@if exist *.err rm *.err
@if exist $(LNKFILE) rm $(LNKFILE)
@if exist $(LIBM) rm $(LIBM)
distclean: .SYMBOLIC clean
@if exist $(LIBHOME)/*.exp rm $(LIBHOME)/*.exp
@if exist $(LIBHOME)/*.map rm $(LIBHOME)/*.map
@if exist $(LIBFILE) rm $(LIBFILE)
@if exist $(DLLFILE) rm $(DLLFILE)

View File

@@ -0,0 +1,60 @@
# Makefile to build the pandora SDL library
AR = arm-none-linux-gnueabi-ar
RANLIB = arm-none-linux-gnueabi-ranlib
CC = arm-none-linux-gnueabi-gcc
CXX = arm-none-linux-gnueabi-g++
STRIP = arm-none-linux-gnueabi-strip
CFLAGS = -O3 -march=armv7-a -mcpu=cortex-a8 -mtune=cortex-a8 -mfloat-abi=softfp \
-mfpu=neon -ftree-vectorize -ffast-math -fomit-frame-pointer -fno-strict-aliasing -fsingle-precision-constant \
-I./include -I$(PNDSDK)/usr/include
TARGET = libSDL.a
SOURCES =
./src/*.c \
./src/atomic/*.c \
./src/audio/*.c \
./src/audio/disk/*.c \
./src/audio/dsp/*.c \
./src/audio/dummy/*.c \
./src/cpuinfo/*.c \
./src/events/*.c \
./src/file/*.c \
./src/filesystem/unix/*.c \
./src/haptic/*.c \
./src/haptic/linux/*.c \
./src/joystick/*.c \
./src/joystick/linux/*.c \
./src/loadso/dlopen/*.c \
./src/power/*.c \
./src/sensor/*.c \
./src/sensor/dummy/*.c \
./src/stdlib/*.c \
./src/thread/*.c \
./src/thread/pthread/SDL_syscond.c \
./src/thread/pthread/SDL_sysmutex.c \
./src/thread/pthread/SDL_syssem.c \
./src/thread/pthread/SDL_systhread.c \
./src/timer/*.c \
./src/timer/unix/*.c \
./src/video/*.c \
./src/video/dummy/*.c \
./src/video/pandora/SDL_pandora.o \
./src/video/pandora/SDL_pandora_events.o \
./src/video/x11/*.c \
OBJECTS = $(shell echo $(SOURCES) | sed -e 's,\.c,\.o,g')
CONFIG_H = $(shell cp include/SDL_config_pandora.h include/SDL_config.h)
all: $(TARGET)
$(TARGET): $(CONFIG_H) $(OBJECTS)
$(AR) crv $@ $^
$(RANLIB) $@
clean:
rm -f $(TARGET) $(OBJECTS)

View File

@@ -31,6 +31,7 @@ OBJS= src/SDL.o \
src/joystick/psp/SDL_sysjoystick.o \
src/power/SDL_power.o \
src/power/psp/SDL_syspower.o \
src/filesystem/dummy/SDL_sysfilesystem.o \
src/render/SDL_render.o \
src/render/SDL_yuv_sw.o \
src/render/psp/SDL_render_psp.o \
@@ -41,13 +42,17 @@ OBJS= src/SDL.o \
src/render/software/SDL_drawpoint.o \
src/render/software/SDL_render_sw.o \
src/render/software/SDL_rotate.o \
src/sensor/SDL_sensor.o \
src/sensor/dummy/SDL_dummysensor.o \
src/stdlib/SDL_getenv.o \
src/stdlib/SDL_iconv.o \
src/stdlib/SDL_malloc.o \
src/stdlib/SDL_qsort.o \
src/stdlib/SDL_stdlib.o \
src/stdlib/SDL_string.o \
src/stdlib/SDL_strtokr.o \
src/thread/SDL_thread.o \
src/thread/generic/SDL_systls.o \
src/thread/psp/SDL_syssem.o \
src/thread/psp/SDL_systhread.o \
src/thread/psp/SDL_sysmutex.o \
@@ -74,7 +79,7 @@ OBJS= src/SDL.o \
src/video/psp/SDL_pspevents.o \
src/video/psp/SDL_pspvideo.o \
src/video/psp/SDL_pspgl.o \
src/video/psp/SDL_pspmouse.o \
src/video/psp/SDL_pspmouse.o
INCDIR = ./include
CFLAGS = -g -O2 -G0 -Wall -D__PSP__ -DHAVE_OPENGL

View File

@@ -0,0 +1,80 @@
# Makefile to build the pandora SDL library
WIZSDK = /mythtv/media/devel/toolchains/openwiz/arm-openwiz-linux-gnu
AR = $(WIZSDK)/bin/arm-openwiz-linux-gnu-ar
RANLIB = $(WIZSDK)/bin/arm-openwiz-linux-gnu-ranlib
CC = $(WIZSDK)/bin/arm-openwiz-linux-gnu-gcc
CXX = $(WIZSDK)/bin/arm-openwiz-linux-gnu-g++
STRIP = $(WIZSDK)/bin/arm-openwiz-linux-gnu-strip
CFLAGS = -Wall -fPIC -I./include -I$(WIZSDK)/include -DWIZ_GLES_LITE
TARGET_STATIC = libSDL2.a
TARGET_SHARED = libSDL2.so
SOURCES = \
./src/*.c \
./src/audio/*.c \
./src/audio/disk/*.c \
./src/audio/dsp/*.c \
./src/audio/dummy/*.c \
./src/cpuinfo/*.c \
./src/events/*.c \
./src/file/*.c \
./src/haptic/*.c \
./src/haptic/linux/*.c \
./src/joystick/*.c \
./src/joystick/linux/*.c \
./src/loadso/dlopen/*.c \
./src/sensor/*.c \
./src/sensor/dummy/*.c \
./src/stdlib/*.c \
./src/thread/*.c \
./src/thread/pthread/SDL_syscond.c \
./src/thread/pthread/SDL_sysmutex.c \
./src/thread/pthread/SDL_syssem.c \
./src/thread/pthread/SDL_systhread.c \
./src/timer/*.c \
./src/timer/unix/*.c \
./src/video/*.c \
./src/video/dummy/*.c \
./src/video/pandora/*.c \
OBJECTS = $(shell echo $(SOURCES) | sed -e 's,\.c,\.o,g')
all: config_copy $(TARGET_STATIC) $(TARGET_SHARED)
$(TARGET_STATIC): $(OBJECTS)
$(AR) crv $@ $^
$(RANLIB) $@
$(TARGET_SHARED):
$(CC) -shared -Wl,-soname,$(TARGET_SHARED).0 -o $(TARGET_SHARED).0.0.1 $(OBJECTS)
ln -s $(TARGET_SHARED).0.0.1 $(TARGET_SHARED).0
ln -s $(TARGET_SHARED).0 $(TARGET_SHARED)
config_copy:
cp include/SDL_config_wiz.h include/SDL_config.h
clean:
rm -f $(TARGET_STATIC) $(TARGET_SHARED)* $(OBJECTS)
install:
mkdir -p $(WIZSDK)/lib
mkdir -p $(WIZSDK)/include/SDL2
cp -f $(TARGET_STATIC) $(WIZSDK)/lib
cp -f $(TARGET_SHARED).0.0.1 $(WIZSDK)/lib
rm -f $(WIZSDK)/lib/$(TARGET_SHARED).0 $(WIZSDK)/lib/$(TARGET_SHARED)
ln -s $(WIZSDK)/lib/$(TARGET_SHARED).0.0.1 $(WIZSDK)/lib/$(TARGET_SHARED).0
ln -s $(WIZSDK)/lib/$(TARGET_SHARED).0 $(WIZSDK)/lib/$(TARGET_SHARED)
cp $(TARGET_STATIC) ../../toolchain/libs
cp $(TARGET_SHARED).0.0.1 ../../toolchain/libs
rm -f ../../toolchain/libs/$(TARGET_SHARED).0 ../../toolchain/libs/$(TARGET_SHARED)
ln -s ../../toolchain/libs/$(TARGET_SHARED).0.0.1 ../../toolchain/libs/$(TARGET_SHARED).0
ln -s ../../toolchain/libs/$(TARGET_SHARED).0 ../../toolchain/libs/$(TARGET_SHARED)
cp $(TARGET_SHARED).0.0.1 ../nehe_demos/build/$(TARGET_SHARED).0
cp -f include/*.h $(WIZSDK)/include/SDL2/
cp -f include/*.h ../../toolchain/include/SDL2/

View File

@@ -1,45 +0,0 @@
Simple DirectMedia Layer
(SDL)
Version 2.0
---
http://www.libsdl.org/
This is the Simple DirectMedia Layer, a general API that provides low
level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL,
and 2D framebuffer across multiple platforms.
The current version supports Windows, Windows CE, Mac OS X, Linux, FreeBSD,
NetBSD, OpenBSD, BSD/OS, Solaris, iOS, and Android. The code contains
support for other operating systems but those are not officially supported.
SDL is written in C, but works with C++ natively, and has bindings to
several other languages, including Ada, C#, Eiffel, Erlang, Euphoria,
Go, Guile, Haskell, Java, Lisp, Lua, ML, Objective C, Pascal, Perl, PHP,
Pike, Pliant, Python, Ruby, and Smalltalk.
This library is distributed under the zlib license, which can be found
in the file "COPYING".
The best way to learn how to use SDL is to check out the header files in
the "include" subdirectory and the programs in the "test" subdirectory.
The header files and test programs are well commented and always up to date.
More documentation is available in HTML format in "docs/index.html", and
a documentation wiki is available online at:
http://www.libsdl.org/cgi/docwiki.cgi
The test programs in the "test" subdirectory are in the public domain.
Frequently asked questions are answered online:
http://www.libsdl.org/faq.php
If you need help with the library, or just want to discuss SDL related
issues, you can join the developers mailing list:
http://www.libsdl.org/mailing-list.php
Enjoy!
Sam Lantinga (slouken@libsdl.org)

View File

@@ -2,11 +2,11 @@
Please distribute this file with the SDL runtime environment:
The Simple DirectMedia Layer (SDL for short) is a cross-platform library
designed to make it easy to write multi-media software, such as games and
emulators.
designed to make it easy to write multi-media software, such as games
and emulators.
The Simple DirectMedia Layer library source code is available from:
http://www.libsdl.org/
https://www.libsdl.org/
This library is distributed under the terms of the zlib license:
http://www.zlib.net/zlib_license.html

View File

@@ -1,31 +0,0 @@
================================================================================
CMake build system for SDL (www.cmake.org)
================================================================================
SDL's build system was traditionally based on autotools. Over time, this
approach has suffered from several issues across the different supported
platforms.
To solve these problems, a new build system based on CMake is under development.
It works in parallel to the legacy system, so users can experiment with it
without complication.
While still experimental, the build system should be usable on the following
platforms:
* FreeBSD
* Linux
* VS.NET 2010
* MinGW and Msys
* OS X with support for XCode
================================================================================
Usage
================================================================================
Assuming the source for SDL is located at ~/sdl
cd ~
mkdir build
cd build
cmake ../sdl
This will build the static and dynamic versions of SDL in the ~/build directory.

View File

@@ -1,23 +0,0 @@
The latest development version of SDL is available via Mercurial.
Mercurial allows you to get up-to-the-minute fixes and enhancements;
as a developer works on a source tree, you can use "hg" to mirror that
source tree instead of waiting for an official release. Please look
at the Mercurial website ( http://mercurial.selenic.com/ ) for more
information on using hg, where you can also download software for
Mac OS X, Windows, and Unix systems.
hg clone http://hg.libsdl.org/SDL
If you are building SDL with an IDE, you will need to copy the file
include/SDL_config.h.default to include/SDL_config.h before building.
If you are building SDL via configure, you will need to run autogen.sh
before running configure.
There is a web interface to the subversion repository at:
http://hg.libsdl.org/SDL/
There is an RSS feed available at that URL, for those that want to
track commits in real time.

View File

@@ -1,222 +0,0 @@
==============================================================================
Building the Simple DirectMedia Layer for iPhone OS 2.0
==============================================================================
Requirements: Mac OS X v10.5 or later and the iPhone SDK.
Instructions:
1. Open SDL.xcodeproj (located in Xcode-iOS/SDL) in XCode.
2. Select your desired target, and hit build.
There are three build targets:
- libSDL.a:
Build SDL as a statically linked library
- testsdl
Build a test program (there are known test failures which are fine)
- Template:
Package a project template together with the SDL for iPhone static libraries and copies of the SDL headers. The template includes proper references to the SDL library and headers, skeleton code for a basic SDL program, and placeholder graphics for the application icon and startup screen.
==============================================================================
Build SDL for iOS from the command line
==============================================================================
1. cd (PATH WHERE THE SDL CODE IS)/build-scripts
2. ./iosbuild.sh
If everything goes fine, you should see a build/ios directory, inside there's
two directories "lib" and "include".
"include" contains a copy of the SDL headers that you'll need for your project,
make sure to configure XCode to look for headers there.
"lib" contains find two files, libSDL2.a and libSDL2main.a, you have to add both
to your XCode project. These libraries contain three architectures in them,
armv6 for legacy devices, armv7, and i386 (for the simulator).
By default, iosbuild.sh will autodetect the SDK version you have installed using
xcodebuild -showsdks, and build for iOS >= 3.0, you can override this behaviour
by setting the MIN_OS_VERSION variable, ie:
MIN_OS_VERSION=4.2 ./iosbuild.sh
==============================================================================
Using the Simple DirectMedia Layer for iOS
==============================================================================
FIXME: This needs to be updated for the latest methods
Here is the easiest method:
1. Build the SDL libraries (libSDL.a and libSDLSimulator.a) and the iPhone SDL Application template.
1. Install the iPhone SDL Application template by copying it to one of XCode's template directories. I recommend creating a directory called "SDL" in "/Developer/Platforms/iOS.platform/Developer/Library/XCode/Project Templates/" and placing it there.
2. Start a new project using the template. The project should be immediately ready for use with SDL.
Here is a more manual method:
1. Create a new iPhone view based application.
2. Build the SDL static libraries (libSDL.a and libSDLSimulator.a) for iPhone and include them in your project. XCode will ignore the library that is not currently of the correct architecture, hence your app will work both on iPhone and in the iPhone Simulator.
3. Include the SDL header files in your project.
4. Remove the ApplicationDelegate.h and ApplicationDelegate.m files -- SDL for iPhone provides its own UIApplicationDelegate. Remove MainWindow.xib -- SDL for iPhone produces its user interface programmatically.
5. Delete the contents of main.m and program your app as a regular SDL program instead. You may replace main.m with your own main.c, but you must tell XCode not to use the project prefix file, as it includes Objective-C code.
==============================================================================
Notes -- Application events
==============================================================================
On iOS the application goes through a fixed life cycle and you will get
notifications of state changes via application events. When these events
are delivered you must handle them in an event callback because the OS may
not give you any processing time after the events are delivered.
e.g.
int HandleAppEvents(void *userdata, SDL_Event *event)
{
switch (event->type)
{
case SDL_APP_TERMINATING:
/* Terminate the app.
Shut everything down before returning from this function.
*/
return 0;
case SDL_APP_LOWMEMORY:
/* You will get this when your app is paused and iOS wants more memory.
Release as much memory as possible.
*/
return 0;
case SDL_APP_WILLENTERBACKGROUND:
/* Prepare your app to go into the background. Stop loops, etc.
This gets called when the user hits the home button, or gets a call.
*/
return 0;
case SDL_APP_DIDENTERBACKGROUND:
/* This will get called if the user accepted whatever sent your app to the background.
If the user got a phone call and canceled it, you'll instead get an SDL_APP_DIDENTERFOREGROUND event and restart your loops.
When you get this, you have 5 seconds to save all your state or the app will be terminated.
Your app is NOT active at this point.
*/
return 0;
case SDL_APP_WILLENTERFOREGROUND:
/* This call happens when your app is coming back to the foreground.
Restore all your state here.
*/
return 0;
case SDL_APP_DIDENTERFOREGROUND:
/* Restart your loops here.
Your app is interactive and getting CPU again.
*/
return 0;
default:
/* No special processing, add it to the event queue */
return 1;
}
}
int main(int argc, char *argv[])
{
SDL_SetEventFilter(HandleAppEvents, NULL);
... run your main loop
return 0;
}
==============================================================================
Notes -- Accelerometer as Joystick
==============================================================================
SDL for iPhone supports polling the built in accelerometer as a joystick device. For an example on how to do this, see the accelerometer.c in the demos directory.
The main thing to note when using the accelerometer with SDL is that while the iPhone natively reports accelerometer as floating point values in units of g-force, SDL_JoystickGetAxis reports joystick values as signed integers. Hence, in order to convert between the two, some clamping and scaling is necessary on the part of the iPhone SDL joystick driver. To convert SDL_JoystickGetAxis reported values BACK to units of g-force, simply multiply the values by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
==============================================================================
Notes -- OpenGL ES
==============================================================================
Your SDL application for iPhone uses OpenGL ES for video by default.
OpenGL ES for iPhone supports several display pixel formats, such as RGBA8 and RGB565, which provide a 32 bit and 16 bit color buffer respectively. By default, the implementation uses RGB565, but you may use RGBA8 by setting each color component to 8 bits in SDL_GL_SetAttribute.
If your application doesn't use OpenGL's depth buffer, you may find significant performance improvement by setting SDL_GL_DEPTH_SIZE to 0.
Finally, if your application completely redraws the screen each frame, you may find significant performance improvement by setting the attribute SDL_GL_RETAINED_BACKING to 1.
==============================================================================
Notes -- Keyboard
==============================================================================
The SDL keyboard API has been extended to support on-screen keyboards:
void SDL_StartTextInput()
-- enables text events and reveals the onscreen keyboard.
void SDL_StopTextInput()
-- disables text events and hides the onscreen keyboard.
SDL_bool SDL_IsTextInputActive()
-- returns whether or not text events are enabled (and the onscreen keyboard is visible)
==============================================================================
Notes -- Reading and Writing files
==============================================================================
Each application installed on iPhone resides in a sandbox which includes its own Application Home directory. Your application may not access files outside this directory.
Once your application is installed its directory tree looks like:
MySDLApp Home/
MySDLApp.app
Documents/
Library/
Preferences/
tmp/
When your SDL based iPhone application starts up, it sets the working directory to the main bundle (MySDLApp Home/MySDLApp.app), where your application resources are stored. You cannot write to this directory. Instead, I advise you to write document files to "../Documents/" and preferences to "../Library/Preferences".
More information on this subject is available here:
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html
==============================================================================
Notes -- iPhone SDL limitations
==============================================================================
Windows:
Full-size, single window applications only. You cannot create multi-window SDL applications for iPhone OS. The application window will fill the display, though you have the option of turning on or off the menu-bar (pass SDL_CreateWindow the flag SDL_WINDOW_BORDERLESS).
Textures:
The optimal texture formats on iOS are SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_ABGR8888, SDL_PIXELFORMAT_BGR888, and SDL_PIXELFORMAT_RGB24 pixel formats.
Loading Shared Objects:
This is disabled by default since it seems to break the terms of the iPhone SDK agreement. It can be re-enabled in SDL_config_iphoneos.h.
==============================================================================
Game Center
==============================================================================
Game Center integration requires that you break up your main loop in order to yield control back to the system. In other words, instead of running an endless main loop, you run each frame in a callback function, using:
int SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam);
This will set up the given function to be called back on the animation callback, and then you have to return from main() to let the Cocoa event loop run.
e.g.
extern "C"
void ShowFrame(void*)
{
... do event handling, frame logic and rendering
}
int main(int argc, char *argv[])
{
... initialize game ...
#if __IPHONEOS__
// Initialize the Game Center for scoring and matchmaking
InitGameCenter();
// Set up the game to run in the window animation callback on iOS
// so that Game Center and so forth works correctly.
SDL_iPhoneSetAnimationCallback(window, 1, ShowFrame, NULL);
#else
while ( running ) {
ShowFrame(0);
DelayFrame();
}
#endif
return 0;
}

View File

@@ -1,30 +0,0 @@
This is a list of the platforms SDL supports, and who maintains them.
Officially supported platforms
==============================
(code compiles, and thoroughly tested for release)
==============================
Windows XP/Vista/7/8
Mac OS X 10.5+
Linux 2.6+
iOS 5.1.1+
Android 2.3.3+
Unofficially supported platforms
================================
(code compiles, but not thoroughly tested)
================================
FreeBSD
NetBSD
OpenBSD
Solaris
Platforms supported by volunteers
=================================
Haiku - maintained by Axel Dörfler <axeld@pinc-software.de>
PSP - maintained by 527721088@qq.com
Pandora - maintained by Scott Smith <pickle136@sbcglobal.net>
Platforms that need maintainers
===============================

View File

@@ -1,106 +0,0 @@
SDL on DirectFB
Supports:
- Hardware YUV overlays
- OpenGL - software only
- 2D/3D accelerations (depends on directfb driver)
- multiple displays
- windows
What you need:
DirectFB 1.0.1, 1.2.x, 1.3.0
Kernel-Framebuffer support: required: vesafb, radeonfb ....
Mesa 7.0.x - optional for OpenGL
/etc/directfbrc
This file should contain the following lines to make
your joystick work and avoid crashes:
------------------------
disable-module=joystick
disable-module=cle266
disable-module=cyber5k
no-linux-input-grab
------------------------
To disable to use x11 backend when DISPLAY variable is found use
export SDL_DIRECTFB_X11_CHECK=0
To disable the use of linux input devices, i.e. multimice/multikeyboard support,
use
export SDL_DIRECTFB_LINUX_INPUT=0
To use hardware accelerated YUV-overlays for YUV-textures, use:
export SDL_DIRECTFB_YUV_DIRECT=1
This is disabled by default. It will only support one
YUV texture, namely the first. Every other YUV texture will be
rendered in software.
In addition, you may use (directfb-1.2.x)
export SDL_DIRECTFB_YUV_UNDERLAY=1
to make the YUV texture an underlay. This will make the cursor to
be shown.
Simple Window Manager
=====================
The driver has support for a very, very basic window manager you may
want to use when runnning with "wm=default". Use
export SDL_DIRECTFB_WM=1
to enable basic window borders. In order to have the window title rendered,
you need to have the following font installed:
/usr/share/fonts/truetype/freefont/FreeSans.ttf
OPENGL Support
==============
The following instructions will give you *software* opengl. However this
works at least on all directfb supported platforms.
As of this writing 20100802 you need to pull Mesa from git and do the following:
------------------------
git clone git://anongit.freedesktop.org/git/mesa/mesa
cd mesa
git checkout 2c9fdaf7292423c157fc79b5ce43f0f199dd753a
------------------------
Edit configs/linux-directfb so that the Directories-section looks like
------------------------
# Directories
SRC_DIRS = mesa glu
GLU_DIRS = sgi
DRIVER_DIRS = directfb
PROGRAM_DIRS =
------------------------
make linux-directfb
make
echo Installing - please enter sudo pw.
sudo make install INSTALL_DIR=/usr/local/dfb_GL
cd src/mesa/drivers/directfb
make
sudo make install INSTALL_DIR=/usr/local/dfb_GL
------------------------
To run the SDL - testprograms:
export SDL_VIDEODRIVER=directfb
export LD_LIBRARY_PATH=/usr/local/dfb_GL/lib
export LD_PRELOAD=/usr/local/dfb_GL/libGL.so.7
./testgl

View File

@@ -1,186 +0,0 @@
==============================================================================
Using the Simple DirectMedia Layer with Mac OS X
==============================================================================
These instructions are for people using Apple's Mac OS X (pronounced
"ten").
From the developer's point of view, OS X is a sort of hybrid Mac and
Unix system, and you have the option of using either traditional
command line tools or Apple's IDE Xcode.
To build SDL using the command line, use the standard configure and make
process:
./configure
make
sudo make install
You can also build SDL as a Universal library (a single binary for both
PowerPC and Intel architectures), on Mac OS X 10.4 and newer, by using
the fatbuild.sh script in build-scripts:
sh build-scripts/fatbuild.sh
sudo build-scripts/fatbuild.sh install
This script builds SDL with 10.2 ABI compatibility on PowerPC and 10.4
ABI compatibility on Intel architectures. For best compatibility you
should compile your application the same way. A script which wraps
gcc to make this easy is provided in test/gcc-fat.sh
To use the library once it's built, you essential have two possibilities:
use the traditional autoconf/automake/make method, or use Xcode.
==============================================================================
Using the Simple DirectMedia Layer with a traditional Makefile
==============================================================================
An existing autoconf/automake build system for your SDL app has good chances
to work almost unchanged on OS X. However, to produce a "real" Mac OS X binary
that you can distribute to users, you need to put the generated binary into a
so called "bundle", which basically is a fancy folder with a name like
"MyCoolGame.app".
To get this build automatically, add something like the following rule to
your Makefile.am:
bundle_contents = APP_NAME.app/Contents
APP_NAME_bundle: EXE_NAME
mkdir -p $(bundle_contents)/MacOS
mkdir -p $(bundle_contents)/Resources
echo "APPL????" > $(bundle_contents)/PkgInfo
$(INSTALL_PROGRAM) $< $(bundle_contents)/MacOS/
You should replace EXE_NAME with the name of the executable. APP_NAME is what
will be visible to the user in the Finder. Usually it will be the same
as EXE_NAME but capitalized. E.g. if EXE_NAME is "testgame" then APP_NAME
usually is "TestGame". You might also want to use @PACKAGE@ to use the package
name as specified in your configure.in file.
If your project builds more than one application, you will have to do a bit
more. For each of your target applications, you need a seperate rule.
If you want the created bundles to be installed, you may want to add this
rule to your Makefile.am:
install-exec-hook: APP_NAME_bundle
rm -rf $(DESTDIR)$(prefix)/Applications/APP_NAME.app
mkdir -p $(DESTDIR)$(prefix)/Applications/
cp -r $< /$(DESTDIR)$(prefix)Applications/
This rule takes the Bundle created by the rule from step 3 and installs them
into $(DESTDIR)$(prefix)/Applications/.
Again, if you want to install multiple applications, you will have to augment
the make rule accordingly.
But beware! That is only part of the story! With the above, you end up with
a bare bone .app bundle, which is double clickable from the Finder. But
there are some more things you should do before shipping yor product...
1) The bundle right now probably is dynamically linked against SDL. That
means that when you copy it to another computer, *it will not run*,
unless you also install SDL on that other computer. A good solution
for this dilemma is to static link against SDL. On OS X, you can
achieve that by linkinag against the libraries listed by
sdl-config --static-libs
instead of those listed by
sdl-config --libs
Depending on how exactly SDL is integrated into your build systems, the
way to achieve that varies, so I won't describe it here in detail
2) Add an 'Info.plist' to your application. That is a special XML file which
contains some meta-information about your application (like some copyright
information, the version of your app, the name of an optional icon file,
and other things). Part of that information is displayed by the Finder
when you click on the .app, or if you look at the "Get Info" window.
More information about Info.plist files can be found on Apple's homepage.
As a final remark, let me add that I use some of the techniques (and some
variations of them) in Exult and ScummVM; both are available in source on
the net, so feel free to take a peek at them for inspiration!
==============================================================================
Using the Simple DirectMedia Layer with Xcode
==============================================================================
These instructions are for using Apple's Xcode IDE to build SDL applications.
- First steps
The first thing to do is to unpack the Xcode.tar.gz archive in the
top level SDL directory (where the Xcode.tar.gz archive resides).
Because Stuffit Expander will unpack the archive into a subdirectory,
you should unpack the archive manually from the command line:
cd [path_to_SDL_source]
tar zxf Xcode.tar.gz
This will create a new folder called Xcode, which you can browse
normally from the Finder.
- Building the Framework
The SDL Library is packaged as a framework bundle, an organized
relocatable folder heirarchy of executible code, interface headers,
and additional resources. For practical purposes, you can think of a
framework as a more user and system-friendly shared library, whose library
file behaves more or less like a standard UNIX shared library.
To build the framework, simply open the framework project and build it.
By default, the framework bundle "SDL.framework" is installed in
/Library/Frameworks. Therefore, the testers and project stationary expect
it to be located there. However, it will function the same in any of the
following locations:
~/Library/Frameworks
/Local/Library/Frameworks
/System/Library/Frameworks
- Build Options
There are two "Build Styles" (See the "Targets" tab) for SDL.
"Deployment" should be used if you aren't tweaking the SDL library.
"Development" should be used to debug SDL apps or the library itself.
- Building the Testers
Open the SDLTest project and build away!
- Using the Project Stationary
Copy the stationary to the indicated folders to access it from
the "New Project" and "Add target" menus. What could be easier?
- Setting up a new project by hand
Some of you won't want to use the Stationary so I'll give some tips:
* Create a new "Cocoa Application"
* Add src/main/macosx/SDLMain.m , .h and .nib to your project
* Remove "main.c" from your project
* Remove "MainMenu.nib" from your project
* Add "$(HOME)/Library/Frameworks/SDL.framework/Headers" to include path
* Add "$(HOME)/Library/Frameworks" to the frameworks search path
* Add "-framework SDL -framework Foundation -framework AppKit" to "OTHER_LDFLAGS"
* Set the "Main Nib File" under "Application Settings" to "SDLMain.nib"
* Add your files
* Clean and build
- Building from command line
Use pbxbuild in the same directory as your .pbproj file
- Running your app
You can send command line args to your app by either invoking it from
the command line (in *.app/Contents/MacOS) or by entering them in the
"Executibles" panel of the target settings.
- Implementation Notes
Some things that may be of interest about how it all works...
* Working directory
As defined in the SDL_main.m file, the working directory of your SDL app
is by default set to its parent. You may wish to change this to better
suit your needs.
* You have a Cocoa App!
Your SDL app is essentially a Cocoa application. When your app
starts up and the libraries finish loading, a Cocoa procedure is called,
which sets up the working directory and calls your main() method.
You are free to modify your Cocoa app with generally no consequence
to SDL. You cannot, however, easily change the SDL window itself.
Functionality may be added in the future to help this.
Known bugs are listed in the file "BUGS"

View File

@@ -1,33 +0,0 @@
This is a list of the platforms SDL supports, and who maintains them.
Officially supported platforms
==============================
(code compiles, and thoroughly tested for release)
==============================
Windows XP
Windows Vista
Windows 7
Mac OS X 10.4+
Linux 2.6+
iOS 3.1.3+
Android 1.6+
Unofficially supported platforms
================================
(code compiles, but not thoroughly tested)
================================
Windows CE
FreeBSD
NetBSD
OpenBSD
Solaris
Platforms supported by volunteers
=================================
Pandora - maintained by Scott Smith <pickle136@sbcglobal.net>
Platforms that need maintainers
===============================
Nintendo DS
Haiku

View File

@@ -1,57 +0,0 @@
* Porting To A New Platform
The first thing you have to do when porting to a new platform, is look at
include/SDL_platform.h and create an entry there for your operating system.
The standard format is __PLATFORM__, where PLATFORM is the name of the OS.
Ideally SDL_platform.h will be able to auto-detect the system it's building
on based on C preprocessor symbols.
There are two basic ways of building SDL at the moment:
1. The "UNIX" way: ./configure; make; make install
If you have a GNUish system, then you might try this. Edit configure.in,
take a look at the large section labelled:
"Set up the configuration based on the target platform!"
Add a section for your platform, and then re-run autogen.sh and build!
2. Using an IDE:
If you're using an IDE or other non-configure build system, you'll probably
want to create a custom SDL_config.h for your platform. Edit SDL_config.h,
add a section for your platform, and create a custom SDL_config_{platform}.h,
based on SDL_config.h.minimal and SDL_config.h.in
Add the top level include directory to the header search path, and then add
the following sources to the project:
src/*.c
src/audio/*.c
src/cdrom/*.c
src/cpuinfo/*.c
src/events/*.c
src/file/*.c
src/joystick/*.c
src/stdlib/*.c
src/thread/*.c
src/timer/*.c
src/video/*.c
src/audio/disk/*.c
src/audio/dummy/*.c
src/video/dummy/*.c
src/joystick/dummy/*.c
src/cdrom/dummy/*.c
src/thread/generic/*.c
src/timer/dummy/*.c
src/loadso/dummy/*.c
Once you have a working library without any drivers, you can go back to each
of the major subsystems and start implementing drivers for your platform.
If you have any questions, don't hesitate to ask on the SDL mailing list:
http://www.libsdl.org/mailing-list.php
Enjoy!
Sam Lantinga (slouken@libsdl.org)

View File

@@ -1,55 +0,0 @@
Project files for embedded Visual C++ 3.0, 4.0 and
Visual Studio 2005 can be found in VisualCE.zip
SDL supports GAPI and WinDib output for Windows CE.
GAPI driver supports:
- all possible WinCE devices (Pocket PC, Smartphones, HPC)
with different orientations of video memory and resolutions.
- 4, 8 and 16 bpp devices
- special handling of 8bpp on 8bpp devices
- VGA mode, you can even switch between VGA and GAPI in runtime
(between 240x320 and 480x640 for example). On VGA devices you can
use either GAPI or VGA.
- Landscape mode and automatic rotation of buttons and stylus coordinates.
To enable landscape mode make width of video screen bigger than height.
For example:
SDL_SetVideoMode(320,240,16,SDL_FULLSCREEN)
- WM2005
- SDL_ListModes
NOTE:
There are several SDL features not available in the WinCE port of SDL.
- DirectX is not yet available
- Semaphores are not available
- Joystick support is not available
- CD-ROM control is not available
In addition, there are several features that run in "degraded" mode:
Preprocessor Symbol Effect
=================== =================================
SDL_systimer.c:
USE_GETTICKCOUNT Less accurate values for SDL time functions
USE_SETTIMER Use only a single marginally accurate timer
SDL_syswm.c:
DISABLE_ICON_SUPPORT Can't set the runtime window icon
SDL_sysmouse.c:
USE_STATIC_CURSOR Only the arrow cursor is available
SDL_sysevents.c:
NO_GETKEYBOARDSTATE Can't get modifier state on keyboard focus
SDL_dibevents.c:
NO_GETKEYBOARDSTATE Very limited keycode translation
SDL_dibvideo.c:
NO_GETDIBITS Can't distinguish between 15 bpp and 16 bpp
NO_CHANGEDISPLAYSETTINGS No fullscreen support
NO_GAMMA_SUPPORT Gamma correction not available

View File

@@ -1,175 +0,0 @@
================================================================================
Simple DirectMedia Layer for Android
================================================================================
Requirements:
Android SDK
http://developer.android.com/sdk/index.html
Android NDK r4 or later
http://developer.android.com/sdk/ndk/index.html
================================================================================
How the port works
================================================================================
- Android applications are Java-based, optionally with parts written in C
- As SDL apps are C-based, we use a small Java shim that uses JNI to talk to
the SDL library
- This means that your application C code must be placed inside an android
Java project, along with some C support code that communicates with Java
- This eventually produces a standard Android .apk package
The Android Java code implements an "activity" and can be found in:
android-project/src/org/libsdl/app/SDLActivity.java
The Java code loads your game code, the SDL shared library, and
dispatches to native functions implemented in the SDL library:
src/SDL_android.cpp
Your project must include some glue code that starts your main() routine:
src/main/android/SDL_android_main.cpp
================================================================================
Building an app
================================================================================
Instructions:
1. Copy the android-project directory wherever you want to keep your projects and rename it to the name of your project.
2. Move this SDL directory into the <project>/jni directory and then copy
SDL_config_android.h to SDL_config.h inside the include folder
3. Place your application source files in the <project>/jni/src directory
4. Edit <project>/jni/src/Android.mk to include your source files
5. Run 'ndk-build' (a script provided by the NDK). This compiles the C source
If you want to use the Eclipse IDE, skip to the Eclipse section below.
6. Edit <project>/local.properties to point to the Android SDK directory
7. Run 'ant debug' in android/project. This compiles the .java and eventually
creates a .apk with the native code embedded
8. 'ant install' will push the apk to the device or emulator (if connected)
Here's an explanation of the files in the Android project, so you can customize them:
android-project/
AndroidManifest.xml - package manifest, do not modify
build.properties - empty
build.xml - build description file, used by ant
default.properties - holds the ABI for the application, currently android-4 which corresponds to the Android 1.6 system image
local.properties - holds the SDK path, you should change this to the path to your SDK
jni/ - directory holding native code
jni/Android.mk - Android makefile that includes all subdirectories
jni/SDL/ - directory holding the SDL library files
jni/SDL/Android.mk - Android makefile for creating the SDL shared library
jni/src/ - directory holding your C/C++ source
jni/src/Android.mk - Android makefile that you should customize to include your source code and any library references
res/ - directory holding resources for your application
res/drawable-* - directories holding icons for different phone hardware
res/layout/main.xml - place holder for the main screen layout, overridden by the SDL video output
res/values/strings.xml - strings used in your application, including the application name shown on the phone.
src/org/libsdl/app/SDLActivity.java - the Java class handling the initialization and binding to SDL. Be very careful changing this, as the SDL library relies on this implementation.
================================================================================
Additional documentation
================================================================================
The documentation in the NDK docs directory is very helpful in understanding the build process and how to work with native code on the Android platform.
The best place to start is with docs/OVERVIEW.TXT
================================================================================
Using Eclipse
================================================================================
First make sure that you've installed Eclipse and the Android extensions as described here:
http://developer.android.com/sdk/eclipse-adt.html
Once you've copied the SDL android project and customized it, you can create an Eclipse project from it:
* File -> New -> Other
* Select the Android -> Android Project wizard and click Next
* Enter the name you'd like your project to have
* Select "Create project from existing source" and browse for your project directory
* Make sure the Build Target is set to Android 1.6
* Click Finish
================================================================================
Loading files and resources
================================================================================
NEED CONTENT
================================================================================
Troubleshooting
================================================================================
You can create and run an emulator from the Eclipse IDE:
* Window -> Android SDK and AVD Manager
You can see if adb can see any devices with the following command:
adb devices
You can see the output of log messages on the default device with:
adb logcat
You can push files to the device with:
adb push local_file remote_path_and_file
You can push files to the SD Card at /sdcard, for example:
adb push moose.dat /sdcard/moose.dat
You can see the files on the SD card with a shell command:
adb shell ls /sdcard/
You can start a command shell on the default device with:
adb shell
You can do a clean build with the following commands:
ndk-build clean
ndk-build
You can see the complete command line that ndk-build is using by passing V=1 on the command line:
ndk-build V=1
If your application crashes in native code, you can use addr2line to convert the addresses in the stack trace to lines in your code.
For example, if your crash looks like this:
I/DEBUG ( 31): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 400085d0
I/DEBUG ( 31): r0 00000000 r1 00001000 r2 00000003 r3 400085d4
I/DEBUG ( 31): r4 400085d0 r5 40008000 r6 afd41504 r7 436c6a7c
I/DEBUG ( 31): r8 436c6b30 r9 435c6fb0 10 435c6f9c fp 4168d82c
I/DEBUG ( 31): ip 8346aff0 sp 436c6a60 lr afd1c8ff pc afd1c902 cpsr 60000030
I/DEBUG ( 31): #00 pc 0001c902 /system/lib/libc.so
I/DEBUG ( 31): #01 pc 0001ccf6 /system/lib/libc.so
I/DEBUG ( 31): #02 pc 000014bc /data/data/org.libsdl.app/lib/libmain.so
I/DEBUG ( 31): #03 pc 00001506 /data/data/org.libsdl.app/lib/libmain.so
You can see that there's a crash in the C library being called from the main code. I run addr2line with the debug version of my code:
arm-eabi-addr2line -C -f -e obj/local/armeabi/libmain.so
and then paste in the number after "pc" in the call stack, from the line that I care about:
000014bc
I get output from addr2line showing that it's in the quit function, in testspriteminimal.c, on line 23.
You can add logging to your code to help show what's happening:
#include <android/log.h>
__android_log_print(ANDROID_LOG_INFO, "foo", "Something happened! x = %d", x);
If you need to build without optimization turned on, you can create a file called "Application.mk" in the jni directory, with the following line in it:
APP_OPTIM := debug
================================================================================
Known issues
================================================================================
- SDL audio (although it's mostly written, just not working properly yet)
- TODO. I'm sure there's a bunch more stuff I haven't thought of

View File

@@ -1,64 +0,0 @@
================================================================================
Simple DirectMedia Layer for Nintendo DS
================================================================================
-Requirements-
* The devkitpro SDK available at http://devkitpro.org.
Read the information at http://devkitpro.org/wiki/Getting_Started/devkitARM
The necessary packages are devkitARM, libnds, libfat and default arm7.
* Optionally, use a DS emulator, such as desmume (http://desmume.org/)
to program and debug.
-Building SDL-
After setting the devkitpro environment, cd into your SDL directory and type:
make -f Makefile.ds
This will compile and install the library and headers into the
devkitpro's portlibs directory (../portlibs/arm/lib/ and
../portlibs/arm/include/). Additionally it will compile several tests
that you can run either on the DS or with desmume. For instance:
desmume --cflash-path=test/ test/nds-test-progs/testsprite2/testsprite2.nds
desmume --cflash-path=test/ test/nds-test-progs/testspriteminimal/testspriteminimal.nds
desmume --cflash-path=test/ test/nds-test-progs/testscale/testscale.nds
desmume test/nds-test-progs/general/general.nds
-Notes-
* The renderer code is based on the gl like engine. It's not using the sprite engine.
* The hardware renderer is using the parts of the libgl2d abstraction library that can be found at:
http://rel.phatcode.net/junk.php?id=117
Used with the author's permission.
* The port is very basic and incomplete:
- SDL currently has to be compiled for either framebuffer mode or renderer mode.
See USE_HW_RENDERER in Makefile.ds.
- some optional renderer functions are not implemented.
- no sound
-Limitations-
* in hardware renderer mode, don't load too many textures. The internal format is
2 bytes per pixel. And there is only 256KB reserved for the textures. For instance,
testscale won't display sample.bmp, unless it's resized to a smaller picture.
* the screen size is 256 x 384. Anything else won't work.
* there is no 8 bits/pixel mode because SDL 2.0 doesn't support palettes.
-Joystick mapping-
The Joystick presented to SDL has 2 axes and 8 buttons
KEY | Code
A | 0
B | 1
X | 2
Y | 3
L | 4
R | 5
select | 6
start | 7
Left-right is axe 0.
Up-down is axe 1.
-Mouse mapping-
todo
-Examples-
Due to memory limitations, to be able to successfully run the testscale example, sample.bmp must be resized to 256x105.

View File

@@ -1,72 +0,0 @@
===========================================================================
Dollar Gestures
===========================================================================
SDL Provides an implementation of the $1 gesture recognition system. This allows for recording, saving, loading, and performing single stroke gestures.
Gestures can be performed with any number of fingers (the centroid of the fingers must follow the path of the gesture), but the number of fingers must be constant (a finger cannot go down in the middle of a gesture). The path of a gesture is considered the path from the time when the final finger went down, to the first time any finger comes up.
Dollar gestures are assigned an Id based on a hash function. This is guaranteed to remain constant for a given gesture. There is a (small) chance that two different gestures will be assigned the same ID. In this case, simply re-recording one of the gestures should result in a different ID.
Recording:
----------
To begin recording on a touch device call:
SDL_RecordGesture(SDL_TouchID touchId), where touchId is the id of the touch device you wish to record on, or -1 to record on all connected devices.
Recording terminates as soon as a finger comes up. Recording is acknowledged by an SDL_DOLLARRECORD event.
A SDL_DOLLARRECORD event is a dgesture with the following fields:
event.dgesture.touchId - the Id of the touch used to record the gesture.
event.dgesture.gestureId - the unique id of the recoreded gesture.
Performing:
-----------
As long as there is a dollar gesture assigned to a touch, every finger-up event will also cause an SDL_DOLLARGESTURE event with the following fields:
event.dgesture.touchId - the Id of the touch which performed the gesture.
event.dgesture.gestureId - the unique id of the closest gesture to the performed stroke.
event.dgesture.error - the difference between the gesture template and the actual performed gesture. Lower error is a better match.
event.dgesture.numFingers - the number of fingers used to draw the stroke.
Most programs will want to define an appropriate error threshold and check to be sure taht the error of a gesture is not abnormally high (an indicator that no gesture was performed).
Saving:
-------
To save a template, call SDL_SaveDollarTemplate(gestureId, src) where gestureId is the id of the gesture you want to save, and src is an SDL_RWops pointer to the file where the gesture will be stored.
To save all currently loaded templates, call SDL_SaveAllDollarTemplates(src) where source is an SDL_RWops pointer to the file where the gesture will be stored.
Both functions return the number of gestures sucessfully saved.
Loading:
--------
To load templates from a file, call SDL_LoadDollarTemplates(touchId,src) where touchId is the id of the touch to load to (or -1 to load to all touch devices), and src is an SDL_RWops pointer to a gesture save file.
SDL_LoadDollarTemplates returns the number of templates sucessfully loaded.
===========================================================================
Multi Gestures
===========================================================================
SDL provides simple support for pinch/rotate/swipe gestures.
Every time a finger is moved an SDL_MULTIGESTURE event is sent with the following fields:
event.mgesture.touchId - the Id of the touch on which the gesture was performed.
event.mgesture.x - the normalized x cooridinate of the gesture. (0..1)
event.mgesture.y - the normalized y cooridinate of the gesture. (0..1)
event.mgesture.dTheta - the amount that the fingers rotated during this motion.
event.mgesture.dDist - the amount that the fingers pinched during this motion.
event.mgesture.numFingers - the number of fingers used in the gesture.
===========================================================================
Notes
===========================================================================
For a complete example see test/testgesture.c
Please direct questions/comments to:
jim.tla+sdl_touch@gmail.com

View File

@@ -1,110 +0,0 @@
==============================================================================
Building the Simple DirectMedia Layer for iPhone OS 2.0
==============================================================================
Requirements: Mac OS X v10.5 or later and the iPhone SDK.
Instructions:
1. Open SDL.xcodeproj (located in Xcode-iOS/SDL) in XCode.
2. Select your desired target, and hit build.
There are three build targets:
- libSDL.a:
Build SDL as a statically linked library
- testsdl
Build a test program (there are known test failures which are fine)
- Template:
Package a project template together with the SDL for iPhone static libraries and copies of the SDL headers. The template includes proper references to the SDL library and headers, skeleton code for a basic SDL program, and placeholder graphics for the application icon and startup screen.
==============================================================================
Using the Simple DirectMedia Layer for iOS
==============================================================================
FIXME: This needs to be updated for the latest methods
Here is the easiest method:
1. Build the SDL libraries (libSDL.a and libSDLSimulator.a) and the iPhone SDL Application template.
1. Install the iPhone SDL Application template by copying it to one of XCode's template directories. I recommend creating a directory called "SDL" in "/Developer/Platforms/iOS.platform/Developer/Library/XCode/Project Templates/" and placing it there.
2. Start a new project using the template. The project should be immediately ready for use with SDL.
Here is a more manual method:
1. Create a new iPhone view based application.
2. Build the SDL static libraries (libSDL.a and libSDLSimulator.a) for iPhone and include them in your project. XCode will ignore the library that is not currently of the correct architecture, hence your app will work both on iPhone and in the iPhone Simulator.
3. Include the SDL header files in your project.
4. Remove the ApplicationDelegate.h and ApplicationDelegate.m files -- SDL for iPhone provides its own UIApplicationDelegate. Remove MainWindow.xib -- SDL for iPhone produces its user interface programmatically.
5. Delete the contents of main.m and program your app as a regular SDL program instead. You may replace main.m with your own main.c, but you must tell XCode not to use the project prefix file, as it includes Objective-C code.
==============================================================================
Notes -- Accelerometer as Joystick
==============================================================================
SDL for iPhone supports polling the built in accelerometer as a joystick device. For an example on how to do this, see the accelerometer.c in the demos directory.
The main thing to note when using the accelerometer with SDL is that while the iPhone natively reports accelerometer as floating point values in units of g-force, SDL_JoystickGetAxis reports joystick values as signed integers. Hence, in order to convert between the two, some clamping and scaling is necessary on the part of the iPhone SDL joystick driver. To convert SDL_JoystickGetAxis reported values BACK to units of g-force, simply multiply the values by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
==============================================================================
Notes -- OpenGL ES
==============================================================================
Your SDL application for iPhone uses OpenGL ES for video by default.
OpenGL ES for iPhone supports several display pixel formats, such as RGBA8 and RGB565, which provide a 32 bit and 16 bit color buffer respectively. By default, the implementation uses RGB565, but you may use RGBA8 by setting each color component to 8 bits in SDL_GL_SetAttribute.
If your application doesn't use OpenGL's depth buffer, you may find significant performance improvement by setting SDL_GL_DEPTH_SIZE to 0.
Finally, if your application completely redraws the screen each frame, you may find significant performance improvement by setting the attribute SDL_GL_RETAINED_BACKING to 1.
==============================================================================
Notes -- Keyboard
==============================================================================
SDL for iPhone contains several additional functions related to keyboard visibility. These functions are not part of the SDL standard API, but are necessary for revealing and hiding the iPhone's virtual onscreen keyboard. You can use them in your own applications by including a copy of the SDL_uikitkeyboard.h header (located in src/video/uikit) in your project.
int SDL_iPhoneKeyboardShow(SDL_Window * window)
-- reveals the onscreen keyboard. Returns 0 on success and -1 on error.
int SDL_iPhoneKeyboardHide(SDL_Window * window)
-- hides the onscreen keyboard. Returns 0 on success and -1 on error.
SDL_bool SDL_iPhoneKeyboardIsShown(SDL_Window * window)
-- returns whether or not the onscreen keyboard is currently visible.
int SDL_iPhoneKeyboardToggle(SDL_Window * window)
-- toggles the visibility of the onscreen keyboard. Returns 0 on success and -1 on error.
==============================================================================
Notes -- Reading and Writing files
==============================================================================
Each application installed on iPhone resides in a sandbox which includes its own Application Home directory. Your application may not access files outside this directory.
Once your application is installed its directory tree looks like:
MySDLApp Home/
MySDLApp.app
Documents/
Library/
Preferences/
tmp/
When your SDL based iPhone application starts up, it sets the working directory to the main bundle (MySDLApp Home/MySDLApp.app), where your application resources are stored. You cannot write to this directory. Instead, I advise you to write document files to "../Documents/" and preferences to "../Library/Preferences".
More information on this subject is available here:
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html
==============================================================================
Notes -- iPhone SDL limitations
==============================================================================
Windows:
Full-size, single window applications only. You cannot create multi-window SDL applications for iPhone OS. The application window will fill the display, though you have the option of turning on or off the menu-bar (pass SDL_CreateWindow the flag SDL_WINDOW_BORDERLESS). Presently, landscape mode is not supported.
Video:
For real time frame-rates, you are advised to use strictly SDL 2.0 video calls. Using compatibility video calls uploads an OpenGL texture for each frame drawn, and this operation is excruciatingly slow.
Textures:
SDL for iPhone Textures supports only SDL_PIXELFORMAT_ABGR8888 and SDL_PIXELFORMAT_RGB24 pixel formats. This is because texture support in SDL for iPhone is done through OpenGL ES, which supports fewer pixel formats than OpenGL, will not re-order pixel data for you, and has no support for color-paletted formats (without extensions).
Audio:
SDL for iPhone does not yet support audio input.
Loading Shared Objects:
This is disabled by default since it seems to break the terms of the iPhone SDK agreement. It can be re-enabled in SDL_config_iphoneos.h.

View File

@@ -1,16 +0,0 @@
SDL 2.0 with open pandora console support ( http://openpandora.org/ )
=====================================================================
- A pandora specific video driver was writed to allow SDL 2.0 with OpenGL ES
support to work on the pandora under the framebuffer. This driver do not have
input support for now, so if you use it you will have to add your own control code.
The video driver name is "pandora" so if you have problem running it from
the framebuffer, try to set the following variable before starting your application :
"export SDL_VIDEODRIVER=pandora"
- OpenGL ES support was added to the x11 driver, so it's working like the normal
x11 driver one with OpenGLX support, with SDL input event's etc..
David Carré (Cpasjuste)
cpasjuste@gmail.com

View File

@@ -1,101 +0,0 @@
===========================================================================
System Specific Notes
===========================================================================
Linux:
The linux touch system is currently based off event streams, and proc/bus/devices. The active user must be given permissions to read /dev/input/TOUCHDEVICE, where TOUCHDEVICE is the event stream for your device. Currently only Wacom tablets are supported. If you have an unsupported tablet contact me at jim.tla+sdl_touch@gmail.com and I will help you get support for it.
Mac:
The Mac and Iphone API's are pretty. If your touch device supports them then you'll be fine. If it doesn't, then there isn't much we can do.
iPhone:
Works out of box.
Windows:
Unfortunately there is no windows support as of yet. Support for Windows 7 is planned, but we currently have no way to test. If you have a Windows 7 WM_TOUCH supported device, and are willing to help test please contact me at jim.tla+sdl_touch@gmail.com
===========================================================================
Events
===========================================================================
SDL_FINGERDOWN:
Sent when a finger (or stylus) is placed on a touch device.
Fields:
event.tfinger.touchId - the Id of the touch device.
event.tfinger.fingerId - the Id of the finger which just went down.
event.tfinger.x - the x coordinate of the touch (0..touch.xres)
event.tfinger.y - the y coordinate of the touch (0..touch.yres)
event.tfinger.pressure - the pressure of the touch (0..touch.pressureres)
SDL_FINGERMOTION:
Sent when a finger (or stylus) is moved on the touch device.
Fields:
Same as FINGERDOWN but with additional:
event.tfginer.dx - change in x coordinate during this motion event.
event.tfginer.dy - change in y coordinate during this motion event.
SDL_FINGERMOTION:
Sent when a finger (or stylus) is lifted from the touch device.
Fields:
Same as FINGERDOWN.
===========================================================================
Functions
===========================================================================
SDL provides the ability to access the underlying Touch and Finger structures.
These structures should _never_ be modified.
The following functions are included from SDL_Touch.h
To get a SDL_Touch device call SDL_GetTouch(touchId).
This returns an SDL_Touch*.
IMPORTANT: If the touch has been removed, or there is no touch with the given ID, SDL_GetTouch will return null. Be sure to check for this!
An SDL_Touch has the following fields:
>xres,yres,pressures:
The resolution at which x,y, and pressure values are reported. Currently these will always be equal to 2^15, but this may not always be the case.
>pressure_max, pressure_min, x_max, x_min, y_max, y_min
Which give, respectively, the maximum and minumum values that the touch digitizer can return for pressure, x coordiniate, and y coordinate AS REPORTED BY THE OPERATING SYSTEM.
On Mac/iPhone systems _max will always be 0, and _min will always be 1.
>native_xres,native_yres,native_pressureres:
The native resolution of the touch device AS REPORTED BY THE OPERATING SYSTEM.
On Mac/iPhone systems these will always be 1.
>num_fingers:
The number of fingers currently down on the device.
>fingers:
An array of pointers to the fingers which are on the device.
The most common reason to access a touch device is to normalize inputs. This would be accomplished by code like the following:
SDL_Touch* inTouch = SDL_GetTouch(event.tfinger.touchId);
if(inTouch == NULL) continue; //The touch has been removed
float x = ((float)event.tfinger.x)/inTouch->xres;
float y = ((float)event.tfinger.y)/inTouch->yres;
To get an SDL_Finger, call SDL_GetFinger(touch,fingerId), where touch is a pointer to an SDL_Touch device, and fingerId is the id of the requested finger.
This returns an SDL_Finger*, or null if the finger does not exist, or has been removed.
An SDL_Finger is guaranteed to be persistent for the duration of a touch, but it will be de-allocated as soon as the finger is removed. This occurs when the SDL_FINGERUP event is _added_ to the event queue, and thus _before_ the FINGERUP event is polled.
As a result, be very careful to check for null return values.
An SDL_Finger has the following fields:
>x,y,pressure:
The current coordinates of the touch.
>xdelta,ydelta:
The change in position resulting from the last finger motion.
>last_x, last_y, last_pressure:
The previous coordinates of the touch.
===========================================================================
Notes
===========================================================================
For a complete example see test/testgesture.c
Please direct questions/comments to:
jim.tla+sdl_touch@gmail.com

View File

@@ -6,7 +6,7 @@
Version 2.0
---
http://www.libsdl.org/
https://www.libsdl.org/
Simple DirectMedia Layer is a cross-platform development library designed
to provide low level access to audio, keyboard, mouse, joystick, and graphics
@@ -14,25 +14,8 @@ hardware via OpenGL and Direct3D. It is used by video playback software,
emulators, and popular games including Valve's award winning catalog
and many Humble Bundle games.
SDL officially supports Windows, Mac OS X, Linux, iOS, and Android.
Support for other platforms may be found in the source code.
SDL is written in C, works natively with C++, and there are bindings
available for several other languages, including C# and Python.
This library is distributed under the zlib license, which can be found
in the file "COPYING.txt".
The best way to learn how to use SDL is to check out the header files in
the "include" subdirectory and the programs in the "test" subdirectory.
The header files and test programs are well commented and always up to date.
More documentation and FAQs are available online at:
http://wiki.libsdl.org/
If you need help with the library, or just want to discuss SDL related
issues, you can join the developers mailing list:
http://www.libsdl.org/mailing-list.php
More extensive documentation is available in the docs directory, starting
with README.md
Enjoy!
Sam Lantinga (slouken@libsdl.org)

View File

@@ -1,7 +1,7 @@
Summary: Simple DirectMedia Layer
Name: SDL2
Version: 2.0.0
Release: 1
Version: 2.0.12
Release: 2
Source: http://www.libsdl.org/release/%{name}-%{version}.tar.gz
URL: http://www.libsdl.org/
License: zlib
@@ -63,28 +63,35 @@ rm -rf $RPM_BUILD_ROOT
%files
%{__defattr}
%doc README-SDL.txt COPYING.txt CREDITS.txt BUGS.txt
%doc README*.txt COPYING.txt CREDITS.txt BUGS.txt
%{_libdir}/lib*.%{__soext}.*
%files devel
%{__defattr}
%doc README README-SDL.txt COPYING CREDITS BUGS WhatsNew
%doc docs/README*.md
%{_bindir}/*-config
%{_libdir}/lib*.a
%{_libdir}/lib*.la
%{_libdir}/lib*.%{__soext}
%{_includedir}/*/*.h
%{_libdir}/pkgconfig/*
%{_libdir}/cmake/*
%{_libdir}/pkgconfig/SDL2/*
%{_datadir}/aclocal/*
%changelog
* Thu Jun 04 2015 Ryan C. Gordon <icculus@icculus.org>
- Fixed README paths.
* Sun Dec 07 2014 Simone Contini <s.contini@oltrelinux.com>
- Fixed changelog date issue and docs filenames
* Sun Jan 22 2012 Sam Lantinga <slouken@libsdl.org>
- Updated for SDL 2.0
* Tue May 16 2006 Sam Lantinga <slouken@libsdl.org>
- Removed support for Darwin, due to build problems on ps2linux
* Mon Jan 03 2004 Anders Bjorklund <afb@algonet.se>
* Sat Jan 03 2004 Anders Bjorklund <afb@algonet.se>
- Added support for Darwin, updated spec file
* Wed Jan 19 2000 Sam Lantinga <slouken@libsdl.org>

View File

@@ -1,7 +1,7 @@
Summary: Simple DirectMedia Layer
Name: SDL2
Version: @SDL_VERSION@
Release: 1
Release: 2
Source: http://www.libsdl.org/release/%{name}-%{version}.tar.gz
URL: http://www.libsdl.org/
License: zlib
@@ -63,28 +63,35 @@ rm -rf $RPM_BUILD_ROOT
%files
%{__defattr}
%doc README-SDL.txt COPYING.txt CREDITS.txt BUGS.txt
%doc README*.txt COPYING.txt CREDITS.txt BUGS.txt
%{_libdir}/lib*.%{__soext}.*
%files devel
%{__defattr}
%doc README README-SDL.txt COPYING CREDITS BUGS WhatsNew
%doc docs/README*.md
%{_bindir}/*-config
%{_libdir}/lib*.a
%{_libdir}/lib*.la
%{_libdir}/lib*.%{__soext}
%{_includedir}/*/*.h
%{_libdir}/pkgconfig/*
%{_libdir}/cmake/*
%{_libdir}/pkgconfig/SDL2/*
%{_datadir}/aclocal/*
%changelog
* Thu Jun 04 2015 Ryan C. Gordon <icculus@icculus.org>
- Fixed README paths.
* Sun Dec 07 2014 Simone Contini <s.contini@oltrelinux.com>
- Fixed changelog date issue and docs filenames
* Sun Jan 22 2012 Sam Lantinga <slouken@libsdl.org>
- Updated for SDL 2.0
* Tue May 16 2006 Sam Lantinga <slouken@libsdl.org>
- Removed support for Darwin, due to build problems on ps2linux
* Mon Jan 03 2004 Anders Bjorklund <afb@algonet.se>
* Sat Jan 03 2004 Anders Bjorklund <afb@algonet.se>
- Added support for Darwin, updated spec file
* Wed Jan 19 2000 Sam Lantinga <slouken@libsdl.org>

View File

@@ -1,112 +0,0 @@
Summary: Simple DirectMedia Layer
Name: SDL2
Version: @SDL_VERSION@
Release: 1
Source: http://www.libsdl.org/release/%{name}-%{version}.tar.gz
URL: http://www.libsdl.org/
License: zlib
Group: System Environment/Libraries
BuildRoot: %{_tmppath}/%{name}-%{version}-buildroot
Prefix: %{_prefix}
%ifos linux
Provides: libSDL2-2.0.so.0
%endif
%define __defattr %defattr(-,root,root)
%define __soext so
%description
This is the Simple DirectMedia Layer, a generic API that provides low
level access to audio, keyboard, mouse, and display framebuffer across
multiple platforms.
%package devel
Summary: Libraries, includes and more to develop SDL applications.
Group: Development/Libraries
Requires: %{name} = %{version}
%description devel
This is the Simple DirectMedia Layer, a generic API that provides low
level access to audio, keyboard, mouse, and display framebuffer across
multiple platforms.
This is the libraries, include files and other resources you can use
to develop SDL applications.
%prep
%setup -q
%build
%ifos linux
CFLAGS="$RPM_OPT_FLAGS" ./configure --prefix=%{prefix} --disable-video-directfb
%else
%configure
%endif
make
%install
rm -rf $RPM_BUILD_ROOT
%ifos linux
make install prefix=$RPM_BUILD_ROOT%{prefix} \
bindir=$RPM_BUILD_ROOT%{_bindir} \
libdir=$RPM_BUILD_ROOT%{_libdir} \
includedir=$RPM_BUILD_ROOT%{_includedir} \
datadir=$RPM_BUILD_ROOT%{_datadir} \
mandir=$RPM_BUILD_ROOT%{_mandir}
%else
%makeinstall
%endif
%clean
rm -rf $RPM_BUILD_ROOT
%files
%{__defattr}
%doc README-SDL.txt COPYING.txt CREDITS.txt BUGS.txt
%{_libdir}/lib*.%{__soext}.*
%files devel
%{__defattr}
%doc README README-SDL.txt COPYING CREDITS BUGS WhatsNew
%{_bindir}/*-config
%{_libdir}/lib*.a
%{_libdir}/lib*.la
%{_libdir}/lib*.%{__soext}
%{_includedir}/*/*.h
%{_libdir}/pkgconfig/*
%{_datadir}/aclocal/*
%changelog
* Sun Jan 22 2012 Sam Lantinga <slouken@libsdl.org>
- Updated for SDL 2.0
* Tue May 16 2006 Sam Lantinga <slouken@libsdl.org>
- Removed support for Darwin, due to build problems on ps2linux
* Mon Jan 03 2004 Anders Bjorklund <afb@algonet.se>
- Added support for Darwin, updated spec file
* Wed Jan 19 2000 Sam Lantinga <slouken@libsdl.org>
- Re-integrated spec file into SDL distribution
- 'name' and 'version' come from configure
- Some of the documentation is devel specific
- Removed SMP support from %build - it doesn't work with libtool anyway
* Tue Jan 18 2000 Hakan Tandogan <hakan@iconsult.com>
- Hacked Mandrake sdl spec to build 1.1
* Sun Dec 19 1999 John Buswell <johnb@mandrakesoft.com>
- Build Release
* Sat Dec 18 1999 John Buswell <johnb@mandrakesoft.com>
- Add symlink for libSDL-1.0.so.0 required by sdlbomber
- Added docs
* Thu Dec 09 1999 Lenny Cartier <lenny@mandrakesoft.com>
- v 1.0.0
* Mon Nov 1 1999 Chmouel Boudjnah <chmouel@mandrakesoft.com>
- First spec file for Mandrake distribution.
# end of file

View File

@@ -1,115 +0,0 @@
--- SDL2.spec.in 2013-10-08 17:46:42.388028693 +0200
+++ SDL2.spec.in 1970-01-01 01:00:00.000000000 +0100
@@ -1,112 +0,0 @@
-Summary: Simple DirectMedia Layer
-Name: SDL2
-Version: @SDL_VERSION@
-Release: 1
-Source: http://www.libsdl.org/release/%{name}-%{version}.tar.gz
-URL: http://www.libsdl.org/
-License: zlib
-Group: System Environment/Libraries
-BuildRoot: %{_tmppath}/%{name}-%{version}-buildroot
-Prefix: %{_prefix}
-%ifos linux
-Provides: libSDL2-2.0.so.0
-%endif
-
-%define __defattr %defattr(-,root,root)
-%define __soext so
-
-%description
-This is the Simple DirectMedia Layer, a generic API that provides low
-level access to audio, keyboard, mouse, and display framebuffer across
-multiple platforms.
-
-%package devel
-Summary: Libraries, includes and more to develop SDL applications.
-Group: Development/Libraries
-Requires: %{name} = %{version}
-
-%description devel
-This is the Simple DirectMedia Layer, a generic API that provides low
-level access to audio, keyboard, mouse, and display framebuffer across
-multiple platforms.
-
-This is the libraries, include files and other resources you can use
-to develop SDL applications.
-
-
-%prep
-%setup -q
-
-%build
-%ifos linux
-CFLAGS="$RPM_OPT_FLAGS" ./configure --prefix=%{prefix} --disable-video-directfb
-%else
-%configure
-%endif
-make
-
-%install
-rm -rf $RPM_BUILD_ROOT
-%ifos linux
-make install prefix=$RPM_BUILD_ROOT%{prefix} \
- bindir=$RPM_BUILD_ROOT%{_bindir} \
- libdir=$RPM_BUILD_ROOT%{_libdir} \
- includedir=$RPM_BUILD_ROOT%{_includedir} \
- datadir=$RPM_BUILD_ROOT%{_datadir} \
- mandir=$RPM_BUILD_ROOT%{_mandir}
-%else
-%makeinstall
-%endif
-
-%clean
-rm -rf $RPM_BUILD_ROOT
-
-%files
-%{__defattr}
-%doc README-SDL.txt COPYING CREDITS BUGS
-%{_libdir}/lib*.%{__soext}.*
-
-%files devel
-%{__defattr}
-%doc README README-SDL.txt COPYING CREDITS BUGS WhatsNew
-%{_bindir}/*-config
-%{_libdir}/lib*.a
-%{_libdir}/lib*.la
-%{_libdir}/lib*.%{__soext}
-%{_includedir}/*/*.h
-%{_libdir}/pkgconfig/*
-%{_datadir}/aclocal/*
-
-%changelog
-* Sun Jan 22 2012 Sam Lantinga <slouken@libsdl.org>
-- Updated for SDL 2.0
-
-* Tue May 16 2006 Sam Lantinga <slouken@libsdl.org>
-- Removed support for Darwin, due to build problems on ps2linux
-
-* Mon Jan 03 2004 Anders Bjorklund <afb@algonet.se>
-- Added support for Darwin, updated spec file
-
-* Wed Jan 19 2000 Sam Lantinga <slouken@libsdl.org>
-- Re-integrated spec file into SDL distribution
-- 'name' and 'version' come from configure
-- Some of the documentation is devel specific
-- Removed SMP support from %build - it doesn't work with libtool anyway
-
-* Tue Jan 18 2000 Hakan Tandogan <hakan@iconsult.com>
-- Hacked Mandrake sdl spec to build 1.1
-
-* Sun Dec 19 1999 John Buswell <johnb@mandrakesoft.com>
-- Build Release
-
-* Sat Dec 18 1999 John Buswell <johnb@mandrakesoft.com>
-- Add symlink for libSDL-1.0.so.0 required by sdlbomber
-- Added docs
-
-* Thu Dec 09 1999 Lenny Cartier <lenny@mandrakesoft.com>
-- v 1.0.0
-
-* Mon Nov 1 1999 Chmouel Boudjnah <chmouel@mandrakesoft.com>
-- First spec file for Mandrake distribution.
-
-# end of file

View File

@@ -0,0 +1 @@
include("${CMAKE_CURRENT_LIST_DIR}/SDL2Targets.cmake")

View File

@@ -1,16 +0,0 @@
2.0 release checklist:
* http://wiki.libsdl.org/moin.cgi/Roadmap
* See why windows are being rearranged. Is the shield window not up?
* Make sure you can create and show a fullscreen window in one step
* Write automated test case for multi-draw APIs
* Implement assertion code on iPhone
* Add __WINDOWS__ in addition to __WIN32__
* Check 1.2 revisions:
3554 - Need to resolve semantics for locking keys on different platforms
4874 - Do we want screen rotation? At what level?
4974 - Windows file code needs to convert UTF-8 to Unicode, but we don't need to tap dance for Windows 95/98
4484, 4485 - Verify that SDL's Windows keyboard handling works correctly
4865 - See if this is still needed (mouse coordinate clamping)
4866 - See if this is still needed (blocking window repositioning)

View File

@@ -1,15 +1,10 @@
Future work roadmap:
* http://wiki.libsdl.org/moin.cgi/Roadmap
* See why windows are being rearranged. Is the shield window not up?
* Add __WINDOWS__ in addition to __WIN32__
* Write test for fullscreen gamma to check X11 colormap handling
* Check 1.2 revisions:
3554 - Need to resolve semantics for locking keys on different platforms
4874 - Do we want screen rotation? At what level?
4974 - Windows file code needs to convert UTF-8 to Unicode, but we don't need to tap dance for Windows 95/98
4484, 4485 - Verify that SDL's Windows keyboard handling works correctly
4865 - See if this is still needed (mouse coordinate clamping)
4866 - See if this is still needed (blocking window repositioning)

View File

@@ -1 +0,0 @@
WARNING: This code is under construction, may not build, and is unstable!

View File

@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>SDL2-WinRT</id>
<version>2.0.4-Unofficial</version>
<authors>Sam Lantinga</authors>
<owners>David Ludwig</owners>
<licenseUrl>http://libsdl.org/license.php</licenseUrl>
<projectUrl>http://libsdl.org</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Unofficial pre-release of LibSDL2, built for WinRT platforms</description>
<copyright>Copyright 2015</copyright>
<tags>SDL2 SDL LibSDL OpenGL C C++ nativepackage</tags>
</metadata>
<files>
<file src="lib\**\*.dll" target="bin"/>
<file src="lib\**\*.lib" target="bin"/>
<file src="lib\**\*.pdb" target="bin"/>
<file src="..\include\**\*.*" target="include"/>
<file src="..\src\**\*.*" target="src"/>
<file src="SDL2-WinRT.targets" target="build\native"/>
</files>
</package>

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'Windows' and '$(TargetPlatformVersion)' == '8.1'">WinRT81</LibSDL2-DeviceType>
<LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'Windows Phone' and '$(TargetPlatformVersion)' == '8.0'">WinPhone80</LibSDL2-DeviceType>
<LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'WindowsPhoneApp' and '$(TargetPlatformVersion)' == '8.1'">WinPhone81</LibSDL2-DeviceType>
<LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'UAP'">UWP</LibSDL2-DeviceType>
<LibSDL2-BinPath>$(MSBuildThisFileDirectory)..\..\bin\$(LibSDL2-DeviceType)\$(Platform)</LibSDL2-BinPath>
</PropertyGroup>
<Target Name="LibSDL2-DeviceType-Check" BeforeTargets="ResolveAssemblyReferences">
<Error Condition="'$(LibSDL2-DeviceType)' == ''" Text="Unable to determine which version of Windows is being built-for" />
</Target>
<ItemDefinitionGroup>
<Link>
<AdditionalLibraryDirectories>$(LibSDL2-BinPath);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>SDL2.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup Label="LibSDL2">
<PackagingOutputs Include="$(LibSDL2-BinPath)\SDL2.dll">
<OutputGroup>LibSDL2Binaries</OutputGroup>
<ProjectName>$(ProjectName)</ProjectName>
<TargetPath>%(Filename)%(Extension)</TargetPath>
</PackagingOutputs>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>SDL2main-WinRT-NonXAML</id>
<version>2.0.4-Unofficial</version>
<authors>Sam Lantinga</authors>
<owners>David Ludwig</owners>
<licenseUrl>http://libsdl.org/license.php</licenseUrl>
<projectUrl>http://libsdl.org</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>WinMain() function for SDL2 + WinRT + CoreWindow (non-XAML) apps</description>
<copyright>Copyright 2015</copyright>
<tags>SDL2 SDL LibSDL OpenGL C C++ nativepackage</tags>
<dependencies>
<dependency id="SDL2-WinRT" version="2.0.4"/>
</dependencies>
</metadata>
<files>
<file src="..\src\main\winrt\SDL_winrt_main_NonXAML.cpp" target="src\main\winrt"/>
<file src="SDL2main-WinRT-NonXAML.targets" target="build\native"/>
</files>
</package>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="LibSDL2">
<ClCompile Include="$(MSBuildThisFileDirectory)..\..\src\main\winrt\SDL_winrt_main_NonXAML.cpp">
<CompileAsWinRT>true</CompileAsWinRT>
</ClCompile>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,34 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SDL2-UWP", "SDL-UWP.vcxproj", "{89E9B32E-A86A-47C3-A948-D2B1622925CE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Debug|ARM.ActiveCfg = Debug|ARM
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Debug|ARM.Build.0 = Debug|ARM
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Debug|x64.ActiveCfg = Debug|x64
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Debug|x64.Build.0 = Debug|x64
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Debug|x86.ActiveCfg = Debug|Win32
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Debug|x86.Build.0 = Debug|Win32
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Release|ARM.ActiveCfg = Release|ARM
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Release|ARM.Build.0 = Release|ARM
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Release|x64.ActiveCfg = Release|x64
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Release|x64.Build.0 = Release|x64
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Release|x86.ActiveCfg = Release|Win32
{89E9B32E-A86A-47C3-A948-D2B1622925CE}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Some files were not shown because too many files have changed in this diff Show More