diff --git a/.gitignore b/.gitignore index 74659ae..58bce9a 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,8 @@ build/ /*/build/ # Local configuration file (sdk path, etc) +affdexme-android.iml +gradle.properties local.properties # Proguard folder generated by Eclipse diff --git a/README.md b/README.md index 264b214..c74f892 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,9 @@ +![Affectiva Logo](http://developer.affectiva.com/images/logo.png) + +###Copyright (c) 2016 Affectiva Inc.
See the file [license.txt](license.txt) for copying permission. + +***************************** + **AffdexMe** is an app that demonstrates the use of the Affectiva Android SDK. It uses the camera on your Android device to view, process and analyze live video of your face. Start the app and you will see your face on the screen and metrics describing your expressions. Tapping the screen will bring up a menu with options to display the Processed Frames Per Second metric, display facial tracking points, and control the rate at which frames are processed by the SDK. Most of the methods in this file control the application's UI. Therefore, if you are just interested in learning how the Affectiva SDK works, you will find the calls relevant to the use of the SDK in the initializeCameraDetector(), startCamera(), stopCamera(), and onImageResults() methods. @@ -8,11 +14,13 @@ In order to use this project, you will need to: - Obtain the Affectiva Android SDK (visit http://www.affectiva.com/solutions/apis-sdks/) - Copy the contents of the SDK's assets folder into this project's app/src/main/assets folder - Copy the contents of the SDK's libs folder into this project's app/libs folder -- Copy the armeabi-v7a folder (found in the SDK libs folder) into this project's app/native-libs folder +- Copy the armeabi-v7a folder (found in the SDK libs folder) into this project's app/jniLibs folder - Copy your license file to this project's app/src/main/assets/Affdex folder and rename to license.txt - Build the project - Run the app and smile! See the comment section at the top of the MainActivity.java file for more information. -Copyright (c) 2014-2015 Affectiva. All rights reserved. +*** + +This app uses some of the excellent [Emoji One emojis](http://emojione.com). diff --git a/affdexme-android.iml b/affdexme-android.iml deleted file mode 100644 index 9e7152e..0000000 --- a/affdexme-android.iml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore index 796b96d..283879a 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -1 +1,10 @@ +/app.iml /build +/jniLibs/armeabi-v7a +/libs/Affdex-sdk.jar +/libs/Affdex-sdk-javadoc.jar +/libs/javax.inject-1.jar +/libs/dagger-1.2.2.jar +/src/main/assets/Affdex/*license* +/src/main/assets/Affdex/Classifiers +/src/main/assets/Affdex/Classifiers/v_9 diff --git a/app/app.iml b/app/app.iml deleted file mode 100644 index 4a2dae6..0000000 --- a/app/app.iml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 3262768..74ae3e6 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,15 +1,15 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 22 - buildToolsVersion '22.0.1' + compileSdkVersion 23 + buildToolsVersion '23.0.2' defaultConfig { applicationId "com.affectiva.affdexme" minSdkVersion 16 - targetSdkVersion 22 - versionCode 14 - versionName "2.0.0" + targetSdkVersion 23 + versionCode 492 + versionName "3.0.0" setProperty("archivesBaseName", "AffdexMe-$versionName-$versionCode") } buildTypes { @@ -23,30 +23,25 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } sourceSets { main { - jniLibs.srcDirs = ['native-libs'] + jniLibs.srcDirs = ['jniLibs'] jni.srcDirs = [] //disable automatic ndk-build } } } dependencies { - //gson is necessary for the license to be parsed - compile 'com.google.code.gson:gson:2.3' - - //include the Affdex SDK jars - compile files('libs/Affdex-sdk.jar') - compile files('libs/Affdex-sdk-javadoc.jar') - compile files('libs/dagger-1.2.2.jar') - compile files('libs/flurry-analytics-4.1.0.jar') - compile files('libs/javax.inject-1.jar') - - //although the use of the CameraDetector class in this project does not require it, you may have to include - //the following dependencies if you use other features of the Affdex SDK - //compile 'com.android.support:support-v4:22.2.0' - //compile 'com.google.android.gms:play-services:7.5.0' - + //include the Affdex SDK jars and its dependencies + compile fileTree(dir: 'libs', include: '*.jar') + + //include project dependencies + compile 'com.android.support:support-v4:23.1.1' + compile 'com.android.support:appcompat-v7:23.1.1' } // build a signed release apk only if the environment is configured diff --git a/app/jniLibs/READ.ME b/app/jniLibs/READ.ME new file mode 100644 index 0000000..232ed8e --- /dev/null +++ b/app/jniLibs/READ.ME @@ -0,0 +1,3 @@ +Place the native library files here. + +armeabi-v7a/libaffdexface_jni.so diff --git a/app/libs/READ.ME b/app/libs/READ.ME new file mode 100644 index 0000000..c740ba4 --- /dev/null +++ b/app/libs/READ.ME @@ -0,0 +1,6 @@ +Place the Affdex SDK JARs here. + +Affdex-sdk.jar +Affdex-sdk-javadoc.jar +dagger-*.java +javax.inject-1.jar diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index dc76e0a..ff5d2da 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,30 +1,37 @@ - - + + + - + - - - + + + + android:label="@string/app_name" + android:theme="@style/MainActivityTheme"> @@ -38,17 +45,14 @@ android:name="android.support.PARENT_ACTIVITY" android:value="com.affectiva.affdexme.MainActivity" /> - + android:textAppearance="@android:style/TextAppearance.Large" + android:theme="@android:style/Theme.DeviceDefault"> - - diff --git a/app/src/main/assets/Affdex/READ.ME b/app/src/main/assets/Affdex/READ.ME new file mode 100644 index 0000000..e5a2081 --- /dev/null +++ b/app/src/main/assets/Affdex/READ.ME @@ -0,0 +1,4 @@ +Place license file and Classifiers folder here. + +license.txt +Classifiers/v_9/* diff --git a/app/src/main/java/com/affectiva/affdexme/DrawingView.java b/app/src/main/java/com/affectiva/affdexme/DrawingView.java index 881f019..f49387e 100644 --- a/app/src/main/java/com/affectiva/affdexme/DrawingView.java +++ b/app/src/main/java/com/affectiva/affdexme/DrawingView.java @@ -1,23 +1,40 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; import android.content.Context; import android.content.res.TypedArray; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PointF; import android.graphics.PorterDuff; +import android.graphics.Rect; import android.graphics.Typeface; import android.os.Process; -import android.os.SystemClock; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; +import android.util.Pair; import android.view.SurfaceHolder; import android.view.SurfaceView; +import android.widget.Toast; import com.affectiva.android.affdex.sdk.detector.Face; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; /** * This class contains a SurfaceView and its own thread that draws to it. @@ -25,316 +42,138 @@ import com.affectiva.android.affdex.sdk.detector.Face; */ public class DrawingView extends SurfaceView implements SurfaceHolder.Callback { - class PointFArraySharer { - boolean isPointsMirrored = false; - PointF[] nextPointsToDraw = null; - } - - //Inner Thread class - class DrawingThread extends Thread{ - private SurfaceHolder mSurfaceHolder; - private Paint circlePaint; - private Paint boxPaint; - private volatile boolean stopFlag = false; //boolean to indicate when thread has been told to stop - private final PointFArraySharer sharer; - private DrawingViewConfig config; - private final long drawPeriod = 33; //draw at 30 fps - - private final int TEXT_RAISE = 10; - - String roll = ""; - String yaw = ""; - String pitch = ""; - String interOcDis = ""; - - public DrawingThread(SurfaceHolder surfaceHolder, DrawingViewConfig con) { - mSurfaceHolder = surfaceHolder; - - circlePaint = new Paint(); - circlePaint.setColor(Color.WHITE); - boxPaint = new Paint(); - boxPaint.setColor(Color.WHITE); - boxPaint.setStyle(Paint.Style.STROKE); - - config = con; - sharer = new PointFArraySharer(); - - setThickness(config.drawThickness); - } - - void setMetrics(float roll, float yaw, float pitch, float interOcDis, float valence) { - //format string for our DrawingView to use when ready - this.roll = String.format("%.2f",roll); - this.yaw = String.format("%.2f",yaw); - this.pitch = String.format("%.2f",pitch); - this.interOcDis = String.format("%.2f",interOcDis); - - //prepare the color of the bounding box using the valence score. Red for -100, White for 0, and Green for +100, with linear interpolation in between. - if (valence > 0) { - float colorScore = ((100f-valence)/100f)*255; - boxPaint.setColor(Color.rgb((int)colorScore,255,(int)colorScore)); - } else { - float colorScore = ((100f+valence)/100f)*255; - boxPaint.setColor(Color.rgb(255, (int) colorScore, (int) colorScore)); - } - - } - - public void stopThread() { - stopFlag = true; - } - - public boolean isStopped() { - return stopFlag; - } - - //Updates thread with latest points returned by the onImageResults() event. - public void updatePoints(PointF[] pointList, boolean isPointsMirrored) { - synchronized (sharer) { - sharer.nextPointsToDraw = pointList; - sharer.isPointsMirrored = isPointsMirrored; - } - } - - void setThickness(int thickness) { - boxPaint.setStrokeWidth(thickness); - } - - //Inform thread face detection has stopped, so array of points is no longer valid. - public void invalidatePoints() { - synchronized (sharer) { - sharer.nextPointsToDraw = null; - } - } - - @Override - public void run() { - android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - - while(!stopFlag) { - - /** - * We use SurfaceHolder.lockCanvas() to get the canvas that draws to the SurfaceView. - * After we are done drawing, we let go of the canvas using SurfaceHolder.unlockCanvasAndPost() - * **/ - Canvas c = null; - try { - c = mSurfaceHolder.lockCanvas(); - - if (c!= null) { - synchronized (mSurfaceHolder) { - c.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); //clear previous dots - draw(c); - } - } - } - finally { - if (c!= null) { - mSurfaceHolder.unlockCanvasAndPost(c); - } - } - - } - - config = null; //nullify object to avoid memory leak - } - - void draw(Canvas c) { - PointF[] points; - boolean mirrorPoints; - synchronized (sharer) { - if (sharer.nextPointsToDraw == null) - return; - points = sharer.nextPointsToDraw; - mirrorPoints = sharer.isPointsMirrored; - } - - //Coordinates around which to draw bounding box. - float leftBx = config.surfaceViewWidth; - float rightBx = 0; - float topBx = config.surfaceViewHeight; - float botBx = 0; - - for (int i = 0; i < points.length; i++) { - - //transform from the camera coordinates to our screen coordinates - //The camera preview is displayed as a mirror, so X pts have to be mirrored back. - float x; - if (mirrorPoints) { - x = (config.imageWidth - points[i].x) * config.screenToImageRatio; - } else { - x = (points[i].x) * config.screenToImageRatio; - } - float y = (points[i].y)* config.screenToImageRatio; - - //We determine the left-most, top-most, right-most, and bottom-most points to draw the bounding box around. - if (x < leftBx) - leftBx = x; - if (x > rightBx) - rightBx = x; - if (y < topBx) - topBx = y; - if (y > botBx) - botBx = y; - - //Draw facial tracking dots. - if (config.isDrawPointsEnabled) { - c.drawCircle(x, y, config.drawThickness, circlePaint); - } - } - - //Draw the bounding box. - if (config.isDrawPointsEnabled) { - c.drawRect(leftBx, topBx, rightBx, botBx, boxPaint); - } - - //Draw the measurement metrics, with a dark border around the words to make them visible for users of all skin colors. - if (config.isDrawMeasurementsEnabled) { - float centerBx = (leftBx + rightBx) / 2; - - float upperText = topBx - TEXT_RAISE; - c.drawText("PITCH", centerBx, upperText - config.textSize,config.textBorderPaint); - c.drawText("PITCH", centerBx, upperText - config.textSize, config.textPaint); - c.drawText(pitch,centerBx ,upperText ,config.textBorderPaint); - c.drawText(pitch, centerBx, upperText, config.textPaint); - - float upperLeft = centerBx - config.upperTextSpacing; - - c.drawText("YAW", upperLeft , upperText - config.textSize , config.textBorderPaint); - c.drawText("YAW", upperLeft, upperText - config.textSize, config.textPaint); - c.drawText(yaw, upperLeft , upperText , config.textBorderPaint); - c.drawText(yaw, upperLeft, upperText, config.textPaint); - - float upperRight = centerBx + config.upperTextSpacing; - c.drawText("ROLL", upperRight , upperText - config.textSize , config.textBorderPaint); - c.drawText("ROLL", upperRight, upperText - config.textSize, config.textPaint); - c.drawText(roll, upperRight , upperText , config.textBorderPaint); - c.drawText(roll, upperRight, upperText, config.textPaint); - - c.drawText("INTEROCULAR DISTANCE", centerBx , botBx + config.textSize , config.textBorderPaint); - c.drawText("INTEROCULAR DISTANCE", centerBx, botBx + config.textSize, config.textPaint); - c.drawText(interOcDis,centerBx , botBx + config.textSize*2 , config.textBorderPaint); - c.drawText(interOcDis, centerBx, botBx + config.textSize * 2, config.textPaint); - } - - - } - } - - class DrawingViewConfig { - private int imageHeight = 1; - private int imageWidth = 1; - private int surfaceViewWidth = 0; - private int surfaceViewHeight = 0; - private float screenToImageRatio = 0; - private int drawThickness = 0; - private boolean isDrawPointsEnabled = true; //by default, have the drawing thread draw tracking dots - private boolean isDrawMeasurementsEnabled = false; - private boolean isDimensionsNeeded = true; - - private Paint textPaint; - private int textSize; - private Paint textBorderPaint; - private int upperTextSpacing; - - public void setMeasurementMetricConfigs(Paint textPaint, Paint dropShadowPaint, int textSize, int upperTextSpacing) { - this.textPaint = textPaint; - this.textSize = textSize; - this.textBorderPaint = dropShadowPaint; - this.upperTextSpacing = upperTextSpacing; - } - - public void updateViewDimensions(int surfaceViewWidth, int surfaceViewHeight, int imageWidth, int imageHeight) { - if (surfaceViewWidth <= 0 || surfaceViewHeight <= 0 || imageWidth <= 0 || imageHeight <= 0) { - throw new IllegalArgumentException("All dimensions submitted to updateViewDimensions() must be positive"); - } - this.imageWidth = imageWidth; - this.imageHeight = imageHeight; - this.surfaceViewWidth = surfaceViewWidth; - this.surfaceViewHeight = surfaceViewHeight; - screenToImageRatio = (float)surfaceViewWidth / imageWidth; - isDimensionsNeeded = false; - } - - public void setDrawThickness(int t) { - - if ( t <= 0) { - throw new IllegalArgumentException("Thickness must be positive."); - } - - drawThickness = t; - } - } - - //Class variables of DrawingView class + private final static String LOG_TAG = "AffdexMe"; + private final float MARGIN = 4; + private Bitmap appearanceMarkerBitmap_genderMale_glassesOn; + private Bitmap appearanceMarkerBitmap_genderFemale_glassesOn; + private Bitmap appearanceMarkerBitmap_genderUnknown_glassesOn; + private Bitmap appearanceMarkerBitmap_genderUnknown_glassesOff; + private Bitmap appearanceMarkerBitmap_genderMale_glassesOff; + private Bitmap appearanceMarkerBitmap_genderFemale_glassesOff; + private Map emojiMarkerBitmapToEmojiTypeMap; private SurfaceHolder surfaceHolder; private DrawingThread drawingThread; //DrawingThread object - private Typeface typeface; private DrawingViewConfig drawingViewConfig; - private static String LOG_TAG = "AffdexMe"; - + private DrawingThreadEventListener listener; //three constructors required of any custom view public DrawingView(Context context) { super(context); - initView(context, null); + initView(); } + public DrawingView(Context context, AttributeSet attrs) { super(context, attrs); - initView(context, attrs); + initView(); } + public DrawingView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - initView(context, attrs); + initView(); } - void initView(Context context, AttributeSet attrs){ + private static int getDrawable(@NonNull Context context, @NonNull String name) { + return context.getResources().getIdentifier(name, "drawable", context.getPackageName()); + } + + public void setEventListener(DrawingThreadEventListener listener) { + this.listener = listener; + + if (drawingThread != null) { + drawingThread.setEventListener(listener); + } + } + + public void requestBitmap() { + if (listener == null) { + String msg = "Attempted to request screenshot without first attaching event listener"; + Log.e(LOG_TAG, msg); + Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); + return; + } + if (drawingThread == null || drawingThread.isStopped()) { + String msg = "Attempted to request screenshot without a running drawing thread"; + Log.e(LOG_TAG, msg); + Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); + return; + } + drawingThread.requestCaptureBitmap = true; + } + + void initView() { surfaceHolder = getHolder(); //The SurfaceHolder object will be used by the thread to request canvas to draw on SurfaceView surfaceHolder.setFormat(PixelFormat.TRANSPARENT); //set to Transparent so this surfaceView does not obscure the one it is overlaying (the one displaying the camera). - surfaceHolder.addCallback(this); //become a Listener to the three events below that SurfaceView throws - + surfaceHolder.addCallback(this); //become a Listener to the three events below that SurfaceView generates drawingViewConfig = new DrawingViewConfig(); - //default values - int upperTextSpacing = 15; - int textSize = 15; + //Default values + Paint emotionLabelPaint = new Paint(); + emotionLabelPaint.setColor(Color.parseColor("#ff8000")); //Orange + emotionLabelPaint.setStyle(Paint.Style.FILL); + emotionLabelPaint.setTextAlign(Paint.Align.CENTER); + emotionLabelPaint.setTextSize(48); - Paint measurementTextPaint = new Paint(); - measurementTextPaint.setStyle(Paint.Style.FILL); - measurementTextPaint.setTextAlign(Paint.Align.CENTER); + Paint emotionValuePaint = new Paint(); + emotionValuePaint.setColor(Color.parseColor("#514a40")); //Grey + emotionValuePaint.setStyle(Paint.Style.FILL); + emotionValuePaint.setTextAlign(Paint.Align.CENTER); + emotionValuePaint.setTextSize(48); - Paint dropShadow = new Paint(); - dropShadow.setColor(Color.BLACK); - dropShadow.setStyle(Paint.Style.STROKE); - dropShadow.setTextAlign(Paint.Align.CENTER); + Paint metricBarPaint = new Paint(); + metricBarPaint.setColor(Color.GREEN); + metricBarPaint.setStyle(Paint.Style.FILL); + int metricBarWidth = 150; //load and parse XML attributes - if (attrs != null) { - TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.drawing_view_attributes,0,0); - upperTextSpacing = a.getDimensionPixelSize(R.styleable.drawing_view_attributes_measurements_upper_spacing,upperTextSpacing); - measurementTextPaint.setColor(a.getColor(R.styleable.drawing_view_attributes_measurements_color,Color.WHITE)); - dropShadow.setColor(a.getColor(R.styleable.drawing_view_attributes_measurements_text_border_color,Color.BLACK)); - dropShadow.setStrokeWidth(a.getInteger(R.styleable.drawing_view_attributes_measurements_text_border_thickness,5)); - textSize = a.getDimensionPixelSize(R.styleable.drawing_view_attributes_measurements_text_size,textSize); - measurementTextPaint.setTextSize(textSize); - dropShadow.setTextSize(textSize); + int[] emotionLabelAttrs = { + android.R.attr.textStyle, // 0 + android.R.attr.textColor, // 1 + android.R.attr.shadowColor, // 2 + android.R.attr.shadowDy, // 3 + android.R.attr.shadowRadius, // 4 + android.R.attr.layout_weight, // 5 + android.R.attr.textSize}; // 6 + TypedArray a = getContext().obtainStyledAttributes(R.style.metricName, emotionLabelAttrs); + if (a != null) { + emotionLabelPaint.setColor(a.getColor(1, emotionLabelPaint.getColor())); + emotionLabelPaint.setShadowLayer( + a.getFloat(4, 1.0f), + a.getFloat(3, 2.0f), a.getFloat(3, 2.0f), + a.getColor(2, Color.BLACK)); + emotionLabelPaint.setTextSize(a.getDimensionPixelSize(6, 48)); + emotionLabelPaint.setFakeBoldText("bold".equalsIgnoreCase(a.getString(0))); a.recycle(); } - drawingViewConfig.setMeasurementMetricConfigs(measurementTextPaint, dropShadow, textSize, upperTextSpacing); + int[] emotionValueAttrs = { + android.R.attr.textColor, // 0 + android.R.attr.textSize, // 1 + R.styleable.custom_attributes_metricBarLength}; // 2 + a = getContext().obtainStyledAttributes(R.style.metricPct, emotionValueAttrs); + if (a != null) { + emotionValuePaint.setColor(a.getColor(0, emotionValuePaint.getColor())); + emotionValuePaint.setTextSize(a.getDimensionPixelSize(1, 36)); + metricBarWidth = a.getDimensionPixelSize(2, 150); + a.recycle(); + } - drawingThread = new DrawingThread(surfaceHolder, drawingViewConfig); + drawingViewConfig.setDominantEmotionLabelPaints(emotionLabelPaint, emotionValuePaint); + drawingViewConfig.setDominantEmotionMetricBarConfig(metricBarPaint, metricBarWidth); + drawingThread = new DrawingThread(surfaceHolder, drawingViewConfig, listener); + + //statically load the emoji bitmaps on-demand and cache + emojiMarkerBitmapToEmojiTypeMap = new HashMap<>(); } public void setTypeface(Typeface face) { - drawingViewConfig.textPaint.setTypeface(face); - drawingViewConfig.textBorderPaint.setTypeface(face); + drawingViewConfig.dominantEmotionLabelPaint.setTypeface(face); + drawingViewConfig.dominantEmotionValuePaint.setTypeface(face); } @Override public void surfaceCreated(SurfaceHolder holder) { if (drawingThread.isStopped()) { - drawingThread = new DrawingThread(surfaceHolder, drawingViewConfig); + drawingThread = new DrawingThread(surfaceHolder, drawingViewConfig, listener); } drawingThread.start(); } @@ -353,9 +192,10 @@ public class DrawingView extends SurfaceView implements SurfaceHolder.Callback { drawingThread.join(); retry = false; } catch (InterruptedException e) { - Log.e(LOG_TAG,e.getMessage()); + Log.e(LOG_TAG, e.getMessage()); } } + cleanup(); } public boolean isDimensionsNeeded() { @@ -368,50 +208,578 @@ public class DrawingView extends SurfaceView implements SurfaceHolder.Callback { public void updateViewDimensions(int surfaceViewWidth, int surfaceViewHeight, int imageWidth, int imageHeight) { try { - drawingViewConfig.updateViewDimensions(surfaceViewWidth,surfaceViewHeight,imageWidth,imageHeight); - } catch (Exception e) { - Log.e(LOG_TAG,e.getMessage()); + drawingViewConfig.updateViewDimensions(surfaceViewWidth, surfaceViewHeight, imageWidth, imageHeight); + } catch (IllegalArgumentException e) { + Log.e(LOG_TAG, "Attempted to set a dimension with a negative value", e); } } public void setThickness(int t) { - drawingViewConfig.setDrawThickness(t); try { + drawingViewConfig.setDrawThickness(t); drawingThread.setThickness(t); - } catch(Exception e) { - Log.e(LOG_TAG,e.getMessage()); + } catch (IllegalArgumentException e) { + Log.e(LOG_TAG, "Attempted to set a thickness with a negative value", e); } } - public void setDrawPointsEnabled(boolean b){ - drawingViewConfig.isDrawPointsEnabled = b; - } - public boolean getDrawPointsEnabled() { return drawingViewConfig.isDrawPointsEnabled; } - public void setDrawMeasurementsEnabled(boolean b) { - drawingViewConfig.isDrawMeasurementsEnabled = b; + public void setDrawPointsEnabled(boolean b) { + drawingViewConfig.isDrawPointsEnabled = b; } - public boolean getDrawMeasurementsEnabled() { - return drawingViewConfig.isDrawMeasurementsEnabled; + public boolean getDrawAppearanceMarkersEnabled() { + return drawingViewConfig.isDrawAppearanceMarkersEnabled; } - public void setMetrics(float roll, float yaw, float pitch, float interOcDis, float valence) { - drawingThread.setMetrics(roll,yaw,pitch,interOcDis,valence); + public void setDrawAppearanceMarkersEnabled(boolean b) { + drawingViewConfig.isDrawAppearanceMarkersEnabled = b; } - public void updatePoints(PointF[] points, boolean isPointsMirrored) { - drawingThread.updatePoints(points, isPointsMirrored); + public boolean getDrawEmojiMarkersEnabled() { + return drawingViewConfig.isDrawEmojiMarkersEnabled; } - public void invalidatePoints(){ + public void setDrawEmojiMarkersEnabled(boolean b) { + drawingViewConfig.isDrawEmojiMarkersEnabled = b; + } + + public void updatePoints(List faces, boolean isPointsMirrored) { + drawingThread.updatePoints(faces, isPointsMirrored); + } + + public void invalidatePoints() { drawingThread.invalidatePoints(); } + /** + * To be called when this view element is potentially being destroyed + * I.E. when the Activity's onPause() gets called. + */ + public void cleanup() { + if (emojiMarkerBitmapToEmojiTypeMap != null) { + for (Bitmap bitmap : emojiMarkerBitmapToEmojiTypeMap.values()) { + bitmap.recycle(); + } + emojiMarkerBitmapToEmojiTypeMap.clear(); + } + + if (appearanceMarkerBitmap_genderMale_glassesOn != null) { + appearanceMarkerBitmap_genderMale_glassesOn.recycle(); + } + if (appearanceMarkerBitmap_genderFemale_glassesOn != null) { + appearanceMarkerBitmap_genderFemale_glassesOn.recycle(); + } + if (appearanceMarkerBitmap_genderUnknown_glassesOn != null) { + appearanceMarkerBitmap_genderUnknown_glassesOn.recycle(); + } + if (appearanceMarkerBitmap_genderUnknown_glassesOff != null) { + appearanceMarkerBitmap_genderUnknown_glassesOff.recycle(); + } + if (appearanceMarkerBitmap_genderMale_glassesOff != null) { + appearanceMarkerBitmap_genderMale_glassesOff.recycle(); + } + if (appearanceMarkerBitmap_genderFemale_glassesOff != null) { + appearanceMarkerBitmap_genderFemale_glassesOff.recycle(); + } + } + + interface DrawingThreadEventListener { + void onBitmapGenerated(Bitmap bitmap); + } + + class FacesSharer { + boolean isPointsMirrored; + List facesToDraw; + + public FacesSharer() { + isPointsMirrored = false; + facesToDraw = new ArrayList<>(); + } + } + + //Inner Thread class + class DrawingThread extends Thread { + private final FacesSharer sharer; + private final SurfaceHolder mSurfaceHolder; + private Paint trackingPointsPaint; + private Paint boundingBoxPaint; + private Paint dominantEmotionScoreBarPaint; + private volatile boolean stopFlag = false; //boolean to indicate when thread has been told to stop + private volatile boolean requestCaptureBitmap = false; //boolean to indicate a snapshot of the surface has been requested + private DrawingViewConfig config; + private DrawingThreadEventListener listener; + + public DrawingThread(SurfaceHolder surfaceHolder, DrawingViewConfig con, DrawingThreadEventListener listener) { + mSurfaceHolder = surfaceHolder; + + //statically load the Appearance marker bitmaps so they only have to load once + appearanceMarkerBitmap_genderMale_glassesOn = ImageHelper.loadBitmapFromInternalStorage(getContext(), "male_glasses.png"); + appearanceMarkerBitmap_genderMale_glassesOff = ImageHelper.loadBitmapFromInternalStorage(getContext(), "male_noglasses.png"); + appearanceMarkerBitmap_genderFemale_glassesOn = ImageHelper.loadBitmapFromInternalStorage(getContext(), "female_glasses.png"); + appearanceMarkerBitmap_genderFemale_glassesOff = ImageHelper.loadBitmapFromInternalStorage(getContext(), "female_noglasses.png"); + appearanceMarkerBitmap_genderUnknown_glassesOn = ImageHelper.loadBitmapFromInternalStorage(getContext(), "unknown_glasses.png"); + appearanceMarkerBitmap_genderUnknown_glassesOff = ImageHelper.loadBitmapFromInternalStorage(getContext(), "unknown_noglasses.png"); + + trackingPointsPaint = new Paint(); + trackingPointsPaint.setColor(Color.WHITE); + boundingBoxPaint = new Paint(); + boundingBoxPaint.setColor(Color.WHITE); + boundingBoxPaint.setStyle(Paint.Style.STROKE); + dominantEmotionScoreBarPaint = new Paint(); + dominantEmotionScoreBarPaint.setColor(Color.GREEN); + dominantEmotionScoreBarPaint.setStyle(Paint.Style.STROKE); + + config = con; + sharer = new FacesSharer(); + this.listener = listener; + + setThickness(config.drawThickness); + } + + public void setEventListener(DrawingThreadEventListener listener) { + this.listener = listener; + } + + void setValenceOfBoundingBox(float valence) { + //prepare the color of the bounding box using the valence score. Red for -100, White for 0, and Green for +100, with linear interpolation in between. + if (valence > 0) { + float colorScore = ((100f - valence) / 100f) * 255; + boundingBoxPaint.setColor(Color.rgb((int) colorScore, 255, (int) colorScore)); + } else { + float colorScore = ((100f + valence) / 100f) * 255; + boundingBoxPaint.setColor(Color.rgb(255, (int) colorScore, (int) colorScore)); + } + } + + public void stopThread() { + stopFlag = true; + } + + public boolean isStopped() { + return stopFlag; + } + + //Updates thread with latest faces returned by the onImageResults() event. + public void updatePoints(List faces, boolean isPointsMirrored) { + synchronized (sharer) { + sharer.facesToDraw.clear(); + if (faces != null) { + sharer.facesToDraw.addAll(faces); + } + sharer.isPointsMirrored = isPointsMirrored; + } + } + + void setThickness(int thickness) { + boundingBoxPaint.setStrokeWidth(thickness); + } + + //Inform thread face detection has stopped, so pending faces are no longer valid. + public void invalidatePoints() { + synchronized (sharer) { + sharer.facesToDraw.clear(); + } + } + + @Override + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + + while (!stopFlag) { + + /** + * We use SurfaceHolder.lockCanvas() to get the canvas that draws to the SurfaceView. + * After we are done drawing, we let go of the canvas using SurfaceHolder.unlockCanvasAndPost() + * **/ + Canvas c = null; + Canvas screenshotCanvas = null; + Bitmap screenshotBitmap = null; + try { + c = mSurfaceHolder.lockCanvas(); + + if (requestCaptureBitmap) { + Rect surfaceBounds = mSurfaceHolder.getSurfaceFrame(); + screenshotBitmap = Bitmap.createBitmap(surfaceBounds.width(), surfaceBounds.height(), Bitmap.Config.ARGB_8888); + screenshotCanvas = new Canvas(screenshotBitmap); + requestCaptureBitmap = false; + } + + if (c != null) { + synchronized (mSurfaceHolder) { + c.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); //clear previous dots + draw(c, screenshotCanvas); + } + } + + } finally { + if (c != null) { + mSurfaceHolder.unlockCanvasAndPost(c); + } + if (screenshotBitmap != null && listener != null) { + listener.onBitmapGenerated(Bitmap.createBitmap(screenshotBitmap)); + screenshotBitmap.recycle(); + } + } + } + + config = null; //nullify object to avoid memory leak + } + + void draw(@NonNull Canvas c, @Nullable Canvas c2) { + Face nextFaceToDraw; + boolean mirrorPoints; + boolean multiFaceMode; + int index = 0; + + synchronized (sharer) { + mirrorPoints = sharer.isPointsMirrored; + multiFaceMode = sharer.facesToDraw.size() > 1; + + if (sharer.facesToDraw.isEmpty()) { + nextFaceToDraw = null; + } else { + nextFaceToDraw = sharer.facesToDraw.get(index); + index++; + } + } + + while (nextFaceToDraw != null) { + + drawFaceAttributes(c, nextFaceToDraw, mirrorPoints, multiFaceMode); + + if (c2 != null) { + drawFaceAttributes(c2, nextFaceToDraw, false, multiFaceMode); + } + + synchronized (sharer) { + mirrorPoints = sharer.isPointsMirrored; + + if (index < sharer.facesToDraw.size()) { + nextFaceToDraw = sharer.facesToDraw.get(index); + index++; + } else { + nextFaceToDraw = null; + } + } + } + } + + private void drawFaceAttributes(Canvas c, Face face, boolean mirrorPoints, boolean isMultiFaceMode) { + //Coordinates around which to draw bounding box. + //Default to an 'inverted' box, where the absolute max and min values of the surface view are inside-out + Rect boundingRect = new Rect(config.surfaceViewWidth, config.surfaceViewHeight, 0, 0); + + for (PointF point : face.getFacePoints()) { + //transform from the camera coordinates to our screen coordinates + //The camera preview is displayed as a mirror, so X pts have to be mirrored back. + float x; + if (mirrorPoints) { + x = (config.imageWidth - point.x) * config.screenToImageRatio; + } else { + x = (point.x) * config.screenToImageRatio; + } + float y = (point.y) * config.screenToImageRatio; + + //For some reason I needed to add each point twice to make sure that all the + //points get properly registered in the bounding box. + boundingRect.union(Math.round(x), Math.round(y)); + boundingRect.union(Math.round(x), Math.round(y)); + + //Draw facial tracking dots. + if (config.isDrawPointsEnabled) { + c.drawCircle(x, y, config.drawThickness, trackingPointsPaint); + } + } + + //Draw the bounding box. + if (config.isDrawPointsEnabled) { + drawBoundingBox(c, face, boundingRect); + } + + float heightOffset = findNecessaryHeightOffset(boundingRect, face); + + //Draw the Appearance markers (gender / glasses) + if (config.isDrawAppearanceMarkersEnabled) { + drawAppearanceMarkers(c, face, boundingRect, heightOffset); + } + + //Draw the Emoji markers + if (config.isDrawEmojiMarkersEnabled) { + drawDominantEmoji(c, face, boundingRect, heightOffset); + } + + //Only draw the dominant emotion bar in multiface mode + if (isMultiFaceMode) { + drawDominantEmotion(c, face, boundingRect); + } + } + + private float findNecessaryHeightOffset(Rect boundingBox, Face face) { + Bitmap appearanceBitmap = getAppearanceBitmapForFace(face); + Bitmap emojiBitmap = getDominantEmojiBitmapForFace(face); + + float appearanceBitmapHeight = (appearanceBitmap != null) ? appearanceBitmap.getHeight() : 0; + float emojiBitmapHeight = (emojiBitmap != null) ? emojiBitmap.getHeight() : 0; + float spacingBetween = (appearanceBitmapHeight > 0 && emojiBitmapHeight > 0) ? MARGIN : 0; + float totalHeightRequired = appearanceBitmapHeight + emojiBitmapHeight + spacingBetween; + + float bitmapHeightOverflow = Math.max(totalHeightRequired - boundingBox.height(), 0); + + return bitmapHeightOverflow / 2; // distribute the overflow evenly on both sides of the bounding box + } + + private void drawBoundingBox(Canvas c, Face f, Rect boundingBox) { + setValenceOfBoundingBox(f.emotions.getValence()); + c.drawRect(boundingBox.left, + boundingBox.top, + boundingBox.right, + boundingBox.bottom, + boundingBoxPaint); + } + + private void drawAppearanceMarkers(Canvas c, Face f, Rect boundingBox, float offset) { + Bitmap bitmap = getAppearanceBitmapForFace(f); + if (bitmap != null) { + drawBitmapIfNotRecycled(c, bitmap, boundingBox.right + MARGIN, boundingBox.bottom - bitmap.getHeight() + offset); + } + } + + private Bitmap getAppearanceBitmapForFace(Face f) { + Bitmap bitmap = null; + switch (f.appearance.getGender()) { + case MALE: + if (Face.GLASSES.YES.equals(f.appearance.getGlasses())) { + bitmap = appearanceMarkerBitmap_genderMale_glassesOn; + } else { + bitmap = appearanceMarkerBitmap_genderMale_glassesOff; + } + break; + case FEMALE: + if (Face.GLASSES.YES.equals(f.appearance.getGlasses())) { + bitmap = appearanceMarkerBitmap_genderFemale_glassesOn; + } else { + bitmap = appearanceMarkerBitmap_genderFemale_glassesOff; + } + break; + case UNKNOWN: + if (Face.GLASSES.YES.equals(f.appearance.getGlasses())) { + bitmap = appearanceMarkerBitmap_genderUnknown_glassesOn; + } else { + bitmap = appearanceMarkerBitmap_genderUnknown_glassesOff; + } + break; + default: + Log.e(LOG_TAG, "Unknown gender: " + f.appearance.getGender()); + } + return bitmap; + } + + private void drawBitmapIfNotRecycled(Canvas c, Bitmap b, float posX, float posY) { + if (!b.isRecycled()) { + c.drawBitmap(b, posX, posY, null); + } + } + + private void drawDominantEmoji(Canvas c, Face f, Rect boundingBox, float offset) { + drawEmojiFromCache(c, f.emojis.getDominantEmoji().name(), boundingBox.right + MARGIN, boundingBox.top - offset); + } + + private void drawDominantEmotion(Canvas c, Face f, Rect boundingBox) { + Pair dominantMetric = findDominantEmotion(f); + + if (dominantMetric == null || dominantMetric.first.isEmpty()) { + return; + } + + String emotionText = dominantMetric.first; + String emotionValue = Math.round(dominantMetric.second) + "%"; + + Rect emotionTextBounds = new Rect(); + config.dominantEmotionLabelPaint.getTextBounds(emotionText, 0, emotionText.length(), emotionTextBounds); + + Rect emotionValueBounds = new Rect(); + config.dominantEmotionValuePaint.getTextBounds(emotionValue, 0, emotionValue.length(), emotionValueBounds); + + float drawAtX = boundingBox.exactCenterX(); + float drawAtY = boundingBox.bottom + MARGIN + emotionTextBounds.height(); + c.drawText(emotionText, drawAtX, drawAtY, config.dominantEmotionLabelPaint); + + //draws the colored bar that appears behind our score + drawAtY += MARGIN + emotionValueBounds.height(); + int halfWidth = Math.round(config.metricBarWidth / 200.0f * dominantMetric.second); + c.drawRect(drawAtX - halfWidth, drawAtY - emotionValueBounds.height(), drawAtX + halfWidth, drawAtY, config.dominantEmotionMetricBarPaint); + + //draws the score + c.drawText(emotionValue, drawAtX, drawAtY, config.dominantEmotionValuePaint); + } + + private Pair findDominantEmotion(Face f) { + String dominantMetricName = ""; + Float dominantMetricValue = 50.0f; // no emotion is dominant unless at least greater than this value + + if (f.emotions.getAnger() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.ANGER); + dominantMetricValue = f.emotions.getAnger(); + } + if (f.emotions.getContempt() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.CONTEMPT); + dominantMetricValue = f.emotions.getContempt(); + } + if (f.emotions.getDisgust() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.DISGUST); + dominantMetricValue = f.emotions.getDisgust(); + } + if (f.emotions.getFear() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.FEAR); + dominantMetricValue = f.emotions.getFear(); + } + if (f.emotions.getJoy() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.JOY); + dominantMetricValue = f.emotions.getJoy(); + } + if (f.emotions.getSadness() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.SADNESS); + dominantMetricValue = f.emotions.getSadness(); + } + if (f.emotions.getSurprise() > dominantMetricValue) { + dominantMetricName = MetricsManager.getCapitalizedName(MetricsManager.Emotions.SURPRISE); + dominantMetricValue = f.emotions.getSurprise(); + } + // Ignore VALENCE and ENGAGEMENT + + if (dominantMetricName.isEmpty()) { + return null; + } else { + return new Pair<>(dominantMetricName, dominantMetricValue); + } + } + + void drawEmojiFromCache(Canvas c, String emojiName, float markerPosX, float markerPosY) { + Bitmap emojiBitmap; + + try { + emojiBitmap = getEmojiBitmapByName(emojiName); + } catch (FileNotFoundException e) { + Log.e(LOG_TAG, "Error, file not found!", e); + return; + } + + if (emojiBitmap != null) { + c.drawBitmap(emojiBitmap, markerPosX, markerPosY, null); + } + } + + private Bitmap getDominantEmojiBitmapForFace(Face f) { + try { + return getEmojiBitmapByName(f.emojis.getDominantEmoji().name()); + } catch (FileNotFoundException e) { + Log.e(LOG_TAG, "Dominant emoji bitmap not available", e); + return null; + } + } + + Bitmap getEmojiBitmapByName(String emojiName) throws FileNotFoundException { + // No bitmap necessary if emoji is unknown + if (emojiName.equals(Face.EMOJI.UNKNOWN.name())) { + return null; + } + + String emojiResourceName = emojiName.trim().replace(' ', '_').toLowerCase(Locale.US).concat("_emoji"); + String emojiFileName = emojiResourceName + ".png"; + + //Try to get the emoji from the cache + Bitmap desiredEmojiBitmap = emojiMarkerBitmapToEmojiTypeMap.get(emojiFileName); + + if (desiredEmojiBitmap != null) { + //emoji bitmap found in the cache + return desiredEmojiBitmap; + } + + //Cache miss, try and load the bitmap from disk + desiredEmojiBitmap = ImageHelper.loadBitmapFromInternalStorage(getContext(), emojiFileName); + + if (desiredEmojiBitmap != null) { + //emoji bitmap found in the app storage + //Bitmap loaded, add to cache for subsequent use. + emojiMarkerBitmapToEmojiTypeMap.put(emojiFileName, desiredEmojiBitmap); + return desiredEmojiBitmap; + } + + Log.d(LOG_TAG, "Emoji not found on disk: " + emojiFileName); + + //Still unable to find the file, try to locate the emoji resource + final int resourceId = getDrawable(getContext(), emojiFileName); + + if (resourceId == 0) { + //unrecognised emoji file name + throw new FileNotFoundException("Resource not found for file named: " + emojiFileName); + } + + desiredEmojiBitmap = BitmapFactory.decodeResource(getResources(), resourceId); + + if (desiredEmojiBitmap == null) { + //still unable to load the resource from the file + throw new FileNotFoundException("Resource id [" + resourceId + "] but could not load bitmap: " + emojiFileName); + } + + //Bitmap loaded, add to cache for subsequent use. + emojiMarkerBitmapToEmojiTypeMap.put(emojiFileName, desiredEmojiBitmap); + + return desiredEmojiBitmap; + } + } + + class DrawingViewConfig { + private int imageWidth = 1; + private int surfaceViewWidth = 0; + private int surfaceViewHeight = 0; + private float screenToImageRatio = 0; + private int drawThickness = 0; + private boolean isDrawPointsEnabled = true; //by default, have the drawing thread draw tracking dots + private boolean isDimensionsNeeded = true; + private boolean isDrawAppearanceMarkersEnabled = true; //by default, draw the appearance markers + private boolean isDrawEmojiMarkersEnabled = true; //by default, draw the dominant emoji markers + + private Paint dominantEmotionLabelPaint; + private Paint dominantEmotionMetricBarPaint; + private Paint dominantEmotionValuePaint; + private int metricBarWidth; + + public void setDominantEmotionLabelPaints(Paint labelPaint, Paint valuePaint) { + dominantEmotionLabelPaint = labelPaint; + dominantEmotionValuePaint = valuePaint; + } + + public void setDominantEmotionMetricBarConfig(Paint metricBarPaint, int metricBarWidth) { + dominantEmotionMetricBarPaint = metricBarPaint; + this.metricBarWidth = metricBarWidth; + } + + public void updateViewDimensions(int surfaceViewWidth, int surfaceViewHeight, int imageWidth, int imageHeight) { + if (surfaceViewWidth <= 0 || surfaceViewHeight <= 0 || imageWidth <= 0 || imageHeight <= 0) { + throw new IllegalArgumentException("All dimensions submitted to updateViewDimensions() must be positive"); + } + this.imageWidth = imageWidth; + this.surfaceViewWidth = surfaceViewWidth; + this.surfaceViewHeight = surfaceViewHeight; + screenToImageRatio = (float) surfaceViewWidth / imageWidth; + isDimensionsNeeded = false; + } + + public void setDrawThickness(int t) { + + if (t <= 0) { + throw new IllegalArgumentException("Thickness must be positive."); + } + + drawThickness = t; + } + } } diff --git a/app/src/main/java/com/affectiva/affdexme/ImageHelper.java b/app/src/main/java/com/affectiva/affdexme/ImageHelper.java new file mode 100644 index 0000000..533da7c --- /dev/null +++ b/app/src/main/java/com/affectiva/affdexme/ImageHelper.java @@ -0,0 +1,306 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + +package com.affectiva.affdexme; + +import android.content.ContentValues; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.ImageFormat; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.graphics.YuvImage; +import android.graphics.drawable.Drawable; +import android.provider.MediaStore; +import android.support.annotation.NonNull; +import android.util.DisplayMetrics; +import android.util.Log; +import android.widget.ImageView; + +import com.affectiva.android.affdex.sdk.Frame; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; + +public class ImageHelper { + + private static final String LOG_TAG = "AffdexMe"; + + // Prevent instantiation of this object + private ImageHelper() { + } + + public static boolean checkIfImageFileExists(@NonNull final Context context, @NonNull final String fileName) { + + // path to /data/data/yourapp/app_data/images + File directory = context.getDir("images", Context.MODE_PRIVATE); + + // File location to save image + File imagePath = new File(directory, fileName); + + return imagePath.exists(); + } + + public static boolean deleteImageFile(@NonNull final Context context, @NonNull final String fileName) { + // path to /data/data/yourapp/app_data/images + File directory = context.getDir("images", Context.MODE_PRIVATE); + + // File location to save image + File imagePath = new File(directory, fileName); + + return imagePath.delete(); + } + + public static void resizeAndSaveResourceImageToInternalStorage(@NonNull final Context context, @NonNull final String fileName, @NonNull final String resourceName) throws FileNotFoundException { + final int resourceId = context.getResources().getIdentifier(resourceName, "drawable", context.getPackageName()); + + if (resourceId == 0) { + //unrecognised resource + throw new FileNotFoundException("Resource not found for file named: " + resourceName); + } + resizeAndSaveResourceImageToInternalStorage(context, fileName, resourceId); + } + + public static void resizeAndSaveResourceImageToInternalStorage(@NonNull final Context context, @NonNull final String fileName, final int resourceId) { + Resources resources = context.getResources(); + Bitmap sourceBitmap = BitmapFactory.decodeResource(resources, resourceId); + Bitmap resizedBitmap = resizeBitmapForDeviceDensity(context, sourceBitmap); + saveBitmapToInternalStorage(context, resizedBitmap, fileName); + sourceBitmap.recycle(); + resizedBitmap.recycle(); + } + + public static Bitmap resizeBitmapForDeviceDensity(@NonNull final Context context, @NonNull final Bitmap sourceBitmap) { + DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + + int targetWidth = Math.round(sourceBitmap.getWidth() * metrics.density); + int targetHeight = Math.round(sourceBitmap.getHeight() * metrics.density); + + return Bitmap.createScaledBitmap(sourceBitmap, targetWidth, targetHeight, false); + } + + public static void saveBitmapToInternalStorage(@NonNull final Context context, @NonNull final Bitmap bitmapImage, @NonNull final String fileName) { + + // path to /data/data/yourapp/app_data/images + File directory = context.getDir("images", Context.MODE_PRIVATE); + + // File location to save image + File imagePath = new File(directory, fileName); + + FileOutputStream fos = null; + try { + fos = new FileOutputStream(imagePath); + + // Use the compress method on the BitMap object to write image to the OutputStream + bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); + fos.flush(); + } catch (FileNotFoundException e) { + Log.e(LOG_TAG, "Exception while trying to save file to internal storage: " + imagePath, e); + } catch (IOException e) { + Log.e(LOG_TAG, "Exception while trying to flush the output stream", e); + } finally { + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + Log.e(LOG_TAG, "Exception wile trying to close file output stream.", e); + } + } + } + } + + public static Bitmap loadBitmapFromInternalStorage(@NonNull final Context applicationContext, @NonNull final String fileName) { + + // path to /data/data/yourapp/app_data/images + File directory = applicationContext.getDir("images", Context.MODE_PRIVATE); + + // File location to save image + File imagePath = new File(directory, fileName); + + try { + return BitmapFactory.decodeStream(new FileInputStream(imagePath)); + } catch (FileNotFoundException e) { + Log.e(LOG_TAG, "Exception wile trying to load image: " + imagePath, e); + return null; + } + } + + public static void preproccessImageIfNecessary(@NonNull final Context context, @NonNull final String fileName, @NonNull final String resourceName) { + // Set this to true to force the app to always load the images for debugging purposes + final boolean DEBUG = false; + + if (ImageHelper.checkIfImageFileExists(context, fileName)) { + // Image file already exists, no need to load the file again. + + if (DEBUG) { + Log.d(LOG_TAG, "DEBUG: Deleting: " + fileName); + ImageHelper.deleteImageFile(context, fileName); + } else { + return; + } + } + + try { + ImageHelper.resizeAndSaveResourceImageToInternalStorage(context, fileName, resourceName); + Log.d(LOG_TAG, "Resized and saved image: " + fileName); + } catch (FileNotFoundException e) { + Log.e(LOG_TAG, "Unable to process image: " + fileName, e); + throw new RuntimeException(e); + } + } + + /** + * Returns the bitmap position inside an imageView. + * Source: http://stackoverflow.com/a/26930938 + * Author: http://stackoverflow.com/users/1474079/chteuchteu + * + * @param imageView source ImageView + * @return 0: left, 1: top, 2: width, 3: height + */ + public static int[] getBitmapPositionInsideImageView(@NonNull final ImageView imageView) { + int[] ret = new int[4]; + + if (imageView.getDrawable() == null) + return ret; + + // Get image dimensions + // Get image matrix values and place them in an array + float[] f = new float[9]; + imageView.getImageMatrix().getValues(f); + + // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY) + final float scaleX = f[Matrix.MSCALE_X]; + final float scaleY = f[Matrix.MSCALE_Y]; + + // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight) + final Drawable d = imageView.getDrawable(); + final int origW = d.getIntrinsicWidth(); + final int origH = d.getIntrinsicHeight(); + + // Calculate the actual dimensions + final int actW = Math.round(origW * scaleX); + final int actH = Math.round(origH * scaleY); + + ret[2] = actW; + ret[3] = actH; + + // Get image position + // We assume that the image is centered into ImageView + int imgViewW = imageView.getWidth(); + int imgViewH = imageView.getHeight(); + + int top = (imgViewH - actH) / 2; + int left = (imgViewW - actW) / 2; + + ret[0] = left; + ret[1] = top; + + return ret; + } + + /** + * This is a HACK. + * We need to update the Android SDK to make this process cleaner. + * We should just be able to call frame.getBitmap() and have it return a bitmap no matter what type + * of frame it is. If any conversion between file types needs to take place, it needs to happen + * inside the SDK layer and put the onus on the developer to know how to convert between YUV and ARGB. + * TODO: See above + * + * @param frame - The Frame containing the desired image + * @return - The Bitmap representation of the image + */ + public static Bitmap getBitmapFromFrame(@NonNull final Frame frame) { + Bitmap bitmap; + + if (frame instanceof Frame.BitmapFrame) { + bitmap = ((Frame.BitmapFrame) frame).getBitmap(); + } else { //frame is ByteArrayFrame + switch (frame.getColorFormat()) { + case RGBA: + bitmap = getBitmapFromRGBFrame(frame); + break; + case YUV_NV21: + bitmap = getBitmapFromYuvFrame(frame); + break; + case UNKNOWN_TYPE: + default: + Log.e(LOG_TAG, "Unable to get bitmap from unknown frame type"); + return null; + } + } + + if (bitmap == null || frame.getTargetRotation().toDouble() == 0.0) { + return bitmap; + } else { + return rotateBitmap(bitmap, (float) frame.getTargetRotation().toDouble()); + } + } + + public static Bitmap getBitmapFromRGBFrame(@NonNull final Frame frame) { + byte[] pixels = ((Frame.ByteArrayFrame) frame).getByteArray(); + Bitmap bitmap = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); + bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(pixels)); + return bitmap; + } + + public static Bitmap getBitmapFromYuvFrame(@NonNull final Frame frame) { + byte[] pixels = ((Frame.ByteArrayFrame) frame).getByteArray(); + YuvImage yuvImage = new YuvImage(pixels, ImageFormat.NV21, frame.getWidth(), frame.getHeight(), null); + return convertYuvImageToBitmap(yuvImage); + } + + /** + * Note: This conversion procedure is sloppy and may result in JPEG compression artifacts + * + * @param yuvImage - The YuvImage to convert + * @return - The converted Bitmap + */ + public static Bitmap convertYuvImageToBitmap(@NonNull final YuvImage yuvImage) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 100, out); + byte[] imageBytes = out.toByteArray(); + try { + out.close(); + } catch (IOException e) { + Log.e(LOG_TAG, "Exception while closing output stream", e); + } + return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); + } + + public static Bitmap rotateBitmap(@NonNull final Bitmap source, final float angle) { + Matrix matrix = new Matrix(); + matrix.postRotate(angle); + return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); + } + + public static void saveBitmapToFileAsPng(@NonNull final Bitmap bitmap, @NonNull final File file) throws IOException { + try { + FileOutputStream outputStream = new FileOutputStream(file); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); + bitmap.recycle(); + outputStream.flush(); + outputStream.close(); + } catch (IOException e) { + throw new FileNotFoundException("Unable to save bitmap to file: " + file.getPath() + "\n" + e.getLocalizedMessage()); + } + } + + public static void addPngToGallery(@NonNull final Context context, @NonNull final File imageFile) { + ContentValues values = new ContentValues(); + + values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); + values.put(MediaStore.Images.Media.MIME_TYPE, "image/png"); + values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath()); + + context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); + } +} diff --git a/app/src/main/java/com/affectiva/affdexme/MainActivity.java b/app/src/main/java/com/affectiva/affdexme/MainActivity.java index 45857e8..6e92aed 100644 --- a/app/src/main/java/com/affectiva/affdexme/MainActivity.java +++ b/app/src/main/java/com/affectiva/affdexme/MainActivity.java @@ -1,21 +1,40 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; -import android.app.Activity; +import android.Manifest; +import android.content.Context; +import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Rect; import android.graphics.Typeface; import android.os.Bundle; +import android.os.Environment; import android.os.SystemClock; import android.preference.PreferenceManager; -import android.util.Log; +import android.support.annotation.NonNull; +import android.support.v4.app.ActivityCompat; +import android.support.v4.content.ContextCompat; +import android.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.text.format.DateFormat; import android.util.DisplayMetrics; +import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; +import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; @@ -23,18 +42,20 @@ import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Method; -import java.util.List; - import com.affectiva.android.affdex.sdk.Frame; import com.affectiva.android.affdex.sdk.Frame.ROTATE; import com.affectiva.android.affdex.sdk.detector.CameraDetector; import com.affectiva.android.affdex.sdk.detector.Detector; import com.affectiva.android.affdex.sdk.detector.Face; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.List; +import java.util.Locale; + /* * AffdexMe is an app that demonstrates the use of the Affectiva Android SDK. It uses the * front-facing camera on your Android device to view, process and analyze live video of your face. @@ -56,27 +77,32 @@ import com.affectiva.android.affdex.sdk.detector.Face; * * In order to use this project, you will need to: * - Obtain the SDK from Affectiva (visit http://www.affdex.com/mobile-sdk) - * - Copy the SDK assets folder contents into this project's assets folder + * - Copy the SDK assets folder contents into this project's assets folder under AffdexMe/app/src/main/assets * - Copy the contents of the SDK's libs folder into this project's libs folder under AffdexMe/app/lib * - Copy the armeabi-v7a folder (found in the SDK libs folder) into this project's jniLibs folder under AffdexMe/app/src/main/jniLibs - * - Add your license file to the /assets/Affdex folder and rename to license.txt. + * - Add your license file to the assets/Affdex folder and rename to license.txt. * (Note: if you name the license file something else you will need to update the licensePath in the initializeCameraDetector() method in MainActivity) * - Build the project * - Run the app on an Android device with a front-facing camera - * - * Copyright (c) 2014 Affectiva. All rights reserved. */ -public class MainActivity extends Activity - implements Detector.FaceListener, Detector.ImageListener, View.OnTouchListener, CameraDetector.CameraEventListener { +public class MainActivity extends AppCompatActivity + implements Detector.FaceListener, Detector.ImageListener, CameraDetector.CameraEventListener, + View.OnTouchListener, ActivityCompat.OnRequestPermissionsResultCallback, DrawingView.DrawingThreadEventListener { - private static final String LOG_TAG = "Affectiva"; + public static final int MAX_SUPPORTED_FACES = 3; + public static final boolean STORE_RAW_SCREENSHOTS = false; // setting to enable saving the raw images when taking screenshots public static final int NUM_METRICS_DISPLAYED = 6; - - //Affectiva SDK Object + private static final String LOG_TAG = "AffdexMe"; + private static final int CAMERA_PERMISSIONS_REQUEST = 42; //value is arbitrary (between 0 and 255) + private static final int EXTERNAL_STORAGE_PERMISSIONS_REQUEST = 73; + int cameraPreviewWidth = 0; + int cameraPreviewHeight = 0; + CameraDetector.CameraType cameraType; + boolean mirrorPoints = false; + private boolean cameraPermissionsAvailable = false; + private boolean storagePermissionsAvailable = false; private CameraDetector detector = null; - - //MetricsManager View UI Objects private RelativeLayout metricViewLayout; private LinearLayout leftMetricsLayout; private LinearLayout rightMetricsLayout; @@ -86,48 +112,206 @@ public class MainActivity extends Activity private TextView fpsPct; private TextView pleaseWaitTextView; private ProgressBar progressBar; - - //Other UI objects - private ViewGroup activityLayout; //top-most ViewGroup in which all content resides private RelativeLayout mainLayout; //layout, to be resized, containing all UI elements private RelativeLayout progressBarLayout; //layout used to show progress circle while camera is starting + private LinearLayout permissionsUnavailableLayout; //layout used to notify the user that not enough permissions have been granted to use the app private SurfaceView cameraView; //SurfaceView used to display camera images private DrawingView drawingView; //SurfaceView containing its own thread, used to draw facial tracking dots private ImageButton settingsButton; private ImageButton cameraButton; - - //Application settings variables - private int detectorProcessRate; + private ImageButton screenshotButton; + private Frame mostRecentFrame; private boolean isMenuVisible = false; private boolean isFPSVisible = false; private boolean isMenuShowingForFirstTime = true; - - //Frames Per Second (FPS) variables private long firstSystemTime = 0; private float numberOfFrames = 0; private long timeToUpdate = 0; - - //Camera-related variables private boolean isFrontFacingCameraDetected = true; private boolean isBackFacingCameraDetected = true; - int cameraPreviewWidth = 0; - int cameraPreviewHeight = 0; - CameraDetector.CameraType cameraType; - boolean mirrorPoints = false; + private boolean multiFaceModeEnabled = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //To maximize UI space, we declare our app to be full-screen + preproccessMetricImages(); setContentView(R.layout.activity_main); - initializeUI(); - + checkForCameraPermissions(); determineCameraAvailability(); - initializeCameraDetector(); } + /** + * Only load the files onto disk the first time the app opens + */ + private void preproccessMetricImages() { + Context context = getBaseContext(); + + for (Face.EMOJI emoji : Face.EMOJI.values()) { + if (emoji.equals(Face.EMOJI.UNKNOWN)) { + continue; + } + String emojiResourceName = emoji.name().trim().replace(' ', '_').toLowerCase(Locale.US).concat("_emoji"); + String emojiFileName = emojiResourceName + ".png"; + ImageHelper.preproccessImageIfNecessary(context, emojiFileName, emojiResourceName); + } + + ImageHelper.preproccessImageIfNecessary(context, "female_glasses.png", "female_glasses"); + ImageHelper.preproccessImageIfNecessary(context, "female_noglasses.png", "female_noglasses"); + ImageHelper.preproccessImageIfNecessary(context, "male_glasses.png", "male_glasses"); + ImageHelper.preproccessImageIfNecessary(context, "male_noglasses.png", "male_noglasses"); + ImageHelper.preproccessImageIfNecessary(context, "unknown_glasses.png", "unknown_glasses"); + ImageHelper.preproccessImageIfNecessary(context, "unknown_noglasses.png", "unknown_noglasses"); + } + + private void checkForCameraPermissions() { + cameraPermissionsAvailable = + ContextCompat.checkSelfPermission( + getApplicationContext(), + Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED; + + if (!cameraPermissionsAvailable) { + + // Should we show an explanation? + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { + + // Show an explanation to the user *asynchronously* -- don't block + // this thread waiting for the user's response! After the user + // sees the explanation, try again to request the permission. + showPermissionExplanationDialog(CAMERA_PERMISSIONS_REQUEST); + } else { + // No explanation needed, we can request the permission. + requestCameraPermissions(); + } + } + } + + private void checkForStoragePermissions() { + storagePermissionsAvailable = + ContextCompat.checkSelfPermission( + getApplicationContext(), + Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; + + if (!storagePermissionsAvailable) { + + // Should we show an explanation? + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { + + // Show an explanation to the user *asynchronously* -- don't block + // this thread waiting for the user's response! After the user + // sees the explanation, try again to request the permission. + showPermissionExplanationDialog(EXTERNAL_STORAGE_PERMISSIONS_REQUEST); + } else { + // No explanation needed, we can request the permission. + requestStoragePermissions(); + } + } else { + takeScreenshot(screenshotButton); + } + } + + private void requestStoragePermissions() { + if (!storagePermissionsAvailable) { + ActivityCompat.requestPermissions( + this, + new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, + EXTERNAL_STORAGE_PERMISSIONS_REQUEST); + + // EXTERNAL_STORAGE_PERMISSIONS_REQUEST is an app-defined int constant that must be between 0 and 255. + // The callback method gets the result of the request. + } + } + + private void requestCameraPermissions() { + if (!cameraPermissionsAvailable) { + ActivityCompat.requestPermissions( + this, + new String[]{Manifest.permission.CAMERA}, + CAMERA_PERMISSIONS_REQUEST); + + // CAMERA_PERMISSIONS_REQUEST is an app-defined int constant that must be between 0 and 255. + // The callback method gets the result of the request. + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + + if (requestCode == CAMERA_PERMISSIONS_REQUEST) { + for (int i = 0; i < permissions.length; i++) { + String permission = permissions[i]; + int grantResult = grantResults[i]; + + if (permission.equals(Manifest.permission.CAMERA)) { + cameraPermissionsAvailable = (grantResult == PackageManager.PERMISSION_GRANTED); + } + } + + if (!cameraPermissionsAvailable) { + permissionsUnavailableLayout.setVisibility(View.VISIBLE); + } else { + permissionsUnavailableLayout.setVisibility(View.GONE); + } + } + + if (requestCode == EXTERNAL_STORAGE_PERMISSIONS_REQUEST) { + for (int i = 0; i < permissions.length; i++) { + String permission = permissions[i]; + int grantResult = grantResults[i]; + + if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { + storagePermissionsAvailable = (grantResult == PackageManager.PERMISSION_GRANTED); + } + } + + if (storagePermissionsAvailable) { + // resume taking the screenshot + takeScreenshot(screenshotButton); + } + } + + } + + private void showPermissionExplanationDialog(int requestCode) { + final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( + MainActivity.this); + + // set title + alertDialogBuilder.setTitle(getResources().getString(R.string.insufficient_permissions)); + + // set dialog message + if (requestCode == CAMERA_PERMISSIONS_REQUEST) { + alertDialogBuilder + .setMessage(getResources().getString(R.string.permissions_camera_needed_explanation)) + .setCancelable(false) + .setPositiveButton(getResources().getString(R.string.understood), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + requestCameraPermissions(); + } + }); + } else if (requestCode == EXTERNAL_STORAGE_PERMISSIONS_REQUEST) { + alertDialogBuilder + .setMessage(getResources().getString(R.string.permissions_storage_needed_explanation)) + .setCancelable(false) + .setPositiveButton(getResources().getString(R.string.understood), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + requestStoragePermissions(); + } + }); + } + + // create alert dialog + AlertDialog alertDialog = alertDialogBuilder.create(); + + // show it + alertDialog.show(); + } + /** * We check to make sure the device has a front-facing camera. * If it does not, we obscure the app with a notice informing the user they cannot @@ -145,22 +329,26 @@ public class MainActivity extends Activity notFoundTextView.setVisibility(View.VISIBLE); } - //TODO: change this to be taken from settings - if (isBackFacingCameraDetected) { - cameraType = CameraDetector.CameraType.CAMERA_BACK; - mirrorPoints = false; - } - if (isFrontFacingCameraDetected) { + //set default camera settings + SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); + + //restore the camera type settings + String cameraTypeName = sharedPreferences.getString("cameraType", CameraDetector.CameraType.CAMERA_FRONT.name()); + if (cameraTypeName.equals(CameraDetector.CameraType.CAMERA_FRONT.name())) { cameraType = CameraDetector.CameraType.CAMERA_FRONT; mirrorPoints = true; + } else { + cameraType = CameraDetector.CameraType.CAMERA_BACK; + mirrorPoints = false; } } void initializeUI() { //Get handles to UI objects - activityLayout = (ViewGroup) findViewById(android.R.id.content); + ViewGroup activityLayout = (ViewGroup) findViewById(android.R.id.content); progressBarLayout = (RelativeLayout) findViewById(R.id.progress_bar_cover); + permissionsUnavailableLayout = (LinearLayout) findViewById(R.id.permissionsUnavialableLayout); metricViewLayout = (RelativeLayout) findViewById(R.id.metric_view_group); leftMetricsLayout = (LinearLayout) findViewById(R.id.left_metrics); rightMetricsLayout = (LinearLayout) findViewById(R.id.right_metrics); @@ -171,8 +359,10 @@ public class MainActivity extends Activity drawingView = (DrawingView) findViewById(R.id.drawing_view); settingsButton = (ImageButton) findViewById(R.id.settings_button); cameraButton = (ImageButton) findViewById(R.id.camera_button); + screenshotButton = (ImageButton) findViewById(R.id.screenshot_button); progressBar = (ProgressBar) findViewById(R.id.progress_bar); pleaseWaitTextView = (TextView) findViewById(R.id.please_wait_textview); + Button retryPermissionsButton = (Button) findViewById(R.id.retryPermissionsButton); //Initialize views to display metrics metricNames = new TextView[NUM_METRICS_DISPLAYED]; @@ -219,6 +409,9 @@ public class MainActivity extends Activity //Attach event listeners to the menu and edit box activityLayout.setOnTouchListener(this); + //Attach event listerner to drawing view + drawingView.setEventListener(this); + /* * This app sets the View.SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. Unfortunately, this flag causes * Android to steal the first touch event after the navigation bar has been hidden, a touch event @@ -229,12 +422,19 @@ public class MainActivity extends Activity activityLayout.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int uiCode) { - if ((uiCode == 0) && (isMenuVisible == false)) { + if ((uiCode == 0) && (!isMenuVisible)) { setMenuVisible(true); } } }); + + retryPermissionsButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + requestCameraPermissions(); + } + }); } void initializeCameraDetector() { @@ -242,10 +442,9 @@ public class MainActivity extends Activity * the camera. If a SurfaceView is passed in as the last argument to the constructor, * that view will be painted with what the camera sees. */ + detector = new CameraDetector(this, cameraType, cameraView, (multiFaceModeEnabled ? MAX_SUPPORTED_FACES : 1), Detector.FaceDetectorMode.LARGE_FACES); - detector = new CameraDetector(this, CameraDetector.CameraType.CAMERA_FRONT, cameraView); - - // update the license path here if you name your file something else + // update the license path here if you name your file something else detector.setLicensePath("license.txt"); detector.setImageListener(this); detector.setFaceListener(this); @@ -258,73 +457,132 @@ public class MainActivity extends Activity @Override public void onResume() { super.onResume(); + checkForCameraPermissions(); restoreApplicationSettings(); setMenuVisible(true); isMenuShowingForFirstTime = true; } + private void setMultiFaceModeEnabled(boolean isEnabled) { + + //if setting change is necessary + if (isEnabled != multiFaceModeEnabled) { + // change the setting, stop the detector, and reinitialize it to change the setting + multiFaceModeEnabled = isEnabled; + stopDetector(); + initializeCameraDetector(); + } + } + /* * We use the Shared Preferences object to restore application settings. */ public void restoreApplicationSettings() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); - //restore camera processing rate - detectorProcessRate = PreferencesUtils.getFrameProcessingRate(sharedPreferences); - detector.setMaxProcessRate(detectorProcessRate); + //restore the camera type settings + String cameraTypeName = sharedPreferences.getString("cameraType", CameraDetector.CameraType.CAMERA_FRONT.name()); + if (cameraTypeName.equals(CameraDetector.CameraType.CAMERA_FRONT.name())) { + setCameraType(CameraDetector.CameraType.CAMERA_FRONT); + } else { + setCameraType(CameraDetector.CameraType.CAMERA_BACK); + } - if (sharedPreferences.getBoolean("fps",isFPSVisible)) { //restore isFPSMetricVisible + //restore the multiface mode setting to reset the detector if necessary + if (sharedPreferences.getBoolean("multiface", false)) { // default to false + setMultiFaceModeEnabled(true); + } else { + setMultiFaceModeEnabled(false); + } + + //restore camera processing rate + int detectorProcessRate = PreferencesUtils.getFrameProcessingRate(sharedPreferences); + detector.setMaxProcessRate(detectorProcessRate); + drawingView.invalidateDimensions(); + + if (sharedPreferences.getBoolean("fps", isFPSVisible)) { //restore isFPSMetricVisible setFPSVisible(true); } else { setFPSVisible(false); } - if (sharedPreferences.getBoolean("track",drawingView.getDrawPointsEnabled())) { //restore isTrackingDotsVisible + if (sharedPreferences.getBoolean("track", drawingView.getDrawPointsEnabled())) { //restore isTrackingDotsVisible setTrackPoints(true); } else { setTrackPoints(false); } - if (sharedPreferences.getBoolean("measurements",drawingView.getDrawMeasurementsEnabled())) { //restore show measurements - setShowMeasurements(true); + if (sharedPreferences.getBoolean("appearance", drawingView.getDrawAppearanceMarkersEnabled())) { + detector.setDetectAllAppearance(true); + setShowAppearance(true); } else { - setShowMeasurements(false); + detector.setDetectAllAppearance(false); + setShowAppearance(false); + } + + if (sharedPreferences.getBoolean("emoji", drawingView.getDrawEmojiMarkersEnabled())) { + detector.setDetectAllEmojis(true); + setShowEmoji(true); + } else { + detector.setDetectAllEmojis(false); + setShowEmoji(false); } //populate metric displays for (int n = 0; n < NUM_METRICS_DISPLAYED; n++) { - activateMetric(n,PreferencesUtils.getMetricFromPrefs(sharedPreferences, n)); + activateMetric(n, PreferencesUtils.getMetricFromPrefs(sharedPreferences, n)); + } + + //if we are in multiface mode, we need to enable the detection of all emotions + if (multiFaceModeEnabled) { + detector.setDetectAllEmotions(true); } } /** * Populates a TextView to display a metric name and readies a MetricDisplay to display the value. * Uses reflection to: - * -enable the corresponding metric in the Detector object by calling Detector.setDetect() - * -save the Method object that will be invoked on the Face object received in onImageResults() to get the metric score + * -enable the corresponding metric in the Detector object by calling Detector.setDetect() + * -save the Method object that will be invoked on the Face object received in onImageResults() to get the metric score */ void activateMetric(int index, MetricsManager.Metrics metric) { - metricNames[index].setText(MetricsManager.getUpperCaseName(metric)); Method getFaceScoreMethod = null; //The method that will be used to get a metric score + try { - //Enable metric detection - Detector.class.getMethod("setDetect" + MetricsManager.getCamelCase(metric), boolean.class).invoke(detector, true); + switch (metric.getType()) { + case Emotion: + Detector.class.getMethod("setDetect" + MetricsManager.getCamelCase(metric), boolean.class).invoke(detector, true); + metricNames[index].setText(MetricsManager.getUpperCaseName(metric)); + getFaceScoreMethod = Face.Emotions.class.getMethod("get" + MetricsManager.getCamelCase(metric)); - if (metric.getType() == MetricsManager.MetricType.Emotion) { - getFaceScoreMethod = Face.Emotions.class.getMethod("get" + MetricsManager.getCamelCase(metric), null); - - //The MetricDisplay for Valence is unique; it shades it color depending on the metric value - if (metric == MetricsManager.Emotions.VALENCE) { - metricDisplays[index].setIsShadedMetricView(true); - } else { - metricDisplays[index].setIsShadedMetricView(false); - } - } else if (metric.getType() == MetricsManager.MetricType.Expression) { - getFaceScoreMethod = Face.Expressions.class.getMethod("get" + MetricsManager.getCamelCase(metric),null); + //The MetricDisplay for Valence is unique; it shades it color depending on the metric value + if (metric == MetricsManager.Emotions.VALENCE) { + metricDisplays[index].setIsShadedMetricView(true); + } else { + metricDisplays[index].setIsShadedMetricView(false); + } + break; + case Expression: + Detector.class.getMethod("setDetect" + MetricsManager.getCamelCase(metric), boolean.class).invoke(detector, true); + metricNames[index].setText(MetricsManager.getUpperCaseName(metric)); + getFaceScoreMethod = Face.Expressions.class.getMethod("get" + MetricsManager.getCamelCase(metric)); + break; + case Emoji: + detector.setDetectAllEmojis(true); + MetricsManager.Emojis emoji = ((MetricsManager.Emojis) metric); + String metricTitle = emoji.getDisplayName(); // + " " + emoji.getUnicodeForEmoji(); + metricNames[index].setText(metricTitle); + Log.d(LOG_TAG, "Getter Method: " + "get" + MetricsManager.getCamelCase(metric)); + getFaceScoreMethod = Face.Emojis.class.getMethod("get" + MetricsManager.getCamelCase(metric)); + break; } - } catch (Exception e) { - Log.e(LOG_TAG,String.format("Error using reflection to generate methods for %s",metric.toString())); + } catch (NoSuchMethodException e) { + Log.e(LOG_TAG, String.format("No such method while using reflection to generate methods for %s", metric.toString()), e); + } catch (InvocationTargetException e) { + Log.e(LOG_TAG, String.format("Invocation error while using reflection to generate methods for %s", metric.toString()), e); + } catch (IllegalAccessException e) { + Log.e(LOG_TAG, String.format("Illegal access error while using reflection to generate methods for %s", metric.toString()), e); } metricDisplays[index].setMetricToDisplay(metric, getFaceScoreMethod); @@ -332,7 +590,7 @@ public class MainActivity extends Activity /** * Reset the variables used to calculate processed frames per second. - * **/ + **/ public void resetFPSCalculations() { firstSystemTime = SystemClock.elapsedRealtime(); timeToUpdate = firstSystemTime + 1000L; @@ -358,6 +616,12 @@ public class MainActivity extends Activity void mainWindowResumedTasks() { + //Notify the user that they can't use the app without authorizing these permissions. + if (!cameraPermissionsAvailable) { + permissionsUnavailableLayout.setVisibility(View.VISIBLE); + return; + } + startDetector(); if (!drawingView.isDimensionsNeeded()) { @@ -388,8 +652,6 @@ public class MainActivity extends Activity } } - - @Override public void onFaceDetectionStarted() { leftMetricsLayout.animate().alpha(1); //make left and right metrics appear @@ -414,6 +676,8 @@ public class MainActivity extends Activity */ @Override public void onImageResults(List faces, Frame image, float timeStamp) { + mostRecentFrame = image; + //If the faces object is null, we received an unprocessed frame if (faces == null) { return; @@ -423,31 +687,131 @@ public class MainActivity extends Activity performFPSCalculations(); //If faces.size() is 0, we received a frame in which no face was detected - if (faces.size() == 0) { - drawingView.updatePoints(null, mirrorPoints); //the drawingView takes null points to mean it doesn't have to draw anything - return; - } + if (faces.size() <= 0) { + drawingView.invalidatePoints(); + } else if (faces.size() == 1) { + metricViewLayout.setVisibility(View.VISIBLE); - //The SDK currently detects one face at a time, so we recover it using .get(0). - //'0' indicates we are recovering the first face. - Face face = faces.get(0); + //update metrics with latest face information. The metrics are displayed on a MetricView, a custom view with a .setScore() method. + for (MetricDisplay metricDisplay : metricDisplays) { + updateMetricScore(metricDisplay, faces.get(0)); + } - //update metrics with latest face information. The metrics are displayed on a MetricView, a custom view with a .setScore() method. - for (MetricDisplay metricDisplay : metricDisplays) { - updateMetricScore(metricDisplay,face); - } + /** + * If the user has selected to have any facial attributes drawn, we use face.getFacePoints() to send those points + * to our drawing thread and also inform the thread what the valence score was, as that will determine the color + * of the bounding box. + */ + if (drawingView.getDrawPointsEnabled() || drawingView.getDrawAppearanceMarkersEnabled() || drawingView.getDrawEmojiMarkersEnabled()) { + drawingView.updatePoints(faces, mirrorPoints); + } - /** - * If the user has selected to have facial tracking dots or measurements drawn, we use face.getFacePoints() to send those points - * to our drawing thread and also inform the thread what the valence score was, as that will determine the color - * of the bounding box. - */ - if (drawingView.getDrawPointsEnabled() || drawingView.getDrawMeasurementsEnabled()) { - drawingView.setMetrics(face.measurements.orientation.getRoll(), face.measurements.orientation.getYaw(), face.measurements.orientation.getPitch(), face.measurements.getInterocularDistance(), face.emotions.getValence()); - drawingView.updatePoints(face.getFacePoints(),mirrorPoints); + } else { + // metrics overlay is hidden in multi face mode + metricViewLayout.setVisibility(View.GONE); + + // always update points in multi face mode + drawingView.updatePoints(faces, mirrorPoints); } } + public void takeScreenshot(View view) { + // Check the permissions to see if we are allowed to save the screenshot + if (!storagePermissionsAvailable) { + checkForStoragePermissions(); + return; + } + + drawingView.requestBitmap(); + + /** + * A screenshot of the drawing view is generated and processing continues via the callback + * onBitmapGenerated() which calls processScreenshot(). + */ + } + + private void processScreenshot(Bitmap drawingViewBitmap, boolean alsoSaveRaw) { + if (mostRecentFrame == null) { + Toast.makeText(getApplicationContext(), "No frame detected, aborting screenshot", Toast.LENGTH_SHORT).show(); + return; + } + + if (!storagePermissionsAvailable) { + checkForStoragePermissions(); + return; + } + + Bitmap faceBitmap = ImageHelper.getBitmapFromFrame(mostRecentFrame); + + if (faceBitmap == null) { + Log.e(LOG_TAG, "Unable to generate bitmap for frame, aborting screenshot"); + return; + } + + metricViewLayout.setDrawingCacheEnabled(true); + Bitmap metricsBitmap = Bitmap.createBitmap(metricViewLayout.getDrawingCache()); + metricViewLayout.setDrawingCacheEnabled(false); + + Bitmap finalScreenshot = Bitmap.createBitmap(faceBitmap.getWidth(), faceBitmap.getHeight(), Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(finalScreenshot); + Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); + + canvas.drawBitmap(faceBitmap, 0, 0, paint); + + float scaleFactor = ((float) faceBitmap.getWidth()) / ((float) drawingViewBitmap.getWidth()); + int scaledHeight = Math.round(drawingViewBitmap.getHeight() * scaleFactor); + canvas.drawBitmap(drawingViewBitmap, null, new Rect(0, 0, faceBitmap.getWidth(), scaledHeight), paint); + + scaleFactor = ((float) faceBitmap.getWidth()) / ((float) metricsBitmap.getWidth()); + scaledHeight = Math.round(metricsBitmap.getHeight() * scaleFactor); + canvas.drawBitmap(metricsBitmap, null, new Rect(0, 0, faceBitmap.getWidth(), scaledHeight), paint); + + metricsBitmap.recycle(); + drawingViewBitmap.recycle(); + + Date now = new Date(); + String timestamp = DateFormat.format("yyyy-MM-dd_hh-mm-ss", now).toString(); + File pictureFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AffdexMe"); + if (!pictureFolder.exists()) { + if (!pictureFolder.mkdir()) { + Log.e(LOG_TAG, "Unable to create directory: " + pictureFolder.getAbsolutePath()); + return; + } + } + + String screenshotFileName = timestamp + ".png"; + File screenshotFile = new File(pictureFolder, screenshotFileName); + + try { + ImageHelper.saveBitmapToFileAsPng(finalScreenshot, screenshotFile); + } catch (IOException e) { + String msg = "Unable to save screenshot"; + Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); + Log.e(LOG_TAG, msg, e); + return; + } + ImageHelper.addPngToGallery(getApplicationContext(), screenshotFile); + + if (alsoSaveRaw) { + String rawScreenshotFileName = timestamp + "_raw.png"; + File rawScreenshotFile = new File(pictureFolder, rawScreenshotFileName); + + try { + ImageHelper.saveBitmapToFileAsPng(faceBitmap, rawScreenshotFile); + } catch (IOException e) { + String msg = "Unable to save screenshot"; + Log.e(LOG_TAG, msg, e); + } + ImageHelper.addPngToGallery(getApplicationContext(), rawScreenshotFile); + } + + faceBitmap.recycle(); + finalScreenshot.recycle(); + + String fileSavedMessage = "Screenshot saved to: " + screenshotFile.getPath(); + Toast.makeText(getApplicationContext(), fileSavedMessage, Toast.LENGTH_SHORT).show(); + Log.d(LOG_TAG, fileSavedMessage); + } /** * Use the method that we saved in activateMetric() to get the metric score and display it @@ -458,14 +822,21 @@ public class MainActivity extends Activity float score = Float.NaN; try { - if (metric.getType() == MetricsManager.MetricType.Emotion) { - score = (Float) metricDisplay.getFaceScoreMethod().invoke(face.emotions,null); - metricDisplay.setScore(score); - } else if (metric.getType() == MetricsManager.MetricType.Expression) { - score = (Float) metricDisplay.getFaceScoreMethod().invoke(face.expressions,null); + switch (metric.getType()) { + case Emotion: + score = (Float) metricDisplay.getFaceScoreMethod().invoke(face.emotions); + break; + case Expression: + score = (Float) metricDisplay.getFaceScoreMethod().invoke(face.expressions); + break; + case Emoji: + score = (Float) metricDisplay.getFaceScoreMethod().invoke(face.emojis); + break; + default: + throw new Exception("Unknown Metric Type: " + metric.getType().toString()); } } catch (Exception e) { - Log.e(LOG_TAG,String.format("Error using reflecting to get %s score from face.",metric.toString())); + Log.e(LOG_TAG, String.format("Error using reflecting to get %s score from face.", metric.toString())); } metricDisplay.setScore(score); } @@ -481,8 +852,8 @@ public class MainActivity extends Activity numberOfFrames += 1; long currentTime = SystemClock.elapsedRealtime(); if (currentTime > timeToUpdate) { - float framesPerSecond = (numberOfFrames/(float)(currentTime - firstSystemTime))*1000f; - fpsPct.setText(String.format(" %.1f",framesPerSecond)); + float framesPerSecond = (numberOfFrames / (float) (currentTime - firstSystemTime)) * 1000f; + fpsPct.setText(String.format(" %.1f", framesPerSecond)); timeToUpdate = currentTime + 1000L; } } @@ -507,33 +878,34 @@ public class MainActivity extends Activity try { detector.stop(); } catch (Exception e) { - Log.e(LOG_TAG,e.getMessage()); + Log.e(LOG_TAG, e.getMessage()); } } detector.setDetectAllEmotions(false); detector.setDetectAllExpressions(false); + detector.setDetectAllAppearance(false); + detector.setDetectAllEmojis(false); } - /** * When the user taps the screen, hide the menu if it is visible and show it if it is hidden. - * **/ - void setMenuVisible(boolean b){ + **/ + void setMenuVisible(boolean b) { isMenuShowingForFirstTime = false; isMenuVisible = b; if (b) { settingsButton.setVisibility(View.VISIBLE); cameraButton.setVisibility(View.VISIBLE); + screenshotButton.setVisibility(View.VISIBLE); //We display the navigation bar again getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - } - else { + } else { //We hide the navigation bar getWindow().getDecorView().setSystemUiVisibility( @@ -541,12 +913,10 @@ public class MainActivity extends Activity | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE); - - + | View.SYSTEM_UI_FLAG_FULLSCREEN); settingsButton.setVisibility(View.INVISIBLE); cameraButton.setVisibility(View.INVISIBLE); + screenshotButton.setVisibility(View.INVISIBLE); } } @@ -568,10 +938,15 @@ public class MainActivity extends Activity drawingView.setDrawPointsEnabled(b); } - void setShowMeasurements(boolean b) { - drawingView.setDrawMeasurementsEnabled(b); + void setShowAppearance(boolean b) { + drawingView.setDrawAppearanceMarkersEnabled(b); } + void setShowEmoji(boolean b) { + drawingView.setDrawEmojiMarkersEnabled(b); + } + + void setFPSVisible(boolean b) { isFPSVisible = b; if (b) { @@ -595,14 +970,7 @@ public class MainActivity extends Activity startActivity(new Intent(this, SettingsActivity.class)); } - /* onCameraStarted is a feature of SDK 2.02, commenting out for 2.01 - @Override - public void onCameraStarted(boolean b, Throwable throwable) { - if (throwable != null) { - Toast.makeText(this,"Failed to start camera.",Toast.LENGTH_LONG).show(); - } - }*/ - + @SuppressWarnings("SuspiciousNameCombination") @Override public void onCameraSizeSelected(int cameraWidth, int cameraHeight, ROTATE rotation) { if (rotation == ROTATE.BY_90_CCW || rotation == ROTATE.BY_90_CW) { @@ -612,7 +980,7 @@ public class MainActivity extends Activity cameraPreviewWidth = cameraWidth; cameraPreviewHeight = cameraHeight; } - drawingView.setThickness((int)(cameraPreviewWidth/100f)); + drawingView.setThickness((int) (cameraPreviewWidth / 100f)); mainLayout.post(new Runnable() { @Override @@ -626,21 +994,21 @@ public class MainActivity extends Activity if (cameraPreviewWidth == 0 || cameraPreviewHeight == 0 || layoutWidth == 0 || layoutHeight == 0) return; - float layoutAspectRatio = (float)layoutWidth/layoutHeight; - float cameraPreviewAspectRatio = (float)cameraPreviewWidth/cameraPreviewHeight; + float layoutAspectRatio = (float) layoutWidth / layoutHeight; + float cameraPreviewAspectRatio = (float) cameraPreviewWidth / cameraPreviewHeight; int newWidth; int newHeight; if (cameraPreviewAspectRatio > layoutAspectRatio) { newWidth = layoutWidth; - newHeight =(int) (layoutWidth / cameraPreviewAspectRatio); + newHeight = (int) (layoutWidth / cameraPreviewAspectRatio); } else { newWidth = (int) (layoutHeight * cameraPreviewAspectRatio); newHeight = layoutHeight; } - drawingView.updateViewDimensions(newWidth,newHeight,cameraPreviewWidth,cameraPreviewHeight); + drawingView.updateViewDimensions(newWidth, newHeight, cameraPreviewWidth, cameraPreviewHeight); ViewGroup.LayoutParams params = mainLayout.getLayoutParams(); params.height = newHeight; @@ -654,32 +1022,54 @@ public class MainActivity extends Activity } - public void camera_button_click(View view) { - if (cameraType == CameraDetector.CameraType.CAMERA_FRONT) { - if (isBackFacingCameraDetected) { - cameraType = CameraDetector.CameraType.CAMERA_BACK; - mirrorPoints = false; - } else { - Toast.makeText(this,"No back-facing camera found",Toast.LENGTH_LONG).show(); - } - } else if (cameraType == CameraDetector.CameraType.CAMERA_BACK) { - if (isFrontFacingCameraDetected) { - cameraType = CameraDetector.CameraType.CAMERA_FRONT; - mirrorPoints = true; - } else { - Toast.makeText(this,"No front-facing camera found",Toast.LENGTH_LONG).show(); - } - } + //Toggle the camera setting + setCameraType(cameraType == CameraDetector.CameraType.CAMERA_FRONT ? CameraDetector.CameraType.CAMERA_BACK : CameraDetector.CameraType.CAMERA_FRONT); + } - performFaceDetectionStoppedTasks(); + private void setCameraType(CameraDetector.CameraType type) { + SharedPreferences.Editor preferencesEditor = PreferenceManager.getDefaultSharedPreferences(this).edit(); + + //If a settings change is necessary + if (cameraType != type) { + switch (type) { + case CAMERA_BACK: + if (isBackFacingCameraDetected) { + cameraType = CameraDetector.CameraType.CAMERA_BACK; + mirrorPoints = false; + } else { + Toast.makeText(this, "No back-facing camera found", Toast.LENGTH_LONG).show(); + return; + } + break; + case CAMERA_FRONT: + if (isFrontFacingCameraDetected) { + cameraType = CameraDetector.CameraType.CAMERA_FRONT; + mirrorPoints = true; + } else { + Toast.makeText(this, "No front-facing camera found", Toast.LENGTH_LONG).show(); + return; + } + break; + default: + Log.e(LOG_TAG, "Unknown camera type selected"); + } + + performFaceDetectionStoppedTasks(); - try { detector.setCameraType(cameraType); - } catch (Exception e) { - Log.e(LOG_TAG,e.getMessage()); + preferencesEditor.putString("cameraType", cameraType.name()); + preferencesEditor.apply(); } } -} - + @Override + public void onBitmapGenerated(@NonNull final Bitmap bitmap) { + runOnUiThread(new Runnable() { + @Override + public void run() { + processScreenshot(bitmap, STORE_RAW_SCREENSHOTS); + } + }); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/affectiva/affdexme/MetricDisplay.java b/app/src/main/java/com/affectiva/affdexme/MetricDisplay.java index 42f64f2..bf87316 100644 --- a/app/src/main/java/com/affectiva/affdexme/MetricDisplay.java +++ b/app/src/main/java/com/affectiva/affdexme/MetricDisplay.java @@ -1,3 +1,8 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; import android.content.Context; @@ -34,15 +39,17 @@ public class MetricDisplay extends View { public MetricDisplay(Context context) { super(context); - initResources(context,null); + initResources(context, null); } + public MetricDisplay(Context context, AttributeSet attrs) { - super(context,attrs); - initResources(context,attrs); + super(context, attrs); + initResources(context, attrs); } - public MetricDisplay(Context context, AttributeSet attrs, int styleID){ + + public MetricDisplay(Context context, AttributeSet attrs, int styleID) { super(context, attrs, styleID); - initResources(context,attrs); + initResources(context, attrs); } void setIsShadedMetricView(boolean b) { @@ -65,11 +72,11 @@ public class MetricDisplay extends View { //load and parse XML attributes if (attrs != null) { - TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.custom_attributes,0,0); + TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.custom_attributes, 0, 0); textPaint.setColor(a.getColor(R.styleable.custom_attributes_textColor, Color.BLACK)); textSize = a.getDimensionPixelSize(R.styleable.custom_attributes_textSize, textSize); textPaint.setTextSize(textSize); - halfWidth = a.getDimensionPixelSize(R.styleable.custom_attributes_barLength,100)/2; + halfWidth = a.getDimensionPixelSize(R.styleable.custom_attributes_metricBarLength, 100) / 2; a.recycle(); } else { textPaint.setColor(Color.BLACK); @@ -83,7 +90,6 @@ public class MetricDisplay extends View { */ height = textSize; textBottom = height - 5; - } public void setMetricToDisplay(MetricsManager.Metrics metricToDisplay, Method faceScoreMethod) { @@ -103,7 +109,7 @@ public class MetricDisplay extends View { textPaint.setTypeface(face); } - public void setScore(float s){ + public void setScore(float s) { text = String.format("%.0f%%", s); //change the text of the view //shading mode is turned on for Valence, which causes this view to shade its color according @@ -117,11 +123,11 @@ public class MetricDisplay extends View { right = midX + (halfWidth * (-s / 100)); } if (s > 0) { - float colorScore = ((100f-s)/100f)*255; - boxPaint.setColor(Color.rgb((int)colorScore,255,(int)colorScore)); + float colorScore = ((100f - s) / 100f) * 255; + boxPaint.setColor(Color.rgb((int) colorScore, 255, (int) colorScore)); } else { - float colorScore = ((100f+s)/100f)*255; - boxPaint.setColor(Color.rgb(255,(int)colorScore,(int)colorScore)); + float colorScore = ((100f + s) / 100f) * 255; + boxPaint.setColor(Color.rgb(255, (int) colorScore, (int) colorScore)); } } else { left = midX - (halfWidth * (s / 100)); //change the coordinates at which the colored bar will be drawn @@ -133,29 +139,27 @@ public class MetricDisplay extends View { /** * set our view to be the minimum of the sizes that Android will allow and our desired sizes - * **/ + **/ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - setMeasuredDimension((int)Math.min(MeasureSpec.getSize(widthMeasureSpec), halfWidth *2), (int)Math.min(MeasureSpec.getSize(heightMeasureSpec),height)); + setMeasuredDimension((int) Math.min(MeasureSpec.getSize(widthMeasureSpec), halfWidth * 2), (int) Math.min(MeasureSpec.getSize(heightMeasureSpec), height)); } @Override protected void onSizeChanged(int w, int h, int oldW, int oldH) { - super.onSizeChanged(w,h,oldW,oldH); - midX = w/2; - midY = h/2; + super.onSizeChanged(w, h, oldW, oldH); + midX = w / 2; + midY = h / 2; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //draws the colored bar that appears behind our score - canvas.drawRect(left,top,right,height, boxPaint); + canvas.drawRect(left, top, right, height, boxPaint); //draws the score - canvas.drawText(text,midX , textBottom, textPaint); + canvas.drawText(text, midX, textBottom, textPaint); } - - } diff --git a/app/src/main/java/com/affectiva/affdexme/MetricSelectionFragment.java b/app/src/main/java/com/affectiva/affdexme/MetricSelectionFragment.java index 785b962..61f61de 100644 --- a/app/src/main/java/com/affectiva/affdexme/MetricSelectionFragment.java +++ b/app/src/main/java/com/affectiva/affdexme/MetricSelectionFragment.java @@ -1,3 +1,8 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; import android.app.Activity; @@ -10,6 +15,7 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; +import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.Surface; @@ -24,13 +30,13 @@ import java.util.ArrayList; import java.util.HashMap; import static com.affectiva.affdexme.MainActivity.NUM_METRICS_DISPLAYED; + /** * A fragment to display a graphical menu which allows the user to select which metrics to display. - * */ public class MetricSelectionFragment extends Fragment implements View.OnClickListener { - final static String LOG_TAG = "Affectiva"; + final static String LOG_TAG = "AffdexMe"; int numberOfSelectedItems = 0; @@ -84,13 +90,11 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } ); - Resources res = getResources(); - messageAtOrUnderLimitColor = res.getColor(R.color.white); - messageOverLimitColor = res.getColor(R.color.red); + messageAtOrUnderLimitColor = ContextCompat.getColor(getActivity(), R.color.white); + messageOverLimitColor = ContextCompat.getColor(getActivity(), R.color.red); } - /** * A method to populate the metricSelectors array using information from either a saved instance bundle (if the activity is being re-created) * or sharedPreferences (if the activity is being created for the first time) @@ -110,15 +114,15 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis if (bundle != null) { //if we were passed a bundle, use its data to configure the MetricSelectors for (MetricsManager.Metrics metric : MetricsManager.getAllMetrics()) { - if (bundle.getBoolean(metric.toString(),false)) { - selectItem(metricSelectors.get(metric),true,false); + if (bundle.getBoolean(metric.toString(), false)) { + selectItem(metricSelectors.get(metric), true, false); } } - + } else { //otherwise, we pull the data from application preferences for (int i = 0; i < NUM_METRICS_DISPLAYED; i++) { MetricsManager.Metrics chosenMetric = PreferencesUtils.getMetricFromPrefs(sharedPreferences, i); - selectItem(metricSelectors.get(chosenMetric),true,false); + selectItem(metricSelectors.get(chosenMetric), true, false); } } } @@ -207,7 +211,7 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis Log.e(LOG_TAG, "Desired Column Width too large! Unable to populate Grid"); return; } - int columnWidth = (int)((float) gridWidth / (float)numColumns); + int columnWidth = (int) ((float) gridWidth / (float) numColumns); //This integer reference will be used across methods to keep track of how many rows we have created. //Each method we pass it into leaves it at a value indicating the next row number that views should be added to. @@ -218,6 +222,10 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis addHeader("Expressions", currentRow, numColumns, inflater); addGridItems(currentRow, numColumns, inflater, res, columnWidth, MetricsManager.Expressions.values()); + // If you wanted to add Emoji as selectable metrics, you would uncomment the two lines below +// addHeader("Emoji", currentRow, numColumns, inflater); +// addGridItems(currentRow, numColumns, inflater, res, columnWidth, MetricsManager.Emojis.values()); + gridLayout.setColumnCount(numColumns); gridLayout.setRowCount(currentRow.value); } @@ -253,18 +261,21 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } MetricSelector item = metricSelectors.get(metric); + if (item != null) { + GridLayout.LayoutParams params = new GridLayout.LayoutParams(); + params.width = size; + params.height = size; + params.columnSpec = GridLayout.spec(col); + params.rowSpec = GridLayout.spec(currentRow.value); + item.setLayoutParams(params); - GridLayout.LayoutParams params = new GridLayout.LayoutParams(); - params.width = size; - params.height = size; - params.columnSpec = GridLayout.spec(col); - params.rowSpec = GridLayout.spec(currentRow.value); - item.setLayoutParams(params); - - item.setOnClickListener(this); - gridLayout.addView(item); + item.setOnClickListener(this); + gridLayout.addView(item); + } else { + Log.e(LOG_TAG, "Unknown MetricSelector item for Metric: " + metric.toString()); + } } - currentRow.value +=1; //point currentRow to row where next views should be added + currentRow.value += 1; //point currentRow to row where next views should be added } @Override @@ -294,18 +305,10 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } metricSelector.setIsSelected(isSelected); - //Create and display message at the top - /*String dMetricsChosen; - if (numberOfSelectedItems == 1) { - dMetricsChosen = "1 metric chosen."; - } else { - dMetricsChosen = String.format("%d metrics chosen.",numberOfSelectedItems); - }*/ - if (numberOfSelectedItems == 1) { metricChooserTextView.setText("1 metric chosen."); } else { - metricChooserTextView.setText(String.format("%d metrics chosen.",numberOfSelectedItems)); + metricChooserTextView.setText(String.format("%d metrics chosen.", numberOfSelectedItems)); } if (numberOfSelectedItems <= NUM_METRICS_DISPLAYED) { @@ -313,25 +316,11 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } else { metricChooserTextView.setTextColor(messageOverLimitColor); } - - - - /*if (numberOfSelectedItems < NUM_METRICS_DISPLAYED) { - metricChooserTextView.setTextColor(messageAtOrUnderLimitColor); - metricChooserTextView.setText(String.format("%s Choose %d more.", dMetricsChosen, NUM_METRICS_DISPLAYED - numberOfSelectedItems)); - } else if (numberOfSelectedItems == NUM_METRICS_DISPLAYED) { - metricChooserTextView.setTextColor(messageAtOrUnderLimitColor); - metricChooserTextView.setText(dMetricsChosen); - } else { - metricChooserTextView.setTextColor(messageOverLimitColor); - metricChooserTextView.setText(String.format("%s Please de-select %d.", dMetricsChosen, numberOfSelectedItems - NUM_METRICS_DISPLAYED)); - }*/ - } void clearItems() { for (MetricsManager.Metrics metric : MetricsManager.getAllMetrics()) { - selectItem(metricSelectors.get(metric),false,true); + selectItem(metricSelectors.get(metric), false, true); } updateAllGridItems(); } @@ -349,28 +338,39 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis fragmentMediaPlayer.destroy(); } + /** + * These are not all the MediaPlayer states defined by Android, but they are all the ones we are interested in. + * Note that SafeMediaPlayer never stays in the STOPPED state, so we don't include it. + */ + enum MediaPlayerState { + IDLE, INIT, PREPARED, PLAYING + } + + + interface OnSafeMediaPlayerPreparedListener { + void onSafeMediaPlayerPrepared(); + } + //IntRef represents a reference to a mutable integer value //It is used to keep track of how many rows have been created in the populateGrid() method class IntRef { public int value; + public IntRef() { value = 0; } } - - - /** * The MetricSelector objects in this fragment will play a video when selected. To keep memory usage low, we use only one MediaPlayer * object to control video playback. Video is rendered on a single TextureView. * Chain of events that lead to video playback: - * -When a MetricSelector is clicked, the MediaPlayer.setDataSource() is called to set the video file - * -The TextureView is added to the view hierarchy of the MetricSelector, causing the onSurfaceTextureAvailable callback to fire - * -The TextureView is bound to the MediaPlayer through MediaPlayer.setSurface(), then MediaPlayer.prepareAsync() is called - * -Once preparation is complete, MediaPlayer.start() is called - * -MediaPlayer.stop() will be called when playback finishes or the item has been de-selected, at which point the TextureView will - * be removed from the MetricSelector's view hierarchy, causing onSurfaceTextureDestroyed(), where we call MediaPlayer.setSurface(null) + * -When a MetricSelector is clicked, the MediaPlayer.setDataSource() is called to set the video file + * -The TextureView is added to the view hierarchy of the MetricSelector, causing the onSurfaceTextureAvailable callback to fire + * -The TextureView is bound to the MediaPlayer through MediaPlayer.setSurface(), then MediaPlayer.prepareAsync() is called + * -Once preparation is complete, MediaPlayer.start() is called + * -MediaPlayer.stop() will be called when playback finishes or the item has been de-selected, at which point the TextureView will + * be removed from the MetricSelector's view hierarchy, causing onSurfaceTextureDestroyed(), where we call MediaPlayer.setSurface(null) */ class MetricSelectionFragmentMediaPlayer { SafeMediaPlayer safePlayer; @@ -429,7 +429,7 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis textureView = new TextureView(getActivity()); textureView.setVisibility(View.GONE); - textureView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + textureView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { @@ -457,8 +457,11 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis private void startVideoPlayback(MetricSelector metricSelector) { videoPlayingSelector = metricSelector; videoPlayingSelector.initIndex(); - safePlayer.setDataSource(metricSelector.getNextVideoResourceURI()); - metricSelector.displayVideo(textureView); //will cause onSurfaceTextureAvailable to fire + Uri videoUri = metricSelector.getNextVideoResourceURI(); + if (videoUri != null) { + safePlayer.setDataSource(videoUri); + metricSelector.displayVideo(textureView); //will cause onSurfaceTextureAvailable to fire + } } private void endVideoPlayback() { @@ -475,9 +478,9 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } void stopMetricSelectorPlayback(MetricSelector metricSelector) { - if (metricSelector == videoPlayingSelector) { //if de-selected item is a playing video, stop it - endVideoPlayback(); - } + if (metricSelector == videoPlayingSelector) { //if de-selected item is a playing video, stop it + endVideoPlayback(); + } } public void destroy() { @@ -491,18 +494,6 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } - /** - * These are not all the MediaPlayer states defined by Android, but they are all the ones we are interested in. - * Note that SafeMediaPlayer never stays in the STOPPED state, so we don't include it. - */ - enum MediaPlayerState { - IDLE, INIT, PREPARED, PLAYING - }; - - interface OnSafeMediaPlayerPreparedListener { - void onSafeMediaPlayerPrepared(); - } - /** * A Facade to ensure our MediaPlayer does not throw an error due to an invalid state change. */ @@ -595,5 +586,3 @@ public class MetricSelectionFragment extends Fragment implements View.OnClickLis } } - - diff --git a/app/src/main/java/com/affectiva/affdexme/MetricSelector.java b/app/src/main/java/com/affectiva/affdexme/MetricSelector.java index 754ba01..86732e0 100644 --- a/app/src/main/java/com/affectiva/affdexme/MetricSelector.java +++ b/app/src/main/java/com/affectiva/affdexme/MetricSelector.java @@ -1,12 +1,21 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; import android.app.Activity; +import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; +import android.support.v4.content.ContextCompat; +import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.TextureView; import android.view.View; +import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; @@ -19,25 +28,35 @@ import android.widget.TextView; */ public class MetricSelector extends FrameLayout { - private boolean isMetricSelected; - private MetricsManager.Metrics metric; - TextureView textureView; - TextView gridItemTextView; ImageView imageView; ImageView imageViewBeneath; + FrameLayout videoHolder; RelativeLayout backgroundLayout; - int itemNotSelectedColor; int itemSelectedColor; int itemSelectedOverLimitColor; - Uri[] videoResourceURIs; int videoResourceURIIndex; TextView videoOverlay; - int picId; + private boolean isMetricSelected; + private boolean isEmoji; + private MetricsManager.Metrics metric; + + // These three constructors only provided to allow the UI Editor to properly render this element + public MetricSelector(Context context) { + super(context); + } + + public MetricSelector(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public MetricSelector(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } public MetricSelector(Activity hostActivity, LayoutInflater inflater, Resources res, String packageName, MetricsManager.Metrics metric) { super(hostActivity); @@ -45,7 +64,11 @@ public class MetricSelector extends FrameLayout { this.metric = metric; this.isMetricSelected = false; - initContent(inflater, res, packageName); + if (metric.getType().equals(MetricsManager.MetricType.Emoji)) { + this.isEmoji = true; + } + + initContent(inflater, res, packageName); } void initContent(LayoutInflater inflater, Resources res, String packageName) { @@ -55,11 +78,13 @@ public class MetricSelector extends FrameLayout { videoOverlay = (TextView) content.findViewById(R.id.video_overlay); - int videoId = res.getIdentifier(resourceName,"raw",packageName); - if (metric == MetricsManager.Emotions.VALENCE) { + int videoId = res.getIdentifier(resourceName, "raw", packageName); + if (isEmoji) { + videoResourceURIs = null; + } else if (metric == MetricsManager.Emotions.VALENCE) { videoResourceURIs = new Uri[2]; - videoResourceURIs[0] = Uri.parse(String.format("android.resource://%s/%d", packageName, videoId )); - videoResourceURIs[1] = Uri.parse(String.format("android.resource://%s/%d", packageName, res.getIdentifier(resourceName+"0","raw",packageName))); + videoResourceURIs[0] = Uri.parse(String.format("android.resource://%s/%d", packageName, videoId)); + videoResourceURIs[1] = Uri.parse(String.format("android.resource://%s/%d", packageName, res.getIdentifier(resourceName + "0", "raw", packageName))); } else { videoResourceURIs = new Uri[1]; videoResourceURIs[0] = Uri.parse(String.format("android.resource://%s/%d", packageName, videoId)); @@ -68,6 +93,9 @@ public class MetricSelector extends FrameLayout { videoResourceURIIndex = 0; //set up image + if (isEmoji) { + resourceName += "_emoji"; + } picId = res.getIdentifier(resourceName, "drawable", packageName); imageView = (ImageView) content.findViewById(R.id.grid_item_image_view); imageViewBeneath = (ImageView) content.findViewById(R.id.grid_item_image_view_beneath); @@ -75,14 +103,15 @@ public class MetricSelector extends FrameLayout { imageViewBeneath.setImageResource(picId); imageViewBeneath.setVisibility(GONE); + videoHolder = (FrameLayout) content.findViewById(R.id.video_holder); backgroundLayout = (RelativeLayout) content.findViewById(R.id.grid_item_background); gridItemTextView = (TextView) content.findViewById(R.id.grid_item_text); gridItemTextView.setText(MetricsManager.getCapitalizedName(metric)); - itemSelectedOverLimitColor = res.getColor(R.color.grid_item_chosen_over_limit); - itemNotSelectedColor = res.getColor(R.color.grid_item_not_chosen); - itemSelectedColor = res.getColor(R.color.grid_item_chosen); + itemSelectedOverLimitColor = ContextCompat.getColor(getContext(), R.color.grid_item_chosen_over_limit); + itemNotSelectedColor = ContextCompat.getColor(getContext(), R.color.grid_item_not_chosen); + itemSelectedColor = ContextCompat.getColor(getContext(), R.color.grid_item_chosen); } boolean getIsSelected() { @@ -105,7 +134,15 @@ public class MetricSelector extends FrameLayout { void displayVideo(TextureView videoView) { textureView = videoView; - backgroundLayout.addView(textureView, 1); + ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(textureView.getLayoutParams()); + + // set the video to the same height and width of the actual bitmap inside the imageview + int[] imageAttr = ImageHelper.getBitmapPositionInsideImageView(imageView); + params.width = imageAttr[2]; //width + params.height = imageAttr[3]; //height + + textureView.setLayoutParams(params); + videoHolder.addView(textureView); textureView.setVisibility(VISIBLE); videoOverlay.setVisibility(VISIBLE); } @@ -113,7 +150,7 @@ public class MetricSelector extends FrameLayout { void removeVideo() { if (textureView != null) { textureView.setVisibility(GONE); - backgroundLayout.removeView(textureView); + videoHolder.removeView(textureView); textureView = null; } videoOverlay.setVisibility(GONE); @@ -128,12 +165,15 @@ public class MetricSelector extends FrameLayout { } Uri getNextVideoResourceURI() { + if (isEmoji) { + return null; + } if (metric == MetricsManager.Emotions.VALENCE) { if (videoResourceURIIndex == 0) { - videoOverlay.setText("NEGATIVE"); + videoOverlay.setText(R.string.negative); videoOverlay.setTextColor(Color.RED); } else { - videoOverlay.setText("POSITIVE"); + videoOverlay.setText(R.string.positive); videoOverlay.setTextColor(Color.GREEN); } } @@ -163,7 +203,4 @@ public class MetricSelector extends FrameLayout { backgroundLayout.setBackgroundColor(itemNotSelectedColor); } } - - - } diff --git a/app/src/main/java/com/affectiva/affdexme/MetricsManager.java b/app/src/main/java/com/affectiva/affdexme/MetricsManager.java index 31da508..1176638 100644 --- a/app/src/main/java/com/affectiva/affdexme/MetricsManager.java +++ b/app/src/main/java/com/affectiva/affdexme/MetricsManager.java @@ -1,10 +1,19 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; +import com.affectiva.android.affdex.sdk.detector.Face; + +import java.util.Locale; + /** * A class containing: - * -enumerations representing the Emotion and Expressions featured in the Affectiva SDK. - * -a Metric interface to allow easy iteration through all Expressions and Emotions - * -utility methods for converting a Metric into several types of strings + * -enumerations representing the Emotion and Expressions featured in the Affectiva SDK. + * -a Metric interface to allow easy iteration through all Expressions and Emotions + * -utility methods for converting a Metric into several types of strings */ public class MetricsManager { @@ -13,67 +22,23 @@ public class MetricsManager { static { Emotions[] emotions = Emotions.values(); Expressions[] expressions = Expressions.values(); - allMetrics = new Metrics[emotions.length + expressions.length]; - System.arraycopy(emotions,0,allMetrics,0,emotions.length); - System.arraycopy(expressions,0,allMetrics,emotions.length,expressions.length); + Emojis[] emojis = Emojis.values(); + allMetrics = new Metrics[emotions.length + expressions.length + emojis.length]; + System.arraycopy(emotions, 0, allMetrics, 0, emotions.length); + System.arraycopy(expressions, 0, allMetrics, emotions.length, expressions.length); + System.arraycopy(emojis, 0, allMetrics, emotions.length + expressions.length, emojis.length); } static Metrics[] getAllMetrics() { return allMetrics; } - enum MetricType {Emotion, Expression}; - - interface Metrics { - MetricType getType(); - } - - enum Emotions implements Metrics { - ANGER, - DISGUST, - FEAR, - JOY, - SADNESS, - SURPRISE, - CONTEMPT, - ENGAGEMENT, - VALENCE; - - @Override - public MetricType getType() { - return MetricType.Emotion; - } - - } - - enum Expressions implements Metrics { - ATTENTION, - BROW_FURROW, - BROW_RAISE, - CHIN_RAISE, - EYE_CLOSURE, - INNER_BROW_RAISE, - LIP_CORNER_DEPRESSOR, - LIP_PRESS, - LIP_PUCKER, - LIP_SUCK, - MOUTH_OPEN, - NOSE_WRINKLE, - SMILE, - SMIRK, - UPPER_LIP_RAISE; - - @Override - public MetricType getType() { - return MetricType.Expression; - } - - } - //Used for displays static String getUpperCaseName(Metrics metric) { if (metric == Expressions.LIP_CORNER_DEPRESSOR) { return "FROWN"; + } else if (metric.getType().equals(MetricType.Emoji)) { + return ((Emojis) metric).getDisplayName().toUpperCase(Locale.US); } else { return metric.toString().replace("_", " "); } @@ -82,6 +47,9 @@ public class MetricsManager { //Used for MetricSelectionFragment //This method is optimized for strings of the form SOME_METRIC_NAME, which all metric names currently are static String getCapitalizedName(Metrics metric) { + if (metric.getType().equals(MetricType.Emoji)) { + return ((Emojis) metric).getDisplayName(); + } if (metric == Expressions.LIP_CORNER_DEPRESSOR) { return "Frown"; } @@ -113,12 +81,12 @@ public class MetricsManager { //Used to construct method names for reflection static String getCamelCase(Metrics metric) { String metricString = metric.toString(); - + StringBuilder builder = new StringBuilder(); builder.append(Character.toUpperCase(metricString.charAt(0))); if (metricString.length() > 1) { - for (int n = 1; n < metricString.length(); n++ ){ + for (int n = 1; n < metricString.length(); n++) { char c = metricString.charAt(n); if (c == '_') { n += 1; @@ -134,5 +102,116 @@ public class MetricsManager { return builder.toString(); } + public enum MetricType {Emotion, Expression, Emoji} + public enum Emotions implements Metrics { + ANGER, + DISGUST, + FEAR, + JOY, + SADNESS, + SURPRISE, + CONTEMPT, + ENGAGEMENT, + VALENCE; + + @Override + public MetricType getType() { + return MetricType.Emotion; + } + } + + public enum Expressions implements Metrics { + ATTENTION, + BROW_FURROW, + BROW_RAISE, + CHIN_RAISE, + EYE_CLOSURE, + INNER_BROW_RAISE, + LIP_CORNER_DEPRESSOR, + LIP_PRESS, + LIP_PUCKER, + LIP_SUCK, + MOUTH_OPEN, + NOSE_WRINKLE, + SMILE, + SMIRK, + UPPER_LIP_RAISE; + + @Override + public MetricType getType() { + return MetricType.Expression; + } + } + + public enum Emojis implements Metrics { + RELAXED("Relaxed"), + SMILEY("Smiley"), + LAUGHING("Laughing"), + KISSING("Kiss"), + DISAPPOINTED("Disappointed"), + RAGE("Rage"), + SMIRK("Smirk Emoji"), + WINK("Wink"), + STUCK_OUT_TONGUE_WINKING_EYE("Tongue Wink"), + STUCK_OUT_TONGUE("Tongue Out"), + FLUSHED("Flushed"), + SCREAM("Scream"); + + private String displayName; + + Emojis(String name) { + displayName = name; + } + + public static Emojis getEnum(String value) { + for (Emojis v : values()) + if (v.displayName.equalsIgnoreCase(value)) return v; + throw new IllegalArgumentException(); + } + + @Override + public MetricType getType() { + return MetricType.Emoji; + } + + public String getDisplayName() { + return displayName; + } + + public String getUnicodeForEmoji() { + switch (this) { + case RELAXED: + return Face.EMOJI.RELAXED.getUnicode(); + case SMILEY: + return Face.EMOJI.SMILEY.getUnicode(); + case LAUGHING: + return Face.EMOJI.LAUGHING.getUnicode(); + case KISSING: + return Face.EMOJI.KISSING.getUnicode(); + case DISAPPOINTED: + return Face.EMOJI.DISAPPOINTED.getUnicode(); + case RAGE: + return Face.EMOJI.RAGE.getUnicode(); + case SMIRK: + return Face.EMOJI.SMIRK.getUnicode(); + case WINK: + return Face.EMOJI.WINK.getUnicode(); + case STUCK_OUT_TONGUE_WINKING_EYE: + return Face.EMOJI.STUCK_OUT_TONGUE_WINKING_EYE.getUnicode(); + case STUCK_OUT_TONGUE: + return Face.EMOJI.STUCK_OUT_TONGUE.getUnicode(); + case FLUSHED: + return Face.EMOJI.FLUSHED.getUnicode(); + case SCREAM: + return Face.EMOJI.SCREAM.getUnicode(); + default: + return ""; + } + } + } + + public interface Metrics { + MetricType getType(); + } } diff --git a/app/src/main/java/com/affectiva/affdexme/PreferencesUtils.java b/app/src/main/java/com/affectiva/affdexme/PreferencesUtils.java index 51cea68..1385a00 100644 --- a/app/src/main/java/com/affectiva/affdexme/PreferencesUtils.java +++ b/app/src/main/java/com/affectiva/affdexme/PreferencesUtils.java @@ -1,6 +1,12 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; import android.content.SharedPreferences; +import android.util.Log; /** * A helper class to translate strings held in preferences into values to be used by the application. @@ -8,6 +14,7 @@ import android.content.SharedPreferences; public class PreferencesUtils { static final int DEFAULT_FPS = 20; + private final static String LOG_TAG = "AffdexMe"; /** * Attempt to parse and return FPS set by user. If the FPS is invalid, we set it to be the default FPS. @@ -18,39 +25,44 @@ public class PreferencesUtils { try { toReturn = Integer.parseInt(rateString); } catch (Exception e) { - saveFrameProcessingRate(pref,DEFAULT_FPS); + saveFrameProcessingRate(pref, DEFAULT_FPS); return DEFAULT_FPS; } if (toReturn > 0) { return toReturn; } else { - saveFrameProcessingRate(pref,DEFAULT_FPS); + saveFrameProcessingRate(pref, DEFAULT_FPS); return DEFAULT_FPS; } } private static void saveFrameProcessingRate(SharedPreferences pref, int rate) { SharedPreferences.Editor editor = pref.edit(); - editor.putString("rate",String.valueOf(rate)); + editor.putString("rate", String.valueOf(rate)); editor.commit(); } public static MetricsManager.Metrics getMetricFromPrefs(SharedPreferences pref, int index) { MetricsManager.Metrics metric; try { - String stringFromPref = pref.getString(String.format("metric_display_%d", index),defaultMetric(index).toString()); - metric = parseSavedMetric(stringFromPref ); + String stringFromPref = pref.getString(String.format("metric_display_%d", index), defaultMetric(index).toString()); + metric = parseSavedMetric(stringFromPref); } catch (IllegalArgumentException e) { metric = defaultMetric(index); SharedPreferences.Editor editor = pref.edit(); - editor.putString(String.format("metric_display_%d", index),defaultMetric(index).toString()); + editor.putString(String.format("metric_display_%d", index), defaultMetric(index).toString()); editor.commit(); } return metric; } - public static void saveMetricToPrefs(SharedPreferences.Editor editor , int index, MetricsManager.Metrics metric) { - editor.putString(String.format("metric_display_%d", index), metric.toString()); + public static void saveMetricToPrefs(SharedPreferences.Editor editor, int index, MetricsManager.Metrics metric) { + if (metric.getType().equals(MetricsManager.MetricType.Emoji)) { + MetricsManager.Emojis emoji = (MetricsManager.Emojis) metric; + editor.putString(String.format("metric_display_%d", index), emoji.getDisplayName()); + } else { + editor.putString(String.format("metric_display_%d", index), metric.toString()); + } } static private MetricsManager.Metrics defaultMetric(int index) { @@ -73,23 +85,30 @@ public class PreferencesUtils { } /** - * We attempt to parse the string as an Emotion or, failing that, as an Expression. + * We attempt to parse the string as any known metric. */ - static MetricsManager.Metrics parseSavedMetric(String metricString) throws IllegalArgumentException{ + static MetricsManager.Metrics parseSavedMetric(String metricString) throws IllegalArgumentException { try { MetricsManager.Emotions emotion; emotion = MetricsManager.Emotions.valueOf(metricString); return emotion; } catch (IllegalArgumentException emotionParseFailed) { - try { - MetricsManager.Expressions expression; - expression = MetricsManager.Expressions.valueOf(metricString); - return expression; - } catch (IllegalArgumentException expressionParseFailed) { - throw new IllegalArgumentException("String did not match an emotion or expression"); - } + Log.v(LOG_TAG, "Not an Emotion..."); } + try { + MetricsManager.Expressions expression; + expression = MetricsManager.Expressions.valueOf(metricString); + return expression; + } catch (IllegalArgumentException expressionParseFailed) { + Log.v(LOG_TAG, "Not an Expression..."); + } + try { + MetricsManager.Emojis emoji; + emoji = MetricsManager.Emojis.getEnum(metricString); + return emoji; + } catch (IllegalArgumentException expressionParseFailed) { + Log.v(LOG_TAG, "Not an Emoji..."); + } + throw new IllegalArgumentException("String did not match any known metric"); } - - } diff --git a/app/src/main/java/com/affectiva/affdexme/SettingsActivity.java b/app/src/main/java/com/affectiva/affdexme/SettingsActivity.java index 310e556..480ffee 100644 --- a/app/src/main/java/com/affectiva/affdexme/SettingsActivity.java +++ b/app/src/main/java/com/affectiva/affdexme/SettingsActivity.java @@ -1,3 +1,8 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.affdexme; import android.app.ActionBar; @@ -5,6 +10,7 @@ import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; +import android.support.v4.content.ContextCompat; import android.view.MenuItem; import java.util.List; @@ -16,19 +22,11 @@ public class SettingsActivity extends PreferenceActivity { public void onCreate(Bundle savedBundleInstance) { super.onCreate(savedBundleInstance); ActionBar actionBar = getActionBar(); - actionBar.setIcon( - new ColorDrawable(getResources().getColor(android.R.color.transparent))); - //actionBar.setDisplayHomeAsUpEnabled(true); - + if (actionBar != null) { + actionBar.setIcon(new ColorDrawable(ContextCompat.getColor(getApplicationContext(), R.color.transparent_overlay))); + } } - /* - @Override - public boolean onNavigateUp() { - this.onBackPressed(); - return true; - }*/ - @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -49,10 +47,7 @@ public class SettingsActivity extends PreferenceActivity { //Boilerplate method, required by Android API @Override protected boolean isValidFragment(String fragmentName) { - if (SettingsFragment.class.getName().equals(fragmentName) || MetricSelectionFragment.class.getName().equals(fragmentName)) { - return(true); - } - return(false); + return SettingsFragment.class.getName().equals(fragmentName) || MetricSelectionFragment.class.getName().equals(fragmentName); } //This fragment shows the preferences for the first header. @@ -65,7 +60,4 @@ public class SettingsActivity extends PreferenceActivity { addPreferencesFromResource(R.xml.settings_preferences); } } - - //The second fragment is defined in a separate file. - } \ No newline at end of file diff --git a/app/src/main/java/com/affectiva/errorreporting/CustomApplication.java b/app/src/main/java/com/affectiva/errorreporting/CustomApplication.java index 224bce5..f769cd0 100644 --- a/app/src/main/java/com/affectiva/errorreporting/CustomApplication.java +++ b/app/src/main/java/com/affectiva/errorreporting/CustomApplication.java @@ -1,3 +1,8 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.errorreporting; import android.app.Application; @@ -5,28 +10,24 @@ import android.content.Intent; public class CustomApplication extends Application { - static volatile boolean wasErrorActivityStarted = false; static final boolean enableCustomErrorMessage = false; + static volatile boolean wasErrorActivityStarted = false; Thread.UncaughtExceptionHandler exceptionHandler; @Override - public void onCreate () - { + public void onCreate() { super.onCreate(); exceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); // Setup handler for uncaught exceptions. - Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() - { + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override - public void uncaughtException (Thread thread, Throwable e) - { - handleUncaughtException (thread, e); + public void uncaughtException(Thread thread, Throwable e) { + handleUncaughtException(thread, e); } }); } - public void handleUncaughtException (Thread thread, Throwable e) - { + public void handleUncaughtException(Thread thread, Throwable e) { if (!wasErrorActivityStarted && enableCustomErrorMessage) { Intent intent = new Intent(); intent.setAction("com.affectiva.REPORT_ERROR"); // see step 5. @@ -36,6 +37,6 @@ public class CustomApplication extends Application { wasErrorActivityStarted = true; } - exceptionHandler.uncaughtException(thread,e); + exceptionHandler.uncaughtException(thread, e); } } diff --git a/app/src/main/java/com/affectiva/errorreporting/ErrorReporter.java b/app/src/main/java/com/affectiva/errorreporting/ErrorReporter.java index f037024..8dbbe32 100644 --- a/app/src/main/java/com/affectiva/errorreporting/ErrorReporter.java +++ b/app/src/main/java/com/affectiva/errorreporting/ErrorReporter.java @@ -1,3 +1,8 @@ +/** + * Copyright (c) 2016 Affectiva Inc. + * See the file license.txt for copying permission. + */ + package com.affectiva.errorreporting; import android.app.Activity; @@ -19,8 +24,7 @@ public class ErrorReporter extends Activity implements View.OnClickListener { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); // make a dialog without a titlebar setContentView(R.layout.error_reporter); @@ -51,7 +55,7 @@ public class ErrorReporter extends Activity implements View.OnClickListener { @Override public void onClick(View v) { - Intent intent = new Intent (Intent.ACTION_SEND); + Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/text"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"sdk@affectiva.com"}); intent.putExtra(Intent.EXTRA_SUBJECT, "AffdexMe Crash Report"); diff --git a/app/src/main/res/drawable-hdpi/affectiva_logo_clear_background.png b/app/src/main/res/drawable-hdpi/affectiva_logo_clear_background.png index 4778791..72e4281 100644 Binary files a/app/src/main/res/drawable-hdpi/affectiva_logo_clear_background.png and b/app/src/main/res/drawable-hdpi/affectiva_logo_clear_background.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_arrow_back_white_24dp.png b/app/src/main/res/drawable-hdpi/ic_arrow_back_white_24dp.png index 83dcecb..5e83c78 100644 Binary files a/app/src/main/res/drawable-hdpi/ic_arrow_back_white_24dp.png and b/app/src/main/res/drawable-hdpi/ic_arrow_back_white_24dp.png differ diff --git a/app/src/main/res/drawable-hdpi/screenshot_button.png b/app/src/main/res/drawable-hdpi/screenshot_button.png new file mode 100644 index 0000000..ac8f1de Binary files /dev/null and b/app/src/main/res/drawable-hdpi/screenshot_button.png differ diff --git a/app/src/main/res/drawable-hdpi/screenshot_button_pressed.png b/app/src/main/res/drawable-hdpi/screenshot_button_pressed.png new file mode 100644 index 0000000..7f94967 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/screenshot_button_pressed.png differ diff --git a/app/src/main/res/drawable-hdpi/settings_button.png b/app/src/main/res/drawable-hdpi/settings_button.png index a67f4c6..03f2e37 100644 Binary files a/app/src/main/res/drawable-hdpi/settings_button.png and b/app/src/main/res/drawable-hdpi/settings_button.png differ diff --git a/app/src/main/res/drawable-hdpi/settings_button_pressed.png b/app/src/main/res/drawable-hdpi/settings_button_pressed.png index 27c44ea..4a0aa2a 100644 Binary files a/app/src/main/res/drawable-hdpi/settings_button_pressed.png and b/app/src/main/res/drawable-hdpi/settings_button_pressed.png differ diff --git a/app/src/main/res/drawable-hdpi/switch_camera_button.png b/app/src/main/res/drawable-hdpi/switch_camera_button.png index 5eb90a6..590c875 100644 Binary files a/app/src/main/res/drawable-hdpi/switch_camera_button.png and b/app/src/main/res/drawable-hdpi/switch_camera_button.png differ diff --git a/app/src/main/res/drawable-hdpi/switch_camera_button_pressed.png b/app/src/main/res/drawable-hdpi/switch_camera_button_pressed.png index 31920a5..8e2cfcb 100644 Binary files a/app/src/main/res/drawable-hdpi/switch_camera_button_pressed.png and b/app/src/main/res/drawable-hdpi/switch_camera_button_pressed.png differ diff --git a/app/src/main/res/drawable-mdpi/affectiva_logo_clear_background.png b/app/src/main/res/drawable-mdpi/affectiva_logo_clear_background.png index 2885705..9f15451 100644 Binary files a/app/src/main/res/drawable-mdpi/affectiva_logo_clear_background.png and b/app/src/main/res/drawable-mdpi/affectiva_logo_clear_background.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_arrow_back_white_24dp.png b/app/src/main/res/drawable-mdpi/ic_arrow_back_white_24dp.png index 4b3b18a..8149fb5 100644 Binary files a/app/src/main/res/drawable-mdpi/ic_arrow_back_white_24dp.png and b/app/src/main/res/drawable-mdpi/ic_arrow_back_white_24dp.png differ diff --git a/app/src/main/res/drawable-mdpi/screenshot_button.png b/app/src/main/res/drawable-mdpi/screenshot_button.png new file mode 100644 index 0000000..8de4566 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/screenshot_button.png differ diff --git a/app/src/main/res/drawable-mdpi/screenshot_button_pressed.png b/app/src/main/res/drawable-mdpi/screenshot_button_pressed.png new file mode 100644 index 0000000..15e0fc6 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/screenshot_button_pressed.png differ diff --git a/app/src/main/res/drawable-mdpi/settings_button.png b/app/src/main/res/drawable-mdpi/settings_button.png index 624d03a..1f94f4b 100644 Binary files a/app/src/main/res/drawable-mdpi/settings_button.png and b/app/src/main/res/drawable-mdpi/settings_button.png differ diff --git a/app/src/main/res/drawable-mdpi/settings_button_pressed.png b/app/src/main/res/drawable-mdpi/settings_button_pressed.png index 90bab00..eb900d5 100644 Binary files a/app/src/main/res/drawable-mdpi/settings_button_pressed.png and b/app/src/main/res/drawable-mdpi/settings_button_pressed.png differ diff --git a/app/src/main/res/drawable-mdpi/switch_camera_button.png b/app/src/main/res/drawable-mdpi/switch_camera_button.png index a3cd276..57b25ed 100644 Binary files a/app/src/main/res/drawable-mdpi/switch_camera_button.png and b/app/src/main/res/drawable-mdpi/switch_camera_button.png differ diff --git a/app/src/main/res/drawable-mdpi/switch_camera_button_pressed.png b/app/src/main/res/drawable-mdpi/switch_camera_button_pressed.png index 5611b14..af95263 100644 Binary files a/app/src/main/res/drawable-mdpi/switch_camera_button_pressed.png and b/app/src/main/res/drawable-mdpi/switch_camera_button_pressed.png differ diff --git a/app/src/main/res/drawable-nodpi/disappointed_emoji.png b/app/src/main/res/drawable-nodpi/disappointed_emoji.png new file mode 100644 index 0000000..ff87088 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/disappointed_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/female_glasses.png b/app/src/main/res/drawable-nodpi/female_glasses.png new file mode 100644 index 0000000..557c7d1 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/female_glasses.png differ diff --git a/app/src/main/res/drawable-nodpi/female_noglasses.png b/app/src/main/res/drawable-nodpi/female_noglasses.png new file mode 100644 index 0000000..8103b2e Binary files /dev/null and b/app/src/main/res/drawable-nodpi/female_noglasses.png differ diff --git a/app/src/main/res/drawable-nodpi/flushed_emoji.png b/app/src/main/res/drawable-nodpi/flushed_emoji.png new file mode 100644 index 0000000..5a9f517 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/flushed_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/kissing_emoji.png b/app/src/main/res/drawable-nodpi/kissing_emoji.png new file mode 100644 index 0000000..e8d76ad Binary files /dev/null and b/app/src/main/res/drawable-nodpi/kissing_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/laughing_emoji.png b/app/src/main/res/drawable-nodpi/laughing_emoji.png new file mode 100644 index 0000000..87b80bd Binary files /dev/null and b/app/src/main/res/drawable-nodpi/laughing_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/male_glasses.png b/app/src/main/res/drawable-nodpi/male_glasses.png new file mode 100644 index 0000000..5d09dd9 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/male_glasses.png differ diff --git a/app/src/main/res/drawable-nodpi/male_noglasses.png b/app/src/main/res/drawable-nodpi/male_noglasses.png new file mode 100644 index 0000000..bcbe87f Binary files /dev/null and b/app/src/main/res/drawable-nodpi/male_noglasses.png differ diff --git a/app/src/main/res/drawable-nodpi/rage_emoji.png b/app/src/main/res/drawable-nodpi/rage_emoji.png new file mode 100644 index 0000000..5c01db4 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/rage_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/relaxed_emoji.png b/app/src/main/res/drawable-nodpi/relaxed_emoji.png new file mode 100644 index 0000000..799c9fd Binary files /dev/null and b/app/src/main/res/drawable-nodpi/relaxed_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/scream_emoji.png b/app/src/main/res/drawable-nodpi/scream_emoji.png new file mode 100644 index 0000000..d908d4b Binary files /dev/null and b/app/src/main/res/drawable-nodpi/scream_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/smiley_emoji.png b/app/src/main/res/drawable-nodpi/smiley_emoji.png new file mode 100644 index 0000000..64b8a3e Binary files /dev/null and b/app/src/main/res/drawable-nodpi/smiley_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/smirk_emoji.png b/app/src/main/res/drawable-nodpi/smirk_emoji.png new file mode 100644 index 0000000..bfc9492 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/smirk_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/stuck_out_tongue_emoji.png b/app/src/main/res/drawable-nodpi/stuck_out_tongue_emoji.png new file mode 100644 index 0000000..8529654 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/stuck_out_tongue_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/stuck_out_tongue_winking_eye_emoji.png b/app/src/main/res/drawable-nodpi/stuck_out_tongue_winking_eye_emoji.png new file mode 100644 index 0000000..628992f Binary files /dev/null and b/app/src/main/res/drawable-nodpi/stuck_out_tongue_winking_eye_emoji.png differ diff --git a/app/src/main/res/drawable-nodpi/unknown_glasses.png b/app/src/main/res/drawable-nodpi/unknown_glasses.png new file mode 100644 index 0000000..c156872 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/unknown_glasses.png differ diff --git a/app/src/main/res/drawable-nodpi/unknown_noglasses.png b/app/src/main/res/drawable-nodpi/unknown_noglasses.png new file mode 100644 index 0000000..24eb2d2 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/unknown_noglasses.png differ diff --git a/app/src/main/res/drawable-nodpi/wink_emoji.png b/app/src/main/res/drawable-nodpi/wink_emoji.png new file mode 100644 index 0000000..d007462 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/wink_emoji.png differ diff --git a/app/src/main/res/drawable-xhdpi/affectiva_logo_clear_background.png b/app/src/main/res/drawable-xhdpi/affectiva_logo_clear_background.png index ed553b9..8dea849 100644 Binary files a/app/src/main/res/drawable-xhdpi/affectiva_logo_clear_background.png and b/app/src/main/res/drawable-xhdpi/affectiva_logo_clear_background.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_arrow_back_white_24dp.png b/app/src/main/res/drawable-xhdpi/ic_arrow_back_white_24dp.png index afe573a..60cfb1b 100644 Binary files a/app/src/main/res/drawable-xhdpi/ic_arrow_back_white_24dp.png and b/app/src/main/res/drawable-xhdpi/ic_arrow_back_white_24dp.png differ diff --git a/app/src/main/res/drawable-xhdpi/screenshot_button.png b/app/src/main/res/drawable-xhdpi/screenshot_button.png new file mode 100644 index 0000000..1ef7d1e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/screenshot_button.png differ diff --git a/app/src/main/res/drawable-xhdpi/screenshot_button_pressed.png b/app/src/main/res/drawable-xhdpi/screenshot_button_pressed.png new file mode 100644 index 0000000..64b4d68 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/screenshot_button_pressed.png differ diff --git a/app/src/main/res/drawable-xhdpi/settings_button.png b/app/src/main/res/drawable-xhdpi/settings_button.png index e9d3ff3..36b2c89 100644 Binary files a/app/src/main/res/drawable-xhdpi/settings_button.png and b/app/src/main/res/drawable-xhdpi/settings_button.png differ diff --git a/app/src/main/res/drawable-xhdpi/settings_button_pressed.png b/app/src/main/res/drawable-xhdpi/settings_button_pressed.png index d6dd890..c0033ca 100644 Binary files a/app/src/main/res/drawable-xhdpi/settings_button_pressed.png and b/app/src/main/res/drawable-xhdpi/settings_button_pressed.png differ diff --git a/app/src/main/res/drawable-xhdpi/switch_camera_button.png b/app/src/main/res/drawable-xhdpi/switch_camera_button.png index d21bb94..390df0f 100644 Binary files a/app/src/main/res/drawable-xhdpi/switch_camera_button.png and b/app/src/main/res/drawable-xhdpi/switch_camera_button.png differ diff --git a/app/src/main/res/drawable-xhdpi/switch_camera_button_pressed.png b/app/src/main/res/drawable-xhdpi/switch_camera_button_pressed.png index fafb475..a695dba 100644 Binary files a/app/src/main/res/drawable-xhdpi/switch_camera_button_pressed.png and b/app/src/main/res/drawable-xhdpi/switch_camera_button_pressed.png differ diff --git a/app/src/main/res/drawable-xxhdpi/affectiva_logo_clear_background.png b/app/src/main/res/drawable-xxhdpi/affectiva_logo_clear_background.png index 484b96b..93724c7 100644 Binary files a/app/src/main/res/drawable-xxhdpi/affectiva_logo_clear_background.png and b/app/src/main/res/drawable-xxhdpi/affectiva_logo_clear_background.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_arrow_back_white_24dp.png b/app/src/main/res/drawable-xxhdpi/ic_arrow_back_white_24dp.png index cc60413..a14bd54 100644 Binary files a/app/src/main/res/drawable-xxhdpi/ic_arrow_back_white_24dp.png and b/app/src/main/res/drawable-xxhdpi/ic_arrow_back_white_24dp.png differ diff --git a/app/src/main/res/drawable-xxhdpi/screenshot_button.png b/app/src/main/res/drawable-xxhdpi/screenshot_button.png new file mode 100644 index 0000000..34c056e Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/screenshot_button.png differ diff --git a/app/src/main/res/drawable-xxhdpi/screenshot_button_pressed.png b/app/src/main/res/drawable-xxhdpi/screenshot_button_pressed.png new file mode 100644 index 0000000..a052fb1 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/screenshot_button_pressed.png differ diff --git a/app/src/main/res/drawable-xxhdpi/settings_button.png b/app/src/main/res/drawable-xxhdpi/settings_button.png index 65fe3d3..4e5afb8 100644 Binary files a/app/src/main/res/drawable-xxhdpi/settings_button.png and b/app/src/main/res/drawable-xxhdpi/settings_button.png differ diff --git a/app/src/main/res/drawable-xxhdpi/settings_button_pressed.png b/app/src/main/res/drawable-xxhdpi/settings_button_pressed.png index b2c4972..ccbbb8a 100644 Binary files a/app/src/main/res/drawable-xxhdpi/settings_button_pressed.png and b/app/src/main/res/drawable-xxhdpi/settings_button_pressed.png differ diff --git a/app/src/main/res/drawable-xxhdpi/switch_camera_button.png b/app/src/main/res/drawable-xxhdpi/switch_camera_button.png index 076b958..4e610be 100644 Binary files a/app/src/main/res/drawable-xxhdpi/switch_camera_button.png and b/app/src/main/res/drawable-xxhdpi/switch_camera_button.png differ diff --git a/app/src/main/res/drawable-xxhdpi/switch_camera_button_pressed.png b/app/src/main/res/drawable-xxhdpi/switch_camera_button_pressed.png index c9c20e9..e7bffa8 100644 Binary files a/app/src/main/res/drawable-xxhdpi/switch_camera_button_pressed.png and b/app/src/main/res/drawable-xxhdpi/switch_camera_button_pressed.png differ diff --git a/app/src/main/res/drawable/affectiva_logo_clear_background.png b/app/src/main/res/drawable/affectiva_logo_clear_background.png index 4778791..72e4281 100644 Binary files a/app/src/main/res/drawable/affectiva_logo_clear_background.png and b/app/src/main/res/drawable/affectiva_logo_clear_background.png differ diff --git a/app/src/main/res/drawable/camera_button_selector.xml b/app/src/main/res/drawable/camera_button_selector.xml index 2da78c1..4a41056 100644 --- a/app/src/main/res/drawable/camera_button_selector.xml +++ b/app/src/main/res/drawable/camera_button_selector.xml @@ -1,5 +1,11 @@ + + + - + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_arrow_back_white_24dp.png b/app/src/main/res/drawable/ic_arrow_back_white_24dp.png index afe573a..60cfb1b 100644 Binary files a/app/src/main/res/drawable/ic_arrow_back_white_24dp.png and b/app/src/main/res/drawable/ic_arrow_back_white_24dp.png differ diff --git a/app/src/main/res/drawable/screenshot_button_selector.xml b/app/src/main/res/drawable/screenshot_button_selector.xml new file mode 100644 index 0000000..989b39a --- /dev/null +++ b/app/src/main/res/drawable/screenshot_button_selector.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/settings_button.png b/app/src/main/res/drawable/settings_button.png deleted file mode 100644 index a67f4c6..0000000 Binary files a/app/src/main/res/drawable/settings_button.png and /dev/null differ diff --git a/app/src/main/res/drawable/settings_button_pressed.png b/app/src/main/res/drawable/settings_button_pressed.png deleted file mode 100644 index 27c44ea..0000000 Binary files a/app/src/main/res/drawable/settings_button_pressed.png and /dev/null differ diff --git a/app/src/main/res/drawable/settings_button_selector.xml b/app/src/main/res/drawable/settings_button_selector.xml index f6f77f6..bfa382f 100644 --- a/app/src/main/res/drawable/settings_button_selector.xml +++ b/app/src/main/res/drawable/settings_button_selector.xml @@ -1,5 +1,11 @@ + + + - + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 8378a3a..7d76498 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -1,93 +1,115 @@ + tools:context=".MainActivity"> + + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_centerInParent="true" /> + - + + + layout="@layout/metric_layout" /> + + android:layout_margin="@dimen/settings_button_margin" + android:background="@null" + android:contentDescription="@string/settings_content_description" + android:onClick="settings_button_click" + android:scaleType="fitCenter" + android:src="@drawable/settings_button_selector" /> + + android:layout_margin="@dimen/settings_button_margin" + android:background="@null" + android:contentDescription="Switch camera button" + android:onClick="camera_button_click" + android:scaleType="fitCenter" + android:src="@drawable/camera_button_selector" /> + + + + android:layout_centerVertical="true" + android:text="@string/loading" + android:textSize="@dimen/please_wait_textview_size" /> + + android:paddingRight="10dp" /> + + android:padding="20sp" + android:text="@string/not_found" + android:textColor="#CCCCCC" + android:textSize="20sp" + android:visibility="gone" /> diff --git a/app/src/main/res/layout/grid_item.xml b/app/src/main/res/layout/grid_item.xml index 193a91b..cfc35d8 100644 --- a/app/src/main/res/layout/grid_item.xml +++ b/app/src/main/res/layout/grid_item.xml @@ -1,39 +1,59 @@ + + android:layout_width="match_parent" + android:layout_height="match_parent" + android:paddingBottom="8dp" + android:paddingLeft="4dp" + android:paddingRight="4dp"> - + + + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_below="@+id/grid_item_text" + android:scaleType="fitCenter" /> + + + + android:textSize="@dimen/grid_item_metric_name" /> + + android:padding="2dp" + android:textSize="@dimen/grid_item_chooser_text_size" + android:textStyle="bold" /> \ No newline at end of file diff --git a/app/src/main/res/layout/insufficent_permissions_panel.xml b/app/src/main/res/layout/insufficent_permissions_panel.xml new file mode 100644 index 0000000..9aa4b9c --- /dev/null +++ b/app/src/main/res/layout/insufficent_permissions_panel.xml @@ -0,0 +1,39 @@ + + + + + + + + + +