Kivy Programming Contest 2014

Kivy is organizing its second application development contest!. This is a great chance for users both new and experienced to show off their skills and compete for prizes. Entries will be judged on a range of criteria accessible to both new and experienced programmers, so don’t be afraid to dive in!

poster_1

A big big thanks to the Python Software Foundation for being our first and lovely sponsor :)

Kivy Programming Contest 2014

Kivy is organizing its second application development contest!. This is a great chance for users both new and experienced to show off their skills and compete for prizes. Entries will be judged on a range of criteria accessible to both new and experienced programmers, so don’t be afraid to dive in!

poster_1

A big big thanks to the Python Software Foundation for being our first and lovely sponsor 🙂

2048, in Python / Kivy

If you don’t know the 2048 puzzle yet, you should. But be careful, it’s time consuming. I won’t go on the whole clone history of the game, but will just say that if you want to play it on the Web, play to the Gabriel Cirulli 2048. The author said it wont make an official iOS/Android app, so… let’s give Kivy a try :)

device-2014-03-15-114048

Only 2 hours of coding where needed for the first published version of the game. Then i learned on the Google Play Game services APIs for integrating a leaderboard and achievements. And after a couple of hours during the night, what i can say is: Be patient! Even if you follow the documentation carefully, you need to wait few hours before your app_id works on their server, even in test mode. There never warn us about it.

When the setup is done and it start working, it is easy to login:

PythonActivity = autoclass('org.renpy.android.PythonActivity')
    GameHelper = autoclass('com.google.example.games.basegameutils.GameHelper')

    gh_instance = GameHelper(PythonActivity.mActivity, GameHelper.CLIENT_ALL)
    gh_instance_listener = GameHelperListener()
    gh_instance.setup(gh_instance_listener)
    gh_instance.onStart(PythonActivity.mActivity)
    android.activity.unbind(on_activity_result=_on_activity_result)
    android.activity.bind(on_activity_result=_on_activity_result)

That’s how you can unlock achievement:

# uid is the Google UID for the achievement you want
if gh_instance.isSignedIn():
    Games.Achievements.unlock(gh_instance.getApiClient(), uid)

And put the user score on the leaderboard:

# uid is the Google UID for the leaderboard you've created.
# You can have multiple leaderboard.
if gh_instance.isSignedIn():
    Games.Leaderboards.submitScore(gh_instance.getApiClient(), uid, score)

There is a little more code around that, but globally, using the new Play Games services APIs is now easy. I hope this little piece of code will help peoples to integrate it into their app. Somebody need to start a Python library for managing Google Play API and Game Center for iOS.

Have a look at the source code for an example of the integration with the Play Games services APIs :)


Get it on Google Play

2048, in Python / Kivy

If you don’t know the 2048 puzzle yet, you should. But be careful, it’s time consuming. I won’t go on the whole clone history of the game, but will just say that if you want to play it on the Web, play to the Gabriel Cirulli 2048. The author said it wont make an official iOS/Android app, so… let’s give Kivy a try 🙂

device-2014-03-15-114048

Only 2 hours of coding where needed for the first published version of the game. Then i learned on the Google Play Game services APIs for integrating a leaderboard and achievements. And after a couple of hours during the night, what i can say is: Be patient! Even if you follow the documentation carefully, you need to wait few hours before your app_id works on their server, even in test mode. There never warn us about it.

When the setup is done and it start working, it is easy to login:

    PythonActivity = autoclass('org.renpy.android.PythonActivity')
    GameHelper = autoclass('com.google.example.games.basegameutils.GameHelper')

    gh_instance = GameHelper(PythonActivity.mActivity, GameHelper.CLIENT_ALL)
    gh_instance_listener = GameHelperListener()
    gh_instance.setup(gh_instance_listener)
    gh_instance.onStart(PythonActivity.mActivity)
    android.activity.unbind(on_activity_result=_on_activity_result)
    android.activity.bind(on_activity_result=_on_activity_result)

That’s how you can unlock achievement:

