From 93573e87cd7c17051e65f632928be4ce568b42bd Mon Sep 17 00:00:00 2001 From: Google Code Exporter Date: Mon, 30 Mar 2015 08:15:45 -0400 Subject: [PATCH] Migrating wiki contents from Google Code --- BuildingModules.md | 88 ++++++++++++++++++ BuildingPython.md | 25 +++++ Contributions.md | 8 ++ CreatingAPKs.md | 19 ++++ CrossCompilingPython.md | 191 ++++++++++++++++++++++++++++++++++++++ Examples.md | 28 ++++++ FullScreenWrapper.md | 29 ++++++ HelperFiles.md | 22 +++++ Modules.md | 64 +++++++++++++ ProjectHome.md | 6 ++ Python3.md | 103 ++++++++++++++++++++ RunPythonFromShell.md | 48 ++++++++++ Toolchain_Installation.md | 25 +++++ Versions.md | 15 +++ fullscreenwrapper2.md | 160 +++++++++++++++++++++++++++++++ 15 files changed, 831 insertions(+) create mode 100644 BuildingModules.md create mode 100644 BuildingPython.md create mode 100644 Contributions.md create mode 100644 CreatingAPKs.md create mode 100644 CrossCompilingPython.md create mode 100644 Examples.md create mode 100644 FullScreenWrapper.md create mode 100644 HelperFiles.md create mode 100644 Modules.md create mode 100644 ProjectHome.md create mode 100644 Python3.md create mode 100644 RunPythonFromShell.md create mode 100644 Toolchain_Installation.md create mode 100644 Versions.md create mode 100644 fullscreenwrapper2.md diff --git a/BuildingModules.md b/BuildingModules.md new file mode 100644 index 00000000..9f3499de --- /dev/null +++ b/BuildingModules.md @@ -0,0 +1,88 @@ +# Introduction # + +A guide on how to build Python Modules. +_Note: For 2.6.2 Python. 3.2.2 is still in development_ + +# Setup # + +Download the latest python-lib from our [Downloads](Downloads.md) section, _At time of writing, this is:_ +``` +python-lib_r14.zip +``` + +Unzip this into python-modules/python-lib + + +# Using setuptools - Creating Egg # +## NDK setup ## +In order to build binary modules you need to have Android NDK installed and correctly setup. Download the latest NDK, drop it somewhere, do a [toolchain installation](Toolchain_Installation.md), and then export the next variables: +``` +export ANDROID_NDK_TOOLCHAIN_ROOT= +``` + +## Setup setup.py ## +In order to use setuptools with Android a few changes need to be done into your setup.py script. First you need to monkey patch setuptools, we provide with a helper script for this, edit your setup.py and add this lines **before** calling **setup** +``` +from py4a import patch_distutils +patch_distutils() +``` + +You also need to either pass **-p linux-armv** or create a file **setup.cfg** inside the same folder than setup.py with this content +``` +[bdist_egg] +plat-name=linux-armv +``` + +## Setup environment ## +If your project uses binary modules, the build process is a bit rougher, but still a lot of fun. Before calling build you need to import a shell script that will setup your environment to work, this script is called **setup.sh** and is part of the python-lib package. + +So supposing we're working on projectX, and our folder structure is this: +``` +python-lib +..........setup.sh +projectX +..........setup.py +..........setup.cfg +``` + +Then you would do from projectX. +``` +source ../python-lib/setup.sh +``` + +## Cooking your eggs ## +Ok so it's time to cook an egg. Once we have all the setup done it's time to boil the water and cook an egg. + +If everything is fine the process is simple just do the regular ` python setup.py bdist_egg `. If it doesn't work for you, then start looking at our other modules, and start asking questions in our mailing list, we don't bite. + + +## Stuff below this line is more or less obsolete ## +But may still be useful... + +# Non egg projects # +cd to the folder containing your module, and run: +``` +bash build.sh +``` + +There are now several modules built and supported by !Py4a. See [Modules](Modules.md). + +## How to Build your Own Modules ## +Currently, the best advice is to look at how pybluez was built, in python-modules/pybluez. + +At this time, we are working on a more comprehensive guide. + +### Rough Guide ### +If your module is pure python, then using it is as simple as copying the module into your phone. The best path for this is: +/sdcard/com.googlecode.pythonforandroid/extras/python + +If it contains C or C++ source code, it gets more complex. Currently we are using the Android NDK to manage module builds. This is easy to install, but requires a little setup to make it compile the needed .so files. + +In general, you need to: + * Copy the .c and .h files into a jni folder. + * Set up an android.mk to tell ndk-build what to do. + * set up a script to run ndk-build and then copy the needed python and .so files into a zip. + +See the source for pybluez for a simple example, and for twisted for something more complex. + +Documentation on the Android.mk can be found in the android-ndk docs folder. \ No newline at end of file diff --git a/BuildingPython.md b/BuildingPython.md new file mode 100644 index 00000000..dc8473ac --- /dev/null +++ b/BuildingPython.md @@ -0,0 +1,25 @@ +# Introduction # +How to build Python for Android. + + +# Details # +_For linux_ + +Download and install [Android NDK](http://developer.android.com/sdk/ndk/index.html). + +Grab the latest [Py4A Source](http://code.google.com/p/python-for-android/source/checkout). + +The build script needs to be able to find both _ndk-build_ and _arm-eabi-strip_. Here is an example of how to set your path: + +``` +export ANDROID_NDK=~/android-ndk-r5 +export PATH=$PATH:$ANDROID_NDK:$ANDROID_NDK/toolchains/arm-eabi-4.4.0/prebuilt/linux-x86 +``` + +Then, to actually build python: + +``` +bash build.sh +``` + +See: BuildingModules for how to build modules. \ No newline at end of file diff --git a/Contributions.md b/Contributions.md new file mode 100644 index 00000000..3cfd02bc --- /dev/null +++ b/Contributions.md @@ -0,0 +1,8 @@ +# Introduction # + +There have been side projects and example code made available from various contributors. + +## List ## + +Thomas Perl's port of Pyside: +http://thp.io/2011/pyside-android/ \ No newline at end of file diff --git a/CreatingAPKs.md b/CreatingAPKs.md new file mode 100644 index 00000000..9853fb54 --- /dev/null +++ b/CreatingAPKs.md @@ -0,0 +1,19 @@ +# Introduction # + +You can mostly follow the instructions in the SL4A Wiki: + +http://code.google.com/p/android-scripting/wiki/SharingScripts + +# Python-specific Tricks # + +This is based on the SL4A project template, and builds on the wiki page linked from above. + +## Adding pure Python modules as dependencies ## + +You can't put folders into /res/raw/, so you have to zip up all the pure Python modules that your script requires, and place the resulting .zip file into /res/raw/ (alongsite script.py). In script.py, you have to add the following snippet before you import any of the dependencies: + +``` +import sys +import os +sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'modules.zip')) +``` \ No newline at end of file diff --git a/CrossCompilingPython.md b/CrossCompilingPython.md new file mode 100644 index 00000000..813cff7b --- /dev/null +++ b/CrossCompilingPython.md @@ -0,0 +1,191 @@ +# Introduction # + +I've decided to annotate my experiences in porting Python3 to Android. + +# Details # + +Install the android toolchain: Toolchain\_Installation + +Make sure the bin directory of whereever you installed the toolchain is in you path. + +ie: +``` +export PATH=$PATH:~/android-toolchain/bin +``` + +NB: Platform-9 supports widechar a bit, Platform-8 doesn't. Be aware. + +It's probably a good idea to make sure the android platform tools are also in your path: + +``` +export PATH=$PATH:~/android-sdk-linux_86/platform-tools +``` + +Get the source code of the version of Python you need to port. + +The following the instructions here: +http://randomsplat.com/id5-cross-compiling-python-for-embedded-linux.html + +The target for Android is **arm-linux-androideabi** + +Now, Android does NOT support Locale properly, and the wcs/mbs routines are completely broken. +Therefore you need to remove any reference to them. +I manually modify pyconfig.h as follows: + +``` +#define ANDROID 1 /* Useful for specific code changes.*/ + +#define HAVE_BROKEN_MBSTOWCS 1 +#undef HAVE_DEV_PTMX +#undef HAVE_GETHOSTBYNAME_R +#undef HAVE_MBRTOWC +#define HAVE_NCURSES_H 1 /* This only if you've cross compiled curses */ +#undef HAVE_SETLOCALE +#undef HAVE_WCSCOLL +#undef HAVE_WCSFTIME +#undef HAVE_WCSXFRM +``` + +Here is my sample configure parameters: +``` +pushd ../thirdparty +export THIRD_PARTY_DIR=`pwd` +popd +export TARGET=arm-linux-androideabi + +CC=${TARGET}-gcc CXX=${TARGET}-g++ AR=${TARGET}-ar RANLIB=${TARGET}-ranlib ./configure --host=${TARGET} --build=x86_64-linux-gnu --prefix=/python --enable-shared +``` + +Note that this refers to a bunch of third party libraries I cross-compiled. +I've put these here in case you don't want to do them yourself: +http://code.google.com/p/python-for-android/downloads/detail?name=thirdparty.tar.gz + +## Setup Changes ## + +setup.py will probably need to be modified. The major changes have to do with making sure setup looks for include files and libraries in your cross-compiled libraries, and not your system defaults. +Mostly this has involved changes in `build_extension(self, ext)` and modifying `inc_dirs` and `lib_dirs`. Look in [setup.py](http://code.google.com/p/python-for-android/source/browse/python3-alpha/python3-src/setup.py), and look for `cross_compile`. + +Note: It's possible a lot of these changes to setup.py may have been rendered needless by correct use of LDFLAGS and CFLAGS (see readline example below). + +## Code Changes ## +Not all references to locale or mbs/wcs are handled with the configuration changes. Some of these have to be handled in code. +For example, Python3 assumes the existance of a working mbstowcs regardless. These not only don't work under Android, they _catastrophically_ don't work. + +I got around the problem thus: +In [pythonrun.c](http://code.google.com/p/python-for-android/source/browse/python3-alpha/python3-src/Python/pythonrun.c) I defined my own versions: + +``` +#ifdef ANDROID +size_t android_mbstowcs(wchar_t *dest, char * in, int maxlen) +{ + wchar_t *out = dest; + int size = 0; + if (in) + { + while(*in && size= 0xdc80 && c <= 0xdcff) + { + /* UTF-8b surrogate */ + c-=0xdc00; + } + if (dest) dest[i]=c; + } + return i; +} + +#endif + +``` + +This is a rough and ready conversion taken from elsewhere in the python 3 code base. Then, in any file where mbstowcs or wcstombs were referenced, I added this header: + +``` +#ifdef ANDROID +size_t android_wcstombs(char * dest, wchar_t *source, int maxlen); +size_t android_mbstowcs(wchar_t * dest, char *source, int maxlen); +#define wcstombs android_wcstombs +#define mbstowcs android_wcstombs +#endif +``` + +Note that this is not the only, or even best way to achieve the results, just the ones I used. + +The first time you compile, you will probably see references to things not being in the lconv structure. + +For the most part, the code will be to obtain structs like the decimal point,thousands seperator and grouping. + +The easiest way to get around these errors is to hardcode in some sensible default values, and to remove references to localeconv and lconv altogether. +``` +// struct lconv *locale_data = localeconv(); + locale_info->decimal_point = "."; + locale_info->thousands_sep = ","; + locale_info->grouping = "3"; +``` + +This should get you off the ground and pointing in the right directions. + +### Unsupported calls ### +These are calls that will compile, but are not actually provided on the android platfrom, so they will throw errors when to you try to load. The trick is to make sure that references to these functions are not compiled in. See `_termios.c` as an example (look for `#ifdef ANDROID`) + * tcdrain + * getgrp and setgrp + * times and chmod do NOT work under fuse file systems (and are almost irrelevant in any case) but the errors they throw will screw up most installation programs. posixmodule.c has been modified to silently fail instead, which allows pip and distribute to behave nicely. + +## Third Party Components ## +http://www.crosscompile.org contains a lot of useful hints and tips. +A lot of configure scripts fail to recognize **arm-linux-androideabi** as a host. This can be solved by replacing config.sub and config.guess from here: +http://git.savannah.gnu.org/gitweb/?p=config.git;a=tree + +or, indeed, here: + +http://code.google.com/p/python-for-android/source/browse/#hg%2Fpython3-alpha%2Fsqlite3 + + +Note: different configurations have sub and guess in different folders... you'll need to work out where. + +As my readline configure command is: +``` +export TARGET=arm-linux-androideabi +pushd ../thirdparty +TARGET_DIR=`pwd` +popd + +LDFLAGS=-L${TARGET_DIR}/lib CFLAGS="-I${TARGET_DIR}/include -I${TARGET_DIR}/include/ncurses" ./configure --host=$TARGET --target=$TARGET --prefix=$TARGET_DIR --enable-shared --with-curses +``` + +This is a pretty good starting point for most libraries. **readline** is one of the ones that require a little patching to work. The patch file is: + +``` +--- config.h 2012-03-27 15:10:24.000000000 +1100 ++++ /home/robbie/readline-6.2/config.h 2012-03-27 10:49:38.000000000 +1100 +@@ -15,6 +15,7 @@ + + #define VOID_SIGHANDLER 1 + ++#define ANDROID 1 + /* Characteristics of the compiler. */ + /* #undef sig_atomic_t */ +``` + +You will probably have to make these minor changes. Most of the time it will be commenting out references to unsupported library calls. + +## Changes to Python modules ## + * subprocess.py has a hardcoded call to `/bin/sh`, which breaks os.popen. This has been changed to `/system/bin/sh` for android. + * locale.py - changed preferred encoding to utf-8 \ No newline at end of file diff --git a/Examples.md b/Examples.md new file mode 100644 index 00000000..0ee5a661 --- /dev/null +++ b/Examples.md @@ -0,0 +1,28 @@ +# Examples and Snippets # + +This page shows some Py4A snippets and examples. + + +### Simple Example ### +``` +import android + +droid = android.Android() +droid.makeToast("Hello, Android!") + +print("Hello World!") +``` + +### Reading Phone State ### +eventWait() will block until an event occurs or an (optional) timeout (in ms) is exceeded. + +``` +import android + +droid = android.Android() +droid.startTrackingPhoneState() +try: + print(droid.eventWait(2000)) +finally: + droid.stopTrackingPhoneState() +``` \ No newline at end of file diff --git a/FullScreenWrapper.md b/FullScreenWrapper.md new file mode 100644 index 00000000..d9403406 --- /dev/null +++ b/FullScreenWrapper.md @@ -0,0 +1,29 @@ +

