<commit_before>/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ca.ilanguage.oprime.bilingualaphasiatest.ui;

import java.io.IOException;
import java.util.ArrayList;

import ca.ilanguage.oprime.bilingualaphasiatest.R;
import ca.ilanguage.oprime.bilingualaphasiatest.service.AudioRecorderService;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.BitmapFactory.Options;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;

/**
 * This is an example of using the accelerometer to integrate the device's
 * acceleration to a position using the Verlet method. This is illustrated with
 * a very simple particle system comprised of a few iron balls freely moving on
 * an inclined wooden table. The inclination of the virtual table is controlled
 * by the device's accelerometer.
 * 
 * @see SensorManager
 * @see SensorEvent
 * @see Sensor
 */

public class AccelerometerUIActivity extends Activity {

	private SimulationView mSimulationView;
	private SensorManager mSensorManager;
	private PowerManager mPowerManager;
	private WindowManager mWindowManager;
	private Display mDisplay;
	private WakeLock mWakeLock;

	private static final int ENGLISH = 0;
	private static final int FRENCH = 1;
	//wait between stimuli, if 999 then wait until user input.
	private static int waitBetweenStimuli = 5;
	public static final String LANGUAGE = "language";
	String mAudioResultsFile;
	MediaRecorder mRecorder;
	private String mParticipantId = "12";
	private String mStimuliId = "1";
	MediaPlayer mp;
	OnCompletionListener mAudioFinishedListener;
	private static final String TAG = "AccelerometerUIActivity";
	private ArrayList<Integer> mStimuliAudio;
	private int mStimuliIndex =0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get an instance of the SensorManager
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

