First public version, compilation on Windows (mingw64) verified

This commit is contained in:
Emil Romanus 2022-08-06 14:06:22 +02:00
commit a5c73f9ea1
10914 changed files with 2521277 additions and 0 deletions

43
.gitignore vendored Normal file
View file

@ -0,0 +1,43 @@
*.sw?
build
bin/
*.o
#llvm-specific temporary object-files
*.o-*
*.lo
*.exe
.deps/
.dirstamp
apparatus2
config.log
config.status
aclocal.m4
configure
Makefile.in
Makefile
Makefile.rules
SDL2.spec
autom4te.cache
libtool
sdl2-config
sdl2.pc
*.mode1v3
*.pbxuser
build-ios/principia/principia.xcodeproj/project.xcworkspace/xcuserdata/
build-linux/Makefile
build-windows/Makefile
*.xcuserstate
R.java
R.java.d
missing
install-sh
.directory
local.properties
callgrind.*
*.dot
gdb.txt
principia.state
sha1_test
.DS_Store

18
AUTHORS.md Normal file
View file

@ -0,0 +1,18 @@
Original Authors of Principia
===========================
Emil Romanus
Original creator, programming, game design, 3D modeling, graphics
Rasmus Karlsson
Game programming, server development, and more
Mikael Romanus
3D Modeling, code twiddling
Contributors
-------------
Anders Schanche
3D Models (Tesla Gun, Rocket Launcher, and more), testing

23
LICENSE.md Normal file
View file

@ -0,0 +1,23 @@
Copyright (c) 2012-2022 Bithack AB
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

41
README.md Normal file
View file

@ -0,0 +1,41 @@
Principia Open Source Project
=========
Principia is a sandbox physics game originally released in November 2013. It is the successor to the Android hit game "Apparatus".
The project can be built on Windows, Linux, Android or iOS. The iOS version lags behind and lacks a lot of UI. The Android version is outdated and probably needs some work to compile.
Compilation on Windows and Linux should be easy, see below.
Compiling and running
--------
Building on Windows
- Install MSYS2 64bit
$ pacman -Syu
Terminal will ask to close it self when done. GO to start menu and run MSYS Mingw32 64-bit
$ pacman -S --neded base-devel mingw-w64-x86_64-toolchain autotools
$ pacman -S mingw-w64-x86_64-gtk2
$ pacman -S mingw-w64-x86_64-curl
Navigate to the 'build-windows' folder inside where you cloned Principia, for example:
$ cd /c/Users/<username>/Principia/build-windows
$ ./autogen.sh
$ ./configure
$ ./go
Clean with:
$ make clean
See the build-linux directory for Linux instructions. More info coming soon.
License
---------
See LICENSE.md

42
THANKS.md Normal file
View file

@ -0,0 +1,42 @@
Thanks
===========
We would like to send a special thanks to some of the most dedicated Apparatus and Principia players who have supported development and helped the community.
Alfajim
Axohmega
BobMonkeypimp
Cheddah
Cralant
Ctjet
Demon666
Doughnuts108
Golden
JOELwindows7
Nighthawk
Ridget
Rubicon
Sasha from Russia
TechZ
Tetsu
The_Blacksmith_
abrackers
incrazyboyy
mrsimb
mznznlt
sjoerd1999
wokstation
woodnut
yo man
zardOz (RIP)
And everyone else in the Principia and Apparatus communities.
In Memory of Keith Tripp
------------------------
I would like to dedicate a few lines to Keith Tripp, aka zardOz. By definition the go-to guy when you had a Principia question, Keith helped newcomers understand and get started building things. Keith created hundreds of tutorial levels and was always one of the first to learn the latest object. Unfortunately, I was notified of his passing late 2015. There will always be tutorials, but never another Keith Tripp.
I was told Principia inspired Keith to become interested in programming. He would have loved to see Principia being open sourced.
Emil

10
build-android-lite/.gitignore vendored Normal file
View file

@ -0,0 +1,10 @@
*.class
.classpath
.project
libs/
obj/
BuildConfig.java
gen/R.java.d
local.properties
R.java
bin

View file

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bithack.principialite"
android:installLocation="auto"
android:versionCode="26"
android:versionName="1.4.0.4">
<supports-screens android:resizeable="true" android:smallScreens="false" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true"></supports-screens>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
<uses-feature android:name="android.hardware.touchscreen" android:required="true"></uses-feature>
<uses-feature android:glEsVersion="0x00020000" android:required="true"></uses-feature>
<uses-feature android:name="android.hardware.screen.landscape" android:required="true"></uses-feature>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
<application
android:allowBackup="false"
android:label="@string/app_name_lite"
android:icon="@drawable/icon"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<activity android:screenOrientation="landscape" android:name="com.bithack.principialite.PrincipiaActivity" android:configChanges="keyboard|keyboardHidden|orientation" android:label="@string/app_name_lite" android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="principia" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/lite_app_id"/>
</application>
</manifest>

View file

@ -0,0 +1 @@
../../data-mobile/

View file

@ -0,0 +1 @@
../../data-shared/

View file

@ -0,0 +1,17 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked in Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Principia-lite" default="help">
<loadproperties srcFile="local.properties" />
<property file="build.properties" />
<property file="default.properties" />
<loadproperties srcFile="default.properties" />
<import file="${sdk.dir}/tools/ant/build.xml" />
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
</project>

View file

@ -0,0 +1,2 @@
# Project target.
target=android-11

View file

@ -0,0 +1,25 @@
while true; do
read -p "Warning: This will remove any changes you have made to the lite sourcefiles. Are you sure you want to continue? [y/n] " yn
case $yn in
[Yy]* ) break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
rm -rfv src/
cp -rv ../build-android/src .
find . -type f -iname "*.java" -exec sed -i 's/com\.bithack\.principia\.R/com.bithack.principialite.R/g' {} \;
find . -type f -iname "*.java" -exec sed -i 's/com\.bithack\.principia\.PrincipiaActivity/com.bithack.principialite.PrincipiaActivity/g' {} \;
find . -type f -iname "*.java" -exec sed -i 's/package com\.bithack\.principia\;/package com.bithack.principialite;/g' {} \;
find . -type f -iname "*.java" -exec sed -i 's/FULL = true/FULL = false/g' {} \;
mkdir -pv src/com/bithack/principialite
mv src/com/bithack/principia/*.java src/com/bithack/principialite/
echo "done"
#bottom two might be necessary if the third one does not work.
#find . -type f -iname "*.java" -exec sed -i 's/package com\.bithack\.principia/package com.bithack.principialite/g' {} \;
#find . -type f -iname "*.java" -exec sed -i 's/package com\.bithack\.principialite\.shared/package com.bithack.principia.shared/g' {} \;

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

1
build-android-lite/jni Normal file
View file

@ -0,0 +1 @@
../src

View file

@ -0,0 +1 @@
keytool -genkey -v -keystore principia-lite-release-key.keystore -alias bithack -keyalg RSA -keysize 2048 -validity 10000

View file

@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View file

@ -0,0 +1,13 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-17
#proguard.config=proguard-android-principia.txt
android.library.reference.1=../src/facebook-android-sdk-3.5/facebook

View file

@ -0,0 +1 @@
../../build-android/res/anim/

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 726 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 888 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:height="1dip" />
<solid android:color="#666666" />
</shape>

View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="false" android:drawable="@drawable/timepicker_down_normal" />
<item android:state_pressed="true" android:state_enabled="true"
android:drawable="@drawable/timepicker_down_pressed" />
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="true" android:drawable="@drawable/timepicker_down_selected" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="false" android:drawable="@drawable/timepicker_down_disabled" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="true" android:drawable="@drawable/timepicker_down_disabled_focused" />
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 956 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 938 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 884 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="false" android:drawable="@drawable/timepicker_input_normal" />
<item android:state_pressed="true" android:state_enabled="true"
android:drawable="@drawable/timepicker_input_pressed" />
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="true" android:drawable="@drawable/timepicker_input_selected" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="false" android:drawable="@drawable/timepicker_input_disabled" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="true" android:drawable="@drawable/timepicker_input_normal" />
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 578 B

View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="false" android:drawable="@drawable/timepicker_up_normal" />
<item android:state_pressed="true" android:state_enabled="true"
android:drawable="@drawable/timepicker_up_pressed" />
<item android:state_pressed="false" android:state_enabled="true"
android:state_focused="true" android:drawable="@drawable/timepicker_up_selected" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="false" android:drawable="@drawable/timepicker_up_disabled" />
<item android:state_pressed="false" android:state_enabled="false"
android:state_focused="true" android:drawable="@drawable/timepicker_up_disabled_focused" />
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View file

@ -0,0 +1 @@
../../build-android/res/layout

View file

@ -0,0 +1 @@
../../build-android/res/layout-land

View file

@ -0,0 +1 @@
../../build-android/res/values

View file

@ -0,0 +1,47 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class AutosaveDialog
{
static Dialog _dialog = null;
public AutosaveDialog()
{
/*
Log.v("Principia", String.format("Board: %s\nBrand:%s\nDevice:%s\nDisplay:%s\nModel:%s",
android.os.Build.BOARD,
android.os.Build.BRAND,
android.os.Build.DEVICE,
android.os.Build.DISPLAY,
android.os.Build.MODEL
));
*/
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setMessage("Autosave file detected. Open or remove?")
.setPositiveButton("Open", new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_OPEN_AUTOSAVE, 0);
}}
)
.setNegativeButton("Remove", new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_REMOVE_AUTOSAVE, 0);
}}
)
.create();
}
public Dialog get_dialog()
{
return _dialog;
}
}

View file

@ -0,0 +1,61 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
public class CamTargeterDialog {
static Dialog _dialog;
static View view;
static Spinner s_follow_mode;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.cam_targeter, null);
s_follow_mode = (Spinner)view.findViewById(R.id.follow_mode);
bld.setTitle("Cam Targeter");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
s_follow_mode.setSelection(PrincipiaBackend.getCamTargeterFollowMode());
}
public static void save()
{
PrincipiaBackend.setCamTargeterFollowMode(s_follow_mode.getSelectedItemPosition());
}
}

View file

@ -0,0 +1,374 @@
package com.bithack.principia.shared;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class CodeEditor extends EditText
{
public interface OnTextChangedListener
{
public void onTextChanged( String text );
}
public OnTextChangedListener onTextChangedListener = null;
public final int updateDelay = 5000;
public boolean dirty = false;
public long last_edit = 0;
private static final int COLOR_NUMBER = 0xff7ba212;
private static final int COLOR_KEYWORD = 0xff399ed7;
private static final int COLOR_BUILTIN = 0xffd79e39;
private static final int COLOR_COMMENT = 0xff808080;
private static final Pattern numbers = Pattern.compile(
"\\b(\\d*[.]?\\d+)\\b" );
private static final Pattern keywords = Pattern.compile(
"\\b("+
"do|for|while|if|then|else|in|out|end|true|false|"+
"function|return|self|local"+
")\\b" );
private static final Pattern builtins = Pattern.compile(
"\\b("+
"this|game|cam|world|math|pairs|ipairs|setmetatable|nil"+
")\\b" );
private static final Pattern comments = Pattern.compile(
"--\\[\\[(?:.|[\\n\\r])*?--\\]\\]|--.*" );
private static final Pattern trailingWhiteSpace = Pattern.compile(
"[\\t ]+$",
Pattern.MULTILINE );
private static final Handler updateHandler = new Handler() {
};
private final Runnable updateRunnable =
new Runnable()
{
@Override
public void run()
{
if (SystemClock.uptimeMillis()-updateDelay < last_edit) {
Log.v("Principia", "skipping!");
return;
}
Editable e = getText();
if( onTextChangedListener != null )
onTextChangedListener.onTextChanged( e.toString() );
highlightWithoutChange( e );
Log.v("Principia", "runnable run end");
}
};
private boolean modified = true;
public CodeEditor( Context context )
{
super( context );
init();
}
public CodeEditor( Context context, AttributeSet attrs )
{
super( context, attrs );
init();
}
public void setTextHighlighted( CharSequence text )
{
cancelUpdate();
dirty = false;
modified = false;
setText( highlight( new SpannableStringBuilder( text ) ) );
modified = true;
if( onTextChangedListener != null )
onTextChangedListener.onTextChanged( text.toString() );
}
public String getCleanText()
{
return trailingWhiteSpace
.matcher( getText() )
.replaceAll( "" );
}
public void refresh()
{
highlightWithoutChange( getText() );
}
private void init()
{
setHorizontallyScrolling( true );
setFilters( new InputFilter[]{
new InputFilter()
{
@Override
public CharSequence filter(
CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend )
{
if( modified &&
end-start == 1 &&
start < source.length() &&
dstart < dest.length() )
{
char c = source.charAt( start );
if( c == '\n' )
return autoIndent(
source,
start,
end,
dest,
dstart,
dend );
}
return source;
}
} } );
addTextChangedListener(
new TextWatcher()
{
public void onTextChanged(
CharSequence s,
int start,
int before,
int count )
{
}
public void beforeTextChanged(
CharSequence s,
int start,
int count,
int after )
{
}
public void afterTextChanged( Editable e )
{
last_edit = SystemClock.uptimeMillis();
Log.v("Principia", "afterTextChanged begin");
cancelUpdate();
if( !modified ) {
Log.v("Principia", "afterTextChanged end");
return;
}
dirty = true;
updateHandler.postDelayed(
updateRunnable,
updateDelay );
Log.v("Principia", "afterTextChanged end");
}
} );
}
private void cancelUpdate()
{
updateHandler.removeCallbacks( updateRunnable );
}
private void highlightWithoutChange( Editable e )
{
modified = false;
highlight( e );
modified = true;
}
private Editable highlight( Editable e )
{
last_edit = SystemClock.uptimeMillis();
if (true) {
//return e;
}
Log.v("Principia", "highlight begin");
try
{
// don't use e.clearSpans() because it will remove
// too much
clearSpans( e );
if( e.length() == 0 )
return e;
/*
for( Matcher m = numbers.matcher( e );
m.find(); )
e.setSpan(
new ForegroundColorSpan( COLOR_NUMBER ),
m.start(),
m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
*/
for( Matcher m = keywords.matcher( e );
m.find(); )
e.setSpan(
new ForegroundColorSpan( COLOR_KEYWORD ),
m.start(),
m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
for( Matcher m = builtins.matcher( e );
m.find(); )
e.setSpan(
new ForegroundColorSpan( COLOR_BUILTIN ),
m.start(),
m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
for( Matcher m = comments.matcher( e );
m.find(); )
e.setSpan(
new ForegroundColorSpan( COLOR_COMMENT ),
m.start(),
m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
}
catch( Exception ex )
{
}
Log.v("Principia", "highlight end");
return e;
}
private void clearSpans( Editable e )
{
// remove foreground color spans
{
ForegroundColorSpan spans[] = e.getSpans(
0,
e.length(),
ForegroundColorSpan.class );
for( int n = spans.length; n-- > 0; )
e.removeSpan( spans[n] );
}
/*
// remove background color spans
{
BackgroundColorSpan spans[] = e.getSpans(
0,
e.length(),
BackgroundColorSpan.class );
for( int n = spans.length; n-- > 0; )
e.removeSpan( spans[n] );
}
*/
}
private CharSequence autoIndent(
CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend )
{
String indent = "";
int istart = dstart-1;
int iend = -1;
// find start of this line
boolean dataBefore = false;
int pt = 0;
for( ; istart > -1; --istart )
{
char c = dest.charAt( istart );
if( c == '\n' )
break;
if( c != ' ' &&
c != '\t' )
{
if( !dataBefore )
{
// indent always after those characters
if( c == '{' ||
c == '+' ||
c == '-' ||
c == '*' ||
c == '/' ||
c == '%' ||
c == '^' ||
c == '=' )
--pt;
dataBefore = true;
}
// parenthesis counter
if( c == '(' )
--pt;
else if( c == ')' )
++pt;
}
}
// copy indent of this line into the next
if( istart > -1 )
{
char charAtCursor = dest.charAt( dstart );
for( iend = ++istart;
iend < dend;
++iend )
{
char c = dest.charAt( iend );
// auto expand comments
if( charAtCursor != '\n' &&
c == '/' &&
iend+1 < dend &&
dest.charAt( iend ) == c )
{
iend += 2;
break;
}
if( c != ' ' &&
c != '\t' )
break;
}
indent += dest.subSequence( istart, iend );
}
// add new indent
if( pt < 0 )
indent += "\t";
// append white space of previous line and new indent
return source+indent;
}
}

View file

@ -0,0 +1,263 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorChooserDialog {
static AlertDialog _dialog;
static EditText et_red;
static EditText et_green;
static EditText et_blue;
static EditText et_alpha;
static SeekBar sb_red;
static SeekBar sb_green;
static SeekBar sb_blue;
static SeekBar sb_alpha;
static ImageView sv_color;
static Canvas color_canvas;
static LinearLayout ll_alpha;
private static View view;
public static void update_canvas()
{
int r,g,b;
r = sb_red.getProgress();
g = sb_green.getProgress();
b = sb_blue.getProgress();
color_canvas.drawRGB(r, g, b);
sv_color.draw(color_canvas);
sv_color.refreshDrawableState();
sv_color.postInvalidate();
}
public static Dialog get_dialog()
{
if (_dialog == null) {
Bitmap bitmap = Bitmap.createBitmap(80, 50, Bitmap.Config.ARGB_8888);
color_canvas = new android.graphics.Canvas(bitmap);
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.color_chooser, null);
et_red = (EditText)view.findViewById(R.id.et_red);
et_green = (EditText)view.findViewById(R.id.et_green);
et_blue = (EditText)view.findViewById(R.id.et_blue);
et_alpha = (EditText)view.findViewById(R.id.et_alpha);
sb_red = (SeekBar)view.findViewById(R.id.sb_red);
sb_green = (SeekBar)view.findViewById(R.id.sb_green);
sb_blue = (SeekBar)view.findViewById(R.id.sb_blue);
sb_alpha = (SeekBar)view.findViewById(R.id.sb_alpha);
sv_color = (ImageView)view.findViewById(R.id.iv_color);
ll_alpha = (LinearLayout)view.findViewById(R.id.ll_alpha);
sv_color.setImageBitmap(bitmap);
sb_red.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
et_red.setText(String.valueOf(progress));
update_canvas();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
sb_green.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
et_green.setText(String.valueOf(progress));
update_canvas();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
sb_blue.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
et_blue.setText(String.valueOf(progress));
update_canvas();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
sb_alpha.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
et_alpha.setText(String.valueOf(progress));
update_canvas();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
et_red.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
int progress = 0;
try {
progress = Integer.parseInt(et_red.getText().toString());
} catch (NumberFormatException e) {
progress = 0;
}
sb_red.setProgress(progress);
}
});
et_green.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
int progress = 0;
try {
progress = Integer.parseInt(et_green.getText().toString());
} catch (NumberFormatException e) {
progress = 0;
}
sb_green.setProgress(progress);
}
});
et_blue.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
int progress = 0;
try {
progress = Integer.parseInt(et_blue.getText().toString());
} catch (NumberFormatException e) {
progress = 0;
}
sb_blue.setProgress(progress);
}
});
et_alpha.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
int progress = 0;
try {
progress = Integer.parseInt(et_alpha.getText().toString());
} catch (NumberFormatException e) {
progress = 0;
}
sb_alpha.setProgress(progress);
}
});
//bld.setTitle("color picker");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di, boolean has_alpha)
{
int color = PrincipiaBackend.getEntityColor();
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
int a = Color.alpha(color);
et_red.setText(String.valueOf(r));
et_green.setText(String.valueOf(g));
et_blue.setText(String.valueOf(b));
et_alpha.setText(String.valueOf(a));
sb_red.setProgress(r);
sb_green.setProgress(g);
sb_blue.setProgress(b);
sb_alpha.setProgress(a);
if (has_alpha) {
ll_alpha.setVisibility(View.VISIBLE);
} else {
ll_alpha.setVisibility(View.GONE);
sb_alpha.setProgress(255);
}
update_canvas();
}
public static void save()
{
int color = 0;
int r,g,b,a;
try {
r = Integer.parseInt(et_red.getText().toString());
} catch (NumberFormatException e) {
r = 0;
}
try {
g = Integer.parseInt(et_green.getText().toString());
} catch (NumberFormatException e) {
g = 0;
}
try {
b = Integer.parseInt(et_blue.getText().toString());
} catch (NumberFormatException e) {
b = 0;
}
try {
a = Integer.parseInt(et_alpha.getText().toString());
} catch (NumberFormatException e) {
a = 0;
}
color = Color.argb(a, r, g, b);
Log.v("Principia", String.format("%d - %d/%d,%d,%d,", color, a, r, g, b));
PrincipiaBackend.setEntityColor(color);
}
}