Pls. note that this has now been superseded by FullScreenWrapper2 Framework

+ +

Introduction

+ +With the latest updates to SL4A event facade functions that Robbie pushed over the last couple of days as the R5x18 release, I've put-together a wrapper class in Python to simplify event-oriented GUI programming using FullScreenUI - event loops and event handling etc.
+
+

Description

+While this still has some rough edges & not too much documentation written in, wanted to share the wrapper-class & a demo script to show what this is headed towards and also get the broader community's feed-back on approach, utility etc. First ALPHA version :-)
+
+To use the wrapper, you basically -
+
+
  1. Derive a class from the wrapper class which will hold your FullScreenUI view (not strictly necessary but much cleaner)
    +
  2. call the initialize() function to supply the xml layout and the "droid" instance
    +
  3. set-up the event handlers (buttons, keys, even your own events) by calling add_event_hander()
    +
  4. The wrapper class also generates some "pseudo-events" for "SHOW_EVENT", "HIDE_EVENT","CLOSE_EVENT", "UNHANDLED_EVENT", "CALL_EVERY_EVENTLOOP" and "EVENT_SNIFFER" (for debugging) that the derived class can connect to the same way by add_event_handler()
    +
  5. call the show() function to display the layout & start the event loop
    +
  6. if you need to programatically set properties, the wrapper class wraps some of the droid.fullSet*() functions as set_property_value(), get_property_value() etc
    +
  7. if you want to show a child window, approach is demonstrated in the function on_but_add_click() of main_screen class in the demo. I will eventually probably move this functionality into a show_child() function
    +
  8. for setting ListView contents you can call set_list_contents(). Some kind of gotcha in terms of not being able to change a list once it's bound to a view - however, creating a copy of the list works as demonstrated in on_show() function of main_screen class in the demo. will probably move this in to the set_list_contents() function
    +
  9. In a real-life execution, you can load the XML from a file or maybe even from the web(?)
