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 !

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 !

Texture compression, why does it matter ?

We all care about cash, time, life, love, and if you’re doing computer graphics, you might care about the memory consumption of your graphics card. Why ? For the same reason when you running out of cash :)

I’ll explain why does it matter to compress texture, and compare available possibilities. My personnal goal is to be able to load a lot of FULL HD pictures on tablet, for a museum project. The analysis is focused on DXT1 compression and size. I’m looking forward to ETC1 and will update that blog post with the result in the future.

What are we dealing with

If you are doing an application that display lot of hd pictures, that’s matter. We’ll start from this simple math statement: a full HD picture is 1980×1020 with 4 channels (RGBA). Whatever if your pictures is in PNG, or JPEG, your graphics card is not able to understand it, and will store it in its memory decompressed. So this image will eat:

1920 x 1080 x 4 = 8294400 bytes = 7.91MB
1920 x 1080 x 4 + mipmaps = 10769252 bytes = 10.27MB

In theory. Because it might be more if your graphics card doesn’t support NPOT texture. If not, usually, the texture will be resized to the closest POT texture available, mean for us: 2048 x 2048. Then the size for POT will be:

2048 x 2048 x 4 = 16777216 bytes = 16MB
2048 x 2048 x 4 + mipmaps = 22369620 bytes = 21MB

Compressions types

They are plenty types of compression availables. The most common are S3TC (including DXT1, DXT3, DXT5) from Savage3 originally, LATC from Nvidia, PVRTC from PowerVR, ETC1 from Ericsson…

Not all of them are available everywhere, and it’s depending a lot from your hardware. Here is a list of tablet / vendor / texture compression available. (only tablet, not desktop computer.) Thanks to this stackoverflow thread about supported OpenGL ES 2.0 extensions on Android devices

Tablette Vendor DXT1 S3TC LATC PVRTC ETC1 3DC ATC
(desktop computer) GeForce GTX 560 NVIDIA X X X
Motorola Xoom NVIDIA X X X X
Nexus One Qualcom X X X
Toshiba Folio NVIDIA X X X X
LGE Tablet NVIDIA X X X X
Galaxy Tab PowerVR X X
Acer Stream Qualcomm X X X
Desire Z Qualcomm X X X
Spica Samsumg X X
HTC Desire Qualcomm X X X
VegaTab NVIDIA X X X X
Nexus S PowerVR X X
HTC Desire HD Qualcomm X X X
HTC Legend Qualcomm X X X
Samsung Corby Qualcomm X X X
Droid 2 PowerVR X X
Galaxy S PowerVR X X
Milestone PowerVR X X

We are seeing that ETC1 is standard compression for OpenGL ES 2, unfortunately, it will not work on desktop.
PVRTC is specific to PowerVR device: it’s a standard on Ipad/Iphone.

Using DXT1

If you use DXT1, you need a POT image. DXT1 doesn’t work on NPOT.

To convert any image to DXT1 without any tool, you must know that your graphics card is capable of doing it, using specials opengl functions. But i wanted to precalculate them.
Nvidia texture tools contains tools for converting them, but you need an Nvidia card. For all others, you might want to look at Libsquish. It’s designed to compress in software a raw image to DXTn.
The result will be not a DXT1 “file”, because DXT1 is the compression format. The result will be stored in a DDS file, that we’ll see later about it.

If you want to be able to use libssquish in Python, you might want to apply my patch available on their issue tracker

For DXT1, the size of the file is not depending of the image content:

DXT1 2048x2048 RGBA = 2097152 bytes = 2MB

That’s already a big improvement. DXTn is able to store mipmaps of the texture too. For this size, the calculation is:

DXT1 2048x2048 RGBA + mipmap = 2795520 bytes = 2.73MB

Comparaison table

Type Resolution File size GPU size Images in a 256MB GPU Images in a 512MB GPU
Raw RGBA image (POT) 2048 x 2048 - 16384KB 16 32
PNG image (NPOT) 1920 x 1080 4373KB 8040KB 32 65
PNG Image in reduced POT resolution 1024 x 1024 1268KB 4096KB 64 128
DXT1 without mipmap 2048 x 2048 2048KB 2048KB 128 256
DXT1 without mipmap, reduced 1024 x 1024 512KB 512KB 512 1024
DXT1 with mipmap 2048 x 2048 2730KB 2730KB 96 192
DXT1 with mipmap, reduced 1024 x 1024 682KB 682KB 384 768

As soon as we use compression, what we see is:

  1. The file size is the same as GPU size
  2. Even with POT texture compared to NPOT dxt1, we can still store 4x more images in GPU

And with Kivy ?

DXT1 itself is the compression format, but you cannot actually use it like that. You need to store the result is a formatted file. DDS.

Kivy is already able to read DDS files. But you must ensure that your graphics card is supporting DXT1 or S3TC. Look at gl_has_capability() function in Kivy then.