View file

@ -0,0 +1,62 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
public class CommandPadDialog {
static Dialog _dialog;
static View view;
static Spinner s_command;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.command_pad, null);
s_command = (Spinner)view.findViewById(R.id.command);
bld.setTitle("Command pad");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
CommandPadDialog._dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
//((Spinner)view.findViewById(R.id.command)).setSelection(PrincipiaActivity.getCommandPadCommand());
s_command.setSelection(PrincipiaBackend.getCommandPadCommand());
}
public static void save()
{
PrincipiaBackend.setCommandPadCommand(s_command.getSelectedItemPosition());
}
}

View file

@ -0,0 +1,52 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
public class CommunityDialog
{
static Dialog _dialog = null;
public CommunityDialog()
{
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setMessage("Do you want to return to the community site or to the main menu?")
.setPositiveButton("Community", new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
//SDLActivity.wv_dialog.show();
/*
PackageManager pm = SDLActivity.mSingleton.getPackageManager();
Intent queryIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://bithack.com"));
ActivityInfo af = queryIntent.resolveActivityInfo(pm, 0);
Intent launchIntent = new Intent(Intent.ACTION_MAIN);
launchIntent.setClassName(af.packageName, af.name);
SDLActivity.mSingleton.startActivity(launchIntent);
*/
SDLActivity.wv.loadUrl(PrincipiaBackend.getCurrentCommunityUrl());
SDLActivity.wv_dialog.show();
}}
)
.setNegativeButton("Main menu", new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_GOTO_MAINMENU, 0);
}}
)
.create();
}
public Dialog get_dialog()
{
return _dialog;
}
}

View file

@ -0,0 +1,59 @@
package com.bithack.principia.shared;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class ConfirmDialog
{
public static final int OPTION_NO = 0;
public static final int OPTION_YES = 1;
private OnOptionSelectedListener mListener = null;
public interface OnOptionSelectedListener {
public void onOptionSelected(int option);
}
public ConfirmDialog set_listener(OnOptionSelectedListener l)
{
this.mListener = l;
return this;
}
public ConfirmDialog run(String message)
{
return this.run(message, "Yes", "No");
}
public ConfirmDialog run(String message, String button1, String button2)
{
AlertDialog dialog = new AlertDialog.Builder(SDLActivity.getContext()).create();
//dialog.setTitle("Confirmation");
dialog.setMessage(message);
dialog.setCancelable(false);
dialog.setOnShowListener(SDLActivity.mSingleton);
dialog.setOnDismissListener(SDLActivity.mSingleton);
dialog.setButton(DialogInterface.BUTTON_POSITIVE, button1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
if (mListener != null) {
mListener.onOptionSelected(OPTION_YES);
}
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, button2, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
if (mListener != null) {
mListener.onOptionSelected(OPTION_NO);
}
}
});
dialog.setIcon(android.R.drawable.ic_dialog_alert);
dialog.show();
return this;
}
}

View file

@ -0,0 +1,67 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class ConsumableDialog {
static Dialog _dialog;
static View view;
static Spinner s_consumable;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.consumable, null);
s_consumable = (Spinner)view.findViewById(R.id.s_consumable);
String[] consumables = PrincipiaBackend.getConsumables().split(",");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(SDLActivity.mSingleton, android.R.layout.select_dialog_item, consumables);
s_consumable.setAdapter(spinnerArrayAdapter);
bld.setTitle("Consumable");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ConsumableDialog._dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
s_consumable.setSelection(PrincipiaBackend.getConsumableType());
}
public static void save()
{
PrincipiaBackend.setConsumableType(s_consumable.getSelectedItemPosition());
}
}

View file

@ -0,0 +1,52 @@
package com.bithack.principia.shared;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class CustomLinearLayout extends LinearLayout {
public static final int KEYBOARD_HIDDEN = 0;
public static final int KEYBOARD_SHOWN = 1;
private OnKeyboardStateChangedListener mListener = null;
public interface OnKeyboardStateChangedListener {
public void onKeyboardStateChanged(int new_state);
}
public CustomLinearLayout set_listener(OnKeyboardStateChangedListener l)
{
this.mListener = l;
return this;
}
public CustomLinearLayout(Context context) {
super(context);
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
final int actualHeight = getHeight();
/* TODO: Make sure this event is only fired off once. */
if (actualHeight > proposedheight){
if (this.mListener != null) {
this.mListener.onKeyboardStateChanged(this.KEYBOARD_SHOWN);
}
} else {
if (this.mListener != null) {
this.mListener.onKeyboardStateChanged(this.KEYBOARD_HIDDEN);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

View file

@ -0,0 +1,350 @@
package com.bithack.principia.shared;
import java.util.ArrayList;
import java.util.List;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DigitalDisplayDialog {
static Dialog _dialog;
static View view;
static CheckBox cb_wrap_around;
static LinearLayout ll_dd;
static LinearLayout ll_wrap;
static NumberPicker np_initial_position;
static EditText et_symbols;
static TextView tv_dd_symbol_id;
static TextView tv_dd_num_symbols;
static Button btn_dd_next;
static Button btn_dd_previous;
static Button btn_dd_insert;
static Button btn_dd_append;
static Button btn_dd_remove;
static int cur_symbol;
static int num_symbols;
static final int MIN_INITIAL_POS = 1;
static final int NUM_CHARS_IN_SYMBOL = 35;
static final String EMPTY_SYMBOL = "00000000000000000000000000000000000";
static CheckBox[] cb_symbols;
static List<String> symbols;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
cur_symbol = 0;
symbols = new ArrayList<String>();
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.digital_display, null);
cb_wrap_around = (CheckBox)view.findViewById(R.id.cb_wrap_around);
ll_dd = (LinearLayout)view.findViewById(R.id.ll_dd);
ll_wrap = (LinearLayout)view.findViewById(R.id.display_ll_wrap);
np_initial_position = new com.bithack.principia.shared.NumberPicker(SDLActivity.getContext());
np_initial_position.setRange(MIN_INITIAL_POS, 40);
ll_dd.addView((View)np_initial_position);
tv_dd_symbol_id = (TextView)view.findViewById(R.id.tv_dd_symbol_id);
tv_dd_num_symbols = (TextView)view.findViewById(R.id.tv_dd_num_symbols);
cb_symbols = new CheckBox[35];
cb_symbols[0] = (CheckBox)view.findViewById(R.id.cb_dd_1);
cb_symbols[1] = (CheckBox)view.findViewById(R.id.cb_dd_2);
cb_symbols[2] = (CheckBox)view.findViewById(R.id.cb_dd_3);
cb_symbols[3] = (CheckBox)view.findViewById(R.id.cb_dd_4);
cb_symbols[4] = (CheckBox)view.findViewById(R.id.cb_dd_5);
cb_symbols[5] = (CheckBox)view.findViewById(R.id.cb_dd_6);
cb_symbols[6] = (CheckBox)view.findViewById(R.id.cb_dd_7);
cb_symbols[7] = (CheckBox)view.findViewById(R.id.cb_dd_8);
cb_symbols[8] = (CheckBox)view.findViewById(R.id.cb_dd_9);
cb_symbols[9] = (CheckBox)view.findViewById(R.id.cb_dd_10);
cb_symbols[10] = (CheckBox)view.findViewById(R.id.cb_dd_11);
cb_symbols[11] = (CheckBox)view.findViewById(R.id.cb_dd_12);
cb_symbols[12] = (CheckBox)view.findViewById(R.id.cb_dd_13);
cb_symbols[13] = (CheckBox)view.findViewById(R.id.cb_dd_14);
cb_symbols[14] = (CheckBox)view.findViewById(R.id.cb_dd_15);
cb_symbols[15] = (CheckBox)view.findViewById(R.id.cb_dd_16);
cb_symbols[16] = (CheckBox)view.findViewById(R.id.cb_dd_17);
cb_symbols[17] = (CheckBox)view.findViewById(R.id.cb_dd_18);
cb_symbols[18] = (CheckBox)view.findViewById(R.id.cb_dd_19);
cb_symbols[19] = (CheckBox)view.findViewById(R.id.cb_dd_20);
cb_symbols[20] = (CheckBox)view.findViewById(R.id.cb_dd_21);
cb_symbols[21] = (CheckBox)view.findViewById(R.id.cb_dd_22);
cb_symbols[22] = (CheckBox)view.findViewById(R.id.cb_dd_23);
cb_symbols[23] = (CheckBox)view.findViewById(R.id.cb_dd_24);
cb_symbols[24] = (CheckBox)view.findViewById(R.id.cb_dd_25);
cb_symbols[25] = (CheckBox)view.findViewById(R.id.cb_dd_26);
cb_symbols[26] = (CheckBox)view.findViewById(R.id.cb_dd_27);
cb_symbols[27] = (CheckBox)view.findViewById(R.id.cb_dd_28);
cb_symbols[28] = (CheckBox)view.findViewById(R.id.cb_dd_29);
cb_symbols[29] = (CheckBox)view.findViewById(R.id.cb_dd_30);
cb_symbols[30] = (CheckBox)view.findViewById(R.id.cb_dd_31);
cb_symbols[31] = (CheckBox)view.findViewById(R.id.cb_dd_32);
cb_symbols[32] = (CheckBox)view.findViewById(R.id.cb_dd_33);
cb_symbols[33] = (CheckBox)view.findViewById(R.id.cb_dd_34);
cb_symbols[34] = (CheckBox)view.findViewById(R.id.cb_dd_35);
for (int x=0; x<35; ++x) {
final int y = x;
cb_symbols[x].setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
String cur_symbol_str = null;
if (symbols.size() < cur_symbol) {
Log.e("Principia", "cur_symbol out of bounds");
cur_symbol_str = EMPTY_SYMBOL;
} else {
cur_symbol_str = symbols.get(cur_symbol);
if (cur_symbol_str.length() != NUM_CHARS_IN_SYMBOL) {
Log.e("Principia", "Invalid number of chars in symbol.");
cur_symbol_str = EMPTY_SYMBOL;
}
}
StringBuilder new_str = new StringBuilder(cur_symbol_str);
try {
new_str.setCharAt(y, (isChecked?'1':'0'));
symbols.set(cur_symbol, new_str.toString());
} catch (StringIndexOutOfBoundsException e) {
Log.e("Principia", "An unknown error occured: " + e.getMessage());
}
}
});
}
btn_dd_next = (Button)view.findViewById(R.id.btn_dd_next);
btn_dd_previous = (Button)view.findViewById(R.id.btn_dd_previous);
btn_dd_insert = (Button)view.findViewById(R.id.btn_dd_insert);
btn_dd_append = (Button)view.findViewById(R.id.btn_dd_append);
btn_dd_remove = (Button)view.findViewById(R.id.btn_dd_remove);
btn_dd_next.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
cur_symbol ++;
if (cur_symbol >= num_symbols) cur_symbol = num_symbols-1;
reload_symbol();
return true;
}
return false;
}
});
btn_dd_previous.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
cur_symbol --;
if (cur_symbol < 0) cur_symbol = 0;
reload_symbol();
return true;
}
return false;
}
});
btn_dd_insert.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (num_symbols == 40) {
SDLActivity.message("Maximum number of symbols reached.", 0);
return false;
}
symbols.add(cur_symbol, "00000000000000000000000000000000000");
reload_symbol();
return true;
}
return false;
}
});
btn_dd_append.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (num_symbols == 40) {
SDLActivity.message("Maximum number of symbols reached.", 0);
return false;
}
cur_symbol ++;
symbols.add(cur_symbol, "00000000000000000000000000000000000");
reload_symbol();
return true;
}
return false;
}
});
btn_dd_remove.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (symbols.size() == 1) {
/* We must have at least one symbol */
return true;
}
symbols.remove(cur_symbol);
if (cur_symbol >= symbols.size()) cur_symbol = symbols.size() - 1;
reload_symbol();
return true;
}
return false;
}
});
bld.setTitle("Digital Display");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void reload_symbol()
{
String symbol = symbols.get(cur_symbol);
int len = symbol.length();
for (int x=0; x<35; ++x) {
if (x >= len) {
cb_symbols[x].setChecked(false);
} else {
cb_symbols[x].setChecked(symbol.charAt(x) == '1'?true:false);
}
}
Log.v("Principia", "Symbol fetched: "+symbol);
refresh_counters();
}
public static void refresh_counters()
{
num_symbols = symbols.size();
tv_dd_symbol_id.setText(Integer.toString(cur_symbol+1));
tv_dd_num_symbols.setText(Integer.toString(num_symbols));
np_initial_position.setRange(MIN_INITIAL_POS, num_symbols);
}
public static void prepare(DialogInterface di)
{
symbols.clear();
int wrap_around = PrincipiaBackend.getPropertyInt8(0);
int initial_position = PrincipiaBackend.getPropertyInt8(1) + 1;
String symbols_str = PrincipiaBackend.getPropertyString(2);
String[] symbols_arr = symbols_str.split("\n\n");
for (int i=0; i<symbols_arr.length; ++i) {
StringBuilder sb = new StringBuilder();
for (int x=0; x<symbols_arr[i].length(); ++x) {
if (symbols_arr[i].charAt(x) != '\n') {
sb.append(symbols_arr[i].charAt(x));
}
}
if (sb.length() != NUM_CHARS_IN_SYMBOL) {
sb.delete(0, sb.length());
Log.e("Principia", "had to manufacture a new string.");
for (int x=0; x<NUM_CHARS_IN_SYMBOL;++x) {
sb.append('0');
}
}
symbols.add(sb.toString());
Log.v("Principia", "Got a cool symbol: "+sb.toString());
}
cur_symbol = initial_position - 1;
reload_symbol();
cb_wrap_around.setChecked(wrap_around == 1?true:false);
np_initial_position.setValue(initial_position);
int g_id = PrincipiaBackend.getSelectionGid();
if (g_id == 193) { // active display
ll_wrap.setVisibility(View.GONE);
} else {
ll_wrap.setVisibility(View.VISIBLE);
}
}
public static void save()
{
StringBuilder full_symbols = new StringBuilder();
for (int i=0; i<symbols.size(); ++i) {
if (i != 0) {
full_symbols.append("\n\n");
}
full_symbols.append(symbols.get(i));
}
int ip = np_initial_position.getValue() - 1;
if (ip >= symbols.size()) ip = symbols.size() - 1;
/* TODO: On save, it should make sure np_initial_position is less than the symbol count */
PrincipiaBackend.setDigitalDisplayStuff(cb_wrap_around.isChecked(), ip, full_symbols.toString());
}
}

View file

@ -0,0 +1,61 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
public class EventListenerDialog {
static Dialog _dialog;
static View view;
static Spinner s_event_type;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.event_listener, null);
s_event_type = (Spinner)view.findViewById(R.id.event_type);
bld.setTitle("Event Listener");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
EventListenerDialog._dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
s_event_type.setSelection(PrincipiaBackend.getEventListenerEventType());
}
public static void save()
{
PrincipiaBackend.setEventListenerEventType(s_event_type.getSelectedItemPosition());
}
}

View file

@ -0,0 +1,56 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class ExportDialog
{
static Dialog _dialog;
static View view;
static EditText et_name;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
bld.setTitle("Export object");
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.export, null);
et_name = (EditText)view.findViewById(R.id.et_object_name);
bld.setView(view);
bld.setNeutralButton("Save", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
String name = et_name.getText().toString().trim();
PrincipiaBackend.saveObject(name);
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
et_name.setText("");
}
}

View file

@ -0,0 +1,68 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class FrequencyDialog {
static Dialog _dialog;
static View view;
static EditText et_frequency;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.frequency, null);
et_frequency = (EditText)view.findViewById(R.id.et_frequency);
bld.setTitle("Frequency");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
et_frequency.setText(Long.toString(PrincipiaBackend.getPropertyInt(0)));
}
public static void save()
{
long freq = 0;
try {
freq = Long.parseLong(et_frequency.getText().toString());
} catch (NumberFormatException e) {
freq = 0;
}
PrincipiaBackend.setFrequency(freq);
}
}

View file

@ -0,0 +1,72 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class FrequencyRangeDialog {
static Dialog _dialog;
static View view;
static EditText et_freqrange_start;
static EditText et_freqrange_range;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.frequency_range, null);
et_freqrange_start = (EditText)view.findViewById(R.id.et_freqrange_start);
et_freqrange_range = (EditText)view.findViewById(R.id.et_freqrange_range);
bld.setTitle("Frequency");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
et_freqrange_start.setText(Long.toString(PrincipiaBackend.getPropertyInt(0)));
et_freqrange_range.setText(Long.toString(PrincipiaBackend.getPropertyInt(1)));
}
public static void save()
{
long f_start = 0;
long f_range = 0;
try {
f_start = Long.parseLong(et_freqrange_start.getText().toString());
} catch (NumberFormatException e) { f_start = 0; }
try {
f_range = Long.parseLong(et_freqrange_range.getText().toString());
} catch (NumberFormatException e) { f_range = 0; }
PrincipiaBackend.setFrequencyRange(f_start, f_range);
}
}

View file

@ -0,0 +1,206 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
public class FxEmitterDialog {
static Dialog _dialog;
static View view;
static Spinner s_effect_1;
static Spinner s_effect_2;
static Spinner s_effect_3;
static Spinner s_effect_4;
static SeekBar seekbar_radius;
static SeekBar seekbar_count;
static SeekBar seekbar_interval;
static TextView tv_radius;
static TextView tv_count;
static TextView tv_interval;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.fx_emitter, null);
s_effect_1 = (Spinner)view.findViewById(R.id.fx_1);
s_effect_2 = (Spinner)view.findViewById(R.id.fx_2);
s_effect_3 = (Spinner)view.findViewById(R.id.fx_3);
s_effect_4 = (Spinner)view.findViewById(R.id.fx_4);
seekbar_radius = (SeekBar)view.findViewById(R.id.seekbar_radius);
seekbar_count = (SeekBar)view.findViewById(R.id.seekbar_count);
seekbar_interval = (SeekBar)view.findViewById(R.id.seekbar_interval);
tv_radius = (TextView)view.findViewById(R.id.tv_radius);
tv_count = (TextView)view.findViewById(R.id.tv_count);
tv_interval = (TextView)view.findViewById(R.id.tv_interval);
seekbar_radius.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
double value = (((double)(progress) / 40.0) * 5.0) + 0.125;
tv_radius.setText(String.format("%.3f", value));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
seekbar_count.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
int value = progress + 1;
tv_count.setText(String.format("%d", value));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
seekbar_interval.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
double value = ((double)(progress) / 20.0f) + 0.05;
tv_interval.setText(String.format("%.2f", value));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
bld.setTitle("FX Emitter");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
FxEmitterDialog._dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
String effects = PrincipiaBackend.getFxEmitterEffects();
String data[] = effects.split(",");
if (data.length == 4) {
long effect_1 = Long.parseLong(data[0]);
long effect_2 = Long.parseLong(data[1]);
long effect_3 = Long.parseLong(data[2]);
long effect_4 = Long.parseLong(data[3]);
if (effect_1 == 3735928559L) {
s_effect_1.setSelection(0);
} else {
s_effect_1.setSelection((int)effect_1 + 1);
}
if (effect_2 == 3735928559L) {
s_effect_2.setSelection(0);
} else {
s_effect_2.setSelection((int)effect_2 + 1);
}
if (effect_3 == 3735928559L) {
s_effect_3.setSelection(0);
} else {
s_effect_3.setSelection((int)effect_3 + 1);
}
if (effect_4 == 3735928559L) {
s_effect_4.setSelection(0);
} else {
s_effect_4.setSelection((int)effect_4 + 1);
}
float radius = PrincipiaBackend.getPropertyFloat(0);
long count = PrincipiaBackend.getPropertyInt(1);
float interval = PrincipiaBackend.getPropertyFloat(2);
int progress = 0;
progress = (int) ((radius - 0.125)/0.125);
seekbar_radius.setProgress(progress);
progress = (int) (count - 1);
seekbar_count.setProgress(progress);
progress = (int) ((interval - 0.05)/0.05);
seekbar_interval.setProgress(progress);
} else {
Log.v("Principia", "invalid number of fx emitter data fields");
}
}
public static void save()
{
float radius = (float) (((double)(seekbar_radius.getProgress()) / 40.0) * 5.0) + 0.125f;
long count = (long) (seekbar_count.getProgress() + 1);
float interval = (float) ((double)(seekbar_interval.getProgress()) / 20.0) + 0.05f;
PrincipiaBackend.setPropertyFloat(0, radius);
PrincipiaBackend.setPropertyInt(1, count);
PrincipiaBackend.setPropertyFloat(2, interval);
PrincipiaBackend.setFxEmitterEffects(s_effect_1.getSelectedItemPosition(),
s_effect_2.getSelectedItemPosition(),
s_effect_3.getSelectedItemPosition(),
s_effect_4.getSelectedItemPosition());
}
}

View file

@ -0,0 +1,37 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.Html;
public class HelpDialog
{
Dialog _dialog;
public static String description ="";
public static String title = "";
public HelpDialog()
{
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
bld.setTitle(title);
bld.setMessage(Html.fromHtml((description.replaceAll("\n", "<br />"))));
bld.setNeutralButton("Close", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
this._dialog = bld.create();
}
public Dialog get_dialog()
{
return this._dialog;
}
}

View file

@ -0,0 +1,112 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ImportDialog
{
private final AlertDialog _dialog;
private final String[] level_names;
public static ListView lv;
public static ArrayAdapter<Level> list_adapter = new ArrayAdapter<Level>(SDLActivity.mSingleton,
android.R.layout.select_dialog_item);
public ImportDialog(final boolean is_multiemitter)
{
ImportDialog.list_adapter.clear();
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
String level_list = PrincipiaBackend.getLevels(SDLActivity.LEVEL_PARTIAL);
String[] levels = level_list.split("\n");
level_names = new String[levels.length];
bld.setTitle("Open object");
if (level_list.length() > 0) {
for (int x=0; x<levels.length; x++) {
String[] data = levels[x].split("\\,", 2);
if (data.length != 2) {
level_names[x] = "";
continue;
}
try {
int id = Integer.parseInt(data[0], 10);
String name = data[1];
ImportDialog.list_adapter.add(new Level(id, name));
level_names[x] = name;
} catch (NumberFormatException e) { }
bld.setItems(new String[0], null);
}
bld.setItems(level_names, new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
} else {
bld.setMessage("No saved objects found.");
}
bld.setNegativeButton("Close", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
this._dialog = bld.create();
this._dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
ListView lv = _dialog.getListView();
ImportDialog.lv = lv;
if (lv != null) {
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Level level = (Level)parent.getAdapter().getItem(position);
Log.v("Principia", String.format("%s: %d", level.get_name(), level.get_id()));
if (is_multiemitter) {
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_MULTIEMITTER_SET, level.get_id());
} else {
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_IMPORT_OBJECT, level.get_id());
}
_dialog.dismiss();
}
});
lv.setAdapter(ImportDialog.list_adapter);
SDLActivity.mSingleton.registerForContextMenu(lv);
} else {
Log.v("Principia", "listview = null");
}
}
});
}
public Dialog get_dialog()
{
return this._dialog;
}
}

View file

@ -0,0 +1,95 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class JumperDialog {
static Dialog _dialog;
static View view;
static SeekBar value_sb;
static EditText value_et;
static float old_value;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.jumper, null);
value_sb = (SeekBar)view.findViewById(R.id.jumper_value);
value_et = (EditText)view.findViewById(R.id.jumper_value_et);
value_sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
float value = progress / 100000.f;
value_et.setText(Float.toString(value));
}
}
@Override public void onStartTrackingTouch(SeekBar seekBar) { }
@Override public void onStopTrackingTouch(SeekBar seekBar) { }
});
bld.setTitle("Jumper");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
float value = PrincipiaBackend.getPropertyFloat(0);
old_value = value;
value_et.setText(Float.toString(value));
int progress = (int)(value * 100000.f);
value_sb.setProgress(progress);
}
public static void save()
{
float new_value;
try {
new_value = Float.parseFloat(value_et.getText().toString());
} catch (NumberFormatException e) {
Log.v("Principia", "Using old value.");
new_value = old_value;
}
Log.v("Principia", String.format("New value: %f", new_value));
PrincipiaBackend.updateJumper(new_value);
}
}

View file

@ -0,0 +1,29 @@
package com.bithack.principia.shared;
public class Level
{
private int id;
private String name;
public Level(int id, String name)
{
this.id = id;
this.name = name;
}
public String get_name()
{
return this.name;
}
public int get_id()
{
return this.id;
}
@Override
public String toString()
{
return this.get_name();
}
}

View file