# uid is the Google UID for the achievement you want
if gh_instance.isSignedIn():
    Games.Achievements.unlock(gh_instance.getApiClient(), uid)

And put the user score on the leaderboard:

# uid is the Google UID for the leaderboard you've created.
# You can have multiple leaderboard.
if gh_instance.isSignedIn():
    Games.Leaderboards.submitScore(gh_instance.getApiClient(), uid, score)

There is a little more code around that, but globally, using the new Play Games services APIs is now easy. I hope this little piece of code will help peoples to integrate it into their app. Somebody need to start a Python library for managing Google Play API and Game Center for iOS.

Have a look at the source code for an example of the integration with the Play Games services APIs 🙂


Get it on Google Play

Using Facebook SDK with Python-for-Android / Kivy

For another museum project, Arnaud asked me to see if we could integrate Facebook in an app on Android. The usual libraries are made for desktop, and manually open a webbrowser to handle the user authorization. But that’s not really nice for us, it would be nicer to have a native integration instead. Let’s see how we can use the official Facebook Android SDK.

Prerequisites

You’ll need to have:
– Kivy’s python-for-android
– A Facebook account (obviously)
Facebook SDK 3.0

Get the example

Clone the Kivy/Facebook example:

$ git clone https://github.com/tito/p4a-facebook-example

Register a Facebook application

  1. Go to the Facebook developers interface
  2. Click on SĂ©lection_107
  3. Fill the information “App Name”. Don’t put “FB” or “Facebook” in the title, or your application name will be considered as Invalid 🙂
    SĂ©lection_108
  4. Pass the captcha
  5. Write down your application id somewhereSĂ©lection_111
  6. Now, you need to activate Native Android App. The package name is the same name as the one we will pass in --package when building the APK. The Class Name is the packagename/activity. Activity class is always the same for all the applications compiled with python-for-android.
    SĂ©lection_109
  7. Right now, the Facebook Android SDK will not authorize our android application to be used, because Facebook want to know the signature hash that will be used by our generated APK. To generate the key hashes, you need to use the keytool. Here is an example for the android “debug” key:
    $ keytool -exportcert -alias androiddebugkey \    -keystore ~/.android/debug.keystore | \    openssl sha1 -binary | openssl base64 Enter keystore password:  android u+bzQmG87L298C4KGM8yODi3W/4=

    Copy the generated key hash, and paste it to the field:

    SĂ©lection_110
  8. Setup the our application
  1. Go into p4a-facebook-example, and edit the main.py
  2. Search for FACEBOOK_APP_ID, and replace with your own Application Id
  3. Go into python-for-android, and create a distribution:
    $ ./distribute.sh -m 'kivy'
  4. Go into the dist/default
  5. Generate the APK one time (for generating all the file we need to customize). Replace /path/to/p4a-facebook-example:
    ./build.py --name "Facebook test" --package org.test.facebook \
      --version 1 --private /path/to/p4a-facebook-example/ \
      --window --permission INTERNET debug
  6. Add a new reference to project.properties to include the Facebook SDK. The path to the Facebook SDK MUST be a relative path, otherwise you’ll get issues during the next build.
    android.library.reference.1=../../facebook-android-sdk-3.0.2/facebook
  7. Edit the templates/AndroidManifest.tmpl.xml to include the Facebook login activity, just under the <application>:
     
  8. Rebuild your application… and you’re ready to test 🙂
  9. Install the application on your device:
    adb install -r bin/Facebooktest-1-debug.apk

Test your application

The Facebook SDK 3.0 require to separate read and publish permissions. To the user, it means you’ll have 2 dialog to accept. Even if you just want to publish to the application stream, you need to have the basic permission (read) accepted by the user before publish permissions. This is already implemented in the example app.

When you start the application the first time, you’ll have:

device-2013-08-08-110647

Depending if you have the Native Facebook application or not, you’ll have 2 kinds of authentification boxes.

device-2013-08-08-110834

Without Facebook installed on the device:

And with Facebook installed on the device:

device-2013-08-08-111002

