Skip to content

Instantly share code, notes, and snippets.

@nmz787
Created September 3, 2016 06:04
Show Gist options
  • Save nmz787/d0e71593240df63436d15037aff46c3e to your computer and use it in GitHub Desktop.
Save nmz787/d0e71593240df63436d15037aff46c3e to your computer and use it in GitHub Desktop.
kivy test for HTC DualLens SDK
[app]
# (str) Title of your application
title = My Application
# (str) Package name
package.name = myapp
# (str) Package domain (needed for android/ios packaging)
package.domain = org.test
# (str) Source code where the main.py live
source.dir = .
# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,so,jar
# (list) List of inclusions using pattern matching
source.include_patterns = assets/*.jpg,images/*.jpg,*.jpg
# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec
# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin
# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg
# (str) Application versioning (method 1)
version = 0.1
# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
# requirements = kivy==42077a382c9e678a794299120333745e41b4ce2f,plyer,python,pyjnius
requirements = kivy,plyer,python,pyjnius
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy
# (list) Garden requirements
#garden_requirements =
# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png
# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png
# (str) Supported orientation (one of landscape, portrait or all)
orientation = all
# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY
#
# OSX Specific
#
#
# author = © Copyright Info
#
# Android specific
#
# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1
android.arch = armeabi-v7a
# (list) Permissions
#android.permissions = INTERNET
# (int) Android API to use
android.api = 19
# (int) Minimum API required
#android.minapi = 9
# (int) Android SDK version to use
#android.sdk = 20
# (str) Android NDK version to use
#android.ndk = 9c
# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True
# (str) Android NDK directory (if empty, it will be automatically downloaded.)
# android.ndk_path =/home/nathan/Downloads/android-ndk-r10c/
# (str) Android SDK directory (if empty, it will be automatically downloaded.)
# android.sdk_path =/home/nathan/NVPACK/android-sdk-linux
# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =
# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#android.p4a_dir =
# (list) python-for-android whitelist
#android.p4a_whitelist =
# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False
# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity
# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
android.add_jars = libs/*.jar
# , libs/htcduallens.jar
# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
android.add_src = doit.java
# (str) python-for-android branch to use, if not master, useful to try
# not yet merged features.
#android.branch = master
# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME
# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png
# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =
# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
android.add_libs_armeabi = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so
# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False
# (list) Android application meta-data to set (key=value format)
#android.meta_data =
# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =
# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D
# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1
#
# iOS specific
#
# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"
# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s
[buildozer]
# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2
# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1
# (str) Path to build artifact storage, absolute or relative to spec file
build_dir = ./.buildozer
# (str) Path to build output (i.e. .apk, .ipa) storage
bin_dir = ./bin
# -----------------------------------------------------------------------------
# List as sections
#
# You can define all the "list" as [section:key].
# Each line will be considered as a option to the list.
# Let's take [app] / source.exclude_patterns.
# Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
# This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#
# -----------------------------------------------------------------------------
# Profiles
#
# You can extend section / key with a profile
# For example, you want to deploy a demo version of your application without
# HD content. You could first change the title to add "(demo)" in the name
# and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
# Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug
package org.test.myapp;
import org.renpy.android.PythonActivity;
import android.content.Context;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.lang.System;
//import org.apache.commons;
//import org.apache.commons.io.FileUtils;
//import org.apache.commons:commons-io.FileUtils
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import com.htc.lib1.duallens.Constants;
import com.htc.lib1.duallens.DualLens;
public class doit {
private boolean mIsBokehReady;
private int mStrength = 60;
//final String filename = "dualLensSample.jpg";
final String filename = "dualLensSample.jpg";
final String fli = "assets" + java.io.File.separator + filename;
final String filepath = Environment.getExternalStorageDirectory()
+ java.io.File.separator + filename;
Bitmap originalImageBitmap;
private Context context = (Context) PythonActivity.mActivity;
private void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void list_files(String path) {
AssetManager assetManager = context.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
System.out.println("Found file: " + path);
} else {
// String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
// File dir = new File(fullPath);
//if (!dir.exists())
// dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
System.out.println("Checking dir: " + path + "/" + assets[i]);
list_files(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("I/O Exception:!");
ex.printStackTrace();
}
}
public void initial(String path) {
mIsBokehReady = false;
AssetManager assetManager = context.getAssets();
try {
try {
String [] f = context.getAssets().list("");
for(String f1 : f){
System.out.println("names: " + f1);
}
String [] f22 = context.getAssets().list("private.mp3");
for(String f1 : f22){
System.out.println("images names: " + f1);
}
InputStream istr = assetManager.open(filename);
originalImageBitmap = BitmapFactory.decodeStream(istr);
System.out.println("originalImageBitmap width = " + originalImageBitmap.getWidth());
System.out.println("originalImageBitmap height = " + originalImageBitmap.getHeight());
copyInputStreamToFile(assetManager.open(filename), new File(filepath));
} catch(FileNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Error loading image");
e.printStackTrace();
}
}
public void buttonClick() {
if (mIsBokehReady) {
mStrength += 10;
if (mStrength > 100) {
mStrength = 0;
}
mIsBokehReady = false;
mDualLens.setStrength(mStrength);
try {
mDualLens.calculateBokeh();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Bitmap drawMask() {
DualLens.Holder<byte[]> buf = mDualLens.new Holder<byte[]>();
DualLens.DataInfo datainfo = mDualLens.getStrengthMap(buf);
int[] outputImage = new int[datainfo.width * datainfo.height];
int pixelDepth;
for (int i = 0; i < datainfo.width * datainfo.height; i++) {
pixelDepth = buf.value[i] & 0x000000ff;
int depthX = i % datainfo.width;
int depthY = i / datainfo.width;
int originalX = originalImageBitmap.getWidth() * depthX / datainfo.width;
int originalY = originalImageBitmap.getHeight() * depthY / datainfo.height;
// White out background, pick original color from foreground.
outputImage[i] = pixelDepth > 64 ? Color.WHITE :
originalImageBitmap.getPixel(originalX, originalY);
}
Bitmap bmp = Bitmap.createBitmap(outputImage, datainfo.width, datainfo.height, Config.ARGB_8888);
return bmp;
}
private DualLens mDualLens = null;
private int[] mColorBar = null;
public void start() {
try {
mDualLens = new DualLens(context, filepath);
mDualLens.setOnCompletionListener(new DualLens.OnCompletionListener() {
@Override
public void onCompletion(DualLens arg0, int event, int extra, String path) {
switch (event) {
case Constants.TASK_COMPLETED_PREPARE:
if (extra == 0) {
mIsBokehReady = false;
mDualLens.setStrength(mStrength);
try {
mDualLens.calculateBokeh();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case Constants.TASK_COMPLETED_BOKEH:
mIsBokehReady = true;
drawMask();
break;
}
}
});
mDualLens.prepare();
} catch (UnsatisfiedLinkError error) {
System.out.println("HTC One M8 with Sense 6 required");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void stop() {
if (mDualLens != null) {
mDualLens.release();
}
}
}
import os
import sys
from kivy.app import App #for the main app
from kivy.uix.floatlayout import FloatLayout #the UI layout
from kivy.uix.label import Label #a label to show information
from kivy.uix.button import Button
from plyer import accelerometer #object to read the accelerometer
from kivy.clock import Clock #clock to schedule a method
from kivy.uix.boxlayout import BoxLayout
import time
#########
# 'autoclass' takes a java class and gives it a Python wrapper
from jnius import autoclass
# Context is a normal java class in the Android API
# Constants = autoclass('com.htc.lib1.duallens.Constants')
from jnius import PythonJavaClass
from jnius import java_method
# OnCompletionListener = autoclass('com.htc.lib1.duallens.DualLens$OnCompletionListener')
DualLens = autoclass('com.htc.lib1.duallens.DualLens')
JavaString = autoclass('java.lang.String')
_File = autoclass('java.io.File')
Environment = autoclass('android.os.Environment')
# PythonActivity is provided by the Kivy bootstrap app in python-for-android
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Locale = autoclass('java.util.Locale')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
TextToSpeech = autoclass('android.speech.tts.TextToSpeech')
# The PythonActivity stores a reference to the currently running activity
# We need this to access the vibrator service
activity = PythonActivity.mActivity
# This is almost identical to the java code for the vibrator
# vibrator = activity.getSystemService(Context.DualLens)
filename = "dualLensSample.jpg";
filepath = '{}{}{}'.format(Environment.getExternalStorageDirectory().getAbsolutePath(), _File.separator, filename)
print filepath
print '*********************JJJ'
print dir(Environment.getExternalStorageDirectory())
print dir(Environment.getExternalStorageDirectory().__dict__)
#prepare
# vibrator.vibrate(10000) # The value is in milliseconds - this is 10s
#########
class UI(BoxLayout):#the app ui
def __init__(self, **kwargs):
super(UI, self).__init__(**kwargs)
self.lblAcce = Label(text="Accelerometer: ") #create a label at the center
self.add_widget(self.lblAcce) #add the label at the screen
b= Button(text='Hello!',
background_color=(0, 0, 1, 1),
font_size=150)
self.add_widget(b) #add the label at the screen
try:
accelerometer.enable() #enable the accelerometer
#if you want do disable it, just run: accelerometer.disable()
Clock.schedule_interval(self.update, 1.0/24) #24 calls per second
except:
self.lblAcce.text = "Failed to start accelerometer" #error
ab_p = JavaString(os.path.join('assets',filename) )
#self.d = DualLens(activity, ab_p)#filepath)
print ' abcdef 12345 '
self.tts = TextToSpeech(PythonActivity.mActivity, None)
# Play something in english
self.tts.setLanguage(Locale.US)
time.sleep(0.2)
self.tts.speak('Chahnd knee.', TextToSpeech.QUEUE_FLUSH, None)
# print os.path.join('assets',filename)
# print filepath # assets/dualLensSample.jpg
# print os.path.isfile(os.path.join('assets',filename) )
# print os.path.isfile(filepath) # assets/dualLensSample.jpg
# print ab_p
# print dir(OnCompletionListener.onCompletion)
# print dir(OnCompletionListener)
# print os.listdir(os.getcwd())
# print os.listdir(os.path.join(os.getcwd(), 'assets'))
# print os.path.abspath(os.path.join(os.getcwd(), 'assets'))
# print os.path.abspath(os.path.join(os.getcwd(), 'assets', filename))
flnm = os.path.abspath(os.path.join(os.getcwd(), 'assets', filename))
# print os.path.isfile(flnm)
#v= OnCompletionListener.__new__()
# OnCompletionListener
print ' abcdef '
# onCompletion(DualLens arg0, int event, int extra, String path)
# class ac(PythonJavaClass):
# __javainterfaces__ = ['com/htc/lib1/duallens/DualLens$OnCompletionListener']
# __javacontext__ = 'app'
# #class onCompletion(OnCompletionListener):
# # onCompletion(DualLens dualLens, int what, int extra, java.lang.String filePath)
# @java_method('(Lcom/htc/lib1/duallens/DualLens;IILjava/lang/String;)V')
# def onCompletion(arg0, event, extra, path):
# print '**$$**$$'
# print '{}\n{}'.format(arg0, event)
#o = OnCompletionListener.onCompletion = onCompletion
#print dir(o)
print '*$*$*$*$*$'
#self.d.setOnCompletionListener(ac())
try:
#self.d.prepare()
DLA = autoclass('org.test.myapp.doit')
print '*$*$*$*$*$ ABOUT TO LIST FILES'
d = DLA()
d.list_files(JavaString(Environment.getExternalStorageDirectory().getAbsolutePath()))
print '*$*$*$*$*$ DONE LISTING FILES'
d.initial(flnm)
print '*$*$*$*$*$'
d.start()
print '*$*$*$*$*$'
bmp = d.drawMask()
print '*$*$*$*$*$'
print bmp
print dir(bmp)
print bmp.__dict__
except Exception as e:
import traceback
print e
print e.message
print traceback.format_exc()
print 'abcdef'
sys.exit()
def update(self, dt):
txt = ""
try:
txt = "Accelerometer:\nX = %.2f\nY = %.2f\nZ = %2.f " %(
accelerometer.acceleration[0], #read the X value
accelerometer.acceleration[1], # Y
accelerometer.acceleration[2]) # Z
except:
txt = "Cannot read accelerometer!" #error
self.lblAcce.text = txt #add the correct text
class Accelerometer(App): #our app
def build(self):
ui = UI()# create the UI
return ui #show it
if __name__ == '__main__':
Accelerometer().run() #start our app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment