Kivy

25 Notes
+ Create a package for IOS (Nov. 4, 2015, 4:36 a.m.)

http://kivy.org/docs/guide/packaging-ios.html sudo apt-get install autoconf automake libtool pkg-config

+ PyCharm Completion (March 19, 2015, 7:55 a.m.)

https://github.com/kivy/kivy/wiki/Setting-Up-Kivy-with-various-popular-IDE%27s --------------------------------------------------------------------------------------------- 1-Download this jar plugin: https://github.com/Zen-CODE/kivybits/blob/master/IDE/PyCharm_kv_completion.jar?raw=true 2-On Pycharm’s main menu, click "File" -> Import Settings 3-Select this file and PyCharm will present a dialog with filetypes ticked. Click OK. 4-You are done. Restart PyCharm

+ Android API (Feb. 12, 2015, 8:24 p.m.)

http://developer.android.com/reference/android/speech/tts/TextToSpeech.html I have this class in Java docs: android.speech.tts.TextToSpeech And in python it is: TextToSpeech = autoclass('android.speech.tts.TextToSpeech') Baed on these, I thought for getting another class in Java (android.speech.tts.TextToSpeech.Engine) I had to: Engine = autoclass('android.speech.tts.TextToSpeech.Engine') But I got this error at runtime on my cellphone and the app would not open: java.lang.ClassNotFoundException: android.speech.tts.TextToSpeech.Engine I even could not access `Engine` using the pythonic way either: TextToSpeech.Engine I had to access the class by: TextToSpeech = autoclass('android.speech.tts.TextToSpeech$Engine') -------------------------------------------------------------------------------------------- Python Dictionaries = Java HashMap: Java: HashMap<String, String> phoneBook = new HashMap<String, String>(); phoneBook.put("Mike", "555-1111"); phoneBook.put("Lucy", "555-2222"); phoneBook.put("Jack", "555-3333"); Python: phoneBook = {} phoneBook = {"Mike":"555-1111", "Lucy":"555-2222", "Jack":"555-3333"} And for implementing it Kivy: HashMap = autoclass('java.util.HashMap') hash_map = HashMap() hash_map.put(key, value) --------------------------------------------------------------------------------------------- To access nested classes, use $ like: autoclass('android.provider.MediaStore$Images$Media'). ---------------------------------------------------------------------------------------------

+ Sign apk files (Oct. 4, 2015, 11:12 a.m.)

https://developer.android.com/tools/publishing/app-signing.html#studio 1-Generate a private key using keytool. For example: $ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000 This example prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore. The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app. 2-Compile your app in release mode to obtain an unsigned APK: buildozer android release 3-Sign your app with your private key using jarsigner: jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name This example prompts you for passwords for the keystore and key. It then modifies the APK in-place to sign it. Note that you can sign an APK multiple times with different keys. 4-Verify that your APK is signed. For example: jarsigner -verify -verbose -certs my_application.apk 5-Align the final APK package using zipalign. The zipalign does not exist in Synaptic Package Manager, it exists in AndroidSD Build Tools. Use locate to find `zipalign` and create a symbolic link in /usr/bin: ln -s /home/moh3en/Programs/Android/Development/android-sdk-linux/build-tools/android-5.0/zipalign /usr/bin/ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk --------------------------------------------------------------------------------------------- Example: buildozer android release jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore excludes/my-release-key.keystore bin/NimkatOnline-1.2.4-release-unsigned.apk mohsen_hassani jarsigner -verify -verbose -certs bin/NimkatOnline-1.2.4-release-unsigned.apk zipalign -v 4 bin/NimkatOnline-1.2.4-release-unsigned.apk bin/NimkatOnline-1.2.4.apk

+ Label (Feb. 12, 2015, 8:22 p.m.)

When creating a label, by default, it places at the bottom left corner with some part of it hidden, but by changing its `size` property it will be solved: size: self.texture_size Scrolling a Label: Label: text: str('A very long text' * 100) font_size: 50 text_size: self.width, None size_hint_y: None height: self.texture.size[1]

+ FloatLayout (Feb. 12, 2015, 8:21 p.m.)

Similar to RelativeLayout, except now position is relative to window, and not Layout. Thus in FloatLayout, pos = 0, 0 refers to lower-left corner.

+ RelativeLayout (Feb. 12, 2015, 8:21 p.m.)

Each child widget size and position has to be give. size_hint, pos_hint: numbers relative to Layout. If those two parameters are used, it does not make any difference if RelativeLayout or FloatLayout are used, as both will yield the same result.

+ GridLayout (Feb. 12, 2015, 8:21 p.m.)

Similar to StackLayout 'lr-tb' Either cols or rows has to be given and the Layout adjusts so the given number is the maximum number of cols or rows.

+ Canvas (Feb. 12, 2015, 8:21 p.m.)

Canvas refers to graphical instructions. The instructions could be non-visual, called context instructions, or visual, called vertex instructions. An example of a non-visual instruction would be to set a color. An example of a visual instruction would be draw a rectangle.

+ StackLayout (Feb. 12, 2015, 8:20 p.m.)

1-More flexible than BoxLayout 2-Orientations: right to left or left to right top to bottom or bottom to top rl-bt, rl-tb, lr-bt, lr-tb (Row-wise) bt-rl, bt-lr, tb-rl, tb-lr (Column-wise)

+ Snippets (Feb. 12, 2015, 8:20 p.m.)

pos_hint: {'x': .1} size_hint: [.2, 2] pos_hint: {'center_x': .3} ---------------------------------------------------------------------------------------------- textinput.bind(text=label.setter('text')) ---------------------------------------------------------------------------------------------- in kv file: TextInput: on_text: my_label.color = [random.random() for i in xrange(3)] + [1] ---------------------------------------------------------------------------------------------- center: self.parent.center ----------------------------------------------------------------------------------------------

+ on_touch_up vs on_release (Feb. 12, 2015, 8:19 p.m.)

When using on_touch_up event with partial, you have to pass three arguments to the calling method: Example: button.ids.speaker_button.bind(on_touch_up=partial(self.speak_word, main_word)) @staticmethod def speak_word(word, arg1, arg2): # I don't know yet what these two extra args are used for. print(word) After touching the button, all the same buttons on the page are also triggered. You have to solve it using something like this: on_touch_up: vibrate() if self.collide_point(*args[1].pos) else None ****** But using on_release, two args are passed: button.ids.speaker_button.bind(on_touch_up=partial(self.speak_word, main_word)) @staticmethod def speak_word(word, button): print(word) After clicking, the only button which has been touched, will be triggered. That's good!

+ Partial (Feb. 12, 2015, 8:19 p.m.)

In Kivy, you register a button release callback with the “bind()” function: myButton.bind(on_release=my_button_release) But the signature of the “on_release” method is “on_release(self)”, which means that the method you provide will receive only one parameter — the button that generated the event. When you release the button, Kivy will invoke your callback method and pass in the button that you released. So does this mean we can’t pass user-defined parameters to our handlers? Does it mean we need to use globals or a bunch of specialized methods to write our button handlers? No, this is where Python’s functools.partial comes in handy. To oversimplify, partial allows you to create a function with one set of arguments that calls another function with a different set of arguments. For example, consider the following function that takes two arguments: def addTwoNumbers(x, y): print "x: %d, y: %d" % (x, y) return x+y You can create a partial from this that automatically supplies one or more of the arguments. Let’s create one that supplies ’1′ for ‘x’: addOne = partial(addTwoNumbers, 1) Which you would then invoke as such: >>> #We pass in '2' for 'y' here. The partial fills in '1' for 'x' ... >>> addOne(2) x: 1, y: 2 3 ***************** Let’s create a function that can set any label to any text: def changeLabel(label, text, button): #Kivy gives us 'button' to let us know which button # caused the event, but we don't use it label.text = text In our UI setup, we can then bind two different buttons to this handler, creating partials that supply values for the extra arguments: startButton = Button(text='Start Car') stopButton = Button(text='Stop Car') startButton.bind( on_press=partial( changeLabel, statusLabel, "Starting Car...")) stopButton.bind( on_press=partial( changeLabel, statusLabel, "Stopping Car...")) Now, by inspecting the setup code, it’s fairly easy to see what the UI does when various events occur. We can even extend this further to perform an action after setting the label: def changeLabelAndRun(label, text, command, button): label.text = text command() This allows our setup code to specify a UI behavior and trigger an action (assume ‘startCar’ and ‘stopCar’ have been defined as functions elsewhere): startButton.bind( on_press=partial( changeLabelAndRun, statusLabel, "Starting Car...", startCar)) stopButton.bind( on_press=partial( changeLabelAndRun, statusLabel, "Stopping Car...", stopCar)) Unlike C, there’s no casting, no packing things into structs, and it’s easy to extend for different needs. Snazzy! This might not scale perfectly to complicated UI interactions, but it greatly simplifies straightforward event processing, making it easier to see at a glance what the application is doing.

+ BoxLayout vs. GridLayout (Sept. 9, 2015, 11:17 a.m.)

The widgets in a BoxLayout can have different width and height, but in a GridLayout, each row or column should have the same size. The widgets in BoxLayout are placed from bottom to top, but those in a GridLayout are placed from top to bottom. In a BoxLayout the widgets can not be placed next to each other! I mean, they are placed one widget per row (if orientation is vertical) or column (if orientation is horizontal)

+ Background Image for Button (Feb. 12, 2015, 8:18 p.m.)

background_normal: 'home_button.png' background_down: 'home_button_down.png'

+ Spinner vs. DropDown (Sept. 9, 2015, 11:14 a.m.)

Spinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values from which the user can select a new one.

+ Commands (Feb. 12, 2015, 8:17 p.m.)

buildozer android debug

+ Buildozer (Feb. 12, 2015, 8:17 p.m.)

-------------------Installation:------------------- 1-git clone https://github.com/kivy/buildozer 2-Activate virtualenv (and test if the default `python` command will lead to python version 2.7) because buildozer needs python2.7 3-cd_to_downloaded_buildozer 4-python setup.py install ---------------------------------------------------------------------------- buildozer init buildozer android debug buildozer android logcat adb logcat ---------------------------------------------------------------------------- AndroidSDK and AndroidNDK are needed for buildozer, if you have already downloaded them, provide the paths like these: android.ndk_path = /home/moh3en/Programs/Android/Development/android-ndk-r9c android.sdk_path = /home/moh3en/Programs/Android/Development/android-sdk-linux if not, buildozer will try to download them, but unfortunately because of the embargo, they won't get downloaded since the source originates from google.com. So you have to download them using proxy and untar/unzip them somewhere. ---------------------------------------------------------------------------- sudo adb uninstall com.nimkatonline.en sudo adb install bin/NimkatOnline-1.2.0.apk --------------------------------------------------------------------------

+ Installing python packages (Feb. 12, 2015, 8:16 p.m.)

For installing python packages use this command: ./distribute.sh -m "kivy requests==2.1.0 SQLAlchemy" You will need these environment variables: export ANDROIDSDK="/home/mohsen/Programs/android-sdk-linux" export ANDROIDNDK="/home/mohsen/Programs/android-ndk-r8c" export ANDROIDNDKVER=r8c export ANDROIDAPI=14

+ Python Android Path (Feb. 12, 2015, 8:16 p.m.)

This is the path to the python used for android. Use this path for managing (installing or uninstalling) packages which are going to be installed, packed and used for your app. python-for-android/dist/default/private/lib/python2.7/site-packages

+ Error ==> Source resource does not exist: python-for-android/dist/default/project.properties (Feb. 12, 2015, 8:13 p.m.)

export ANDROIDAPI=15

+ Chat (Feb. 12, 2015, 8:12 p.m.)

<Mohsen_Hassani> Hello guys. I am very new to Kivy. I am using psycopg2 to read data from my remote VPS. I wanted to know if it will work after making apk too? <brousch> Mohsen_Hassani: Pure Python modules will work fine. I'm not sure if psycopg2 is pure Python <kovak> Mohsen_Hassani: the first step is to write a recipe for python-for-android to see if you can compile for ARM without any problems <kovak> I think psycopg2 has C bits <kovak> if it compiles in arm no problem you are good to go, if not you may need to patch the source <brousch> However, except in very rare cases, your Android app should not be communicating directly with your database server. There should be a proper API on top of that database ------------------------------------------------------------------------------- <tito> Mohsen_Hassani: the best shot you have is to put your tgz into a directory, go into the directory, and start python -m SimpleHTTPServer <tito> then do: URL_python=http://localhost:8000/Python-2.7.2.tar.bz2 URL_hostpython=http://localhost:8000/Python-2.7.2.tar.bz2 ./distribute.sh -m 'openssl pil kivy'

+ Building the application (Feb. 12, 2015, 8:06 p.m.)

cd dist/default ./build.py --permission INTERNET --orientation sensor --package com.mohsenhassani.notes --name My\ Notes --version 1.0 --dir ~/Projects/kivy_projects/notes/ debug ---------------------------------------------------------------------------- Install the debug apk to your device: adb install bin/touchtracer-1.0-debug.apk ---------------------------------------------------------------------------- /usr/bin/python2.7 build.py --name 'My Notes' --version 1.0 --package com.mohsenhassani.notes --private /home/mohsen/Projects/kivy_projects/notes/.buildozer/android/app --s dk 14 --minsdk 8 --permission INTERNET --icon /home/mohsen/Projects/kivy_projects/notes/./static/icon.png --orientation sensor debug ----------------------------------------------------------------------------

+ Installation (July 16, 2015, 11:56 p.m.)

Installation: http://kivy.org/docs/installation/installation-linux.html#linux-run-app --------------------------------------------------------------------------------------------- Installation Steps: 1-apt-get install python-gst0.10-dev python-gst-1.0 freeglut3-dev libsdl-image1.2-dev libsdl-ttf2.0-dev libsdl-mixer1.2-dev libsmpeg-dev libportmidi-dev libswscale-dev libavformat-dev libavcodec-dev libv4l-dev libserf-1-1 libsvn1 subversion openjdk-7-jdk python-pygame 2-Create and activate a virtualenv 3-easy_install requests 4-easy_install -U setuptools 5-pip install cython==0.20 6-pip install pygments 7-pip install --allow-all-external pil --allow-unverified pil 8.1-For installing next step (pygame) you will need to link a file or get the following error. So first create the symlink: fatal error: linux/videodev.h: No such file or directory: sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h 8.2-pip install pygame (It won't be found or downloaded! You need to download the tar file from www.pygame.org/download.shtml and install it using pip install <the_downloaded_tar_file>.) 9-pip install kivy