After authentication, the user will need to accept our permissions:

device-2013-08-08-111111

It’s done!

The application have now the right to post 🙂 The example post in the user stream as the application itself, not as the user. It’s called “publish_actions”.

Getting further

Obviously, when you use the Facebook SDK itself, you feel the pain of an API designed for Java. For every callback that Facebook want to call, you need to implement a Java class and define the callback method. Python is really simpler and fun to use.

See for yourself: we want to make a call of “Request.newStatusUpdateRequest“. Se weed first to implement a GraphUserCallback class, in Java. Thanks to Pyjnius, we can do it directly in Python:

Python
class _FacebookGraphUserCallback(PythonJavaClass):

    __javainterfaces__ = ['com.facebook.Request$GraphUserCallback']
    __javacontext__ = 'app'

    def __init__(self, callback):
        self.callback = callback
        super(_FacebookGraphUserCallback, self).__init__()

    @java_method('(Lcom/facebook/model/GraphUser;Lcom/facebook/Response;)V')
    def onCompleted(self, user, response):
        self.callback(user, response)

This Python/Java class will call our own python callback when the Java callback onCompleted will be called. Then:

Python
@run_on_ui_thread
def post(self, text, callback):
    req = Request.newStatusUpdateRequest(
            self._session, text, _FacebookRequestCallback(callback))
    req.executeAsync()

All you have to do at the end, is to call the post method:

Python
def fb_post(self, text):
    def callback(*args):
        from time import time
        self.post_status = 'message posted at {}'.format(time())
    self.facebook.post(text, callback=callback)

I don’t provide a wrapper around all the possible Request method you can do with Facebook. I just have an example for “post” and “me”. Both wrap “Request.newStatusUpdateRequest” and “Request.newMeRequest“. Please note that every request call must happen in the UI thread. Use the python-for-android/runnable module for that, with @run_on_ui_thread decorator.

The end

It was not easy to get it right, and it still complex to make all the pieces together. I’ve tried to use their own LoginButton (because they said that’s how they want it, everywhere), but i’ve not be able to use it in our app. Mostly because the LoginButton is a pure android widget, and because it doesn’t want to bring back the Activity after login. I was stuck too much time on it, and preferred to go in another way.
Please note that you should not share an application with a fake Facebook button, the design / look-and-feel must be the same as the original one.

I hope that will help some of you to get started !

Using Facebook SDK with Python-for-Android / Kivy

For another museum project, Arnaud asked me to see if we could integrate Facebook in an app on Android. The usual libraries are made for desktop, and manually open a webbrowser to handle the user authorization. But that’s not really nice for us, it would be nicer to have a native integration instead. Let’s see how we can use the official Facebook Android SDK.

Prerequisites

You’ll need to have:
– Kivy’s python-for-android
– A Facebook account (obviously)
Facebook SDK 3.0

Get the example

Clone the Kivy/Facebook example:

$ git clone https://github.com/tito/p4a-facebook-example

Register a Facebook application

  1. Go to the Facebook developers interface
  2. Click on SĂ©lection_107
  3. Fill the information “App Name”. Don’t put “FB” or “Facebook” in the title, or your application name will be considered as Invalid :)
    SĂ©lection_108
  4. Pass the captcha
  5. Write down your application id somewhereSĂ©lection_111
  6. Now, you need to activate Native Android App. The package name is the same name as the one we will pass in --package when building the APK. The Class Name is the packagename/activity. Activity class is always the same for all the applications compiled with python-for-android.
    SĂ©lection_109
  7. Right now, the Facebook Android SDK will not authorize our android application to be used, because Facebook want to know the signature hash that will be used by our generated APK. To generate the key hashes, you need to use the keytool. Here is an example for the android “debug” key:
    $ keytool -exportcert -alias androiddebugkey \
       -keystore ~/.android/debug.keystore | \
       openssl sha1 -binary | openssl base64
    Enter keystore password:  android
    u+bzQmG87L298C4KGM8yODi3W/4=

    Copy the generated key hash, and paste it to the field:

    SĂ©lection_110