@ -0,0 +1,585 @@
package com.bithack.principia.shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import com.bithack.principia.shared.ConfirmDialog.OnOptionSelectedListener;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.ToggleButton;
public class LevelDialog {
public static final int NUM_TABS = 3;
static Dialog _dialog;
static View view;
static ToggleButton tab_buttons[];
static ScrollView tab_views[];
static EditText et_name;
static EditText et_descr;
static Spinner s_bg;
static EditText et_border_left;
static EditText et_border_right;
static EditText et_border_bottom;
static EditText et_border_top;
static EditText et_gravity_x;
static EditText et_gravity_y;
static EditText et_final_score;
static NumberPicker np_position_iterations;
static NumberPicker np_velocity_iterations;
static CheckBox cb_pause_on_win;
static CheckBox cb_display_score;
static List<LevelProperty> level_properties;
static RadioGroup level_type;
static RadioButton level_puzzle;
static RadioButton level_adventure;
static RadioButton level_custom;
static Button level_upgrade_version;
static SeekBar sb_prismatic_tolerance;
static SeekBar sb_pivot_tolerance;
static EditText et_prismatic_tolerance;
static EditText et_pivot_tolerance;
static Button btn_save;
static Button btn_cancel;
static int border_left = 10, border_right = 10, border_top = 10, border_bottom = 10, final_score = 10;
static float gravity_x = 0.f, gravity_y = -20.f;
public static Dialog get_dialog()
{
if (_dialog == null) {
tab_buttons = new ToggleButton[LevelDialog.NUM_TABS];
tab_views = new ScrollView[LevelDialog.NUM_TABS];
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.level, null);
_dialog = new Dialog(PrincipiaActivity.mSingleton, android.R.style.Theme_NoTitleBar_Fullscreen){
@Override
protected void onCreate(Bundle saved_instance) {
super.onCreate(saved_instance);
getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
};
_dialog.setContentView(view);
btn_save = (Button)view.findViewById(R.id.level_btn_save);
btn_cancel = (Button)view.findViewById(R.id.level_btn_cancel);
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
_dialog.dismiss();
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_dialog.dismiss();
}
});
tab_buttons[0] = (ToggleButton)view.findViewById(R.id.tb_info);
tab_buttons[1] = (ToggleButton)view.findViewById(R.id.tb_world);
tab_buttons[2] = (ToggleButton)view.findViewById(R.id.tb_gameplay);
tab_views[0] = (ScrollView)view.findViewById(R.id.sv_info);
tab_views[1] = (ScrollView)view.findViewById(R.id.sv_world);
tab_views[2] = (ScrollView)view.findViewById(R.id.sv_gameplay);
OnCheckedChangeListener l = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
for (int x=0; x<LevelDialog.NUM_TABS; ++x) {
if (x == ((Integer)buttonView.getTag())) {
tab_views[x].setVisibility(ScrollView.VISIBLE);
} else {
tab_views[x].setVisibility(ScrollView.GONE);
tab_buttons[x].setChecked(false);
}
}
}
}
};
for (int x=0; x<LevelDialog.NUM_TABS; ++x) {
tab_buttons[x].setTag(x);
tab_buttons[x].setOnCheckedChangeListener(l);
}
level_type = (RadioGroup)view.findViewById(R.id.level_type);
level_puzzle = (RadioButton)view.findViewById(R.id.level_type_puzzle);
level_adventure = (RadioButton)view.findViewById(R.id.level_type_adventure);
level_custom = (RadioButton)view.findViewById(R.id.level_type_custom);
/* Info */
et_name = (EditText)view.findViewById(R.id.level_name);
et_descr = (EditText)view.findViewById(R.id.level_descr);
level_upgrade_version = (Button)view.findViewById(R.id.level_upgrade_version);
/* World */
s_bg = (Spinner)view.findViewById(R.id.level_bg);
ArrayList<String> bg_array = Material.get_bgs();
ArrayAdapter<String> bg_adapter = new ArrayAdapter<String>(PrincipiaActivity.mSingleton, android.R.layout.simple_spinner_dropdown_item, bg_array);
s_bg.setAdapter(bg_adapter);
et_border_left = (EditText)view.findViewById(R.id.et_border_left);
et_border_right = (EditText)view.findViewById(R.id.et_border_right);
et_border_bottom = (EditText)view.findViewById(R.id.et_border_bottom);
et_border_top = (EditText)view.findViewById(R.id.et_border_top);
et_gravity_x = (EditText)view.findViewById(R.id.level_gravity_x);
et_gravity_y = (EditText)view.findViewById(R.id.level_gravity_y);
et_final_score = (EditText)view.findViewById(R.id.level_final_score);
sb_prismatic_tolerance = (SeekBar)view.findViewById(R.id.level_prismatic_tolerance_sb);
et_prismatic_tolerance = (EditText)view.findViewById(R.id.level_prismatic_tolerance_et);
sb_pivot_tolerance = (SeekBar)view.findViewById(R.id.level_pivot_tolerance_sb);
et_pivot_tolerance = (EditText)view.findViewById(R.id.level_pivot_tolerance_et);
np_position_iterations = (NumberPicker)view.findViewById(R.id.level_position_iterations);
np_position_iterations.setRange(10, 255);
np_position_iterations.setStep(5);
np_velocity_iterations = (NumberPicker)view.findViewById(R.id.level_velocity_iterations);
np_velocity_iterations.setRange(10, 255);
np_velocity_iterations.setStep(5);
sb_prismatic_tolerance.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
@Override public void onStartTrackingTouch(SeekBar seekBar) { }
@Override public void onStopTrackingTouch(SeekBar sb) {
float value = sb.getProgress() / 1000.f;
et_prismatic_tolerance.setText(Float.toString(value));
}
});
et_prismatic_tolerance.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null) {
return true;
}
float val;
try {
val = Float.parseFloat(v.getText().toString());
} catch (NumberFormatException e) {
int progress = sb_prismatic_tolerance.getProgress();
val = progress / 1000.f;
}
if (val < 0.f) val = 0.f;
else if (val > 0.075f) val = 0.075f;
v.setText(Float.toString(val));
int p = (int)(val * 1000.f);
sb_prismatic_tolerance.setProgress(p);
return false;
}
});
et_prismatic_tolerance.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
TextView tv = (TextView)v;
float val;
try {
val = Float.parseFloat(tv.getText().toString());
} catch (NumberFormatException e) {
int progress = sb_prismatic_tolerance.getProgress();
val = progress / 1000.f;
}
if (val < 0.f) val = 0.f;
else if (val > 0.075f) val = 0.075f;
tv.setText(Float.toString(val));
int p = (int)(val * 1000.f);
sb_prismatic_tolerance.setProgress(p);
}
}
});
sb_pivot_tolerance.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
@Override public void onStartTrackingTouch(SeekBar seekBar) { }
@Override public void onStopTrackingTouch(SeekBar sb) {
float value = sb.getProgress() / 1000.f;
et_pivot_tolerance.setText(Float.toString(value));
}
});
et_pivot_tolerance.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null) {
return true;
}
float val;
try {
val = Float.parseFloat(v.getText().toString());
} catch (NumberFormatException e) {
int progress = sb_pivot_tolerance.getProgress();
val = progress / 1000.f;
}
if (val < 0.f) val = 0.f;
else if (val > 0.075f) val = 0.075f;
v.setText(Float.toString(val));
int p = (int)(val * 1000.f);
sb_pivot_tolerance.setProgress(p);
return false;
}
});
et_pivot_tolerance.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
TextView tv = (TextView)v;
float val;
try {
val = Float.parseFloat(tv.getText().toString());
} catch (NumberFormatException e) {
int progress = sb_pivot_tolerance.getProgress();
val = progress / 1000.f;
}
if (val < 0.f) val = 0.f;
else if (val > 0.075f) val = 0.075f;
tv.setText(Float.toString(val));
int p = (int)(val * 1000.f);
sb_pivot_tolerance.setProgress(p);
}
}
});
cb_pause_on_win = (CheckBox)view.findViewById(R.id.pause_on_win);
cb_display_score = (CheckBox)view.findViewById(R.id.display_score);
level_properties = new ArrayList<LevelProperty>();
CheckBox cb;
cb = (CheckBox)view.findViewById(R.id.disable_layer_switch);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_interactive);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_static_connections);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_jumping);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_fall_damage);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_connections);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_cam_movement);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_initial_wait);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_robot_hit_score);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_zoom);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.absorb_dead_enemies);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.snap_by_default);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.unlimited_enemy_vision);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.interactive_destruction);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_damage);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.single_layer_explosions);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_continue_button);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.hide_beam_connections);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_3rd_layer);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.portrait_mode);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_camera_rc_snap);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_physics);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.do_not_require_dragfield);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_robot_special_action);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_adventure_max_zoom);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
cb = (CheckBox)view.findViewById(R.id.disable_roam_layer_switch);
level_properties.add(new LevelProperty(cb, Long.parseLong((String)cb.getTag())));
level_upgrade_version.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ConfirmDialog()
.set_listener(new OnOptionSelectedListener() {
@Override
public void onOptionSelected(int option) {
if (option == ConfirmDialog.OPTION_YES) {
PrincipiaBackend.addActionAsInt(PrincipiaActivity.ACTION_UPGRADE_LEVEL, 0);
}
}
})
.run(PrincipiaActivity.mSingleton.getString(R.string.confirm_level_upgrade));
}
});
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
String level_name = PrincipiaBackend.getLevelName();
String level_descr = PrincipiaBackend.getLevelDescription();
String level_info = PrincipiaBackend.getLevelInfo();
String data[] = level_info.split(",");
/**
* int bg,
* int left_border, int right_border, int bottom_border, int top_border,
* float gravity_x, float gravity_y,
* int position_iterations, int velocity_iterations,
* int final_score,
* boolean pause_on_win,
* boolean display_score
* float prismatic_tolerance, float pivot_tolerance
**/
if (data.length == 14) {
try {
int i = Integer.parseInt(data[0]);
s_bg.setSelection(i);
} catch (NumberFormatException e) {
s_bg.setSelection(0);
}
et_border_left.setText(data[1]);
et_border_right.setText(data[2]);
et_border_bottom.setText(data[3]);
et_border_top.setText(data[4]);
et_gravity_x.setText(data[5]);
et_gravity_y.setText(data[6]);
try {
np_position_iterations.setValue(Integer.parseInt(data[7]));
np_velocity_iterations.setValue(Integer.parseInt(data[8]));
} catch (NumberFormatException e) {
np_position_iterations.setValue(10);
np_velocity_iterations.setValue(10);
}
et_final_score.setText(data[9]);
cb_pause_on_win.setChecked(Boolean.parseBoolean(data[10]));
cb_display_score.setChecked(Boolean.parseBoolean(data[11]));
try {
border_left = Integer.parseInt(data[1]);
border_right = Integer.parseInt(data[2]);
border_bottom = Integer.parseInt(data[3]);
border_top = Integer.parseInt(data[4]);
gravity_x = Float.parseFloat(data[5]);
gravity_y = Float.parseFloat(data[6]);
final_score = Integer.parseInt(data[9]);
} catch (NumberFormatException e) { }
float prismatic_tolerance, pivot_tolerance;
try {
prismatic_tolerance = Float.parseFloat(data[12]);
pivot_tolerance = Float.parseFloat(data[13]);
} catch (NumberFormatException e) {
prismatic_tolerance = 0.f;
pivot_tolerance = 0.f;
}
int p;
et_prismatic_tolerance.setText(Float.toString(prismatic_tolerance));
et_pivot_tolerance.setText(Float.toString(pivot_tolerance));
p = (int)(prismatic_tolerance * 1000.f);
sb_prismatic_tolerance.setProgress(p);
p = (int)(pivot_tolerance * 1000.f);
sb_pivot_tolerance.setProgress(p);
} else {
Log.v("Principia", "invalid number of level info data fields");
}
et_name.setText(level_name);
et_descr.setText(level_descr);
for (int x=0; x<level_properties.size(); ++x) {
LevelProperty p = level_properties.get(x);
p.cb.setChecked(PrincipiaBackend.getLevelFlag(p.bs_value));
}
int lt = PrincipiaBackend.getLevelType();
Log.v("Principia", String.format("Level type: %d", lt));
if (lt == 0) {
level_type.check(R.id.level_type_puzzle);
} else if (lt == 1) {
level_type.check(R.id.level_type_adventure);
} else {
level_type.check(R.id.level_type_custom);
}
int level_version = PrincipiaBackend.getLevelVersion();
int max_level_version = PrincipiaBackend.getMaxLevelVersion();
if (level_version == max_level_version) {
level_upgrade_version.setText(String.format(Locale.US, "%d (latest)", level_version));
level_upgrade_version.setEnabled(false);
} else {
level_upgrade_version.setText(String.format(Locale.US, "%d (Upgrade to %d)", level_version, max_level_version));
level_upgrade_version.setEnabled(true);
}
}
public static void save()
{
PrincipiaBackend.setLevelName(et_name.getText().toString().trim());
PrincipiaBackend.setLevelDescription(et_descr.getText().toString().trim());
PrincipiaBackend.resetLevelFlags();
for (int x=0; x<level_properties.size(); ++x) {
LevelProperty p = level_properties.get(x);
if (p.cb.isChecked()) {
/* TODO: flags are not set properly */
Log.v("Principia", String.format("Setting level flag: %d", p.bs_value));
PrincipiaBackend.setLevelFlag(p.bs_value);
}
}
/**
* int bg,
* int left_border, int right_border, int bottom_border, int top_border,
* float gravity_x, float gravity_y,
* int position_iterations, int velocity_iterations,
* int final_score,
* boolean pause_on_win,
* boolean display_score,
* float prismatic_tolerance, float pivot_tolerance
**/
int _border_left = border_left;
int _border_right = border_right;
int _border_bottom = border_bottom;
int _border_top = border_top;
int _final_score = final_score;
float _gravity_x = gravity_x;
float _gravity_y = gravity_y;
StringBuilder sb = new StringBuilder();
try {
_border_left = Integer.parseInt(et_border_left.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Left border");
}
try {
_border_right = Integer.parseInt(et_border_right.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Right border");
}
try {
_border_bottom = Integer.parseInt(et_border_bottom.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Bottom border");
}
try {
_border_top = Integer.parseInt(et_border_top.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Top border");
}
try {
_final_score = Integer.parseInt(et_final_score.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Final score.");
}
try {
_gravity_x = Float.parseFloat(et_gravity_x.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Gravity X.");
}
try {
_gravity_y = Float.parseFloat(et_gravity_y.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Gravity y.");
}
float prismatic_tolerance, pivot_tolerance;
try {
prismatic_tolerance = Float.parseFloat(et_prismatic_tolerance.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Prismatic tolerance");
prismatic_tolerance = 0.f;
}
try {
pivot_tolerance = Float.parseFloat(et_pivot_tolerance.getText().toString());
} catch (NumberFormatException e) {
sb.append("Invalid input given to Pivot tolerance");
pivot_tolerance = 0.f;
}
if (sb.length() > 0) {
PrincipiaActivity.message(sb.toString(), 0);
}
PrincipiaBackend.setLevelInfo(s_bg.getSelectedItemPosition(),
_border_left, _border_right,
_border_bottom, _border_top,
_gravity_x, _gravity_y,
np_position_iterations.getValue(), np_velocity_iterations.getValue(),
_final_score,
cb_pause_on_win.isChecked(),
cb_display_score.isChecked(),
prismatic_tolerance, pivot_tolerance
);
int checked_id = LevelDialog.level_type.getCheckedRadioButtonId();
int lt = 2;
if (checked_id == R.id.level_type_puzzle) {
lt = 0;
} else if (checked_id == R.id.level_type_adventure) {
lt = 1;
} else if (checked_id == R.id.level_type_custom) {
lt = 2;
}
Log.v("Principia", String.format("new lt: %d. checked_id: %d", lt ,checked_id));
PrincipiaBackend.setLevelType(lt);
}
}

View file

@ -0,0 +1,15 @@
package com.bithack.principia.shared;
import android.widget.CheckBox;
public class LevelProperty
{
public CheckBox cb;
public long bs_value;
public LevelProperty(CheckBox _cb, long _bs_value)
{
cb = _cb;
bs_value = _bs_value;
}
}

View file

@ -0,0 +1,109 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.google.android.vending.licensing.LicenseValidator;
public class LinkAccountDialog
{
static AlertDialog _dialog;
static View view;
static EditText et_username;
static EditText et_password;
public static ProgressBar progressbar;
public static int num_tries = 0;
public static final int MAX_TRIES = 3;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.link_account, null);
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(view)
.setTitle("Link account")
.setPositiveButton("Link account", null)
.setNegativeButton("Cancel", new OnClickListener(){public void onClick(DialogInterface dialog, int which){}})
.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
Button b = _dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
if (password.length() < 6 || password.length() > 100) {
SDLActivity.message("You must enter a valid password.", 0);
return;
}
if (username.length() < 3 || username.length() > 20) {
SDLActivity.message("You must enter a valid username.", 0);
return;
}
progressbar.setVisibility(View.VISIBLE);
LicenseValidator.setListener(new LicenseValidator.Listener() {
@Override
public void onUpdate(String signature,
String userdata) {
PrincipiaBackend.linkAccount(username, password, signature, userdata);
}
@Override
public void onFailure() {
Log.v("Principia", "Failed!");
SDLActivity.mSingleton.runOnUiThread(new Runnable(){
public void run() {
LinkAccountDialog.num_tries ++;
if (LinkAccountDialog.num_tries < LinkAccountDialog.MAX_TRIES) {
SDLActivity.mSingleton.do_check();
} else {
progressbar.setVisibility(View.GONE);
SDLActivity.message("An unknown error has occured when attempting to link your account.", 0);
}
}
});
}
});
LinkAccountDialog.num_tries = 0;
SDLActivity.mSingleton.do_check();
}
});
}
});
et_username = (EditText)view.findViewById(R.id.link_account_username);
et_password = (EditText)view.findViewById(R.id.link_account_password);
progressbar = (ProgressBar)view.findViewById(R.id.link_account_progress);
}
return _dialog;
}
}

View file

@ -0,0 +1,100 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginDialog
{
static AlertDialog _dialog;
static View view;
static EditText et_username;
static EditText et_password;
static Button btn_register_account;
static Button btn_link_account;
/* TODO */
//static CheckBox cb_remember_username;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.login, null);
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(view)
.setTitle("Log in")
.setPositiveButton("Log in", null)
.setNegativeButton("Cancel", new OnClickListener(){public void onClick(DialogInterface dialog, int which){}})
.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
Button b = _dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = et_username.getText().toString().trim();
String password = et_password.getText().toString().trim();
if (username.length() <= 0 || password.length() <= 0) {
SDLActivity.message("You must enter a valid username and password.", 0);
return;
}
PrincipiaBackend.login(username, password);
_dialog.dismiss();
}
});
}
});
et_username = (EditText)view.findViewById(R.id.login_username);
et_password = (EditText)view.findViewById(R.id.login_password);
btn_register_account = (Button)view.findViewById(R.id.btn_register_account);
btn_link_account = (Button)view.findViewById(R.id.btn_link_account);
btn_register_account.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SDLActivity.open_dialog(SDLActivity.DIALOG_REGISTER);
_dialog.dismiss();
}
});
btn_link_account.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SDLActivity.open_dialog(SDLActivity.DIALOG_LINK_ACCOUNT);
_dialog.dismiss();
}
});
}
return _dialog;
}
public static void prepare(Dialog d)
{
//TODO
//et_username.setText(PrincipiaActivity.getSavedUsername());
}
}

View file

@ -0,0 +1,40 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.widget.Toast;
public class MainMenuPkgDialog
{
static Dialog _dialog = null;
public MainMenuPkgDialog()
{
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setMessage("Select package")
.setPositiveButton("Main Puzzles", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.addActionAsInt(PrincipiaActivity.ACTION_MAIN_MENU_PKG, 0);
}
})
.setNeutralButton("Adventure Introduction", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.addActionAsInt(PrincipiaActivity.ACTION_MAIN_MENU_PKG, 1);
}
})
.create();
}
public Dialog get_dialog()
{
return _dialog;
}
}

View file

@ -0,0 +1,27 @@
package com.bithack.principia.shared;
import java.util.ArrayList;
import org.libsdl.app.PrincipiaBackend;
import android.util.Log;
public class Material {
private static ArrayList<String> bgs = null;
public static ArrayList<String> get_bgs()
{
if (bgs == null) {
bgs = new ArrayList<String>();
String bg_str = PrincipiaBackend.getAvailableBgs();
String[] bg_arr = bg_str.split("\n");
for (int x=0; x<bg_arr.length; ++x) {
Log.v("p", bg_arr[x]);
bgs.add(bg_arr[x]);
}
}
return bgs;
}
}

View file

@ -0,0 +1,84 @@
package com.bithack.principia.shared;
import java.util.List;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MultiSpinner extends Spinner implements OnMultiChoiceClickListener, OnCancelListener {
private List<String> items;
public boolean[] selected;
private MultiSpinnerListener listener;
public MultiSpinner(Context context) {
super(context);
}
public MultiSpinner(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
public MultiSpinner(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked)
selected[which] = true;
else
selected[which] = false;
}
@Override
public void onCancel(DialogInterface dialog) {
listener.onItemsSelected(selected);
}
@Override
public boolean performClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMultiChoiceItems(
items.toArray(new CharSequence[items.size()]), selected, this);
builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setOnCancelListener(this);
builder.show();
return true;
}
public void setItems(List<String> items, String label,
MultiSpinnerListener listener) {
this.items = items;
this.listener = listener;
// all selected by default
selected = new boolean[items.size()];
for (int i = 0; i < selected.length; i++)
selected[i] = true;
// all text on the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, new String[] { label });
setAdapter(adapter);
}
public interface MultiSpinnerListener {
public void onItemsSelected(boolean[] selected);
}
}

View file

@ -0,0 +1,56 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.widget.Toast;
public class NewLevelDialog
{
static Dialog _dialog = null;
public static String filename = "";
public NewLevelDialog()
{
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
bld.setTitle("Create new level");
bld.setMessage("Please select the level type:\nPuzzle\nAdventure - Control a robot\nCustom - Create whatever you want here!");
bld.setPositiveButton("Puzzle", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.triggerCreateLevel(0);
Toast.makeText(PrincipiaActivity.mSingleton, "New Puzzle level created!", Toast.LENGTH_SHORT).show();
}
});
bld.setNeutralButton("Adventure", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.triggerCreateLevel(1);
Toast.makeText(PrincipiaActivity.mSingleton, "New Adventure level created!", Toast.LENGTH_SHORT).show();
}
});
bld.setNegativeButton("Custom", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.triggerCreateLevel(2);
Toast.makeText(PrincipiaActivity.mSingleton, "New Custom level created!", Toast.LENGTH_SHORT).show();
}
});
_dialog = bld.create();
}
public Dialog get_dialog()
{
return _dialog;
}
}

View file

@ -0,0 +1,518 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bithack.principia.shared;
// // stealing from github HeHe
// Stealing this class directly from the android internal namespace because why
// the hell didn't they ship with this public!?!?!?!
// Changed to allow negative numbers.
import java.util.Locale;
import android.content.Context;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.bithack.principialite.R;
public class NumberPicker extends LinearLayout implements OnClickListener,
OnFocusChangeListener, OnLongClickListener, OnEditorActionListener {
public interface OnChangedListener {
void onChanged(NumberPicker picker, int oldVal, int newVal);
}
public interface Formatter {
String toString(int value);
}
/*
* Use a custom NumberPicker formatting callback to use two-digit
* minutes strings like "01". Keeping a static formatter etc. is the
* most efficient way to do this; it avoids creating temporary objects
* on every call to format().
*/
public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER =
new NumberPicker.Formatter() {
final StringBuilder mBuilder = new StringBuilder();
final java.util.Formatter mFmt = new java.util.Formatter(mBuilder);
final Object[] mArgs = new Object[1];
public String toString(int value) {
mArgs[0] = value;
mBuilder.delete(0, mBuilder.length());
mFmt.format("%02d", mArgs);
return mFmt.toString();
}
};
private final Handler mHandler;
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mIncrement) {
changeCurrent(mCurrent + mLongStep, mSlideUpInAnimation, mSlideUpOutAnimation);
mHandler.postDelayed(this, mSpeed);
} else if (mDecrement) {
changeCurrent(mCurrent - mLongStep, mSlideDownInAnimation, mSlideDownOutAnimation);
mHandler.postDelayed(this, mSpeed);
}
}
};
private final LayoutInflater mInflater;
private final EditText mText;
private final InputFilter mInputFilter;
private final InputFilter mNumberInputFilter;
private final Animation mSlideUpOutAnimation;
private final Animation mSlideUpInAnimation;
private final Animation mSlideDownOutAnimation;
private final Animation mSlideDownInAnimation;
private String[] mDisplayedValues;
private int mStart;
private int mEnd;
private int mCurrent;
private int mPrevious;
private int mStep = 1;
private int mLongStep = 5;
private OnChangedListener mListener;
private Formatter mFormatter;
private long mSpeed = 300;
private boolean mIncrement;
private boolean mDecrement;
public NumberPicker(Context context) {
this(context, null);
}
public NumberPicker(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NumberPicker(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs);
setOrientation(VERTICAL);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mInflater.inflate(R.layout.number_picker, this, true);
mHandler = new Handler();
mInputFilter = new NumberPickerInputFilter();
// TODO: Make which NumberRangeKeyListener it uses selected from |attrs|
// if I ever make a Big Numbers Mode for Yugioh.
//
// mNumberInputFilter = new NumberRangeKeyListener();
mNumberInputFilter = new NumberWithMinusRangeKeyListener();
mIncrementButton = (NumberPickerButton) findViewById(R.id.increment);
mIncrementButton.setOnClickListener(this);
mIncrementButton.setOnLongClickListener(this);
mIncrementButton.setNumberPicker(this);
mDecrementButton = (NumberPickerButton) findViewById(R.id.decrement);
mDecrementButton.setOnClickListener(this);
mDecrementButton.setOnLongClickListener(this);
mDecrementButton.setNumberPicker(this);
mText = (EditText) findViewById(R.id.timepicker_input);
mText.setOnFocusChangeListener(this);
mText.setOnEditorActionListener(this);
//mText.setFilters(new InputFilter[] { mInputFilter });
// mText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
mSlideUpOutAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,
0, Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, -100);
mSlideUpOutAnimation.setDuration(200);
mSlideUpInAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,
0, Animation.RELATIVE_TO_SELF, 100,
Animation.RELATIVE_TO_SELF, 0);
mSlideUpInAnimation.setDuration(200);
mSlideDownOutAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,
0, Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 100);
mSlideDownOutAnimation.setDuration(200);
mSlideDownInAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF,
0, Animation.RELATIVE_TO_SELF, -100,
Animation.RELATIVE_TO_SELF, 0);
mSlideDownInAnimation.setDuration(200);
if (!isEnabled()) {
setEnabled(false);
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mIncrementButton.setEnabled(enabled);
mDecrementButton.setEnabled(enabled);
mText.setEnabled(enabled);
}
public void setOnChangeListener(OnChangedListener listener) {
mListener = listener;
}
public void setFormatter(Formatter formatter) {
mFormatter = formatter;
}
/**
* Set the range of numbers allowed for the number picker. The current
* value will be automatically set to the start.
*
* @param start the start of the range (inclusive)
* @param end the end of the range (inclusive)
*/
public void setRange(int start, int end) {
mStart = start;
mEnd = end;
mCurrent = start;
updateView();
}
/**
* The amount the value with increment or decrement each time one of the two buttons are pressed.
* @param step the number of steps to increment/decrement.
*/
public void setStep(int step)
{
mStep = step;
updateView();
}
public void setLongStep(int longStep)
{
mLongStep = longStep;
updateView();
}
/**
* Set the range of numbers allowed for the number picker. The current
* value will be automatically set to the start. Also provide a mapping
* for values used to display to the user.
*
* @param start the start of the range (inclusive)
* @param end the end of the range (inclusive)
* @param displayedValues the values displayed to the user.
*/
public void setRange(int start, int end, String[] displayedValues) {
mDisplayedValues = displayedValues;
mStart = start;
mEnd = end;
mCurrent = start;
updateView();
}
public void setCurrent(int current) {
mCurrent = current;
updateView();
}
public void setValue(int value) {
this.setCurrent(value);
}
/**
* The speed (in milliseconds) at which the numbers will scroll
* when the the +/- buttons are longpressed. Default is 300ms.
*/
public void setSpeed(long speed) {
mSpeed = speed;
}
public void onClick(View v) {
/* The text view may still have focus so clear it's focus which will
* trigger the on focus changed and any typed values to be pulled.
*/
mText.clearFocus();
// now perform the increment/decrement
if (R.id.increment == v.getId()) {
changeCurrent(mCurrent + mStep, mSlideUpInAnimation, mSlideUpOutAnimation);
} else if (R.id.decrement == v.getId()) {
changeCurrent(mCurrent - mStep, mSlideDownInAnimation, mSlideDownOutAnimation);
}
}
private String formatNumber(int value) {
return (mFormatter != null)
? mFormatter.toString(value)
: String.valueOf(value);
}
private void changeCurrent(int current, Animation in, Animation out) {
// Wrap around the values if we go past the start or end
if (current > mEnd) {
current = mStart;
} else if (current < mStart) {
current = mEnd;
}
mPrevious = mCurrent;
mCurrent = current;
notifyChange();
updateView();
}
private void notifyChange() {
if (mListener != null) {
mListener.onChanged(this, mPrevious, mCurrent);
}
}
private void updateView() {
/* If we don't have displayed values then use the
* current number else find the correct value in the
* displayed values for the current number.
*/
if (mDisplayedValues == null) {
mText.setText(formatNumber(mCurrent));
} else {
mText.setText(mDisplayedValues[mCurrent - mStart]);
}
}
private void validateCurrentView(CharSequence str) {
int val = getSelectedPos(str.toString());
if ((val >= mStart) && (val <= mEnd)) {
mPrevious = mCurrent;
mCurrent = val;
notifyChange();
}
updateView();
}
public void onFocusChange(View v, boolean hasFocus) {
/* When focus is lost check that the text field
* has valid values.
*/
if (!hasFocus) {
String str = String.valueOf(((EditText) v).getText());
if ("".equals(str)) {
// Restore to the old value as we don't allow empty values
updateView();
} else {
// Check the new value and ensure it's in range
validateCurrentView(str);
}
}
}
/**
* We start the long click here but rely on the {@link NumberPickerButton}
* to inform us when the long click has ended.
*/
public boolean onLongClick(View v) {
/* The text view may still have focus so clear it's focus which will
* trigger the on focus changed and any typed values to be pulled.
*/
mText.clearFocus();
if (R.id.increment == v.getId()) {
mIncrement = true;
mHandler.post(mRunnable);
} else if (R.id.decrement == v.getId()) {
mDecrement = true;
mHandler.post(mRunnable);
}
return true;
}
public void cancelIncrement() {
mIncrement = false;
}
public void cancelDecrement() {
mDecrement = false;
}
private static final char[] DIGIT_CHARACTERS = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
private static final char[] DIGIT_CHARACTERS_WITH_MINUS = new char[] {
'-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
private NumberPickerButton mIncrementButton;
private NumberPickerButton mDecrementButton;
private class NumberPickerInputFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (mDisplayedValues == null) {
return mNumberInputFilter.filter(source, start, end, dest, dstart, dend);
}
CharSequence filtered = String.valueOf(source.subSequence(start, end));
String result = String.valueOf(dest.subSequence(0, dstart))
+ filtered
+ dest.subSequence(dend, dest.length());
String str = String.valueOf(result).toLowerCase(Locale.US);
for (String val : mDisplayedValues) {
val = val.toLowerCase(Locale.US);
if (val.startsWith(str)) {
return filtered;
}
}
return "";
}
}
private class NumberRangeKeyListener extends NumberKeyListener {
// XXX This doesn't allow for range limits when controlled by a
// soft input method!
public int getInputType() {
return 0x00000002; // InputType.TYPE_CLASS_NUMBER;
}
@Override
protected char[] getAcceptedChars() {
return DIGIT_CHARACTERS;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
CharSequence filtered = super.filter(source, start, end, dest, dstart, dend);
if (filtered == null) {
filtered = source.subSequence(start, end);
}
String result = String.valueOf(dest.subSequence(0, dstart))
+ filtered
+ dest.subSequence(dend, dest.length());
if ("".equals(result)) {
return result;
}
int val = getSelectedPos(result);
/* Ensure the user can't type in a value greater
* than the max allowed. We have to allow less than min
* as the user might want to delete some numbers
* and then type a new number.
*/
if (val > mEnd) {
return "";
} else {
return filtered;
}
}
}
private class NumberWithMinusRangeKeyListener extends NumberRangeKeyListener {
@Override
protected char[] getAcceptedChars() {
return DIGIT_CHARACTERS_WITH_MINUS;
}
}
private int getSelectedPos(String str) {
if (mDisplayedValues == null) {
// CHANGE: Accept the '-' raw!
// ASSUMPTION: Any NumberFormatException will be because of a raw '-'
// because that's the only non-numeric character allowed into this
// method.
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
// Pathological case: If they enter "5-2", we'll interpret that
// mess as 0. I dare you to care.
return 0;
}
} else {
for (int i = 0; i < mDisplayedValues.length; i++) {
/* Don't force the user to type in jan when ja will do */
str = str.toLowerCase(Locale.US);
if (mDisplayedValues[i].toLowerCase(Locale.US).startsWith(str)) {
return mStart + i;
}
}
/* The user might have typed in a number into the month field i.e.
* 10 instead of OCT so support that too.
*/
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
/* Ignore as if it's not a number we don't care */
}
}
return mStart;
}
/**
* @return the current value.
*/
public int getCurrent() {
return mCurrent;
}
public int getValue() {
return this.getCurrent();
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null) {
// if shift key is down, then we want to insert the '\n' char in the TextView;
// otherwise, the default action is to send the message.
return true;
}
String str = String.valueOf(((EditText) v).getText());
if ("".equals(str)) {
// Restore to the old value as we don't allow empty values
updateView();
} else {
// Check the new value and ensure it's in range
validateCurrentView(str);
}
return false;
}
}

View file

@ -0,0 +1,90 @@
package com.bithack.principia.shared;
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// // stealing this from github HeHe
//Stealing this class directly from the android internal namespace because why
//the hell didn't they ship with this public!?!?!?!
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ImageButton;
import com.bithack.principialite.R;
/**
* This class exists purely to cancel long click events.
*/
public class NumberPickerButton extends ImageButton {
private NumberPicker mNumberPicker;
public NumberPickerButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public NumberPickerButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NumberPickerButton(Context context) {
super(context);
}
public void setNumberPicker(NumberPicker picker) {
mNumberPicker = picker;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTouchEvent(event);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTrackballEvent(event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
|| (keyCode == KeyEvent.KEYCODE_ENTER)) {
cancelLongpress();
}
return super.onKeyUp(keyCode, event);
}
private void cancelLongpressIfRequired(MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_CANCEL)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
cancelLongpress();
}
}
private void cancelLongpress() {
if (R.id.increment == getId()) {
mNumberPicker.cancelIncrement();
} else if (R.id.decrement == getId()) {
mNumberPicker.cancelDecrement();
}
}
}

View file

@ -0,0 +1,94 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class OpenDialog
{
final AlertDialog _dialog;
final String[] level_names;
public static ListView lv;
public OpenDialog()
{
SDLActivity.open_adapter.clear();
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
String level_list = PrincipiaBackend.getLevels(0);
String[] levels = level_list.split("\n");
level_names = new String[levels.length];
bld.setTitle("Open Level");
if (level_list.length() > 0) {
for (int x=0; x<levels.length; x++) {
String[] data = levels[x].split("\\,", 2);
if (data.length != 2) {
level_names[x] = "";
continue;
}
int id = Integer.parseInt(data[0], 10);
String name = data[1];
SDLActivity.open_adapter.add(new Level(id, name));
level_names[x] = name;
}
bld.setItems(new String[0], null);
} else {
bld.setMessage("No saved levels found.");
}
bld.setNegativeButton("Close", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
this._dialog = bld.create();
this._dialog.setOnShowListener(new OnShowListener()
{
@Override
public void onShow(DialogInterface dialog)
{
SDLActivity.on_show(dialog);
ListView lv = _dialog.getListView();
OpenDialog.lv = lv;
if (lv != null) {
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Level level = (Level)parent.getAdapter().getItem(position);
PrincipiaBackend.addActionAsInt(PrincipiaActivity.ACTION_OPEN, level.get_id());
_dialog.dismiss();
}
});
lv.setAdapter(SDLActivity.open_adapter);
SDLActivity.mSingleton.registerForContextMenu(lv);
}
}
});
}
public Dialog get_dialog()
{
return this._dialog;
}
}

View file

@ -0,0 +1,69 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
public class PkgLevelDialog {
static Dialog _dialog;
static View view;
static LinearLayout layout;
static NumberPicker np_level_id;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.pkg_level_id, null);
np_level_id = new com.bithack.principia.shared.NumberPicker(SDLActivity.getContext());
np_level_id.setRange(0, 255);
np_level_id.setValue(1);
layout = (LinearLayout)view.findViewById(R.id.ll_pkg_level_id);
layout.addView(np_level_id);
bld.setTitle("Package level ID");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
PkgLevelDialog._dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
np_level_id.setValue(PrincipiaBackend.getPkgItemLevelId());
}
public static void save()
{
PrincipiaBackend.setPkgItemLevelId(np_level_id.getValue());
}
}

View file

@ -0,0 +1,44 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class PlayDialog
{
static Dialog _dialog = null;
public PlayDialog()
{
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setPositiveButton("Restart level", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_RESTART_LEVEL, 0);
}
})
.setNeutralButton("Back", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_BACK, 0);
}
})
.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
})
.create();
}
public Dialog get_dialog()
{
return _dialog;
}
}

View file

@ -0,0 +1,28 @@
package com.bithack.principia.shared;
public class PrincipiaObject {
private int id;
private String name;
public PrincipiaObject(int id, String name)
{
this.id = id;
this.name = name;
}
public String get_name()
{
return this.name;
}
public int get_id()
{
return this.id;
}
@Override
public String toString()
{
return this.get_name();
}
}

View file

@ -0,0 +1,93 @@
package com.bithack.principia.shared;
import java.util.ArrayList;
import java.util.List;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class PromptDialog
{
Dialog _dialog;
public PromptDialog()
{
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
bld.setMessage(PrincipiaBackend.getPromptPropertyString(3));
bld.setCancelable(false);
String b1 = PrincipiaBackend.getPromptPropertyString(0);
String b2 = PrincipiaBackend.getPromptPropertyString(1);
String b3 = PrincipiaBackend.getPromptPropertyString(2);
if (PrincipiaBackend.getLevelVersion() >= 21) {
if (b1.length() > 0) {
bld.setPositiveButton(b1, new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
PrincipiaBackend.setPromptResponse(PrincipiaActivity.PROMPT_RESPONSE_A);
}
});
}
if (b2.length() > 0) {
bld.setNeutralButton(b2, new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
PrincipiaBackend.setPromptResponse(PrincipiaActivity.PROMPT_RESPONSE_B);
}
});
}
if (b3.length() > 0) {
bld.setNegativeButton(b3, new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
PrincipiaBackend.setPromptResponse(PrincipiaActivity.PROMPT_RESPONSE_C);
}
});
}
} else {
List<String> button_texts = new ArrayList<String>();
if (b1.length() > 0) button_texts.add(b1);
if (b2.length() > 0) button_texts.add(b2);
if (b3.length() > 0) button_texts.add(b3);
int x = 0;
for (String text : button_texts) {
if (x == 0) {
bld.setPositiveButton(text, new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
PrincipiaBackend.setPromptResponse(PrincipiaActivity.PROMPT_RESPONSE_A);
}
});
} else if (x == 1) {
bld.setNeutralButton(text, new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
PrincipiaBackend.setPromptResponse(PrincipiaActivity.PROMPT_RESPONSE_B);
}
});
} else if (x == 2) {
bld.setNegativeButton(text, new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
PrincipiaBackend.setPromptResponse(PrincipiaActivity.PROMPT_RESPONSE_C);
}
});
}
x ++;
}
}
this._dialog = bld.create();
this._dialog.setCanceledOnTouchOutside(false);
this._dialog.getWindow().setWindowAnimations(R.style.DialogNoAnimation);
}
public Dialog get_dialog()
{
return this._dialog;
}
}

View file