+ +Would value feedback!
+
+Hariharan Srinath
+
+

Download

+full_screen_ui_wrapper.py + +full_screen_ui_wrapper_demo.py \ No newline at end of file diff --git a/HelperFiles.md b/HelperFiles.md new file mode 100644 index 00000000..6dcb909c --- /dev/null +++ b/HelperFiles.md @@ -0,0 +1,22 @@ +# Introduction # + +[androidhelper.py](http://code.google.com/p/python-for-android/downloads/detail?name=androidhelper.py) for simplifying Python-for-Android SL4A development in IDEs. This creates a "helper" class derived from the default Android class and defines SL4A [R5](https://code.google.com/p/python-for-android/source/detail?r=5) functions with API documentation in DocString & uses RPC calls derived from the base android.py. + +# Details # + +You can import this file into your scripts in your IDE to use Autocompletion, Documentation popups etc. + +To Use: replace the standard `import android` line with +``` +try: + import androidhelper as android +except: + import android +``` + +This will pull the helper class in if it is available, and fall through to the default android class if not. + +## Generating ## +To generate this file, I have written [createandroidhelper.py](http://code.google.com/p/python-for-android/downloads/detail?name=createandroidhelper.py). + +After some trial & error, I finally chose to use the HTML documentation contained at http://android-scripting.googlecode.com/hg/android/ScriptingLayerForAndroid/assets/sl4adoc.zip to generate androidhelper.py. Note that this currently has issues with 2 API functions which need manual corrections in androidhelper.py - both documented in the file comments. \ No newline at end of file diff --git a/Modules.md b/Modules.md new file mode 100644 index 00000000..aadad74a --- /dev/null +++ b/Modules.md @@ -0,0 +1,64 @@ +# Introduction # + +List of pre-built python modules. + +## PySerial ## +This module encapsulates the access for the serial port + +Home Page: http://pyserial.sourceforge.net/ + +Download: [pyserial-2.6-py2.6.egg](http://python-for-android.googlecode.com/files/pyserial-2.6-py2.6.egg) + +Egg contributed by Robin Gilham + +## PyBluez ## +A library for Bluetooth functionality. + +Home page: http://code.google.com/p/pybluez/ + +Download: [PyBluez-0.19-py2.6-linux-armv.egg](http://python-for-android.googlecode.com/files/PyBluez-0.19-py2.6-linux-armv.egg) + +## Twisted ## +An event-driven networking engine written in Python. + +Home page: http://twistedmatrix.com/trac/ + +Download: [Twisted-12.0.0-py2.7-linux-armv.egg](http://python-for-android.googlecode.com/files/Twisted-12.0.0-py2.7-linux-armv.egg) + +Required Zope interface (see below) + +## Zope ## +An interface to zope. + +Home page: http://www.zope.org/Products/ZopeInterface + +Download: [zope.interface-3.3.0-py2.7-linux-armv.egg](http://python-for-android.googlecode.com/files/zope.interface-3.3.0-py2.7-linux-armv.egg) + +Required by twisted. + +## pyEphem ## +PyEphem provides scientific-grade astronomical computations + +Home Page: http://rhodesmill.org/pyephem/ + +Download: http://python-for-android.googlecode.com/files/pyephem-3.7.4.1-py2.6-linux-armv.egg + +## pyCrypto ## +The Python Cryptography Toolkit + +Home page: https://www.dlitz.net/software/pycrypto/ + +[pycrypto-2.3-py2.7-linux-armv.egg](http://python-for-android.googlecode.com/files/pycrypto-2.3-py2.7-linux-armv.egg) + +There may be others we forgot to update. +Look here for more: [Module Downloads](http://code.google.com/p/python-for-android/downloads/list?q=Type-Module) + +# Requests we can't do yet # +Anything requiring Qt, Tk, or SDL is right out at present, because Android really doesn't support them. This includes PySide, PyQt, PyGtk and PyGames. And wxPython. + +Yes, there are ports in progress, but the important point is that sl4a (which py4a runs under) doesn't offer a mechanism to support these features. + +This is not to say they will **never** be supplied, but not in the short term, and each technology is significant sub-project in its own right. + +# How can I contribute my own Modules? # +Send link to the mailing list, and if it looks OK we'll add it. \ No newline at end of file diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 00000000..1dd76918 --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1,6 @@ +This is Python built to run on Android devices. It is made to be used together with SL4A (Scripting Layer For Android). +Nearly all the actual non-python specific documentation can be found at [android-scripting](http://code.google.com/p/android-scripting/) + +Feel free to use our [Python For Android Support and Discussion Group](http://groups.google.com/group/python-for-android) for any Python related questions. If your question is related to SL4A then do it at [SL4A Support and Discussion](http://groups.google.com/group/android-scripting). + +For Python specific issues and enhancements _only_, please use the issues tab. \ No newline at end of file diff --git a/Python3.md b/Python3.md new file mode 100644 index 00000000..7e25a98e --- /dev/null +++ b/Python3.md @@ -0,0 +1,103 @@ +# Introduction # + +This page is about the Python3 port to Android + + +# Details # + +I have started a conversion of Python3 for Android, tentatively codenamed Py3k4a. + +A Beta release of Python3.2.2 for Android is available here: + +http://code.google.com/p/python-for-android/downloads/detail?name=Python3ForAndroid_r6.apk + +## Instructions ## + +To use: + * You must have Android 2.3.1 or later. Earlier versions do not have even rudimentary wide character support, which Python3 uses extensively. + * Completely uninstall Py4a (Python 2.6.2) both with the Uninstall button in the Py4a app, and Settings-->Applications-->Manage Applications-->Python for Android-->Uninstall + * Install the Python3ForAndroid apk + * Open the Python3 for Android application, and hit the "Install" button. (It may say "Uninstall" when you first go in. Hit that button and it will quickly change to "Install".) + * You'll need web access to download the Python3 runtime environment. This may take a little while. + * As part of the download, it may ask to overwrite the sample scripts. Say "Yes to All", as the sample python2 scripts have been converted in Python3 syntax. + +#### Python Code Updates #### +As of Python3ForAndroid\_r5.apk, new versions of the Python binaries can +installed as they become available. +Check the Installed vs Available versions (displayed in the Installer screen). In the available is later than the installed, simply uninstall then reinstall. No need to re-install the apk. + +## State of Play ## +_As of 19-Apr-2012_ + +Python3 exists in an Beta release. All the basic modules that android can support have been included. + +All of the usual additional modules have been added (although new versions as might be expected) + +I have got sqlite3 importing, and also hashlib and ssl working with +the latest openssl libraries. + +readline is now implemented, allowing command line editing from within the interpreter. + +curses is implemented, allowing text-based screen control. + +bzip2 and ctypes are now included. + +The Python3 build module is in the python-for-android repository under 'python3-alpha'. This may have bloated the repository notably... oops. + +Build instructions: + * Install [android toolchain](Toolchain_Installation.md) + * Make sure the toolchain bin folder is in your path. + * from python3-alpha, run 'buildall.sh' + +### Things not working: ### + * egg handling (the install modules stuff is potentially working but untested) + +### Next steps: ### + + * Get the modules installation working for Python3. _first pass done_ + * Work out eggifying process for Python3 impure modules + * Tidy up installation process. (At the moment, it's all loaded from +the website. I'll look at embedded and manual install options) + * Go through the currently installed modules, trim if needed, convert +to pyc for speed. (NB: this is what we do with Py4a at present... is +it actually still desirable?) + +### What I need: ### + * General testing and feedback. Let me know what doesn't work, and what extra bits are desirable. + +## Running from the command line ## +This script will allow you to run Python3 from the command line: +[Standalone Script](http://code.google.com/p/python-for-android/source/browse/python3-alpha/python3-src/standalone.sh) + +I usually test by going: +``` +adb push standalone.sh /sdcard/standalone.sh +adb shell +sh /sdcard/standalone.sh +``` + +Note that the script takes arguments. + +The reason to put in on /sdcard is that should be writable on almost any device. + +## Importing Modules ## +As of apk [r6](https://code.google.com/p/python-for-android/source/detail?r=6) and version 9 of the install files, there is support for importing (pure python) modules using **pip** and **distribute** +This is still a little messy, but seems to basically work. + +How to use: + * Use latest python3forandroid\_r6.apk + * Install latest python versions (9,9,9) + * Run 'distribute\_setup.py' (included in scripts) (NB: This can take a while, and may pause on ''skipping ws\_comma' for quite a long time) + * Download https://raw.github.com/pypa/pip/master/contrib/get-pip.py into /sdcard/sl4a/scripts, and run it. + +Once installed, you can install packages from pypi etc as follows: +``` +import pip +pip.main(['install','pytz']) +``` + +(pytz is used as an example) + +Since pip is intended to be run from the command line, I've included at utility called 'pip\_console.py' which will emulate this behavior. + +I've added some notes on [Cross Compiling Python](CrossCompilingPython.md) \ No newline at end of file diff --git a/RunPythonFromShell.md b/RunPythonFromShell.md new file mode 100644 index 00000000..a90aac4a --- /dev/null +++ b/RunPythonFromShell.md @@ -0,0 +1,48 @@ +# Running Python from a shell # + +The necessary environment settings required to run python from a shell script can be found here: + +http://code.google.com/p/python-for-android/source/browse/python-build/standalone_python.sh + +To use, make the script executable and run from the shell: +``` +chmod a+x standalone_python.sh +./standalone_python.sh +``` + +or, if that doesn't work (and it may not, depending on filesystem) just: +``` +sh /sdcard/standalone_python.sh +``` + +The script at time of writing looks like this: +``` +#! /bin/sh + +export EXTERNAL_STORAGE=/mnt/storage +PYTHONPATH=/mnt/storage/com.googlecode.pythonforandroid/extras/python +PYTHONPATH=${PYTHONPATH}:/data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6/lib-dynload +export PYTHONPATH +export TEMP=/mnt/storage/com.googlecode.pythonforandroid/extras/python/tmp +export PYTHON_EGG_CACHE=$TEMP +export PYTHONHOME=/data/data/com.googlecode.pythonforandroid/files/python +export LD_LIBRARY_PATH=/data/data/com.googlecode.pythonforandroid/files/python/lib +/data/data/com.googlecode.pythonforandroid/files/python/bin/python "$@" +``` + +Note that you can pass arguments to python, ie: + +``` +./standalone_python.sh hello.Py +``` + +### Why is it so complicated? ### + +Android is quite fussy about what it lets you have access to. +Executables and shared libraries have to be on the main file system (typically /data/data somewhere) + +The only writable parts of /data/data are the ones allocated to your package (apk) (ie: /data/data/com.googlecode.pythonforandroid ) although you can use chmod to override this. + +Bulky items should live on the /sdcard, (not always an actual sdcard). Android allocates a package based spot to store this stuff (ie, /sdcard/com.googlecode.pythongorandroid/extras). For most android devices, space in the main fs is at a premium. Thus the extensive library files are places on the /sdcard. + +Python needs to be told where all these non-standard places are. (Thus, PYTHONHOME etc) \ No newline at end of file diff --git a/Toolchain_Installation.md b/Toolchain_Installation.md new file mode 100644 index 00000000..36f43def --- /dev/null +++ b/Toolchain_Installation.md @@ -0,0 +1,25 @@ +# Introduction # + +How to install a cross-compiler toolchain for Android. + + +# Details # + +Download the [NDK from Android](http://developer.android.com/sdk/ndk/index.html). + +Install. (typically would be in ~/android-ndk-[r5](https://code.google.com/p/python-for-android/source/detail?r=5) or similar) + + +``` +export ANDROID_NDK=~/android-ndk-r5 +export ANDROID_NDK_TOOLCHAIN_ROOT=~/android-toolchain +$ANDROID_NDK/build/tools/make-standalone-toolchain.sh --platform=android-9 --install-dir=$ANDROID_NDK_TOOLCHAIN_ROOT +``` + +_NB: The ~ does not expand to your home folder in --install-dir. That's why I've put it in a shell variable, which we're going to be using later anyway._ + +I picked the latest platform as an example, but anything reasonably sensible will do. + +You can find more detail by looking in $ANDROID\_NDK/docs/STANDALONE-TOOLCHAIN.html. (Why it's not available directly on the web, I have no idea) + +_I have only been able to get this working under Linux. In theory it ought to work for Windows with Cygwin installed, but so far it's not looking good._ \ No newline at end of file diff --git a/Versions.md b/Versions.md new file mode 100644 index 00000000..db461046 --- /dev/null +++ b/Versions.md @@ -0,0 +1,15 @@ +# PythonForAndroid\_r5 # + * Should cope with shared libraries in installed modules better, + * Will handle egg (and zip) files automatically. +# PythonForAndroid\_r4 # + * Fixed bug with module installer and empty files. +# PythonForAndroid\_r3 # + * Added egg support: Python modules can now be self contained into an egg file, so standard Python eggs can be installed easily. + * Added modules removal: Along with Robbie's great Module installer I came up with a rough but still work Egg uninstaller, now you can install an egg module, the system will take care on installing each piece on the right place (scripts into sdcard and binary into /data) and then you'll be able to uninstall them. + * Shows the latest available version for each piece: Now the main Python application (the one from where you install) let's you know which are the latest available versions for each of the needed parts by just going and ask our Google Code site. + * Added `_struct module` + * Improved binary module creation, now we provide with a system compatible with setuptools so egg files can be created by just calling python setup.py (after some slight patching of the setup.py script). See BuildingModules + * Added Py4A Logo, thanks to Robbie for working on this, I suck for that. + +This version is the first one signed with our official key, so you will +have to remove previous installations of Py4A. \ No newline at end of file diff --git a/fullscreenwrapper2.md b/fullscreenwrapper2.md new file mode 100644 index 00000000..e6389109 --- /dev/null +++ b/fullscreenwrapper2.md @@ -0,0 +1,160 @@ +# FullScreenWrapper2 Framework # +FullScreenWapper2 is a GUI Framework for developing full screen apps using the [FullScreenUI API](http://code.google.com/p/android-scripting/wiki/FullScreenUI) functions provided by SL4A in Python. This lets you design a look & feel similar to Android Java apps using the same XML Layouts and let you respond to View events. + +It is a significant (**non-backward compatible**) enhancement over [FullScreenWrapper](http://code.google.com/p/python-for-android/wiki/FullScreenWrapper) that attempts to make programming using FullScreenUI as simple as programming in standard GUI Frameworks. + +Update:**A working [Python3 compatible version](http://python-for-android.googlecode.com/hg/sl4atools/fullscreenwrapper2/py3/fullscreenwrapper2_py3.py) is now available - could do with more testing.** + +## Features ## + * An FullScreenWrapper2App class that manages the eventloop & a layout stack enabling easy parent->child->parent transitions + * EventHandler classes with event-matching functions pre-built for standard View events like **click**,**itemclick**(ListView) and **key** + * Device Sensors & other similar SL4A/Custom events can also be caught & managed using the same eventloop + EventHandler class + * Object like access to a layout's views and properties (ie. MainLayout.views.txt\_label.background = "#FFAA00AA") + +![http://python-for-android.googlecode.com/files/fullscreenwrapper2.png](http://python-for-android.googlecode.com/files/fullscreenwrapper2.png) + +## Demo Screenshots ## +![http://python-for-android.googlecode.com/files/fullscreenwrapper2_demo_screenshots.png](http://python-for-android.googlecode.com/files/fullscreenwrapper2_demo_screenshots.png) + +## Download ## +You can find [FullScreenWrapper2 files](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/) under the sl4atools directory in the Python for Android repository. + 1. **[fullscreenwrapper2.py](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/fullscreenwrapper2.py)** is the main file you need to import + 1. Update:**A working [Python3 compatible version](http://python-for-android.googlecode.com/hg/sl4atools/fullscreenwrapper2/py3/fullscreenwrapper2_py3.py) is now available - could do with more testing. + 1.**[API Docs](http://python-for-android.googlecode.com/hg/sl4atools/fullscreenwrapper2/docs.zip)**generated from docstrings are available + 1. The following FullScreenWrapper2 examples are available + ***[Simple Demo](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/examples/fullscreenwrapper2demo/fullscreenwrapper2demo.py)**to show basic usage of the Framework + ***[Gyroscope Sensor](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/examples/gyro_sl4a_test/gyro_sl4a_test.py)**tilting example to show how FullScreenWrapper2 EventHandler classes can be used to catch SL4A events & use them in your User Interface + ***[A Full App](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/examples/calcount2_example.zip)**(a calorie counter) that has parent & child layouts, resources & layouts being loaded from files, database access etc. + 1. A zip file with**[everything](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/fullscreenwrapper2_everything.zip)**is available** + +## How to Use Guide ## +#### 1. Import fullscreenwrapper2 & define your layout class #### +First place fullscreenwrapper2.py in the same folder as your script. You start by importing everything from fullscreenwrapper2 & inheriting a class for your own layout from the Layout class and calling **init** function of Layout using **super** keyword with the XML Layout (string) and the Screen Title (string). +``` +from fullscreenwrapper2 import * + +class DemoLayout(Layout): + def __init__(self): + super(DemoLayout,self).__init__(xmldata,"FullScreenWrapper Demo") +``` + +#### 2. Define **on\_show()** and **on\_close()** functions #### + +The **on\_show()** function is **very important** as your views become accessible through the FullScreenWrapper2 framework **ONLY AFTER** on\_show() is called by the framework. This is the place where you initialize / set the values of your views & setup event handlers. If you're having parent->child layouts, on\_show() is also called when a child layout closes & the parent layout comes back on. + +Views & their properties can be accessed via **Layout.views.view\_id.property**. In the example below, we're setting the background color - most simple properties should work without a hitch. + +Both the Layout & the individual Views can have events associated with them. You would typically use **click\_EventHandler** & **itemclick\_EventHandlers** (for ListView) with Views. The **init** for these take the View itself & an event handler function reference to call when the event occurs as parameters. + +You would typically associate **key\_EventHandler** with the layout itself. The **init** for key\_EventHandler takes a key\_match\_id (defaults to "4" which is the back key), a view (defaults to None) and an event handler function reference as parameters. + +``` + def on_show(self): + self.add_event(key_EventHandler(handler_function=self.close_app)) + self.views.but_change.add_event(click_EventHandler(self.views.but_change, self.change_color)) + self.views.but_exit.add_event(click_EventHandler(self.views.but_exit, self.close_app)) + self.views.txt_colorbox.background="#ffffffff" + +``` + +For Sensor events like Gyroscope, you can directly use the EventHandler class - just set + +You can access a view's properties Layout.views.view\_id.property + +``` + def on_show(self): + self.add_event(key_EventHandler(handler_function=self.close_app)) + self.views.but_change.add_event(click_EventHandler(self.views.but_change, self.change_color)) + self.views.but_exit.add_event(click_EventHandler(self.views.but_exit, self.close_app)) + self.views.txt_colorbox.background="#ffffffff" +``` + +The on\_close() is mainly allow you to save state before a layout dissappears if needed. You can have **pass** as the only statement. +``` + def on_close(self): + pass +``` + +The restriction of views becoming accessible only after the framework calls on\_show() of a layout is because of the the way FullScreenUI works. You need to show a layout first before you can access its views. FullScreenWrapper2 uses Android.fullGetProperty() to find out which views contain an "id" and are available for access and creates & populates View objects in each layout's views collection. These View objects let you associate events with them & allow you to access properties through SL4A reflection using setattr() and getattr(). Layouts handle their events through a special view added to the views collection. + +#### 3. Create your event handler functions & other functions #### +The event handler function definition signature should be as follows: +``` + def event_handler_function(self,view,event): +``` +Each event handler is passed a reference to the view with which the event is associated (can be None) & the SL4A event data obtained from Android.eventPoll().result[0](0.md). In the example below, every time a button on screen is pressed, the textbox changes to a random color background. +``` + def close_app(self,view,event): + FullScreenWrapper2App.exit_FullScreenWrapper2App() + + def change_color(self,view, event): + colorvalue = "#ff"+self.get_rand_hex_byte()+self.get_rand_hex_byte()+self.get_rand_hex_byte() + self.views.txt_colorbox.background=colorvalue + + def get_rand_hex_byte(self): + j = random.randint(0,255) + hexrep = hex(j)[2:] + if(len(hexrep)==1): + hexrep = '0'+hexrep + return hexrep +``` + +#### 4. Initialize FullScreenWrapper2, Show Layout & Execute eventloop #### +Once your layout class is setup, in your main function, initialize the framework first with Android.Android(). Then show the layout using **FullScreenWrapper2App.show\_layout()** and initiate the eventloop(). +``` +if __name__ == '__main__': + droid = android.Android() + random.seed() + FullScreenWrapper2App.initialize(droid) + FullScreenWrapper2App.show_layout(DemoLayout()) + FullScreenWrapper2App.eventloop() +``` + +#### 5. Putting it together #### +The full code from above example is shown here to show how simple it all is. The full source code **[including the XML Layout](http://code.google.com/p/python-for-android/source/browse/sl4atools/fullscreenwrapper2/examples/fullscreenwrapper2demo/fullscreenwrapper2demo.py)** is also availble. + +For simple XML layouts, you can just define layout in a string variable in your module. However, as your apps become more complex, you may want to load from sdcard files or even the internet. +``` +import android, random +from fullscreenwrapper2 import * + +class DemoLayout(Layout): + def __init__(self): + super(DemoLayout,self).__init__(xmldata,"FullScreenWrapper Demo") + + def on_show(self): + self.add_event(key_EventHandler(handler_function=self.close_app)) + self.views.but_change.add_event(click_EventHandler(self.views.but_change, self.change_color)) + self.views.but_exit.add_event(click_EventHandler(self.views.but_exit, self.close_app)) + self.views.txt_colorbox.background="#ffffffff" + + def on_close(self): + pass + + def close_app(self,view,event): + FullScreenWrapper2App.exit_FullScreenWrapper2App() + + def change_color(self,view, event): + colorvalue = "#ff"+self.get_rand_hex_byte()+self.get_rand_hex_byte()+self.get_rand_hex_byte() + self.views.txt_colorbox.background=colorvalue + + def get_rand_hex_byte(self): + j = random.randint(0,255) + hexrep = hex(j)[2:] + if(len(hexrep)==1): + hexrep = '0'+hexrep + return hexrep + +if __name__ == '__main__': + droid = android.Android() + random.seed() + FullScreenWrapper2App.initialize(droid) + FullScreenWrapper2App.show_layout(DemoLayout()) + FullScreenWrapper2App.eventloop() + +``` + +## License ## +This work is open source & licensed under a [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/deed.en_US). This is a very permissive license & you're pretty much free to use & modify any way you want (including commercial use) with attribution. + +[![](http://i.creativecommons.org/l/by/3.0/88x31.png)](http://creativecommons.org/licenses/by/3.0/deed.en_US) \ No newline at end of file