Setup the our application

  1. Go into p4a-facebook-example, and edit the main.py
  2. Search for FACEBOOK_APP_ID, and replace with your own Application Id
  3. Go into python-for-android, and create a distribution:

    $ ./distribute.sh -m 'kivy'

  4. Go into the dist/default
  5. Generate the APK one time (for generating all the file we need to customize). Replace /path/to/p4a-facebook-example:

    ./build.py --name "Facebook test" --package org.test.facebook \
      --version 1 --private /path/to/p4a-facebook-example/ \
      --window --permission INTERNET debug

  6. Add a new reference to project.properties to include the Facebook SDK. The path to the Facebook SDK MUST be a relative path, otherwise you’ll get issues during the next build.

    android.library.reference.1=../../facebook-android-sdk-3.0.2/facebook

  7. Edit the templates/AndroidManifest.tmpl.xml to include the Facebook login activity, just under the <application>:

    <application android:label="@string/appName" android:icon="@drawable/icon">
    <activity android:name="com.facebook.LoginActivity"/>

  8. Rebuild your application… and you’re ready to test :)
  9. Install the application on your device:

    adb install -r bin/Facebooktest-1-debug.apk

Test your application

The Facebook SDK 3.0 require to separate read and publish permissions. To the user, it means you’ll have 2 dialog to accept. Even if you just want to publish to the application stream, you need to have the basic permission (read) accepted by the user before publish permissions. This is already implemented in the example app.

When you start the application the first time, you’ll have:

device-2013-08-08-110647

Depending if you have the Native Facebook application or not, you’ll have 2 kinds of authentification boxes.

Without Facebook installed on the device:
device-2013-08-08-110834

And with Facebook installed on the device:

device-2013-08-08-111002

After authentication, the user will need to accept our permissions:

device-2013-08-08-111111

It’s done!

The application have now the right to post :) The example post in the user stream as the application itself, not as the user. It’s called “publish_actions”.

Getting further

Obviously, when you use the Facebook SDK itself, you feel the pain of an API designed for Java. For every callback that Facebook want to call, you need to implement a Java class and define the callback method. Python is really simpler and fun to use.

See for yourself: we want to make a call of “Request.newStatusUpdateRequest“. Se weed first to implement a GraphUserCallback class, in Java. Thanks to Pyjnius, we can do it directly in Python:

class _FacebookGraphUserCallback(PythonJavaClass):

    __javainterfaces__ = ['com.facebook.Request$GraphUserCallback']
    __javacontext__ = 'app'

    def __init__(self, callback):
        self.callback = callback
        super(_FacebookGraphUserCallback, self).__init__()

    @java_method('(Lcom/facebook/model/GraphUser;Lcom/facebook/Response;)V')
    def onCompleted(self, user, response):
        self.callback(user, response)

This Python/Java class will call our own python callback when the Java callback onCompleted will be called. Then:

@run_on_ui_thread
    def post(self, text, callback):
        req = Request.newStatusUpdateRequest(
                self._session, text, _FacebookRequestCallback(callback))
        req.executeAsync()

All you have to do at the end, is to call the post method:

def fb_post(self, text):
        def callback(*args):
            from time import time
            self.post_status = 'message posted at {}'.format(time())
        self.facebook.post(text, callback=callback)

I don’t provide a wrapper around all the possible Request method you can do with Facebook. I just have an example for “post” and “me”. Both wrap “Request.newStatusUpdateRequest” and “Request.newMeRequest“. Please note that every request call must happen in the UI thread. Use the python-for-android/runnable module for that, with @run_on_ui_thread decorator.

The end

It was not easy to get it right, and it still complex to make all the pieces together. I’ve tried to use their own LoginButton (because they said that’s how they want it, everywhere), but i’ve not be able to use it in our app. Mostly because the LoginButton is a pure android widget, and because it doesn’t want to bring back the Activity after login. I was stuck too much time on it, and preferred to go in another way.
Please note that you should not share an application with a fake Facebook button, the design / look-and-feel must be the same as the original one.