@ -0,0 +1,102 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PromptSettingsDialog
{
static AlertDialog _dialog;
static View view;
static EditText et_b1;
static EditText et_b2;
static EditText et_b3;
static EditText et_message;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.prompt_settings, null);
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(view)
.setTitle("Prompt settings")
.setPositiveButton("Save", null)
.setNegativeButton("Cancel", new OnClickListener(){public void onClick(DialogInterface dialog, int which){}})
.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
Button b = _dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String b1_text = et_b1.getText().toString().trim();
String b2_text = et_b2.getText().toString().trim();
String b3_text = et_b3.getText().toString().trim();
String message = et_message.getText().toString().trim();
int b1_len = b1_text.length();
int b2_len = b2_text.length();
int b3_len = b3_text.length();
int message_len = message.length();
if (message_len <= 0) {
SDLActivity.message("You must enter a message for the prompt.", 0);
return;
}
if (b1_len <= 0 && b2_len <= 0 && b3_len <= 0) {
SDLActivity.message("You must use at least one button.", 0);
return;
}
PrincipiaBackend.setPromptPropertyString(0, b1_text);
PrincipiaBackend.setPromptPropertyString(1, b2_text);
PrincipiaBackend.setPromptPropertyString(2, b3_text);
PrincipiaBackend.setPromptPropertyString(3, message);
PrincipiaBackend.refreshPrompt();
Log.v("Principia", String.format("[%s]: %s/%s/%s", message, b1_text, b2_text, b3_text));
_dialog.dismiss();
}
});
}
});
et_b1 = (EditText)view.findViewById(R.id.prompt_button1_text);
et_b2 = (EditText)view.findViewById(R.id.prompt_button2_text);
et_b3 = (EditText)view.findViewById(R.id.prompt_button3_text);
et_message = (EditText)view.findViewById(R.id.prompt_message);
}
return _dialog;
}
public static void prepare(Dialog d)
{
et_b1.setText(PrincipiaBackend.getPromptPropertyString(0));
et_b2.setText(PrincipiaBackend.getPromptPropertyString(1));
et_b3.setText(PrincipiaBackend.getPromptPropertyString(2));
et_message.setText(PrincipiaBackend.getPromptPropertyString(3));
}
}

View file

@ -0,0 +1,93 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class PublishDialog
{
static AlertDialog _dialog;
static View view;
static EditText et_name;
static EditText et_descr;
static CheckBox cb_allow_derivatives;
static CheckBox cb_locked;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.publish, null);
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(view)
.setTitle("Publish")
.setPositiveButton("Publish", null)
.setNegativeButton("Cancel", new OnClickListener(){public void onClick(DialogInterface dialog, int which){}})
.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
Button b = _dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = et_name.getText().toString().trim();
String descr = et_descr.getText().toString().trim();
if (name.length() <= 0) {
SDLActivity.message("You must enter a name for your level!", 0);
return;
}
if (descr.length() <= 15) {
SDLActivity.message("You must enter a description of at least 15 characters for your level!", 0);
return;
}
PrincipiaBackend.setLevelName(name);
PrincipiaBackend.setLevelDescription(descr);
PrincipiaBackend.setLevelAllowDerivatives(cb_allow_derivatives.isChecked());
PrincipiaBackend.setLevelLocked(cb_locked.isChecked());
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_PUBLISH, 0);
_dialog.dismiss();
}
});
}
});
et_name = (EditText)view.findViewById(R.id.publish_name);
et_descr = (EditText)view.findViewById(R.id.publish_descr);
cb_allow_derivatives = (CheckBox)view.findViewById(R.id.publish_allow_derivatives);
cb_locked = (CheckBox)view.findViewById(R.id.publish_locked);
}
return _dialog;
}
public static void prepare(Dialog d)
{
et_name.setText(PrincipiaBackend.getLevelName());
et_descr.setText(PrincipiaBackend.getLevelDescription());
}
}

View file

@ -0,0 +1,35 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
public class PublishedDialog
{
private final AlertDialog _dialog;
public PublishedDialog()
{
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.published, null))
.setTitle(R.string.published_successfully)
.setPositiveButton(R.string.go_to_level_page, new OnClickListener(){
public void onClick(DialogInterface dialog, int which){
PrincipiaActivity.open_url(PrincipiaBackend.getLevelPage());
}
})
.setNegativeButton(R.string.cancel, new OnClickListener(){public void onClick(DialogInterface dialog, int which){}})
.create();
}
public Dialog get_dialog()
{
return this._dialog;
}
}

View file

@ -0,0 +1,52 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import com.bithack.principialite.PrincipiaActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class PuzzlePlayDialog
{
static Dialog _dialog = null;
public PuzzlePlayDialog()
{
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
bld.setTitle("Play method");
bld.setMessage("Do you want to test play the level, or just simulate it?");
bld.setPositiveButton("Test play", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_PUZZLEPLAY, 0);
SDLActivity.message("Test-playing level!", 0);
}
});
bld.setNeutralButton("Simulate", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
PrincipiaBackend.addActionAsInt(SDLActivity.ACTION_PUZZLEPLAY, 1);
SDLActivity.message("Simulating level!", 0);
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
_dialog = bld.create();
}
public Dialog get_dialog()
{
return _dialog;
}
}

View file

@ -0,0 +1,101 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class QuickaddDialog
{
static Dialog _dialog;
static View view;
static SurfaceView sv_man;
static AutoCompleteTextView et_name;
public static ArrayAdapter<String> object_adapter;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.quickadd, null);
//AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
_dialog = new Dialog(PrincipiaActivity.mSingleton, R.style.TinyDialog);
_dialog.setContentView(view);
sv_man = (SurfaceView)view.findViewById(R.id.quickadd_sv);
et_name = (AutoCompleteTextView)view.findViewById(R.id.quickadd_text);
et_name.setAdapter(object_adapter);
et_name.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null) {
return true;
}
String str = String.valueOf(((AutoCompleteTextView) v).getText());
if ("".equals(str)) {
} else {
PrincipiaBackend.createObject(str);
}
_dialog.dismiss();
return false;
}
});
sv_man.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_dialog.dismiss();
}
});
et_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
_dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
//bld.setView(view);
//_dialog = bld.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
PrincipiaActivity.on_show(dialog);
sv_man.requestFocus();
et_name.requestFocus();
InputMethodManager imm = (InputMethodManager)PrincipiaActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//imm.showSoftInput(et_name, InputMethodManager.SHOW_FORCED);
imm.showSoftInput(et_name, 0);
}
});
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
}
}

View file

@ -0,0 +1,616 @@
package com.bithack.principia.shared;
import java.math.BigDecimal;
import com.bithack.principialite.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ImageView;
/**
* Widget that lets users select a minimum and maximum value on a given numerical range. The range value types can be one of Long, Double, Integer, Float, Short, Byte or BigDecimal.<br />
* <br />
* Improved {@link MotionEvent} handling for smoother use, anti-aliased painting for improved aesthetics.
*
* @author Stephan Tittel (stephan.tittel@kom.tu-darmstadt.de)
* @author Peter Sinnott (psinnott@gmail.com)
* @author Thomas Barrasso (tbarrasso@sevenplusandroid.org)
*
* @param <T>
* The Number type of the range values. One of Long, Double, Integer, Float, Short, Byte or BigDecimal.
*/
public class RangeSeekBar<T extends Number> extends ImageView {
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Bitmap thumbImage = BitmapFactory.decodeResource(getResources(), R.drawable.seek_thumb_normal);
private final Bitmap thumbPressedImage = BitmapFactory.decodeResource(getResources(), R.drawable.seek_thumb_pressed);
private final float thumbWidth = thumbImage.getWidth();
private final float thumbHalfWidth = 0.5f * thumbWidth;
private final float thumbHalfHeight = 0.5f * thumbImage.getHeight();
private final float lineHeight = 0.3f * thumbHalfHeight;
private final float padding = thumbHalfWidth;
private final T absoluteMinValue, absoluteMaxValue;
private final NumberType numberType;
private final double absoluteMinValuePrim, absoluteMaxValuePrim;
private double normalizedMinValue = 0d;
private double normalizedMaxValue = 1d;
private Thumb pressedThumb = null;
private boolean notifyWhileDragging = false;
private OnRangeSeekBarChangeListener<T> listener;
/**
* Default color of a {@link RangeSeekBar}, #FF33B5E5. This is also known as "Ice Cream Sandwich" blue.
*/
public static final int DEFAULT_COLOR = Color.argb(0xFF, 0x33, 0xB5, 0xE5);
/**
* An invalid pointer id.
*/
public static final int INVALID_POINTER_ID = 255;
// Localized constants from MotionEvent for compatibility
// with API < 8 "Froyo".
public static final int ACTION_POINTER_UP = 0x6, ACTION_POINTER_INDEX_MASK = 0x0000ff00, ACTION_POINTER_INDEX_SHIFT = 8;
private float mDownMotionX;
private int mActivePointerId = INVALID_POINTER_ID;
/**
* On touch, this offset plus the scaled value from the position of the touch will form the progress value. Usually 0.
*/
float mTouchProgressOffset;
private int mScaledTouchSlop;
private boolean mIsDragging;
/**
* Creates a new RangeSeekBar.
*
* @param absoluteMinValue
* The minimum value of the selectable range.
* @param absoluteMaxValue
* The maximum value of the selectable range.
* @param context
* @throws IllegalArgumentException
* Will be thrown if min/max value type is not one of Long, Double, Integer, Float, Short, Byte or BigDecimal.
*/
public RangeSeekBar(T absoluteMinValue, T absoluteMaxValue, Context context) throws IllegalArgumentException {
super(context);
this.absoluteMinValue = absoluteMinValue;
this.absoluteMaxValue = absoluteMaxValue;
absoluteMinValuePrim = absoluteMinValue.doubleValue();
absoluteMaxValuePrim = absoluteMaxValue.doubleValue();
numberType = NumberType.fromNumber(absoluteMinValue);
// make RangeSeekBar focusable. This solves focus handling issues in case EditText widgets are being used along with the RangeSeekBar within ScollViews.
setFocusable(true);
setFocusableInTouchMode(true);
init();
}
private final void init() {
mScaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
public boolean isNotifyWhileDragging() {
return notifyWhileDragging;
}
/**
* Should the widget notify the listener callback while the user is still dragging a thumb? Default is false.
*
* @param flag
*/
public void setNotifyWhileDragging(boolean flag) {
this.notifyWhileDragging = flag;
}
/**
* Returns the absolute minimum value of the range that has been set at construction time.
*
* @return The absolute minimum value of the range.
*/
public T getAbsoluteMinValue() {
return absoluteMinValue;
}
/**
* Returns the absolute maximum value of the range that has been set at construction time.
*
* @return The absolute maximum value of the range.
*/
public T getAbsoluteMaxValue() {
return absoluteMaxValue;
}
/**
* Returns the currently selected min value.
*
* @return The currently selected min value.
*/
public T getSelectedMinValue() {
return normalizedToValue(normalizedMinValue);
}
/**
* Sets the currently selected minimum value. The widget will be invalidated and redrawn.
*
* @param value
* The Number value to set the minimum value to. Will be clamped to given absolute minimum/maximum range.
*/
public void setSelectedMinValue(T value) {
// in case absoluteMinValue == absoluteMaxValue, avoid division by zero when normalizing.
if (0 == (absoluteMaxValuePrim - absoluteMinValuePrim)) {
setNormalizedMinValue(0d);
}
else {
setNormalizedMinValue(valueToNormalized(value));
}
}
/**
* Returns the currently selected max value.
*
* @return The currently selected max value.
*/
public T getSelectedMaxValue() {
return normalizedToValue(normalizedMaxValue);
}
/**
* Sets the currently selected maximum value. The widget will be invalidated and redrawn.
*
* @param value
* The Number value to set the maximum value to. Will be clamped to given absolute minimum/maximum range.
*/
public void setSelectedMaxValue(T value) {
// in case absoluteMinValue == absoluteMaxValue, avoid division by zero when normalizing.
if (0 == (absoluteMaxValuePrim - absoluteMinValuePrim)) {
setNormalizedMaxValue(1d);
}
else {
setNormalizedMaxValue(valueToNormalized(value));
}
}
/**
* Registers given listener callback to notify about changed selected values.
*
* @param listener
* The listener to notify about changed selected values.
*/
public void setOnRangeSeekBarChangeListener(OnRangeSeekBarChangeListener<T> listener) {
this.listener = listener;
}
/**
* Handles thumb selection and movement. Notifies listener callback on certain events.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled())
return false;
int pointerIndex;
final int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
// Remember where the motion event started
mActivePointerId = event.getPointerId(event.getPointerCount() - 1);
pointerIndex = event.findPointerIndex(mActivePointerId);
mDownMotionX = event.getX(pointerIndex);
pressedThumb = evalPressedThumb(mDownMotionX);
// Only handle thumb presses.
if (pressedThumb == null)
return super.onTouchEvent(event);
setPressed(true);
invalidate();
onStartTrackingTouch();
trackTouchEvent(event);
attemptClaimDrag();
break;
case MotionEvent.ACTION_MOVE:
if (pressedThumb != null) {
if (mIsDragging) {
trackTouchEvent(event);
}
else {
// Scroll to follow the motion event
pointerIndex = event.findPointerIndex(mActivePointerId);
final float x = event.getX(pointerIndex);
if (Math.abs(x - mDownMotionX) > mScaledTouchSlop) {
setPressed(true);
invalidate();
onStartTrackingTouch();
trackTouchEvent(event);
attemptClaimDrag();
}
}
if (notifyWhileDragging && listener != null) {
listener.onRangeSeekBarValuesChanged(this, getSelectedMinValue(), getSelectedMaxValue());
}
}
break;
case MotionEvent.ACTION_UP:
if (mIsDragging) {
trackTouchEvent(event);
onStopTrackingTouch();
setPressed(false);
}
else {
// Touch up when we never crossed the touch slop threshold
// should be interpreted as a tap-seek to that location.
onStartTrackingTouch();
trackTouchEvent(event);
onStopTrackingTouch();
}
pressedThumb = null;
invalidate();
if (listener != null) {
listener.onRangeSeekBarValuesChanged(this, getSelectedMinValue(), getSelectedMaxValue());
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = event.getPointerCount() - 1;
// final int index = ev.getActionIndex();
mDownMotionX = event.getX(index);
mActivePointerId = event.getPointerId(index);
invalidate();
break;
}
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(event);
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
if (mIsDragging) {
onStopTrackingTouch();
setPressed(false);
}
invalidate(); // see above explanation
break;
}
return true;
}
private final void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose
// a new active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mDownMotionX = ev.getX(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
}
private final void trackTouchEvent(MotionEvent event) {
final int pointerIndex = event.findPointerIndex(mActivePointerId);
final float x = event.getX(pointerIndex);
if (Thumb.MIN.equals(pressedThumb)) {
setNormalizedMinValue(screenToNormalized(x));
}
else if (Thumb.MAX.equals(pressedThumb)) {
setNormalizedMaxValue(screenToNormalized(x));
}
}
/**
* Tries to claim the user's drag motion, and requests disallowing any ancestors from stealing events in the drag.
*/
private void attemptClaimDrag() {
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
}
/**
* This is called when the user has started touching this widget.
*/
void onStartTrackingTouch() {
mIsDragging = true;
}
/**
* This is called when the user either releases his touch or the touch is canceled.
*/
void onStopTrackingTouch() {
mIsDragging = false;
}
/**
* Ensures correct size of the widget.
*/
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 200;
if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(widthMeasureSpec)) {
width = MeasureSpec.getSize(widthMeasureSpec);
}
int height = thumbImage.getHeight();
if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec)) {
height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
}
setMeasuredDimension(width, height);
}
/**
* Draws the widget on the given canvas.
*/
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw seek bar background line
final RectF rect = new RectF(padding, 0.5f * (getHeight() - lineHeight), getWidth() - padding, 0.5f * (getHeight() + lineHeight));
paint.setStyle(Style.FILL);
paint.setColor(Color.GRAY);
paint.setAntiAlias(true);
canvas.drawRect(rect, paint);
// draw seek bar active range line
rect.left = normalizedToScreen(normalizedMinValue);
rect.right = normalizedToScreen(normalizedMaxValue);
// orange color
paint.setColor(DEFAULT_COLOR);
canvas.drawRect(rect, paint);
// draw minimum thumb
drawThumb(normalizedToScreen(normalizedMinValue), Thumb.MIN.equals(pressedThumb), canvas);
// draw maximum thumb
drawThumb(normalizedToScreen(normalizedMaxValue), Thumb.MAX.equals(pressedThumb), canvas);
}
/**
* Overridden to save instance state when device orientation changes. This method is called automatically if you assign an id to the RangeSeekBar widget using the {@link #setId(int)} method. Other members of this class than the normalized min and max values don't need to be saved.
*/
@Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable("SUPER", super.onSaveInstanceState());
bundle.putDouble("MIN", normalizedMinValue);
bundle.putDouble("MAX", normalizedMaxValue);
return bundle;
}
/**
* Overridden to restore instance state when device orientation changes. This method is called automatically if you assign an id to the RangeSeekBar widget using the {@link #setId(int)} method.
*/
@Override
protected void onRestoreInstanceState(Parcelable parcel) {
final Bundle bundle = (Bundle) parcel;
super.onRestoreInstanceState(bundle.getParcelable("SUPER"));
normalizedMinValue = bundle.getDouble("MIN");
normalizedMaxValue = bundle.getDouble("MAX");
}
/**
* Draws the "normal" resp. "pressed" thumb image on specified x-coordinate.
*
* @param screenCoord
* The x-coordinate in screen space where to draw the image.
* @param pressed
* Is the thumb currently in "pressed" state?
* @param canvas
* The canvas to draw upon.
*/
private void drawThumb(float screenCoord, boolean pressed, Canvas canvas) {
canvas.drawBitmap(pressed ? thumbPressedImage : thumbImage, screenCoord - thumbHalfWidth, (float) ((0.5f * getHeight()) - thumbHalfHeight), paint);
}
/**
* Decides which (if any) thumb is touched by the given x-coordinate.
*
* @param touchX
* The x-coordinate of a touch event in screen space.
* @return The pressed thumb or null if none has been touched.
*/
private Thumb evalPressedThumb(float touchX) {
Thumb result = null;
boolean minThumbPressed = isInThumbRange(touchX, normalizedMinValue);
boolean maxThumbPressed = isInThumbRange(touchX, normalizedMaxValue);
if (minThumbPressed && maxThumbPressed) {
// if both thumbs are pressed (they lie on top of each other), choose the one with more room to drag. this avoids "stalling" the thumbs in a corner, not being able to drag them apart anymore.
result = (touchX / getWidth() > 0.5f) ? Thumb.MIN : Thumb.MAX;
}
else if (minThumbPressed) {
result = Thumb.MIN;
}
else if (maxThumbPressed) {
result = Thumb.MAX;
}
return result;
}
/**
* Decides if given x-coordinate in screen space needs to be interpreted as "within" the normalized thumb x-coordinate.
*
* @param touchX
* The x-coordinate in screen space to check.
* @param normalizedThumbValue
* The normalized x-coordinate of the thumb to check.
* @return true if x-coordinate is in thumb range, false otherwise.
*/
private boolean isInThumbRange(float touchX, double normalizedThumbValue) {
return Math.abs(touchX - normalizedToScreen(normalizedThumbValue)) <= thumbHalfWidth;
}
/**
* Sets normalized min value to value so that 0 <= value <= normalized max value <= 1. The View will get invalidated when calling this method.
*
* @param value
* The new normalized min value to set.
*/
public void setNormalizedMinValue(double value) {
normalizedMinValue = Math.max(0d, Math.min(1d, Math.min(value, normalizedMaxValue)));
invalidate();
}
/**
* Sets normalized max value to value so that 0 <= normalized min value <= value <= 1. The View will get invalidated when calling this method.
*
* @param value
* The new normalized max value to set.
*/
public void setNormalizedMaxValue(double value) {
normalizedMaxValue = Math.max(0d, Math.min(1d, Math.max(value, normalizedMinValue)));
invalidate();
}
/**
* Converts a normalized value to a Number object in the value space between absolute minimum and maximum.
*
* @param normalized
* @return
*/
@SuppressWarnings("unchecked")
private T normalizedToValue(double normalized) {
return (T) numberType.toNumber(absoluteMinValuePrim + normalized * (absoluteMaxValuePrim - absoluteMinValuePrim));
}
/**
* Converts the given Number value to a normalized double.
*
* @param value
* The Number value to normalize.
* @return The normalized double.
*/
private double valueToNormalized(T value) {
if (0 == absoluteMaxValuePrim - absoluteMinValuePrim) {
// prevent division by zero, simply return 0.
return 0d;
}
return (value.doubleValue() - absoluteMinValuePrim) / (absoluteMaxValuePrim - absoluteMinValuePrim);
}
/**
* Converts a normalized value into screen space.
*
* @param normalizedCoord
* The normalized value to convert.
* @return The converted value in screen space.
*/
private float normalizedToScreen(double normalizedCoord) {
return (float) (padding + normalizedCoord * (getWidth() - 2 * padding));
}
/**
* Converts screen space x-coordinates into normalized values.
*
* @param screenCoord
* The x-coordinate in screen space to convert.
* @return The normalized value.
*/
private double screenToNormalized(float screenCoord) {
int width = getWidth();
if (width <= 2 * padding) {
// prevent division by zero, simply return 0.
return 0d;
}
else {
double result = (screenCoord - padding) / (width - 2 * padding);
return Math.min(1d, Math.max(0d, result));
}
}
/**
* Callback listener interface to notify about changed range values.
*
* @author Stephan Tittel (stephan.tittel@kom.tu-darmstadt.de)
*
* @param <T>
* The Number type the RangeSeekBar has been declared with.
*/
public interface OnRangeSeekBarChangeListener<T> {
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, T minValue, T maxValue);
}
/**
* Thumb constants (min and max).
*/
private static enum Thumb {
MIN, MAX
};
/**
* Utility enumaration used to convert between Numbers and doubles.
*
* @author Stephan Tittel (stephan.tittel@kom.tu-darmstadt.de)
*
*/
private static enum NumberType {
LONG, DOUBLE, INTEGER, FLOAT, SHORT, BYTE, BIG_DECIMAL;
public static <E extends Number> NumberType fromNumber(E value) throws IllegalArgumentException {
if (value instanceof Long) {
return LONG;
}
if (value instanceof Double) {
return DOUBLE;
}
if (value instanceof Integer) {
return INTEGER;
}
if (value instanceof Float) {
return FLOAT;
}
if (value instanceof Short) {
return SHORT;
}
if (value instanceof Byte) {
return BYTE;
}
if (value instanceof BigDecimal) {
return BIG_DECIMAL;
}
throw new IllegalArgumentException("Number class '" + value.getClass().getName() + "' is not supported");
}
public Number toNumber(double value) {
switch (this) {
case LONG:
return new Long((long) value);
case DOUBLE:
return value;
case INTEGER:
return new Integer((int) value);
case FLOAT:
return new Float(value);
case SHORT:
return new Short((short) value);
case BYTE:
return new Byte((byte) value);
case BIG_DECIMAL:
return new BigDecimal(value);
}
throw new InstantiationError("can't convert " + this + " to a Number object");
}
}
}