		// Get an instance of the PowerManager
		mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);

		// Get an instance of the WindowManager
		mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
		mDisplay = mWindowManager.getDefaultDisplay();

		// Create a bright wake lock
		mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
				getClass().getName());

		// instantiate our simulation view and set it as the activity's content
		mSimulationView = new SimulationView(this);
		setContentView(mSimulationView);

		mAudioResultsFile = BilingualAphasiaTestHome.OUTPUT_DIRECTORY
				+ System.currentTimeMillis() + "_" + mParticipantId + "_" + mStimuliId
				+ ".mp3";
		Intent intent = new Intent(this, AudioRecorderService.class);
		// intent.setData(mUri);
		intent.putExtra(AudioRecorderService.EXTRA_AUDIOFILE_FULL_PATH,
				mAudioResultsFile);
		startService(intent);
		
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		/*
		 * when the activity is resumed, we acquire a wake-lock so that the screen
		 * stays on, since the user will likely not be fiddling with the screen or
		 * buttons.
		 */
		mWakeLock.acquire();

		// Start the simulation
		mSimulationView.startSimulation();


		mStimuliAudio = new ArrayList<Integer>();
		mStimuliAudio.add(R.raw.e_synonyms_instructions);
		mStimuliAudio.add(R.raw.e165);
		mStimuliAudio.add(R.raw.e166);
		mStimuliAudio.add(R.raw.e167);
		mStimuliIndex=0;
		playNext();
		
		
	}

	
	/**
	 * Play a sample with the Android MediaPLayer.
	 * http://stackoverflow.com/questions/2969242/problems-with-mediaplayer-raw-resources-stop-and-start
	 * @param resid Resource ID of the sample to play.
	 */
	private void playSample() {
		// if the index is outside of the array of stimuli
		if (mStimuliIndex >= mStimuliAudio.size()) {
			return;
		}
		try {
			if (mp != null) {
				mp.release();
				mp = null;
			}
			mp = MediaPlayer.create(getApplicationContext(), mStimuliAudio.get(mStimuliIndex));
		
			// on completion listener to play next audio
			mp.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					mStimuliIndex++;
					playNext();
				}
			});
			mp.start();
			
		} catch (IllegalArgumentException e) {
			Log.e(TAG,
					"Unable to play audio queue do to exception: " + e.getMessage(), e);
		} catch (IllegalStateException e) {
			Log.e(TAG,<commit_msg>voice recognizer works only when mediarecorder isnt running<commit_after>/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ca.ilanguage.oprime.bilingualaphasiatest.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ca.ilanguage.oprime.bilingualaphasiatest.R;
import ca.ilanguage.oprime.bilingualaphasiatest.service.AudioRecorderService;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.BitmapFactory.Options;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.speech.RecognizerIntent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * This is an example of using the accelerometer to integrate the device's
 * acceleration to a position using the Verlet method. This is illustrated with
 * a very simple particle system comprised of a few iron balls freely moving on
 * an inclined wooden table. The inclination of the virtual table is controlled
 * by the device's accelerometer.
 * 
 * @see SensorManager
 * @see SensorEvent
 * @see Sensor
 */

public class AccelerometerUIActivity extends Activity {

	private SimulationView mSimulationView;
	private SensorManager mSensorManager;
	private PowerManager mPowerManager;
	private WindowManager mWindowManager;
	private Display mDisplay;
	private WakeLock mWakeLock;

	private static final int ENGLISH = 0;
	private static final int FRENCH = 1;
	//wait between stimuli, if 999 then wait until user input.
	private static int waitBetweenStimuli = 5;
	public static final String LANGUAGE = "language";
	String mAudioResultsFile;
	MediaRecorder mRecorder;
	private String mParticipantId = "12";
	private String mStimuliId = "1";
	MediaPlayer mp;
	OnCompletionListener mAudioFinishedListener;
	private static final String TAG = "AccelerometerUIActivity";
	private ArrayList<Integer> mStimuliAudio;
	private int mStimuliIndex =0;
	
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	Context mContext;
	Boolean mSpeechRecognitionOkay;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get an instance of the SensorManager
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

		// Get an instance of the PowerManager
		mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);

		// Get an instance of the WindowManager
		mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
		mDisplay = mWindowManager.getDefaultDisplay();

		// Create a bright wake lock
		mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
				getClass().getName());

		// instantiate our simulation view and set it as the activity's content
		mSimulationView = new SimulationView(this);
		setContentView(mSimulationView);

		mAudioResultsFile = BilingualAphasiaTestHome.OUTPUT_DIRECTORY
				+ System.currentTimeMillis() + "_" + mParticipantId + "_" + mStimuliId
				+ ".mp3";
		Intent intent = new Intent(this, AudioRecorderService.class);
		// intent.setData(mUri);
		intent.putExtra(AudioRecorderService.EXTRA_AUDIOFILE_FULL_PATH,
				mAudioResultsFile);
		//startService(intent);

		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() != 0) {
			mSpeechRecognitionOkay = true;
			// speakButton.setOnClickListener(this);
		} else {
			Toast
					.makeText(
							AccelerometerUIActivity.this,
							"Speech recognizer is not present. Taking you to the market and install it. ",
							Toast.LENGTH_LONG).show();
			Intent goToMarket = new Intent(Intent.ACTION_VIEW).setData(Uri
					.parse("market://details?id=com.google.android.voicesearch"));
			startActivity(goToMarket);
			mSpeechRecognitionOkay = false;
		}
		
	}

	private void startVoiceRecognitionActivity() {
		if (mp != null) {
			mp.release();
			mp = null;
		}
		if (mSpeechRecognitionOkay) {
			Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
					RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
			// intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "no prompt");
			startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
		} else {
			finish();
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		/*
		 * when the activity is resumed, we acquire a wake-lock so that the screen
		 * stays on, since the user will likely not be fiddling with the screen or
		 * buttons.
		 */
		mWakeLock.acquire();

		// Start the simulation
		mSimulationView.startSimulation();


		mStimuliAudio = new ArrayList<Integer>();
		mStimuliAudio.add(R.raw.e_synonyms_instructions);
		mStimuliAudio.add(R.raw.e165);
		mStimuliAudio.add(R.raw.e166);
		mStimuliAudio.add(R.raw.e167);
		mStimuliIndex=0;
		playNext();
		
		
	}
	/**
   * Handle the results from the recognition activity.
   */
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
          // Fill the list view with the strings the recognizer thought it could have heard
          ArrayList<String> matches = data.getStringArrayListExtra(
                  RecognizerIntent.EXTRA_RESULTS);
          Toast.makeText(AccelerometerUIActivity.this, "Possible recognitions: "+matches.toString(), Toast.LENGTH_LONG).show();
//          mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
//                  matches));
          //finish();
          
          /*
           * Play next stimuli without waiting
           */
//        	mStimuliIndex++;
//					playNext();
      }
      
      super.onActivityResult(requestCode, resultCode, data);
      return;
  }
	
	/**
	 * Play a sample with the Android MediaPLayer.
	 * http://stackoverflow.com/questions/2969242/problems-with-mediaplayer-raw-resources-stop-and-start
	 * @param resid Resource ID of the sample to play.
	 */
	private void playSample() {
		// if the index is outside of the array of stimuli
		if (mStimuliIndex >= mStimuliAudio.size()) {
			return;
		}
		try {
			if (mp != null) {
				mp.release();
				mp = null;
			}
			mp = MediaPlayer.create(getApplicationContext(), mStimuliAudio.get(mStimuliIndex));
		
			// on completion listener to play next audio
			mp.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					
					/*get response*/
					startVoiceRecognitionActivity();
					
					
				
				}
			});
			mp.start();
			
		} catch (IllegalArgumentException e) {
			Log.e(TAG,
					"Unable to play audio queue do to exception: " + e.getMessage(), e);
		} catch (IllegalStateException e) {
			Log.e(TAG,
{'fraction_non_alphanumeric': 0.08918529199711608, 'fraction_numerical': 0.005695746214852199, 'mean_word_length': 4.240272006044579, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5046541', 'n_tokens_mistral': 4490, 'n_tokens_neox': 4038, 'n_words': 1146}