<commit_before>/*
 * Copyright (C) 2007 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.
 */
// This project is using one of the Android Open Source files, specifically FingerPaint.java
// Please note that this has been changed from the original versions to incorporate the Pressure Pen technology

package com.option8.PressurePaint;

import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class PressurePenActivity extends Activity
        implements ColorPickerDialog.OnColorChangedListener {
	
	private static MediaRecorder recorder = null;
	protected static int maxWidthPercent;
	protected static int minWidthPercent;
	private SharedPreferences prefs;
	private static Timer timer;
	private int testNumber = 0;
	private ScheduledExecutorService scheduler;
	private BroadcastReceiver receiver;
	public static final String PREFS_NAME = "MyPrefsFile";

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFF000000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(5);
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_HEADSET_PLUG);

        receiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
        	  if (intent.getIntExtra("state", -1) == 0){
        		  //state 0 = unplugged
        			scheduler.shutdown();
        			try {
        				if (scheduler.awaitTermination(500, TimeUnit.MILLISECONDS)){			
        			        if (recorder != null) {
        			        	recorder.stop();
        			        	recorder.release();
        			        	recorder = null;
        			        }
        				}
        			} catch (Exception e) {
        			}
        		  mPaint.setStrokeWidth(5);
        	  }
        	  else{
        		  initPressurePen();
        	  }
          }
        };

        registerReceiver(receiver, filter);

    }   

	@Override
	protected void onResume() {
		super.onResume();
		getPrefs();
        initPressurePen();
	}

	protected void initPressurePen() {
        if (recorder == null) {
//       	 you need to add the following line to the manifest for this to work
//       	 <uses-permission android:name="android.permission.RECORD_AUDIO"/>
       	 recorder = new MediaRecorder();
       	 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
       	 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
       	 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
       	 recorder.setOutputFile("/dev/null"); 
       	 try {
				recorder.prepare();
			} catch (Exception e) {
				Log.e("prepare", "oops");
				e.printStackTrace();
			}
       	 recorder.start();
        }
        scheduler = Executors.newScheduledThreadPool(1);
        final Runnable beeper = new Runnable() {
        	public void run() {
        		
        		// from Kindle Fire:
        		// min level ~1000
        		// max level ~21000
        		
        		float tempVolumeLevel = (recorder.getMaxAmplitude() - 1000)/200 ; // ~0 - 100
        		//float tempVolumeLevel = recorder.getMaxAmplitude()/328;
				float maxPenPressurePercent = 65;
				final float multiplier = maxPenPressurePercent / 100;
				final int volumePercent = (int) (tempVolumeLevel * multiplier);
				if (recorder != null){
					getWindow().getDecorView().findViewById(android.R.id.content).
					post(new Runnable() {
						@Override
						public void run() {
							if (volumePercent != 0){
								setStrokeWidthAccordingly(volumePercent);
							}
						}
					});
					if (findViewById(R.id.debugTextView) != null){
						final TextView debugTextView = (TextView) findViewById(R.id.debugTextView);
						debugTextView.post(new Runnable() {
							@Override
							public void run() {
								if (volumePercent != 0){
									debugTextView.setText(String.valueOf(volumePercent));
								}
//									debugTextView.setText(String.valueOf(testNumberMethod()));
							}
						});
					}
				}
        	}
        };     
        
//		you need to add the following line to the manifest for this to work:
//		<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
//		this only checks if the Pen is plugged in at onCreate time
//		we use a broadcast receiver for the intent: ACTION_HEADSET_PLUG to check if this changes
		AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		boolean penConnected = am.isWiredHeadsetOn();
		if (penConnected){
			int refreshDelay = 100;
			scheduler.scheduleWithFixedDelay(beeper, 0, refreshDelay, TimeUnit.MILLISECONDS);
		}	
	}
	
	@SuppressWarnings("unused")
	private int testNumberMethod() {
		testNumber ++;
		return testNumber;
	}
	
	private void setStrokeWidthAccordingly(int volumePercent) {
		float width = 5;
		float absoluteMaxWidth = 99;
		float relativeMinWidth = minWidthPercent;
		float relativeMaxWidth = relativeMinWidth + ((absoluteMaxWidth - relativeMinWidth) *
				maxWidthPercent / 100);
		width = relativeMinWidth + (relativeMaxWidth - relativeMinWidth) *
				volumePercent / 100;
		mPaint.setStrokeWidth(width);
	}

	private void getPrefs() {
		final String PREFS_NAME = "MyPrefsFile";
		prefs = getSharedPreferences(PREFS_NAME, 0);
		maxWidthPercent = prefs.getInt("maxWidthPercent", 70);
		minWidthPercent = prefs.getInt("minWidthPercent", 10);
		<commit_msg>incorporate some fixed from sardeenz<commit_after>/*
 * Copyright (C) 2007 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.
 */
// This project is using one of the Android Open Source files, specifically FingerPaint.java
// Please note that this has been changed from the original versions to incorporate the Pressure Pen technology

package com.option8.PressurePaint;

import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class PressurePenActivity extends Activity
        implements ColorPickerDialog.OnColorChangedListener {
	
	private static MediaRecorder recorder = null;
	protected static int maxWidthPercent;
	protected static int minWidthPercent;
	private SharedPreferences prefs;
	private static Timer timer;
	private int testNumber = 0;
	private ScheduledExecutorService scheduler;
	private BroadcastReceiver receiver;
	public static final String PREFS_NAME = "MyPrefsFile";

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFF000000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(5);
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_HEADSET_PLUG);

        receiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
        	  if (intent.getIntExtra("state", -1) == 0){
        		  //state 0 = unplugged
        			scheduler.shutdown();
        			try {
        				if (scheduler.awaitTermination(500, TimeUnit.MILLISECONDS)){			
        			        if (recorder != null) {
        			        	recorder.stop();
        			        	recorder.release();
        			        	recorder = null;
        			        }
        				}
        			} catch (Exception e) {
        			}
        		  mPaint.setStrokeWidth(5);
        	  }
        	  else{
        		  initPressurePen();
        	  }
          }
        };

        registerReceiver(receiver, filter);

    }   

	@Override
	protected void onResume() {
		super.onResume();
		getPrefs();
        initPressurePen();
	}

	protected void initPressurePen() {
        if (recorder == null) {
//       	 you need to add the following line to the manifest for this to work
//       	 <uses-permission android:name="android.permission.RECORD_AUDIO"/>
       	 recorder = new MediaRecorder();
       	 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
       	 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
       	 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
       	 recorder.setOutputFile("/dev/null"); 
       	 try {
				recorder.prepare();
			} catch (Exception e) {
				Log.e("prepare", "oops");
				e.printStackTrace();
			}
       	 recorder.start();
        }
        scheduler = Executors.newScheduledThreadPool(1);
        final Runnable beeper = new Runnable() {
        	public void run() {
        		
        		// from Kindle Fire:
        		// min level ~1000
        		// max level ~21000
        		
        		float tempVolumeLevel = (recorder.getMaxAmplitude() - 1000)/200 ; // ~0 - 100
        		//float tempVolumeLevel = recorder.getMaxAmplitude()/328;
				float maxPenPressurePercent = 65;
				final float multiplier = maxPenPressurePercent / 100;
				final int volumePercent = (int) (tempVolumeLevel * multiplier);
				if (recorder != null){
					getWindow().getDecorView().findViewById(android.R.id.content).
					post(new Runnable() {
						@Override
						public void run() {
							if (volumePercent != 0){
								setStrokeWidthAccordingly(volumePercent);
							}
						}
					});
					if (findViewById(R.id.debugTextView) != null){
						final TextView debugTextView = (TextView) findViewById(R.id.debugTextView);
						debugTextView.post(new Runnable() {
							@Override
							public void run() {
								if (volumePercent >= 0){
									debugTextView.setText(String.valueOf(volumePercent));
								}
//									debugTextView.setText(String.valueOf(testNumberMethod()));
							}
						});
					}
				}
        	}
        };     
        
//		you need to add the following line to the manifest for this to work:
//		<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
//		this only checks if the Pen is plugged in at onCreate time
//		we use a broadcast receiver for the intent: ACTION_HEADSET_PLUG to check if this changes
		AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		boolean penConnected = am.isWiredHeadsetOn();
		if (penConnected){
			int refreshDelay = 100;
			scheduler.scheduleWithFixedDelay(beeper, 0, refreshDelay, TimeUnit.MILLISECONDS);
		}	
	}
	
	@SuppressWarnings("unused")
	private int testNumberMethod() {
		testNumber ++;
		return testNumber;
	}
	
	private void setStrokeWidthAccordingly(int volumePercent) {
		float width = 5;
		float absoluteMaxWidth = 99;
		float relativeMinWidth = minWidthPercent;
		float relativeMaxWidth = relativeMinWidth + ((absoluteMaxWidth - relativeMinWidth) *
				maxWidthPercent / 100);
		width = relativeMinWidth + (relativeMaxWidth - relativeMinWidth) *
				volumePercent / 100;
		//mPaint.setStrokeWidth(width);
		float vol = volumePercent;
		mPaint.setStrokeWidth(vol);
	}

	private void getPrefs() {
		final String PREFS_NAME = "MyPrefsFile";
		prefs = getSharedPreferences(PREFS_NAME, 0);
		maxWidthPercent = prefs.getInt("maxWidthPercent", 70);
		minWidthPercent = prefs.getInt("minWidthPercent", 10);
		
{'fraction_non_alphanumeric': 0.09363455527138391, 'fraction_numerical': 0.010514350667803353, 'mean_word_length': 2.975430669302457, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2772118', 'n_tokens_mistral': 4531, 'n_tokens_neox': 3933, 'n_words': 1012}