I hope that will help some of you to get started !

Crowdfunding Kivy on Raspberry Pi

Kivy doesn’t run yet on the Raspberry Pi, and we need your help to crowdfund it!
Even is Kivy is built to be compatible for GLES 2.0, we lack of a python EGL support.

The plan is to add a new EGL Window provider, in addition to the detection of non-multitouch devices such as keyboard and mouse.

All the informations are available at: https://www.bountysource.com/#fundraisers/143-kivy-on-raspberry-pi

Crowdfunding Kivy on Raspberry Pi

Kivy doesn’t run yet on the Raspberry Pi, and we need your help to crowdfund it!
Even is Kivy is built to be compatible for GLES 2.0, we lack of a python EGL support.

The plan is to add a new EGL Window provider, in addition to the detection of non-multitouch devices such as keyboard and mouse.

All the informations are available at: https://www.bountysource.com/#fundraisers/143-kivy-on-raspberry-pi

Pyjnius: Accessing Java classes from Python

We’re pleased to announce the Pyjnius project. It’s a Python library to access Java classes from Python, on the desktop or on Android.

We found others libraries such as JPype or Py4j, but we weren’t happy with the design and the usability. Using Jython wasn’t an option either, because we wanted to use the library within our python for android project.

Let me show you how simple it is to use Pyjnius:

>>> from jnius import autoclass
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> stack.pop()
'world'
>>> stack.pop()
'hello'

What we demonstrate here is the autoclass function that create kind-of proxy that reflect all the methods and fields available from the Java class java.util.Stack.

Ok, maybe you want an Android-related example? Just have a look:

from jnius import autoclass
from time import sleep

MediaRecorder = autoclass('android.media.MediaRecorder')
AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')

# Record the Microphone with a 3GP recorder
mRecorder = MediaRecorder()
mRecorder.setAudioSource(AudioSource.MIC)
mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
mRecorder.setOutputFile('/sdcard/testrecorder.3gp')
mRecorder.setAudioEncoder(AudioEncoder.ARM_NB)
mRecorder.prepare()

# Record 5 seconds
mRecorder.start()
sleep(5)
mRecorder.stop()
mRecorder.release()

More examples are available in the documentation. We have a mapping between Java/Python type, native arrays, support for methods with multiple signatures, and a lot more. We are using Cython + JNI internally. The performance cost is minimal.

The library is already available for Python for android.

The library have been done by Gabriel Pettier and myself, under the Kivy organization.

Pyjnius: Accessing Java classes from Python

We’re pleased to announce the Pyjnius project. It’s a Python library to access Java classes from Python, on the desktop or on Android.

We found others libraries such as JPype or Py4j, but we weren’t happy with the design and the usability. Using Jython wasn’t an option either, because we wanted to use the library within our python for android project.

Let me show you how simple it is to use Pyjnius:

>>> from jnius import autoclass
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> stack.pop()
'world'
>>> stack.pop()
'hello'

What we demonstrate here is the autoclass function that create kind-of proxy that reflect all the methods and fields available from the Java class java.util.Stack.

Ok, maybe you want an Android-related example? Just have a look:

from jnius import autoclass
from time import sleep

MediaRecorder = autoclass('android.media.MediaRecorder')
AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')

# Record the Microphone with a 3GP recorder
mRecorder = MediaRecorder()
mRecorder.setAudioSource(AudioSource.MIC)
mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
mRecorder.setOutputFile('/sdcard/testrecorder.3gp')
mRecorder.setAudioEncoder(AudioEncoder.ARM_NB)
mRecorder.prepare()

# Record 5 seconds
mRecorder.start()
sleep(5)
mRecorder.stop()
mRecorder.release()

More examples are available in the documentation. We have a mapping between Java/Python type, native arrays, support for methods with multiple signatures, and a lot more. We are using Cython + JNI internally. The performance cost is minimal.

The library is already available for Python for android.

The library have been done by Gabriel Pettier and myself, under the Kivy organization.