View file

@ -0,0 +1,125 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.google.android.vending.licensing.LicenseValidator;
public class RegisterDialog
{
static AlertDialog _dialog;
static View view;
static EditText et_username;
static EditText et_email;
static EditText et_password;
static EditText et_password_confirm;
public static ProgressBar progressbar;
public static int num_tries = 0;
public static final int MAX_TRIES = 3;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.register, null);
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(view)
.setTitle("Register")
.setPositiveButton("Register", null)
.setNegativeButton("Cancel", new OnClickListener(){public void onClick(DialogInterface dialog, int which){}})
.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
Button b = _dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
final String password_confirm = et_password_confirm.getText().toString().trim();
final String email = et_email.getText().toString().trim();
if (password.length() < 6 || password.length() > 100) {
SDLActivity.message("Your password must be at least 3 and at most 100 characters.", 0);
return;
}
if (!password.equals(password_confirm)) {
SDLActivity.message("The two passwords you entered don't match.", 0);
return;
}
if (username.length() < 3 || username.length() > 20) {
SDLActivity.message("Your username must be at least 3 and at most 20 characters.", 0);
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
SDLActivity.message("You must enter a valid email address.", 0);
return;
}
progressbar.setVisibility(View.VISIBLE);
LicenseValidator.setListener(new LicenseValidator.Listener() {
@Override
public void onUpdate(String signature,
String userdata) {
PrincipiaBackend.register(username, email, password, signature, userdata);
}
@Override
public void onFailure() {
Log.v("Principia", "Failed!");
SDLActivity.mSingleton.runOnUiThread(new Runnable(){
public void run() {
RegisterDialog.num_tries ++;
if (RegisterDialog.num_tries < RegisterDialog.MAX_TRIES) {
SDLActivity.mSingleton.do_check();
} else {
progressbar.setVisibility(View.GONE);
SDLActivity.message("An unknown error has occured when attempting to register an account.", 0);
}
}
});
}
});
RegisterDialog.num_tries = 0;
SDLActivity.mSingleton.do_check();
}
});
}
});
et_username = (EditText)view.findViewById(R.id.register_username);
et_email = (EditText)view.findViewById(R.id.register_email);
et_password = (EditText)view.findViewById(R.id.register_password);
et_password_confirm = (EditText)view.findViewById(R.id.register_password_confirm);
progressbar = (ProgressBar)view.findViewById(R.id.register_progress);
}
return _dialog;
}
}

View file

@ -0,0 +1,98 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class RobotDialog {
static Dialog _dialog;
static View view;
static RadioGroup rg_default_state;
static CheckBox cb_roam;
static RadioGroup rg_initial_dir;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.robot, null);
rg_default_state = (RadioGroup)view.findViewById(R.id.robot_default_state);
cb_roam = (CheckBox)view.findViewById(R.id.robot_roam);
rg_initial_dir = (RadioGroup)view.findViewById(R.id.robot_initial_dir);
bld.setTitle("Robot");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
RobotDialog._dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
boolean roam = PrincipiaBackend.getRobotRoam();
int state = PrincipiaBackend.getRobotState();
int dir = PrincipiaBackend.getRobotDir();
cb_roam.setChecked(roam);
switch (state) {
case 0: ((RadioButton)view.findViewById(R.id.robot_state_idle)).setChecked(true); break;
case 1: ((RadioButton)view.findViewById(R.id.robot_state_walk)).setChecked(true); break;
case 3: ((RadioButton)view.findViewById(R.id.robot_state_dead)).setChecked(true); break;
}
switch (dir) {
case 1: ((RadioButton)view.findViewById(R.id.robot_dir_left)).setChecked(true); break;
case 0: ((RadioButton)view.findViewById(R.id.robot_dir_random)).setChecked(true); break;
case 2: ((RadioButton)view.findViewById(R.id.robot_dir_right)).setChecked(true); break;
}
}
public static void save()
{
int state = 0;
int dir = 0;
switch (rg_default_state.getCheckedRadioButtonId()) {
case R.id.robot_state_idle: state = 0; break;
case R.id.robot_state_walk: state = 1; break;
case R.id.robot_state_dead: state = 3; break;
}
switch (rg_initial_dir.getCheckedRadioButtonId()) {
case R.id.robot_dir_left: dir = 1; break;
case R.id.robot_dir_random: dir = 0; break;
case R.id.robot_dir_right: dir = 2; break;
}
PrincipiaBackend.setRobotStuff(state, cb_roam.isChecked(), dir);
}
}

View file

@ -0,0 +1,180 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class RubberDialog {
static Dialog _dialog;
static View view;
static SeekBar sb_restitution;
static SeekBar sb_friction;
static EditText et_restitution;
static EditText et_friction;
static float old_restitution;
static float old_friction;
public static Dialog get_dialog()
{
if (_dialog == null) {
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.rubber, null);
sb_restitution = (SeekBar)view.findViewById(R.id.rubber_restitution);
et_restitution = (EditText)view.findViewById(R.id.rubber_restitution_et);
sb_friction = (SeekBar)view.findViewById(R.id.rubber_friction);
et_friction = (EditText)view.findViewById(R.id.rubber_friction_et);
sb_restitution.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
float value = progress / 100000.f;
et_restitution.setText(Float.toString(value));
}
}
@Override public void onStartTrackingTouch(SeekBar seekBar) { }
@Override public void onStopTrackingTouch(SeekBar seekBar) { }
});
sb_friction.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
float value = (progress / 10000.f) + 1.f;
et_friction.setText(Float.toString(value));
}
}
@Override public void onStartTrackingTouch(SeekBar seekBar) { }
@Override public void onStopTrackingTouch(SeekBar seekBar) { }
});
et_restitution.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null) {
return true;
}
float val;
try {
val = Float.parseFloat(v.getText().toString());
} catch (NumberFormatException e) {
val = RubberDialog.old_restitution;
}
if (val < 0.f) val = 0.f;
else if (val > 1.f) val = 1.f;
v.setText(Float.toString(val));
int p = (int)(val * 100000.f);
sb_restitution.setProgress(p);
return false;
}
});
et_friction.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null) {
return true;
}
float val;
try {
val = Float.parseFloat(v.getText().toString());
} catch (NumberFormatException e) {
val = RubberDialog.old_friction;
}
if (val < 1.f) val = 1.f;
else if (val > 10.f) val = 10.f;
v.setText(Float.toString(val));
int p = (int)((val-1) * 10000.f);
sb_friction.setProgress(p);
return false;
}
});
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setTitle("Rubber properties")
.setView(view)
.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
save();
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
float v_restitution = PrincipiaBackend.getPropertyFloat(1);
float v_friction = PrincipiaBackend.getPropertyFloat(2);
RubberDialog.old_restitution = v_restitution;
RubberDialog.old_friction = v_friction;
et_restitution.setText(Float.toString(v_restitution));
et_friction.setText(Float.toString(v_friction));
int p = (int)(v_restitution * 100000.f);
sb_restitution.setProgress(p);
p = (int)((v_friction-1) * 10000.f);
sb_friction.setProgress(p);
}
public static void save()
{
float v_restitution = RubberDialog.old_restitution;
float v_friction = RubberDialog.old_friction;
try {
v_restitution = Float.parseFloat(et_restitution.getText().toString());
} catch (NumberFormatException e) {
Log.v("Principia", "Using old restitution value.");
v_restitution = RubberDialog.old_restitution;
}
try {
v_friction = Float.parseFloat(et_friction.getText().toString());
} catch (NumberFormatException e) {
Log.v("Principia", "Using old friction value.");
v_friction = RubberDialog.old_friction;
}
Log.v("Principia", String.format("New values: %.2f/%.2f", v_restitution, v_friction));
PrincipiaBackend.updateRubberEntity(v_restitution, v_friction);
}
}

View file

@ -0,0 +1,82 @@
package com.bithack.principia.shared;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import org.libsdl.app.PrincipiaBackend;
import org.libsdl.app.SDLActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class SandboxTipsDialog
{
AlertDialog _dialog;
final View view;
final TextView tv_tip;
final CheckBox cb_dont_show_again;
public SandboxTipsDialog()
{
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.sandbox_tips, null);
_dialog = new AlertDialog.Builder(PrincipiaActivity.mSingleton)
.setView(view)
.setTitle("Tips & tricks")
.setPositiveButton("OK", new OnClickListener(){public void onClick(DialogInterface dialog, int which) {}})
.setNeutralButton("Next", null)
.setNegativeButton("More tips & tricks", new OnClickListener(){public void onClick(DialogInterface dialog, int which){SDLActivity.open_url("http://principiagame.com/gettingstarted.php");}})
.create();
_dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
SDLActivity.on_show(dialog);
Button b = _dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new_tip();
}
});
}
});
tv_tip = (TextView)view.findViewById(R.id.sandbox_tips_text);
cb_dont_show_again = (CheckBox)view.findViewById(R.id.sandbox_tips_dont_show_again);
cb_dont_show_again.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
PrincipiaBackend.setSetting("hide_tips", isChecked);
}
});
this.new_tip();
}
public void new_tip()
{
tv_tip.setText(PrincipiaBackend.getSandboxTip());
}
public Dialog get_dialog()
{
return this._dialog;
}
}

View file

@ -0,0 +1,73 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class SaveAsDialog
{
static Dialog _dialog;
static View view;
static EditText et_name;
public static boolean refresh_name = false;
public static boolean copy;
public static Dialog get_dialog()
{
if (_dialog == null && PrincipiaActivity.FULL) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
bld.setTitle("Save a copy");
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.save_as, null);
et_name = (EditText)view.findViewById(R.id.save_name);
bld.setView(view);
bld.setNeutralButton("Save", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
String name = et_name.getText().toString().trim();
PrincipiaBackend.setLevelName(name);
PrincipiaBackend.triggerSave(SaveAsDialog.copy);
Toast.makeText(PrincipiaActivity.mSingleton, "Saved!", Toast.LENGTH_SHORT).show();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
if (refresh_name) {
String name = PrincipiaBackend.getLevelName();
if (copy) {
_dialog.setTitle("Save a copy");
name = name + " (copy)";
} else
_dialog.setTitle("Save level");
et_name.setText(name);
refresh_name = false;
}
}
}

View file

@ -0,0 +1,132 @@
package com.bithack.principia.shared;
import java.util.ArrayList;
import java.util.List;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import com.bithack.principia.shared.ConfirmDialog.OnOptionSelectedListener;
import com.bithack.principia.shared.CustomLinearLayout.OnKeyboardStateChangedListener;
import com.bithack.principia.shared.MultiSpinner.MultiSpinnerListener;
import org.libsdl.app.PrincipiaBackend;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class ScriptDialog {
public static final int NUM_LIBRARIES = 2;
static Dialog _dialog;
static View view;
static EditText code;
static Button save;
static Button cancel;
static CustomLinearLayout ll_code;
static LinearLayout ll_end;
static MultiSpinner sp_libraries;
static int current_keyboard_state = CustomLinearLayout.KEYBOARD_HIDDEN;
static List<String> items;
public static Dialog get_dialog()
{
if (_dialog == null) {
items = new ArrayList<String>();
items.add("string");
items.add("table");
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.script, null);
_dialog = new Dialog(PrincipiaActivity.getContext(), R.style.CodeDialog) {
@Override
protected void onCreate(Bundle saved_instance) {
super.onCreate(saved_instance);
getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
};
_dialog.setContentView(view);
ll_code = (CustomLinearLayout)view.findViewById(R.id.ll_code);
ll_code.set_listener(new OnKeyboardStateChangedListener() {
@Override
public void onKeyboardStateChanged(int new_state) {
//if (current_keyboard_state == new_state) return;
if (new_state == CustomLinearLayout.KEYBOARD_HIDDEN) {
ll_end.setVisibility(View.VISIBLE);
} else if (new_state == CustomLinearLayout.KEYBOARD_SHOWN) {
ll_end.setVisibility(View.GONE);
}
}
});
ll_end = (LinearLayout)view.findViewById(R.id.ll_end);
code = (EditText)view.findViewById(R.id.script_code);
code.setHorizontallyScrolling(true);
save = (Button)view.findViewById(R.id.script_save);
cancel = (Button)view.findViewById(R.id.script_cancel);
sp_libraries = (MultiSpinner)view.findViewById(R.id.script_libraries);
sp_libraries.setItems(items, PrincipiaActivity.mSingleton.getString(R.string.libraries), new MultiSpinnerListener() {
@Override public void onItemsSelected(boolean[] selected) { }
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
_dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ConfirmDialog()
.set_listener(new OnOptionSelectedListener() {
@Override
public void onOptionSelected(int option) {
if (option == ConfirmDialog.OPTION_YES) {
_dialog.dismiss();
}
}
})
.run(PrincipiaActivity.mSingleton.getString(R.string.confirm_cancel_script_dialog));
}
});
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
code.setText(PrincipiaBackend.getPropertyString(0));
long included_libraries = PrincipiaBackend.getPropertyInt(1);
for (int x=0; x<ScriptDialog.NUM_LIBRARIES; ++x) {
if ((included_libraries & (1 << x)) == 0) {
sp_libraries.selected[x] = false;
} else {
sp_libraries.selected[x] = true;
}
}
}
public static void save()
{
long included_libraries = 0;
for (int x=0; x<ScriptDialog.NUM_LIBRARIES; ++x) {
included_libraries |= (sp_libraries.selected[x] ? 1 : 0) * (1 << x);
}
PrincipiaBackend.setPropertyString(0, code.getText().toString());
PrincipiaBackend.setPropertyInt(1, included_libraries);
PrincipiaBackend.addActionAsInt(PrincipiaActivity.ACTION_HIGHLIGHT_SELECTED, 0);
PrincipiaBackend.addActionAsInt(PrincipiaActivity.ACTION_ENTITY_MODIFIED, 0);
}
}

View file

@ -0,0 +1,85 @@
package com.bithack.principia.shared;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
public class SequencerDialog {
static Dialog _dialog;
static View view;
static EditText sequence;
static NumberPicker np_seconds;
static NumberPicker np_milliseconds;
static CheckBox wrap_around;
public static Dialog get_dialog()
{
if (_dialog == null) {
AlertDialog.Builder bld = new AlertDialog.Builder(PrincipiaActivity.mSingleton);
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.sequencer, null);
np_seconds = (NumberPicker)view.findViewById(R.id.sequencer_seconds);
np_seconds.setRange(0, 360);
np_milliseconds = (NumberPicker)view.findViewById(R.id.sequencer_milliseconds);
np_milliseconds.setRange(0, 1000);
np_milliseconds.setLongStep(50);
sequence = (EditText)view.findViewById(R.id.sequencer_sequence);
wrap_around = (CheckBox)view.findViewById(R.id.sequencer_wrap_around);
bld.setTitle("Sequencer");
bld.setView(view);
bld.setPositiveButton("OK", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
int x = (SequencerDialog.np_seconds.getValue() * 1000) + SequencerDialog.np_milliseconds.getValue();
if (x < 16) SequencerDialog.np_milliseconds.setValue(16);
save();
dialog.dismiss();
}
});
bld.setNegativeButton("Cancel", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
_dialog = bld.create();
}
return _dialog;
}
public static void prepare(DialogInterface di)
{
String _sequence = PrincipiaBackend.getPropertyString(0);
long full_time = PrincipiaBackend.getPropertyInt(1);
boolean wrap = (PrincipiaBackend.getPropertyInt8(2) == 1);
int s = (int)(full_time / 1000);
int ms = (int)(full_time % 1000);
np_seconds.setValue(s);
np_milliseconds.setValue(ms);
wrap_around.setChecked(wrap);
sequence.setText(_sequence);
}
public static void save()
{
PrincipiaBackend.setSequencerData(sequence.getText().toString().trim(), np_seconds.getValue(), np_milliseconds.getValue(), wrap_around.isChecked());
}
}

View file

@ -0,0 +1,24 @@
package com.bithack.principia.shared;
public class Settings
{
public boolean enable_shadows;
public int shadow_quality;
public float uiscale;
public float cam_speed;
public float zoom_speed;
public boolean smooth_cam;
public boolean smooth_zoom;
public boolean border_scroll_enabled;
public float border_scroll_speed;
public int shadow_map_resx;
public int shadow_map_resy;
public int ao_map_res;
public boolean enable_ao;
public int texture_quality;
public boolean display_object_ids;
//boolean enable_bloom;
}

View file

@ -0,0 +1,325 @@
package com.bithack.principia.shared;
import java.util.Locale;
import org.libsdl.app.PrincipiaBackend;
import com.bithack.principialite.PrincipiaActivity;
import com.bithack.principialite.R;
import com.facebook.AppEventsLogger;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SettingsDialog implements OnSeekBarChangeListener, OnClickListener {
Dialog _dialog;
CharSequence[] filelist = null;
String[] absolute_filelist = null;
final View view;
final SeekBar sb_shadowresolution;
final SeekBar sb_shadowsoftness;
final SeekBar sb_uiscale;
final SeekBar settings_cam_speed;
final SeekBar settings_zoom_speed;
final CheckBox cb_enableshadows;
final RadioGroup rg_ao;
final RadioGroup rg_texture_quality;
final CheckBox settings_smooth_cam;
final CheckBox settings_smooth_zoom;
final CheckBox settings_border_scroll_enabled;
final CheckBox settings_facebook_opt_out;
final CheckBox settings_display_object_ids;
final SeekBar settings_border_scroll_speed;
final Button btn_preset_low, btn_preset_medium, btn_preset_high;
final Button btn_save, btn_cancel;
final TextView text_curr_res;
final TextView text_curr_softness;
final TextView text_curr_uiscale;
final TextView settings_cam_speed_tv;
final TextView settings_zoom_speed_tv;
final TextView settings_border_scroll_speed_tv;
final private String shadow_resolutions[] = {
"256x256",
"512x256",
"512x512",
"1024x512",
"1024x1024",
"2048x2048"
};
public SettingsDialog()
{
view = LayoutInflater.from(PrincipiaActivity.mSingleton).inflate(R.layout.settings, null);
this._dialog = new Dialog(PrincipiaActivity.mSingleton, android.R.style.Theme_NoTitleBar_Fullscreen){
@Override
protected void onCreate(Bundle saved_instance) {
super.onCreate(saved_instance);
getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
};
this._dialog.setContentView(view);
sb_shadowresolution = (SeekBar)view.findViewById(R.id.seekbar_shadowresolution);
sb_shadowsoftness = (SeekBar)view.findViewById(R.id.seekbar_shadowsoftness);
sb_uiscale = (SeekBar)view.findViewById(R.id.settings_uiscale);
rg_ao = (RadioGroup)view.findViewById(R.id.radiogroup_ao);
rg_texture_quality = (RadioGroup)view.findViewById(R.id.tex_quality);
cb_enableshadows = (CheckBox)view.findViewById(R.id.checkbox_enableshadows);
btn_preset_low = (Button)view.findViewById(R.id.btn_preset_low);
btn_preset_medium = (Button)view.findViewById(R.id.btn_preset_medium);
btn_preset_high = (Button)view.findViewById(R.id.btn_preset_high);
text_curr_res = (TextView)view.findViewById(R.id.curr_res);
text_curr_softness = (TextView)view.findViewById(R.id.curr_softness);
text_curr_uiscale = (TextView)view.findViewById(R.id.tv_uiscale);
settings_cam_speed = (SeekBar)view.findViewById(R.id.settings_cam_speed);
settings_cam_speed_tv = (TextView)view.findViewById(R.id.settings_cam_speed_tv);
settings_zoom_speed = (SeekBar)view.findViewById(R.id.settings_zoom_speed);
settings_zoom_speed_tv = (TextView)view.findViewById(R.id.settings_zoom_speed_tv);
settings_smooth_cam = (CheckBox)view.findViewById(R.id.settings_smooth_cam);
settings_smooth_zoom = (CheckBox)view.findViewById(R.id.settings_smooth_zoom);
settings_border_scroll_enabled = (CheckBox)view.findViewById(R.id.settings_border_scroll);
settings_border_scroll_speed = (SeekBar)view.findViewById(R.id.settings_border_scroll_speed);
settings_border_scroll_speed_tv = (TextView)view.findViewById(R.id.settings_border_scroll_speed_tv);
settings_display_object_ids = (CheckBox)view.findViewById(R.id.settings_display_object_ids);
settings_facebook_opt_out = (CheckBox)view.findViewById(R.id.settings_facebook_opt_out);
btn_save = (Button)view.findViewById(R.id.settings_save);
btn_cancel = (Button)view.findViewById(R.id.settings_cancel);
settings_cam_speed.setOnSeekBarChangeListener(this);
settings_zoom_speed.setOnSeekBarChangeListener(this);
settings_border_scroll_speed.setOnSeekBarChangeListener(this);
sb_shadowresolution.setOnSeekBarChangeListener(this);
sb_shadowsoftness.setOnSeekBarChangeListener(this);
sb_uiscale.setOnSeekBarChangeListener(this);
btn_preset_low.setOnClickListener(this);
btn_preset_medium.setOnClickListener(this);
btn_preset_high.setOnClickListener(this);
btn_save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
save();
_dialog.dismiss();
}
});
btn_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_dialog.dismiss();
}
});
}
public void save()
{
boolean enable_shadows = cb_enableshadows.isChecked();
boolean enable_ao = true;
int shadow_quality;
int shadow_map_resx;
int shadow_map_resy;
int ao_map_res = 256;
int texture_quality = 2;
float uiscale_base = (float)sb_uiscale.getProgress() / 10.f;
float uiscale = uiscale_base + 0.5f;
float cam_speed_base = (float)settings_cam_speed.getProgress() / 10.f;
float cam_speed = cam_speed_base + 0.3f;
float zoom_speed_base = (float)settings_zoom_speed.getProgress() / 10.f;
float zoom_speed = zoom_speed_base + 0.3f;
boolean smooth_cam = this.settings_smooth_cam.isChecked();
boolean smooth_zoom = this.settings_smooth_zoom.isChecked();
boolean display_object_ids = this.settings_display_object_ids.isChecked();
boolean border_scroll_enabled = this.settings_border_scroll_enabled.isChecked();
float border_scroll_speed_base = (float)this.settings_border_scroll_speed.getProgress() / 10.f;
float border_scroll_speed = border_scroll_speed_base + 0.5f;
switch (rg_ao.getCheckedRadioButtonId()) {
case R.id.rg_values_off: enable_ao = false; break;
case R.id.rg_values_low: ao_map_res = 128; break;
case R.id.rg_values_medium: ao_map_res = 256; break;
case R.id.rg_values_high: ao_map_res = 512; break;
}
switch (sb_shadowresolution.getProgress()) {
case 0: shadow_map_resx = 256; shadow_map_resy = 256; break;
case 1: shadow_map_resx = 512; shadow_map_resy = 256; break;
case 2: shadow_map_resx = 512; shadow_map_resy = 512; break;
case 3: shadow_map_resx = 1024; shadow_map_resy = 512; break;
default: case 4: shadow_map_resx = 1024; shadow_map_resy = 1024; break;
case 5: shadow_map_resx = 2048; shadow_map_resy = 2048; break;
}
switch (rg_texture_quality.getCheckedRadioButtonId()) {
case R.id.tex_low: texture_quality = 0; break;
case R.id.tex_high: texture_quality = 2; break;
}
shadow_quality = sb_shadowsoftness.getProgress();
AppEventsLogger.setLimitEventUsage(PrincipiaActivity.getContext(), !this.settings_facebook_opt_out.isChecked());
PrincipiaBackend.setSettings(enable_shadows, enable_ao,
shadow_quality, shadow_map_resx, shadow_map_resy,
ao_map_res, texture_quality, uiscale,
cam_speed, zoom_speed,
smooth_cam, smooth_zoom,
border_scroll_enabled, border_scroll_speed,
display_object_ids);
}
public void load()
{
Log.v("Principia", "Loading settings.");
Settings s = PrincipiaBackend.getSettings();
int sr = -1;
String sr_str = String.format(Locale.US, "%dx%d", s.shadow_map_resx, s.shadow_map_resy);
for (int x=0; x<shadow_resolutions.length; ++x) {
if (sr_str.equals(shadow_resolutions[x])) {
sr = x;
break;
}
}
if (sr == -1) {
sb_shadowresolution.setProgress(0);
} else {
sb_shadowresolution.setProgress(sr);
}
text_curr_res.setText(sr_str);
cb_enableshadows.setChecked(s.enable_shadows);
sb_shadowsoftness.setProgress(s.shadow_quality);
if (s.enable_ao) {
if (s.ao_map_res == 512)
rg_ao.check(R.id.rg_values_high);
if (s.ao_map_res == 256)
rg_ao.check(R.id.rg_values_medium);
else
rg_ao.check(R.id.rg_values_low);
} else {
rg_ao.check(R.id.rg_values_off);
}
if (s.texture_quality == 0) {
rg_texture_quality.check(R.id.tex_low);
} else if (s.texture_quality == 2) {
rg_texture_quality.check(R.id.tex_high);
} else {
rg_texture_quality.check(R.id.tex_low);
}
int uiscale_step = (int)Math.round((((double)s.uiscale - 0.5) * 10.0));
if (uiscale_step == 0) {
text_curr_uiscale.setText("0.5");
}
sb_uiscale.setProgress(uiscale_step);
int cam_speed_step = (int)Math.round((((double)s.cam_speed - 0.3) * 10.0));
if (cam_speed_step == 0) this.settings_cam_speed_tv.setText("0.5");
this.settings_cam_speed.setProgress(cam_speed_step);
int zoom_speed_step = (int)Math.round((((double)s.zoom_speed - 0.3) * 10.0));
if (zoom_speed_step == 0) this.settings_zoom_speed_tv.setText("0.5");
this.settings_zoom_speed.setProgress(zoom_speed_step);
this.settings_smooth_cam.setChecked(s.smooth_cam);
this.settings_smooth_zoom.setChecked(s.smooth_zoom);
this.settings_border_scroll_enabled.setChecked(s.border_scroll_enabled);
int border_scroll_speed_step = (int)Math.round((((double)s.border_scroll_speed - 0.5) * 10.0));
if (border_scroll_speed_step == 0) this.settings_cam_speed_tv.setText("0.5");
this.settings_border_scroll_speed.setProgress(border_scroll_speed_step);
this.settings_display_object_ids.setChecked(s.display_object_ids);
this.settings_facebook_opt_out.setChecked(!AppEventsLogger.getLimitEventUsage(PrincipiaActivity.getContext()));
}
public Dialog get_dialog()
{
return this._dialog;
}
@Override
public void onProgressChanged(SeekBar sb, int progress,
boolean from_user) {
if (sb == this.settings_cam_speed) {
this.settings_cam_speed_tv.setText(String.format(Locale.US, "%.2f", ((float)progress / 10.f)+.3f));
} else if (sb == this.sb_shadowresolution) {
this.text_curr_res.setText(this.shadow_resolutions[progress]);
} else if (sb == this.sb_shadowsoftness) {
if (progress == 0) {
text_curr_softness.setText(R.string.sharp);
} else {
text_curr_softness.setText(R.string.soft);
}
} else if (sb == this.sb_uiscale) {
double base = (double)progress / 10.f;
double uiscale = base + 0.5f;
text_curr_uiscale.setText(String.format(Locale.US, "%.1f", uiscale));
} else if (sb == this.settings_zoom_speed) {
this.settings_zoom_speed_tv.setText(String.format(Locale.US, "%.2f", ((float)progress / 10.f)+.3f));
} else if (sb == this.settings_border_scroll_speed) {
this.settings_border_scroll_speed_tv.setText(String.format(Locale.US, "%.2f", ((float)progress / 10.f)+.5f));
}
}
@Override
public void onClick(View v) {
if (v == this.btn_preset_low) {
sb_shadowresolution.setProgress(0);
sb_shadowsoftness.setProgress(0);
rg_ao.check(R.id.rg_values_off);
cb_enableshadows.setChecked(false);
rg_texture_quality.check(R.id.tex_low);
} else if (v == this.btn_preset_medium) {
sb_shadowresolution.setProgress(3);
sb_shadowsoftness.setProgress(0);
rg_ao.check(R.id.rg_values_low);
cb_enableshadows.setChecked(true);
rg_texture_quality.check(R.id.tex_high);
} else if (v == this.btn_preset_high) {
sb_shadowresolution.setProgress(5);
sb_shadowsoftness.setProgress(1);
rg_ao.check(R.id.rg_values_medium);
cb_enableshadows.setChecked(true);
rg_texture_quality.check(R.id.tex_high);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
}

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