file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
HungerGamesPlayer.java | /FileExtraction/Java_unseen/PatoTheBest_MiniGames/Games/HungerGames/src/main/java/me/patothebest/hungergames/player/HungerGamesPlayer.java | package me.patothebest.hungergames.player;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import me.patothebest.gamecore.lang.Locale;
import me.patothebest.gamecore.player.CorePlayer;
import me.patothebest.gamecore.scoreboard.ScoreboardFile;
public class HungerGamesPlayer extends CorePlayer {
@Inject private HungerGamesPlayer(ScoreboardFile scoreboardFile, @Assisted Locale defaultLocale) {
super(scoreboardFile, defaultLocale);
}
}
| 490 | Java | .java | PatoTheBest/MiniGames | 13 | 2 | 1 | 2020-08-07T03:43:56Z | 2022-01-23T23:52:46Z |
Preferences.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/edu/mit/mobile/android/demomode/Preferences.java | package edu.mit.mobile.android.demomode;
/*
* Copyright (C) 2012 MIT Mobile Experience Lab
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License Version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import android.content.ComponentName;
import android.content.ContentProviderOperation;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class Preferences extends PreferenceActivity implements OnPreferenceClickListener {
private static final String TAG = Preferences.class.getSimpleName();
private SharedPreferences mPrefs;
public static final String KEY_PASSWORD = "password";
public static final String KEY_LOCKED = "locked";
public static final String KEY_SHARE_CONFIG = "share_config";
public static final String KEY_SCAN_CONFIG = "scan_config";
public static final String KEY_ENABLED = "enable";
private static String CFG_PKG_SEP = ",";
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.addPreferencesFromResource(R.xml.preferences);
mPrefs = getPreferenceManager().getSharedPreferences();
findPreference(KEY_SHARE_CONFIG).setOnPreferenceClickListener(this);
findPreference(KEY_SCAN_CONFIG).setOnPreferenceClickListener(this);
mPrefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (KEY_ENABLED.equals(key)) {
updateDemoModeEnabled();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if (mPrefs.getBoolean(KEY_LOCKED, false)) {
finish();
}
}
private static final String CFG_K_VER = "v", CFG_K_SECRETKEY = "k", CFG_K_APPS = "a";
public static final String CFG_MIME_TYPE = "application/x-demo-mode";
private String toConfigString() {
final String password = mPrefs.getString(KEY_PASSWORD, null);
final ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();
int ver;
try {
ver = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch (final NameNotFoundException e) {
// this should never happen
ver = 0;
e.printStackTrace();
}
nvp.add(new BasicNameValuePair(CFG_K_VER, String.valueOf(ver)));
nvp.add(new BasicNameValuePair(CFG_K_SECRETKEY, password));
final Cursor c = getContentResolver().query(LauncherItem.CONTENT_URI, null, null, null,
null);
try {
final int pkgCol = c.getColumnIndex(LauncherItem.PACKAGE_NAME);
final int actCol = c.getColumnIndex(LauncherItem.ACTIVITY_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
nvp.add(new BasicNameValuePair(CFG_K_APPS, c.getString(pkgCol) + CFG_PKG_SEP
+ c.getString(actCol)));
}
return "data:" + CFG_MIME_TYPE + "," + URLEncodedUtils.format(nvp, "utf-8");
} finally {
c.close();
}
}
private void shareConfig() {
startActivity(Intent.createChooser(
new Intent(Intent.ACTION_SEND).setType("text/plain")
.putExtra(Intent.EXTRA_TEXT, toConfigString())
.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.app_name) + " Config"),
getText(R.string.share_config)));
}
private void fromCfgString(String cfg) {
final Uri cfgUri = Uri.parse(cfg);
if ("data".equals(cfgUri.getScheme())) {
final String[] cfgParts = cfgUri.getEncodedSchemeSpecificPart().split(",", 2);
if (CFG_MIME_TYPE.equals(cfgParts[0])) {
final Editor ed = mPrefs.edit();
final ArrayList<ContentProviderOperation> cpos = new ArrayList<ContentProviderOperation>();
// first erase everything
cpos.add(ContentProviderOperation.newDelete(LauncherItem.CONTENT_URI).build());
try {
final StringEntity entity = new StringEntity(cfgParts[1]);
entity.setContentType("application/x-www-form-urlencoded");
final List<NameValuePair> nvp = URLEncodedUtils.parse(entity);
for (final NameValuePair pair : nvp) {
final String name = pair.getName();
Log.d(TAG, "parsed pair: " + pair);
if (CFG_K_SECRETKEY.equals(name)) {
ed.putString(KEY_PASSWORD, pair.getValue());
} else if (CFG_K_APPS.equals(name)) {
final String[] app = pair.getValue().split(CFG_PKG_SEP, 2);
final ContentProviderOperation cpo = ContentProviderOperation
.newInsert(LauncherItem.CONTENT_URI)
.withValue(LauncherItem.PACKAGE_NAME, app[0])
.withValue(LauncherItem.ACTIVITY_NAME, app[1]).build();
cpos.add(cpo);
Log.d(TAG, "adding " + cpo);
}
}
ed.commit();
getContentResolver().applyBatch(HomescreenProvider.AUTHORITY, cpos);
} catch (final UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e(TAG, "unknown MIME type for data URI: " + cfgParts[0]);
}
} else {
Log.e(TAG, "not a data URI");
}
}
private void scanQRCode() {
final IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
final IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,
resultCode, intent);
if (scanResult != null && scanResult.getContents() != null) {
fromCfgString(scanResult.getContents());
}
}
@Override
public boolean onPreferenceClick(Preference preference) {
final String pref = preference.getKey();
if (KEY_SCAN_CONFIG.equals(pref)) {
scanQRCode();
return true;
} else if (KEY_SHARE_CONFIG.equals(pref)) {
shareConfig();
return true;
}
return false;
}
private void updateDemoModeEnabled() {
getPackageManager()
.setComponentEnabledSetting(
new ComponentName(this, DemoMode.class),
mPrefs.getBoolean(KEY_ENABLED, true) ? PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
| 7,806 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
HomescreenProvider.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/edu/mit/mobile/android/demomode/HomescreenProvider.java | package edu.mit.mobile.android.demomode;
/*
* Copyright (C) 2012 MIT Mobile Experience Lab
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License Version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import edu.mit.mobile.android.content.GenericDBHelper;
import edu.mit.mobile.android.content.SimpleContentProvider;
public class HomescreenProvider extends SimpleContentProvider {
public static final String AUTHORITY = "edu.mit.mobile.android.demomode";
private static final int DB_VERSION = 1;
public HomescreenProvider() {
super(AUTHORITY, DB_VERSION);
}
@Override
public boolean onCreate() {
super.onCreate();
final GenericDBHelper items = new GenericDBHelper(LauncherItem.class);
addDirAndItemUri(items, LauncherItem.PATH);
return true;
}
}
| 1,251 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
LauncherItem.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/edu/mit/mobile/android/demomode/LauncherItem.java | package edu.mit.mobile.android.demomode;
/*
* Copyright (C) 2012 MIT Mobile Experience Lab
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License Version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import android.net.Uri;
import edu.mit.mobile.android.content.ContentItem;
import edu.mit.mobile.android.content.ProviderUtils;
import edu.mit.mobile.android.content.UriPath;
import edu.mit.mobile.android.content.column.DBColumn;
import edu.mit.mobile.android.content.column.TextColumn;
@UriPath(LauncherItem.PATH)
public class LauncherItem implements ContentItem {
@DBColumn(type = TextColumn.class)
public static final String PACKAGE_NAME = "package";
@DBColumn(type = TextColumn.class)
public static final String ACTIVITY_NAME = "activity";
public static final String PATH = "apps";
public static Uri CONTENT_URI = ProviderUtils.toContentUri(HomescreenProvider.AUTHORITY, PATH);
}
| 1,378 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
DemoMode.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/edu/mit/mobile/android/demomode/DemoMode.java | package edu.mit.mobile.android.demomode;
/*
* Copyright (C) 2012 MIT Mobile Experience Lab
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License Version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.home.ApplicationInfo;
public class DemoMode extends FragmentActivity implements LoaderCallbacks<Cursor>,
OnItemClickListener, OnItemLongClickListener {
@SuppressWarnings("unused")
private static final String TAG = DemoMode.class.getSimpleName();
private GridView mGridView;
private GridView mAllApps;
private LauncherItemAdapter mAdapter;
private static ArrayList<ApplicationInfo> mApplications;
private boolean mLocked;
private String mPassword;
private SharedPreferences mPrefs;
private SlidingDrawer mDrawer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGridView = (GridView) findViewById(R.id.grid);
getSupportLoaderManager().initLoader(0, null, this);
mAdapter = new LauncherItemAdapter(this, R.layout.launcher_item, null);
mGridView.setAdapter(mAdapter);
mGridView.setOnItemClickListener(this);
mGridView.setOnItemLongClickListener(this);
mAllApps = (GridView) findViewById(R.id.all_apps);
loadApplications(true);
mDrawer = (SlidingDrawer) findViewById(R.id.slidingDrawer1);
mAllApps.setAdapter(new ApplicationsAdapter(this, mApplications));
mAllApps.setOnItemClickListener(this);
mAllApps.setOnItemLongClickListener(this);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
mPassword = mPrefs.getString(Preferences.KEY_PASSWORD, null);
mLocked = mPrefs.getBoolean(Preferences.KEY_LOCKED, false);
updateLocked();
}
/**
* Loads the list of installed applications in mApplications.
*/
private void loadApplications(boolean isLaunching) {
if (isLaunching && mApplications != null) {
return;
}
final PackageManager manager = getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
if (apps != null) {
final int count = apps.size();
if (mApplications == null) {
mApplications = new ArrayList<ApplicationInfo>(count);
}
mApplications.clear();
for (int i = 0; i < count; i++) {
final ApplicationInfo application = new ApplicationInfo();
final ResolveInfo info = apps.get(i);
application.title = info.loadLabel(manager);
application.setActivity(new ComponentName(
info.activityInfo.applicationInfo.packageName, info.activityInfo.name),
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
application.icon = info.activityInfo.loadIcon(manager);
mApplications.add(application);
}
}
}
private static class LauncherItemAdapter extends CursorAdapter {
private final LayoutInflater mLayoutInflater;
private final int mLayout;
private final PackageManager mPackageManager;
private final int mAppIconWidth;
private final int mAppIconHeight;
public LauncherItemAdapter(Context context, int layout, Cursor c) {
super(context, c, 0);
mLayout = layout;
mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
mPackageManager = context.getPackageManager();
final Resources resources = context.getResources();
mAppIconWidth = (int) resources.getDimension(android.R.dimen.app_icon_size);
mAppIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);
}
private Drawable scaleDrawableToAppIconSize(Drawable icon) {
int width = mAppIconWidth;
int height = mAppIconHeight;
final int iconWidth = icon.getIntrinsicWidth();
final int iconHeight = icon.getIntrinsicHeight();
if (width > 0 && height > 0 && (width < iconWidth || height < iconHeight)) {
final float ratio = (float) iconWidth / iconHeight;
if (iconWidth > iconHeight) {
height = (int) (width / ratio);
} else if (iconHeight > iconWidth) {
width = (int) (height * ratio);
}
}
icon.setBounds(0, 0, width, height);
return icon;
}
@Override
public void bindView(View v, Context context, Cursor c) {
final String pkg = c.getString(c.getColumnIndex(LauncherItem.PACKAGE_NAME));
final String cls = c.getString(c.getColumnIndex(LauncherItem.ACTIVITY_NAME));
final ComponentName activity = new ComponentName(pkg, cls);
try {
final ActivityInfo i = mPackageManager.getActivityInfo(activity, 0);
final android.content.pm.ApplicationInfo appInfo = mPackageManager
.getApplicationInfo(pkg, 0);
final TextView label = (TextView) v.findViewById(R.id.label);
final Drawable icon = i.loadIcon(mPackageManager);
scaleDrawableToAppIconSize(icon);
label.setCompoundDrawables(null, icon, null, null);
label.setText(mPackageManager.getText(cls,
i.labelRes == 0 ? i.applicationInfo.labelRes : i.labelRes, appInfo));
} catch (final NameNotFoundException e) {
e.printStackTrace();
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View v = mLayoutInflater.inflate(mLayout, parent, false);
bindView(v, context, cursor);
return v;
}
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(this, LauncherItem.CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
mAdapter.swapCursor(c);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.lock).setVisible(!mLocked);
menu.findItem(R.id.unlock).setVisible(mLocked);
menu.findItem(R.id.settings).setVisible(!mLocked);
menu.findItem(R.id.preferences).setVisible(!mLocked);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onBackPressed() {
if (!mLocked) {
super.onBackPressed();
}
}
@SuppressWarnings("deprecation")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
return true;
case R.id.lock:
setLocked(true);
return true;
case R.id.unlock:
showDialog(DIALOG_PASSWORD, null);
return true;
case R.id.preferences:
startActivity(new Intent(this, Preferences.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setLocked(boolean locked) {
mPrefs.edit().putBoolean(Preferences.KEY_LOCKED, locked).commit();
mLocked = locked;
updateLocked();
}
private void updateLocked() {
findViewById(R.id.slidingDrawer1).setVisibility(mLocked ? View.GONE : View.VISIBLE);
if (mLocked) {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
} else {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mLocked && keyCode != KeyEvent.KEYCODE_MENU) {
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (mLocked) {
return true;
} else {
return super.onKeyLongPress(keyCode, event);
}
}
/**
* GridView adapter to show the list of all installed applications.
*/
private class ApplicationsAdapter extends ArrayAdapter<ApplicationInfo> {
private final Rect mOldBounds = new Rect();
private final int mAppIconHeight;
private final int mAppIconWidth;
public ApplicationsAdapter(Context context, ArrayList<ApplicationInfo> apps) {
super(context, 0, apps);
final Resources resources = getContext().getResources();
mAppIconWidth = (int) resources.getDimension(android.R.dimen.app_icon_size);
mAppIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ApplicationInfo info = mApplications.get(position);
if (convertView == null) {
final LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.launcher_item, parent, false);
}
Drawable icon = info.icon;
if (!info.filtered) {
int width = mAppIconWidth;
int height = mAppIconHeight;
final int iconWidth = icon.getIntrinsicWidth();
final int iconHeight = icon.getIntrinsicHeight();
if (icon instanceof PaintDrawable) {
final PaintDrawable painter = (PaintDrawable) icon;
painter.setIntrinsicWidth(width);
painter.setIntrinsicHeight(height);
}
if (width > 0 && height > 0 && (width < iconWidth || height < iconHeight)) {
final float ratio = (float) iconWidth / iconHeight;
if (iconWidth > iconHeight) {
height = (int) (width / ratio);
} else if (iconHeight > iconWidth) {
width = (int) (height * ratio);
}
final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
final Bitmap thumb = Bitmap.createBitmap(width, height, c);
final Canvas canvas = new Canvas(thumb);
canvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, 0));
// Copy the old bounds to restore them later
// If we were to do oldBounds = icon.getBounds(),
// the call to setBounds() that follows would
// change the same instance and we would lose the
// old bounds
mOldBounds.set(icon.getBounds());
icon.setBounds(0, 0, width, height);
icon.draw(canvas);
icon.setBounds(mOldBounds);
icon = info.icon = new BitmapDrawable(getResources(), thumb);
info.filtered = true;
}
}
final TextView textView = (TextView) convertView.findViewById(R.id.label);
textView.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null);
textView.setText(info.title);
return convertView;
}
}
private static final int DIALOG_PASSWORD = 100;
@SuppressWarnings("deprecation")
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
switch (id) {
case DIALOG_PASSWORD: {
final EditText v = (EditText) getLayoutInflater().inflate(R.layout.password, null);
return new AlertDialog.Builder(this)
.setView(v)
.setCancelable(true)
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
v.getEditableText().clear();
}
})
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mPassword.equals(v.getText().toString())) {
setLocked(false);
} else {
Toast.makeText(getApplicationContext(),
R.string.toast_incorrect_password,
Toast.LENGTH_SHORT).show();
}
v.getEditableText().clear();
}
}).create();
}
default:
return super.onCreateDialog(id, args);
}
}
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
switch (adapter.getId()) {
case R.id.grid: {
final Intent launch = new Intent();
final Cursor c = mAdapter.getCursor();
launch.setClassName(c.getString(c.getColumnIndex(LauncherItem.PACKAGE_NAME)),
c.getString(c.getColumnIndex(LauncherItem.ACTIVITY_NAME)));
launch.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);
}
break;
case R.id.all_apps: {
final ApplicationInfo appInfo = (ApplicationInfo) mAllApps.getAdapter().getItem(
position);
startActivity(appInfo.intent);
}
break;
}
}
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View v, int position, long id) {
switch (adapter.getId()) {
case R.id.grid: {
if (!mLocked) {
getContentResolver().delete(
ContentUris.withAppendedId(LauncherItem.CONTENT_URI, id), null, null);
return true;
}
}
break;
case R.id.all_apps: {
final ApplicationInfo appInfo = (ApplicationInfo) mAllApps
.getItemAtPosition(position);
final ContentValues cv = new ContentValues();
final ComponentName c = appInfo.intent.getComponent();
cv.put(LauncherItem.ACTIVITY_NAME, c.getClassName());
cv.put(LauncherItem.PACKAGE_NAME, c.getPackageName());
getContentResolver().insert(LauncherItem.CONTENT_URI, cv);
mDrawer.close();
return true;
}
}
return false;
}
}
| 19,116 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
ApplicationInfo.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/com/example/android/home/ApplicationInfo.java | /*
* 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.
*/
package com.example.android.home;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.drawable.Drawable;
/**
* Represents a launchable application. An application is made of a name (or title), an intent
* and an icon.
*/
public class ApplicationInfo {
/**
* The application name.
*/
public CharSequence title;
/**
* The intent used to start the application.
*/
public Intent intent;
/**
* The application icon.
*/
public Drawable icon;
/**
* When set to true, indicates that the icon has been resized.
*/
public boolean filtered;
/**
* Creates the application intent based on a component name and various launch flags.
*
* @param className the class name of the component representing the intent
* @param launchFlags the launch flags
*/
public final void setActivity(ComponentName className, int launchFlags) {
intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(className);
intent.setFlags(launchFlags);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ApplicationInfo)) {
return false;
}
final ApplicationInfo that = (ApplicationInfo) o;
return title.equals(that.title) &&
intent.getComponent().getClassName().equals(
that.intent.getComponent().getClassName());
}
@Override
public int hashCode() {
int result;
result = (title != null ? title.hashCode() : 0);
final String name = intent.getComponent().getClassName();
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
| 2,478 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
IntentResult.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/com/google/zxing/integration/android/IntentResult.java | /*
* Copyright 2009 ZXing authors
*
* 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 com.google.zxing.integration.android;
/**
* <p>Encapsulates the result of a barcode scan invoked through {@link IntentIntegrator}.</p>
*
* @author Sean Owen
*/
public final class IntentResult {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResult() {
this(null, null, null, null, null);
}
IntentResult(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
/**
* @return raw content of barcode
*/
public String getContents() {
return contents;
}
/**
* @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
*/
public String getFormatName() {
return formatName;
}
/**
* @return raw bytes of the barcode content, if applicable, or null otherwise
*/
public byte[] getRawBytes() {
return rawBytes;
}
/**
* @return rotation of the image, in degrees, which resulted in a successful scan. May be null.
*/
public Integer getOrientation() {
return orientation;
}
/**
* @return name of the error correction level used in the barcode, if applicable
*/
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
@Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
| 2,781 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
IntentIntegrator.java | /FileExtraction/Java_unseen/mitmel_Demo-Mode/src/com/google/zxing/integration/android/IntentIntegrator.java | /*
* Copyright 2009 ZXing authors
*
* 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 com.google.zxing.integration.android;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;
/**
* <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
* way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
* project's source code.</p>
*
* <h2>Initiating a barcode scan</h2>
*
* <p>To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
* for the result in your app.</p>
*
* <p>It does require that the Barcode Scanner (or work-alike) application is installed. The
* {@link #initiateScan()} method will prompt the user to download the application, if needed.</p>
*
* <p>There are a few steps to using this integration. First, your {@link Activity} must implement
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p>
*
* <pre>{@code
* public void onActivityResult(int requestCode, int resultCode, Intent intent) {
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
* if (scanResult != null) {
* // handle scan result
* }
* // else continue with any other code you need in the method
* ...
* }
* }</pre>
*
* <p>This is where you will handle a scan result.</p>
*
* <p>Second, just call this in response to a user action somewhere to begin the scan process:</p>
*
* <pre>{@code
* IntentIntegrator integrator = new IntentIntegrator(yourActivity);
* integrator.initiateScan();
* }</pre>
*
* <p>Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
* user was prompted to download the application. This lets the calling app potentially manage the dialog.
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
* method.</p>
*
* <p>You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
* yes/no button labels can be changed.</p>
*
* <p>By default, this will only allow applications that are known to respond to this intent correctly
* do so. The apps that are allowed to response can be set with {@link #setTargetApplications(Collection)}.
* For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.</p>
*
* <h2>Sharing text via barcode</h2>
*
* <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.</p>
*
* <p>Some code, particularly download integration, was contributed from the Anobiit application.</p>
*
* @author Sean Owen
* @author Fred Lin
* @author Isaac Potoczny-Jones
* @author Brad Drehmer
* @author gcstang
*/
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final Collection<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singleton(BS_PACKAGE);
public static final Collection<String> TARGET_ALL_KNOWN = list(
BS_PACKAGE, // Barcode Scanner
"com.srowen.bs.android", // Barcode Scanner+
"com.srowen.bs.android.simple" // Barcode Scanner+ Simple
// TODO add more -- what else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private Collection<String> targetApplications;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public void setTargetApplications(Collection<String> targetApplications) {
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singleton(targetApplication);
}
/**
* Initiates a scan for all known barcode types.
*/
public AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
/**
* Initiates a scan only for a certain set of barcode types, given as strings corresponding
* to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
* like {@link #PRODUCT_CODE_TYPES} for example.
*/
public AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
/**
* Start an activity.<br>
* This method is defined to allow different methods of activity starting for
* newer versions of Android and for compatibility library.
*
* @param intent Intent to start.
* @param code Request code for the activity
* @see android.app.Activity#startActivityForResult(Intent, int)
* @see android.app.Fragment#startActivityForResult(Intent, int)
*/
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApplications.contains(packageName)) {
return packageName;
}
}
}
return null;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://details?id=" + BS_PACKAGE);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG, "Android Market is not installed; cannot install Barcode Scanner");
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
return downloadDialog.show();
}
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Shares the given text by encoding it as a barcode, such that another user can
* scan the text off the screen of the device.
*
* @param text the text string to encode as a barcode
*/
public void shareText(CharSequence text) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
showDownloadDialog();
} else {
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
}
private static Collection<String> list(String... values) {
return Collections.unmodifiableCollection(Arrays.asList(values));
}
}
| 12,888 | Java | .java | mitmel/Demo-Mode | 32 | 18 | 1 | 2012-03-20T15:44:30Z | 2013-03-01T20:02:00Z |
DialerTalkerService.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/DialerTalkerService.java | package com.matejdro.pebbledialer;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebbledialer.modules.CallLogModule;
import com.matejdro.pebbledialer.modules.CallModule;
import com.matejdro.pebbledialer.modules.ContactsModule;
import com.matejdro.pebbledialer.modules.NumberPickerModule;
import com.matejdro.pebbledialer.modules.SMSReplyModule;
import com.matejdro.pebbledialer.modules.SystemModule;
public class DialerTalkerService extends PebbleTalkerService
{
@Override
public void onCreate() {
super.onCreate();
// Disable until properly tested
setEnableDeveloperConnectionRefreshing(false);
}
@Override
public void registerModules()
{
addModule(new SystemModule(this), SystemModule.MODULE_SYSTEM);
addModule(new CallModule(this), CallModule.MODULE_CALL);
addModule(new CallLogModule(this), CallLogModule.MODULE_CALL_LOG);
addModule(new NumberPickerModule(this), NumberPickerModule.MODULE_NUMBER_PICKER);
addModule(new ContactsModule(this), ContactsModule.MODULE_CONTACTS);
addModule(new SMSReplyModule(this), SMSReplyModule.MODULE_SMS_REPLIES);
}
}
| 1,194 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
PebbleDialerApplication.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/PebbleDialerApplication.java | package com.matejdro.pebbledialer;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.preference.PreferenceManager;
import com.crashlytics.android.Crashlytics;
import com.matejdro.pebblecommons.PebbleCompanionApplication;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebblecommons.util.LogWriter;
import com.matejdro.pebblecommons.util.RTLUtility;
import com.matejdro.pebblecommons.util.TextUtil;
import io.fabric.sdk.android.Fabric;
import java.util.UUID;
import timber.log.Timber;
/**
* Created by Matej on 28.12.2014.
*/
public class PebbleDialerApplication extends PebbleCompanionApplication
{
public static final UUID WATCHAPP_UUID = UUID.fromString("158A074D-85CE-43D2-AB7D-14416DDC1058");
@Override
public void onCreate() {
super.onCreate();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Timber.setAppTag("PebbleDialer");
Timber.plant(new Timber.AppTaggedDebugTree());
LogWriter.init(preferences, "PebbleDialer", this);
boolean isDebuggable = ( 0 != ( getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) );
if (!isDebuggable)
Fabric.with(this, new Crashlytics());
boolean rtlEnabled = preferences.getBoolean("EnableRTL", true);
RTLUtility.getInstance().setEnabled(rtlEnabled);
}
@Override
public UUID getPebbleAppUUID()
{
return WATCHAPP_UUID;
}
@Override
public Class<? extends PebbleTalkerService> getTalkerServiceClass()
{
return DialerTalkerService.class;
}
}
| 1,669 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
CallStatusReceiver.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/CallStatusReceiver.java | package com.matejdro.pebbledialer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.matejdro.pebbledialer.modules.CallModule;
import timber.log.Timber;
/**
* Created by Matej on 31.12.2014.
*/
public class CallStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Timber.d("callStatusReceived");
Intent startIntent = new Intent(context, DialerTalkerService.class);
startIntent.setAction(CallModule.INTENT_CALL_STATUS);
startIntent.putExtra("callIntent", intent);
context.startService(startIntent);
}
}
| 686 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
StringListPopup.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/StringListPopup.java | package com.matejdro.pebbledialer.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.matejdro.pebblecommons.util.ListSerialization;
import com.matejdro.pebbledialer.R;
import java.util.ArrayList;
import java.util.List;
public class StringListPopup extends Dialog
{
private int titleResurce;
private SharedPreferences settings;
private String setting;
private List<String> storage = new ArrayList<String>();
private List<TextView> listViews = new ArrayList<TextView>();
private List<View> listSeparators = new ArrayList<View>();
private DisplayMetrics displayMetrics;
private LinearLayout listContainer;
private TextView listEmptyText;
private Button addButton;
private boolean changed = false;
public StringListPopup(Context context, int titleResurce, SharedPreferences settings, String setting)
{
super(context);
this.titleResurce = titleResurce;
this.settings = settings;
this.setting = setting;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setTitle(titleResurce);
setContentView(R.layout.stringlistpopup);
((Button) findViewById(R.id.closeButton)).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dismiss();
}
});
displayMetrics = getContext().getResources().getDisplayMetrics();
addButton = (Button) findViewById(R.id.addButton);
listContainer = (LinearLayout) findViewById(R.id.listContainer);
listEmptyText = (TextView) findViewById(R.id.listEmptyText);
addButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
openAddDialog("");
}
});
load();
setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
save();
}
});
}
private TextView createViewItem(String text)
{
TextView view = new TextView(getContext());
view.setText(text);
view.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
int id = listViews.indexOf(view);
openEditDialog(id, storage.get(id));
}
});
view.setBackgroundResource(R.drawable.list_background);
return view;
}
private View createSeparatorView()
{
View view = new View(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dpToPixels(2));
params.setMargins(dpToPixels(30), dpToPixels(2), dpToPixels(30), dpToPixels(10));
view.setLayoutParams(params);
view.setBackgroundColor(0xFFDDDDDD);
return view;
}
protected void openAddDialog(String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
final EditText editField = new EditText(getContext());
editField.setText(text);
builder.setTitle(R.string.add);
builder.setView(editField);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
add(editField.getText().toString());
}
});
builder.setNegativeButton(R.string.cancel, null);
builder.show();
}
protected void openEditDialog(final int id, String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
final EditText editField = new EditText(getContext());
editField.setText(text);
builder.setTitle(R.string.edit);
builder.setView(editField);
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
update(id, editField.getText().toString());
}
});
builder.setNeutralButton(R.string.delete, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
remove(id);
}
});
builder.setNegativeButton(R.string.cancel, null);
builder.show();
}
public void remove(int id)
{
changed = true;
View textView = listViews.get(id);
listContainer.removeView(textView);
listViews.remove(id);
if (storage.size() > 1)
{
int separatorToRemove = id;
if (separatorToRemove >= storage.size())
separatorToRemove--;
View separatorView = listSeparators.get(separatorToRemove);
listSeparators.remove(separatorToRemove);
listContainer.removeView(separatorView);
}
storage.remove(id);
if (storage.isEmpty())
listEmptyText.setVisibility(View.VISIBLE);
}
public void add(String text)
{
changed = true;
TextView listItem = createViewItem(text);
View separator = createSeparatorView();
storage.add(text);
listViews.add(listItem);
listSeparators.add(separator);
if (storage.size() > 1)
listContainer.addView(separator);
listContainer.addView(listItem);
listEmptyText.setVisibility(View.GONE);
}
public void update(int id, String text)
{
changed = true;
storage.set(id, text);
listViews.get(id).setText(text);
}
private int dpToPixels(int dp)
{
return (int)((dp * displayMetrics.density) + 0.5);
}
protected void load()
{
List<String> entries = ListSerialization.loadList(settings, setting);
for (String item : entries)
add(item);
changed = false;
}
protected void save()
{
SharedPreferences.Editor editor = settings.edit();
ListSerialization.saveList(editor, storage, setting);
editor.apply();
}
}
| 6,843 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
DialogVibrationPatternPicker.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/DialogVibrationPatternPicker.java | package com.matejdro.pebbledialer.ui;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.matejdro.pebblecommons.vibration.VibrationPatternPicker;
import com.matejdro.pebbledialer.R;
public class DialogVibrationPatternPicker extends DialogFragment
{
private VibrationPatternPicker vibrationPatternPicker;
private SharedPreferences sharedPreferences;
@Override
public void onAttach(Context context)
{
super.onAttach(context);
if (context instanceof PreferenceSource)
sharedPreferences = ((PreferenceSource) context).getCustomPreferences();
else
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
return inflater.inflate(R.layout.dialog_vibration_pattern, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
String currentPattern = sharedPreferences.getString("vibrationPattern", "100, 100, 100, 1000");
vibrationPatternPicker = (VibrationPatternPicker) view.findViewById(R.id.vibration_pattern_picker);
vibrationPatternPicker.setCurrentPattern(currentPattern);
vibrationPatternPicker.setAddedPause(1000);
view.findViewById(R.id.button_help).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showHelp();
}
});
view.findViewById(R.id.button_ok).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onOkPressed();
}
});
view.findViewById(R.id.button_cancel).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onCancelPressed();
}
});
}
private void showHelp()
{
new AlertDialog.Builder(getContext())
.setTitle(R.string.setting_vibration_pattern)
.setMessage(R.string.setting_vibration_pattern_dialog_description)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void onCancelPressed()
{
dismiss();
}
private void onOkPressed()
{
String newPattern = vibrationPatternPicker.validateAndGetCurrentPattern();
if (newPattern != null)
{
dismiss();
sharedPreferences.edit().putString("vibrationPattern", newPattern).apply();
}
}
}
| 3,078 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
ContactGroupsPickerDialog.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/ContactGroupsPickerDialog.java | package com.matejdro.pebbledialer.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.matejdro.pebblecommons.util.ListSerialization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ContactGroupsPickerDialog
{
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor preferencesEditor;
private List<ContactGroup> contactGroups;
private boolean[] checkedItems;
public ContactGroupsPickerDialog(Context context, SharedPreferences sharedPreferences, SharedPreferences.Editor preferencesEditor)
{
this.context = context;
this.sharedPreferences = sharedPreferences;
this.preferencesEditor = preferencesEditor;
}
public void show()
{
List<Integer> existingSettings = ListSerialization.loadIntegerList(sharedPreferences, "displayedGroupsListNew");
contactGroups = getAllContactGroups(context);
checkedItems = new boolean[contactGroups.size()];
for (int i = 0; i < contactGroups.size(); i++)
{
if (existingSettings.contains(contactGroups.get(i).getId()))
{
checkedItems[i] = true;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMultiChoiceItems(getNameArray(contactGroups), checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
}
}).setPositiveButton("OK", new OKButtonListener())
.setNegativeButton("Cancel", null).setTitle("Displayed contact groups").show();
}
private class OKButtonListener implements DialogInterface.OnClickListener
{
@Override
public void onClick(DialogInterface dialog, int which)
{
List<Integer> pickedGroups = new ArrayList<Integer>();
int numChecked = 0;
for (int i = 0; i < contactGroups.size(); i++)
{
if (checkedItems[i])
{
numChecked++;
if (numChecked > 20)
{
Toast.makeText(context, "Sorry, you can only pick up to 20 groups.", Toast.LENGTH_SHORT).show();
break;
}
pickedGroups.add(contactGroups.get(i).getId());
}
}
ListSerialization.saveIntegerList(preferencesEditor, pickedGroups, "displayedGroupsListNew");
}
}
public static List<ContactGroup> getAllContactGroups(Context context)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
{
ContactGroup dummyGroup = new ContactGroup(-1, "No permission");
return Collections.singletonList(dummyGroup);
}
List<ContactGroup> groups = new ArrayList<ContactGroup>();
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Groups.CONTENT_SUMMARY_URI, new String[] { ContactsContract.Groups._ID, ContactsContract.Groups.TITLE, ContactsContract.Groups.ACCOUNT_NAME, ContactsContract.Groups.SUMMARY_COUNT}, ContactsContract.Groups.SUMMARY_COUNT + " > 0", null, null);
while (cursor.moveToNext())
{
int id = cursor.getInt(0);
String name = cursor.getString(1) + " (" + cursor.getString(2) + ")";
groups.add(new ContactGroup(id, name));
}
cursor.close();
return groups;
}
public static List<ContactGroup> getSpecificContactGroups(Context context, List<Integer> picks)
{
List<ContactGroup> groups = new ArrayList<ContactGroup>();
if (picks.size() == 0)
return groups;
String picksCommaSeparated = "";
for (Integer i : picks)
picksCommaSeparated += i + ",";
picksCommaSeparated = picksCommaSeparated.substring(0, picksCommaSeparated.length() - 1);
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Groups.CONTENT_SUMMARY_URI, new String[] { ContactsContract.Groups._ID, ContactsContract.Groups.TITLE, ContactsContract.Groups.SUMMARY_COUNT}, ContactsContract.Groups.SUMMARY_COUNT + " > 0 AND " + ContactsContract.Groups._ID + " IN (" + picksCommaSeparated + ")", null, null);
if (cursor != null)
{
while (cursor.moveToNext())
{
int id = cursor.getInt(0);
String name = cursor.getString(1);
if (name == null)
continue;
groups.add(new ContactGroup(id, name));
}
cursor.close();
}
return groups;
}
public static String[] getNameArray(List<ContactGroup> groups)
{
String[] names = new String[groups.size()];
for (int i = 0; i < groups.size(); i++)
names[i] = groups.get(i).getName();
return names;
}
public static class ContactGroup
{
private int id;
private String name;
private ContactGroup(int id, String name)
{
this.id = id;
this.name = name;
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
}
}
| 6,025 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
MainActivity.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/MainActivity.java | package com.matejdro.pebbledialer.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.annotation.XmlRes;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.matejdro.pebblecommons.util.LogWriter;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.pebble.WatchappHandler;
import com.matejdro.pebbledialer.ui.fragments.settings.GenericPreferenceScreen;
import com.matejdro.pebbledialer.ui.fragments.HomeFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.AboutSettingsFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.CallscreenSettingsFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.GeneralSettingsFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.MessagingSettingsFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.PreferenceActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, PreferenceActivity
{
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar toolbar;
private NavigationView navigationView;
private SharedPreferences settings;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(0);
settings = PreferenceManager.getDefaultSharedPreferences(this);
if (WatchappHandler.isFirstRun(settings))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.pebbleAppInstallDialog).setNegativeButton(
"No", null).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
WatchappHandler.openPebbleStore(MainActivity.this);
}
}).show();
}
}
@Override
protected void onStart()
{
super.onStart();
navigationView.setCheckedItem(R.id.home);
onNavigationItemSelected(navigationView.getMenu().findItem(R.id.home));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
checkPermissions();
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.pebble_store)
{
WatchappHandler.openPebbleStore(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.home)
{
switchToFragment(new HomeFragment());
}
else if (item.getItemId() == R.id.general_settings)
{
switchToFragment(new GeneralSettingsFragment());
}
else if (item.getItemId() == R.id.customize_callscreen)
{
switchToFragment(new CallscreenSettingsFragment());
}
else if (item.getItemId() == R.id.sms)
{
switchToFragment(new MessagingSettingsFragment());
}
else if (item.getItemId() == R.id.about)
{
switchToFragment(new AboutSettingsFragment());
}
drawerLayout.closeDrawers();
return true;
}
private void switchToFragment(Fragment fragment)
{
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
public void switchToGenericPreferenceScreen(@XmlRes int xmlRes, String root)
{
Fragment fragment = GenericPreferenceScreen.newInstance(xmlRes, root);
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.content_frame, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
@TargetApi(Build.VERSION_CODES.M)
private void checkPermissions()
{
List<String> wantedPermissions = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.RECORD_AUDIO);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.BLUETOOTH);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_CONTACTS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.CALL_PHONE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_PHONE_STATE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_CALL_LOG);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_SMS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.SEND_SMS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ANSWER_PHONE_CALLS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.ANSWER_PHONE_CALLS);
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//Log writer needs to access external storage
if (preferences.getBoolean(LogWriter.SETTING_ENABLE_LOG_WRITING, false) &&
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
{
wantedPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!wantedPermissions.isEmpty())
ActivityCompat.requestPermissions(this, wantedPermissions.toArray(new String[wantedPermissions.size()]), 0);
}
}
| 8,678 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
PreferenceSource.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/PreferenceSource.java | package com.matejdro.pebbledialer.ui;
import android.content.SharedPreferences;
public interface PreferenceSource
{
SharedPreferences getCustomPreferences();
}
| 166 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
HomeFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/HomeFragment.java | package com.matejdro.pebbledialer.ui.fragments;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.callactions.ToggleRingerAction;
import com.matejdro.pebbledialer.notifications.JellybeanNotificationListener;
import timber.log.Timber;
public class HomeFragment extends Fragment
{
private View notificationServiceWarningCard;
private View ringerMuteAccessWarningCard;
@Override
public void onResume()
{
super.onResume();
boolean hideServiceWarning = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
hideServiceWarning = JellybeanNotificationListener.isActive() || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2;
}
notificationServiceWarningCard.setVisibility(hideServiceWarning ? View.GONE : View.VISIBLE);
ringerMuteAccessWarningCard.setVisibility(ToggleRingerAction.canMuteRinger(getContext()) ? View.GONE : View.VISIBLE);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_home, container, false);
notificationServiceWarningCard = view.findViewById(R.id.tip_no_notification_service);
notificationServiceWarningCard.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
else
startActivity(new Intent("android.settings.ACTION_ACCESSIBILITY_SETTINGS"));
Toast.makeText(getContext(), R.string.notification_service_enabling_instructions, Toast.LENGTH_SHORT).show();
}
});
ringerMuteAccessWarningCard = view.findViewById(R.id.tip_no_ringer_mute_access);
ringerMuteAccessWarningCard.setOnClickListener(new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.N)
public void onClick(View view) {
startActivity(new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
}
});
view.findViewById(R.id.tip_tertiary_text).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
openLink("http://pebble.rickyayoub.com/");
}
});
view.findViewById(R.id.tip_faq).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
openLink("https://docs.google.com/document/d/12EUvuYrydLCrfdAb6wLLvWn-v4C0HfI1f6WP2CT3bCE/pub");
}
});
return view;
}
private void openLink(String url)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getContext(), R.string.error_no_web_browser, Toast.LENGTH_SHORT).show();
}
}
}
| 3,855 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
MessagingSettingsFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/MessagingSettingsFragment.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.ui.StringListPopup;
public class MessagingSettingsFragment extends CustomStoragePreferenceFragment
{
@Override
public void onCreatePreferencesEx(Bundle bundle, String s)
{
addPreferencesFromResource(R.xml.settings_sms);
findPreference("smsCannedResponsesDialog").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
StringListPopup popup = new StringListPopup(getContext(), R.string.settingCannedResponses, getPreferenceManager().getSharedPreferences(), "smsCannedResponses");
popup.show();
return true;
}
});
findPreference("smsWritingPhrasesDialog").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
StringListPopup popup = new StringListPopup(getContext(), R.string.settingWritingPhrases, getPreferenceManager().getSharedPreferences(), "smsWritingPhrases");
popup.show();
return true;
}
});
}
}
| 1,453 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
CallscreenSettingsFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/CallscreenSettingsFragment.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceScreen;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.ui.DialogVibrationPatternPicker;
import com.matejdro.pebbledialer.ui.MainActivity;
public class CallscreenSettingsFragment extends CustomStoragePreferenceFragment
{
@Override
public void onCreatePreferencesEx(Bundle bundle, String s)
{
setPreferencesFromResource(R.xml.settings_callscreen, s);
findPreference("vibrationPatternButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
new DialogVibrationPatternPicker().show(getFragmentManager(), "VibrationPatternPicker");
return true;
}
});
}
}
| 977 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
AboutSettingsFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/AboutSettingsFragment.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.preference.Preference;
import com.matejdro.pebblecommons.util.LogWriter;
import com.matejdro.pebbledialer.R;
import de.psdev.licensesdialog.LicensesDialog;
public class AboutSettingsFragment extends CustomStoragePreferenceFragment
{
@Override
public void onCreatePreferencesEx(Bundle bundle, String s)
{
addPreferencesFromResource(R.xml.settings_about);
try
{
findPreference("version").setSummary( getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0).versionName);
}
catch (PackageManager.NameNotFoundException e)
{
}
Preference notifierLicenseButton = findPreference("license");
notifierLicenseButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
new LicensesDialog.Builder(getContext())
.setNotices(R.raw.notices)
.setIncludeOwnLicense(true)
.build()
.show();
return true;
}
});
findPreference("donateButton").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()
{
@Override
public boolean onPreferenceClick(Preference preference)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5HV63YFE6SW44"));
startActivity(intent);
return true;
}
});
findPreference(LogWriter.SETTING_ENABLE_LOG_WRITING).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
if (((Boolean) newValue) && ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
return false;
}
return true;
}
});
}
}
| 2,671 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
GenericPreferenceScreen.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/GenericPreferenceScreen.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.os.Bundle;
import android.support.annotation.XmlRes;
import android.support.v7.preference.PreferenceFragmentCompat;
public class GenericPreferenceScreen extends CustomStoragePreferenceFragment
{
private @XmlRes int preferenceXml;
@Override
public void onCreate(Bundle savedInstanceState)
{
preferenceXml = getArguments().getInt("PreferencesXML", preferenceXml);
super.onCreate(savedInstanceState);
}
@Override
public void onCreatePreferencesEx(Bundle bundle, String root)
{
setPreferencesFromResource(preferenceXml, root);
}
public static GenericPreferenceScreen newInstance(@XmlRes int preferenceXml, String root)
{
Bundle arguments = new Bundle();
arguments.putInt("PreferencesXML", preferenceXml);
arguments.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, root);
GenericPreferenceScreen genericPreferenceScreen = new GenericPreferenceScreen();
genericPreferenceScreen.setArguments(arguments);
return genericPreferenceScreen;
}
}
| 1,139 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
GeneralSettingsFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/GeneralSettingsFragment.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.app.TimePickerDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.Preference;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import android.widget.Toast;
import com.matejdro.pebblecommons.util.RTLUtility;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.ui.ContactGroupsPickerDialog;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.TimeZone;
public class GeneralSettingsFragment extends CustomStoragePreferenceFragment
{
private java.text.DateFormat dateFormat;
private SharedPreferences sharedPreferences;
@Override
public void onCreatePreferencesEx(Bundle bundle, String s)
{
dateFormat = DateFormat.getTimeFormat(getContext());
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
sharedPreferences = getPreferenceManager().getSharedPreferences();
addPreferencesFromResource(R.xml.settings_general);
Preference rtlEnabled = findPreference("EnableRTL");
rtlEnabled.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
RTLUtility.getInstance().setEnabled((Boolean) newValue);
return true;
}
});
Preference displayedGroups = findPreference("displayedGroups");
displayedGroups.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
new ContactGroupsPickerDialog(getContext(), getPreferenceManager().getSharedPreferences(), getPreferenceManager().getSharedPreferences().edit()).show();
return false;
}
});
CheckBoxPreference rootMethod = (CheckBoxPreference) findPreference("rootMode");
rootMethod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean newChecked = (Boolean) newValue;
if (!newChecked)
return true;
if (!hasRoot())
{
Toast.makeText(getContext(), "Sorry, you need ROOT for that method.", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
});
setupQuietTimePreferences();
}
private void setupQuietTimePreferences()
{
final Preference quietFrom = findPreference("quietTimeStart");
int startHour = sharedPreferences.getInt("quiteTimeStartHour", 0);
int startMinute = sharedPreferences.getInt("quiteTimeStartMinute", 0);
quietFrom.setSummary(formatTime(startHour, startMinute));
quietFrom.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
int startHour = sharedPreferences.getInt("quiteTimeStartHour", 0);
int startMinute = sharedPreferences.getInt("quiteTimeStartMinute", 0);
TimePickerDialog dialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("quiteTimeStartHour", hourOfDay);
editor.putInt("quiteTimeStartMinute", minute);
editor.apply();
quietFrom.setSummary(formatTime(hourOfDay, minute));
}
}, startHour, startMinute, DateFormat.is24HourFormat(getContext()));
dialog.show();
return true;
}
});
final Preference quietTo = findPreference("quietTimeEnd");
int endHour = sharedPreferences.getInt("quiteTimeEndHour", 23);
int endMinute = sharedPreferences.getInt("quiteTimeEndMinute", 59);
quietTo.setSummary(formatTime(endHour, endMinute));
quietTo.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
int startHour = sharedPreferences.getInt("quiteTimeEndHour", 0);
int startMinute = sharedPreferences.getInt("quiteTimeEndMinute", 0);
TimePickerDialog dialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("quiteTimeEndHour", hourOfDay);
editor.putInt("quiteTimeEndMinute", minute);
editor.apply();
quietTo.setSummary(formatTime(hourOfDay, minute));
}
}, startHour, startMinute, DateFormat.is24HourFormat(getContext()));
dialog.show();
return true;
}
});
}
private static boolean hasRoot()
{
try {
Process proces = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(proces.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(proces.getInputStream()));
out.writeBytes("id\n");
out.flush();
String line = in.readLine();
if (line == null) return false;
return true;
} catch (IOException e) {
return false;
}
}
public String formatTime(int hours, int minutes)
{
long datestampMs = (hours * 60 + minutes) * 60 * 1000;
Date date = new Date(datestampMs);
return dateFormat.format(date);
}
}
| 6,489 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
PreferenceActivity.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/PreferenceActivity.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.support.annotation.XmlRes;
public interface PreferenceActivity
{
public void switchToGenericPreferenceScreen(@XmlRes int xmlRes, String root);
}
| 223 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
CustomStoragePreferenceFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/ui/fragments/settings/CustomStoragePreferenceFragment.java | package com.matejdro.pebbledialer.ui.fragments.settings;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceManager;
import android.support.v7.preference.PreferenceScreen;
import com.matejdro.pebblecommons.util.BundleSharedPreferences;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.ui.MainActivity;
import com.matejdro.pebbledialer.ui.PreferenceSource;
import java.lang.reflect.Field;
public abstract class CustomStoragePreferenceFragment extends PreferenceFragmentCompat
{
@Override
public void onCreatePreferences(Bundle bundle, String s)
{
if (getActivity() instanceof PreferenceSource)
{
SharedPreferences sharedPreferences = ((PreferenceSource) getActivity()).getCustomPreferences();
injectSharedPreferences(sharedPreferences);
}
onCreatePreferencesEx(bundle, s);
}
protected abstract void onCreatePreferencesEx(Bundle bundle, String s);
@Override
public void onNavigateToScreen(PreferenceScreen preferenceScreen)
{
((PreferenceActivity) getActivity()).switchToGenericPreferenceScreen(R.xml.settings_callscreen, preferenceScreen.getKey());
}
@SuppressLint("CommitPrefEdits")
private void injectSharedPreferences(SharedPreferences preferences)
{
PreferenceManager manager = getPreferenceManager();
try
{
Field field = PreferenceManager.class.getDeclaredField("mSharedPreferences");
field.setAccessible(true);
field.set(manager, preferences);
field = PreferenceManager.class.getDeclaredField("mEditor");
field.setAccessible(true);
field.set(manager, preferences.edit());
} catch (Exception e)
{
e.printStackTrace();
}
}
}
| 1,977 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
SMSReplyModule.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/modules/SMSReplyModule.java | package com.matejdro.pebbledialer.modules;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.matejdro.pebblecommons.messages.MessageTextProvider;
import com.matejdro.pebblecommons.messages.MessageTextProviderListener;
import com.matejdro.pebblecommons.messages.PhoneVoiceProvider;
import com.matejdro.pebblecommons.messages.TimeVoiceProvider;
import com.matejdro.pebblecommons.pebble.CommModule;
import com.matejdro.pebblecommons.pebble.PebbleCommunication;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebblecommons.userprompt.NativePebbleUserPrompter;
import com.matejdro.pebblecommons.util.ListSerialization;
import com.matejdro.pebblecommons.util.TextUtil;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.callactions.EndCallAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import timber.log.Timber;
/**
* Created by Matej on 3.12.2014.
*/
public class SMSReplyModule extends CommModule implements MessageTextProviderListener
{
public static final int MODULE_SMS_REPLIES = 5;
public static final int MAX_NUMBER_OF_ACTIONS = 20;
private List<String> actionList;
int listSize = -1;
private int nextListItemToSend = -1;
private boolean tertiaryTextMode = false;
private int timeVoiceIndex = -1;
private int phoneVoiceIndex = -1;
private int writingIndex = -1;
private String number;
public SMSReplyModule(PebbleTalkerService service)
{
super(service);
}
private void sendNextListItems()
{
Timber.d("Sending action list items");
PebbleDictionary data = new PebbleDictionary();
byte[] bytes = new byte[3];
data.addUint8(0, (byte) 5);
data.addUint8(1, (byte) 0);
int segmentSize = Math.min(listSize - nextListItemToSend, 4);
bytes[0] = (byte) nextListItemToSend;
bytes[1] = (byte) listSize;
bytes[2] = (byte) (tertiaryTextMode ? 1 : 0);
byte[] textData = new byte[segmentSize * 19];
for (int i = 0; i < segmentSize; i++)
{
String text = TextUtil.prepareString(actionList.get(i + nextListItemToSend), 18);
System.arraycopy(text.getBytes(), 0, textData, i * 19, text.getBytes().length);
textData[19 * (i + 1) -1 ] = 0;
}
data.addBytes(2, bytes);
data.addBytes(3, textData);
getService().getPebbleCommunication().sendToPebble(data);
nextListItemToSend += 4;
if (nextListItemToSend >= listSize)
nextListItemToSend = -1;
}
@Override
public boolean sendNextMessage()
{
if (actionList != null && nextListItemToSend >= 0 )
{
sendNextListItems();
return true;
}
return false;
}
public void startSMSProcess(String number)
{
Timber.d("StartSMSProcess %s", number);
this.number = number;
if (number == null)
{
Crashlytics.logException(new NullPointerException("Number is null!"));
sendFailNotification();
return;
}
tertiaryTextMode = false;
SharedPreferences settings = getService().getGlobalSettings();
actionList = new ArrayList<>();
if (settings.getBoolean("timeVoice", true) && getService().getPebbleCommunication().getConnectedWatchCapabilities().hasMicrophone())
{
actionList.add("Time Voice");
timeVoiceIndex = actionList.size() - 1;
}
if (settings.getBoolean("phoneVoice", true))
{
actionList.add("Phone Voice");
phoneVoiceIndex = actionList.size() - 1;
}
if (settings.getBoolean("enableSMSWriting", true))
{
actionList.add("Write");
writingIndex = actionList.size() - 1;
}
actionList.addAll(ListSerialization.loadList(settings, "smsCannedResponses"));
listSize = Math.min(actionList.size(), MAX_NUMBER_OF_ACTIONS);
nextListItemToSend = 0;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
public void showWritingList()
{
tertiaryTextMode = true;
SharedPreferences settings = getService().getGlobalSettings();
actionList = new ArrayList<>();
actionList.add("Send");
actionList.addAll(ListSerialization.loadList(settings, "smsWritingPhrases"));
actionList.addAll(ListSerialization.loadList(settings, "smsCannedResponses"));
listSize = Math.min(actionList.size(), MAX_NUMBER_OF_ACTIONS);
nextListItemToSend = 0;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
public void startTimeVoice()
{
Timber.d("Starting time voice");
MessageTextProvider voiceProvider = new TimeVoiceProvider(getService());
voiceProvider.startRetrievingText(this);
}
public void startPhoneVoice()
{
Timber.d("Starting phone voice");
MessageTextProvider voiceProvider = new PhoneVoiceProvider(new NativePebbleUserPrompter(getService()), getService());
voiceProvider.startRetrievingText(this);
}
@Override
public void gotText(String text)
{
Timber.d("SendingMessage %s %s", text, number);
if (ContextCompat.checkSelfPermission(getService(), Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_DENIED)
{
Notification notification = new NotificationCompat.Builder(getService())
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("SMS Sending failed")
.setContentText("No permission")
.build();
NotificationManagerCompat.from(getService()).notify(123, notification);
return;
}
if (number == null || text == null)
{
sendFailNotification();
return;
}
EndCallAction.get(CallModule.get(getService())).executeAction();
SmsManager.getDefault().sendTextMessage(number, null, text, null, null);
//Pre-Kitkat Android versions do not automatically insert sent SMS to system's SMS provider.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
{
ContentValues values = new ContentValues();
values.put("address", number);
values.put("body", text);
try
{
getService().getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
catch (Exception e)
{
e.printStackTrace();
Crashlytics.logException(e);
}
}
}
private void sendFailNotification()
{
NotificationManager mNotificationManager = (NotificationManager) getService().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getService())
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getService().getString(R.string.app_name))
.setContentText(getService().getString(R.string.sms_failed));
mNotificationManager.notify(1000, mBuilder.build());
}
public void gotMessageActionItemPicked(PebbleDictionary message)
{
int index = message.getUnsignedIntegerAsLong(2).intValue();
Timber.d("SMS list picked %d", index);
if (index == timeVoiceIndex)
startTimeVoice();
else if (index == phoneVoiceIndex)
startPhoneVoice();
else if (index == writingIndex)
showWritingList();
else
{
if (index >= actionList.size())
{
Timber.e("Action out of bounds!");
sendFailNotification();
return;
}
gotText(actionList.get(index));
}
}
private void gotMessageReplyText(PebbleDictionary data)
{
String text = data.getString(2);
gotText(text);
}
@Override
public void gotMessageFromPebble(PebbleDictionary message)
{
int id = message.getUnsignedIntegerAsLong(1).intValue();
switch (id)
{
case 0:
gotMessageActionItemPicked(message);
break;
case 1:
gotMessageReplyText(message);
break;
}
}
public static SMSReplyModule get(PebbleTalkerService service)
{
return (SMSReplyModule) service.getModule(MODULE_SMS_REPLIES);
}
}
| 9,464 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
CallModule.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/modules/CallModule.java | package com.matejdro.pebbledialer.modules;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.service.notification.NotificationListenerService;
import android.telephony.TelephonyManager;
import android.util.SparseArray;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.matejdro.pebblecommons.pebble.CommModule;
import com.matejdro.pebblecommons.pebble.PebbleCommunication;
import com.matejdro.pebblecommons.pebble.PebbleImageToolkit;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebblecommons.pebble.PebbleUtil;
import com.matejdro.pebblecommons.util.ContactUtils;
import com.matejdro.pebblecommons.util.Size;
import com.matejdro.pebblecommons.util.TextUtil;
import com.matejdro.pebblecommons.vibration.PebbleVibrationPattern;
import com.matejdro.pebbledialer.callactions.AnswerCallAction;
import com.matejdro.pebbledialer.callactions.AnswerCallWithSpeakerAction;
import com.matejdro.pebbledialer.callactions.CallAction;
import com.matejdro.pebbledialer.callactions.DummyAction;
import com.matejdro.pebbledialer.callactions.EndCallAction;
import com.matejdro.pebbledialer.callactions.SMSReplyAction;
import com.matejdro.pebbledialer.callactions.ToggleMicrophoneAction;
import com.matejdro.pebbledialer.callactions.ToggleRingerAction;
import com.matejdro.pebbledialer.callactions.ToggleSpeakerAction;
import com.matejdro.pebbledialer.callactions.VolumeDownAction;
import com.matejdro.pebbledialer.callactions.VolumeUpAction;
import com.matejdro.pebbledialer.notifications.JellybeanNotificationListener;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import timber.log.Timber;
public class CallModule extends CommModule
{
public static final String INTENT_CALL_STATUS = "CallStatus";
public static final String INTENT_ACTION_FROM_NOTIFICATION = "ActionFromNotification";
public static int MODULE_CALL = 1;
private SparseArray<CallAction> actions = new SparseArray<CallAction>();
private boolean updateRequired;
private boolean identityUpdateRequired;
private boolean callerNameUpdateRequired;
private int callerImageNextByte = -1;
private String number = "Outgoing Call";
private String name = null;
private String type = null;
private Bitmap callerImage = null;
private byte[] callerImageBytes;
private CallState callState = CallState.NO_CALL;
private boolean vibrating;
private boolean closeAutomaticallyAfterThisCall = true;
long callStartTime;
public CallModule(PebbleTalkerService service)
{
super(service);
service.registerIntent(INTENT_CALL_STATUS, this);
service.registerIntent(INTENT_ACTION_FROM_NOTIFICATION, this);
registerCallAction(new AnswerCallAction(this), AnswerCallAction.ANSWER_ACTION_ID);
registerCallAction(new EndCallAction(this), EndCallAction.END_CALL_ACTION_ID);
registerCallAction(new ToggleRingerAction(this), ToggleRingerAction.TOGGLE_RINGER_ACTION_ID);
registerCallAction(new ToggleMicrophoneAction(this), ToggleMicrophoneAction.TOGGLE_MICROPHONE_ACTION_ID);
registerCallAction(new SMSReplyAction(this), SMSReplyAction.SMS_REPLY_ACTION_ID);
registerCallAction(new ToggleSpeakerAction(this), ToggleSpeakerAction.TOGGLE_SPEAKER_ACTION_ID);
registerCallAction(new AnswerCallWithSpeakerAction(this), AnswerCallWithSpeakerAction.ANSWER_WITH_SPEAKER_ACTION_ID);
registerCallAction(new VolumeDownAction(this), VolumeDownAction.VOLUME_DOWN_ACTION_ID);
registerCallAction(new VolumeUpAction(this), VolumeUpAction.VOLUME_UP_ACTION_ID);
registerCallAction(new DummyAction(this), DummyAction.DUMMY_ACTION_ID);
updateRequired = false;
callerNameUpdateRequired = false;
}
private void registerCallAction(CallAction action, int id)
{
actions.put(id, action);
}
public CallAction getCallAction(int id)
{
return actions.get(id);
}
@Override
public void gotIntent(Intent intent) {
if (intent.getAction().equals(INTENT_CALL_STATUS))
{
Intent callIntent = intent.getParcelableExtra("callIntent");
intentDelivered(callIntent);
}
else if (intent.getAction().equals(INTENT_ACTION_FROM_NOTIFICATION))
{
int actionType = intent.getIntExtra("actionType", 0);
PendingIntent actionIntent = intent.getParcelableExtra("action");
Timber.d("Got action from notification %d %s", actionType, actionIntent);
if (actionType == 0)
AnswerCallAction.get(this).registerNotificationAnswerIntent(actionIntent);
else
EndCallAction.get(this).registerNotificationEndCallIntent(actionIntent);
}
}
private void intentDelivered(Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL))
{
Timber.d("Outgoing intent");
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
callState = CallState.ESTABLISHED;
updateNumberData();
updatePebble();
if (getService().getGlobalSettings().getBoolean("popupOnOutgoing", true))
SystemModule.get(getService()).openApp();
return;
}
Timber.d("phone state intent " + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state == null)
return;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
ringingStarted(intent);
}
else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
{
callEnded();
}
else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
callEstablished();
}
}
private void callEnded()
{
if (closeAutomaticallyAfterThisCall)
SystemModule.get(getService()).startClosing();
callState = CallState.NO_CALL;
for (int i = 0; i < actions.size(); i++)
actions.valueAt(i).onCallEnd();
updateRequired = false;
callerNameUpdateRequired = false;
callerImageNextByte = -1;
}
private void callEstablished()
{
callStartTime = System.currentTimeMillis();
callState = CallState.ESTABLISHED;
updatePebble();
for (int i = 0; i < actions.size(); i++)
actions.valueAt(i).onPhoneOffhook();
closeAutomaticallyAfterThisCall = true;
}
private void ringingStarted(Intent intent)
{
Timber.d("Ringing");
callState = CallState.RINGING;
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
vibrating = true;
updateNumberData();
updatePebble();
if (canPopupIncomingCall())
SystemModule.get(getService()).openApp();
for (int i = 0; i < actions.size(); i++)
actions.valueAt(i).onCallRinging();
closeAutomaticallyAfterThisCall = true;
}
private boolean canPopupIncomingCall()
{
if (!getService().getGlobalSettings().getBoolean("popupOnIncoming", true))
{
Timber.d("Call popup failed - popup disabled");
return false;
}
if (getService().getGlobalSettings().getBoolean("respectDoNotInterrupt", false) && isPhoneInDoNotInterrupt())
{
Timber.d("Call popup failed - do not interrupt");
return false;
}
if (isInQuietTime())
{
Timber.d("call popup failed - quiet time");
return false;
}
return true;
}
private boolean isInQuietTime()
{
SharedPreferences preferences = getService().getGlobalSettings();
if (!preferences.getBoolean("enableQuietTime", false))
return false;
int startHour = preferences.getInt("quiteTimeStartHour", 0);
int startMinute = preferences.getInt("quiteTimeStartMinute", 0);
int startTime = startHour * 60 + startMinute;
int endHour = preferences.getInt("quiteTimeEndHour", 23);
int endMinute = preferences.getInt("quiteTimeEndMinute", 59);
int endTime = endHour * 60 + endMinute;
Calendar calendar = Calendar.getInstance();
int curHour = calendar.get(Calendar.HOUR_OF_DAY);
int curMinute = calendar.get(Calendar.MINUTE);
int curTime = curHour * 60 + curMinute;
return (endTime > startTime && curTime <= endTime && curTime >= startTime) || (endTime < startTime && (curTime <= endTime || curTime >= startTime));
}
public void updatePebble()
{
updateRequired = true;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
public void setVibration(boolean vibrating)
{
this.vibrating = vibrating;
}
public void setCloseAutomaticallyAfterThisCall(boolean closeAutomaticallyAfterThisCall)
{
this.closeAutomaticallyAfterThisCall = closeAutomaticallyAfterThisCall;
}
public String getNumber()
{
return number;
}
private void updateNumberData()
{
Timber.d("Updating number...");
identityUpdateRequired = true;
callerImage = null;
if (number == null)
{
name = null;
number = "Unknown Number";
return;
}
Cursor cursor = null;
try
{
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
cursor = getService().getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.TYPE, ContactsContract.PhoneLookup.LABEL, ContactsContract.PhoneLookup.PHOTO_URI}, null, null, "contacts_view.last_time_contacted DESC");
} catch (IllegalArgumentException e)
{
//This is sometimes thrown when number is in invalid format, so phone cannot recognize it.
}
catch (SecurityException e)
{
name = "No contacts permission";
type = "Error";
return;
}
name = null;
if (cursor != null)
{
if (cursor.moveToNext())
{
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
String label = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.LABEL));
int typeId = cursor.getInt(cursor.getColumnIndex(ContactsContract.PhoneLookup.TYPE));
type = ContactUtils.convertNumberType(typeId, label);
if (type == null)
type = "Other";
String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_URI));
if (photoUri != null && getService().getGlobalSettings().getBoolean("displayCallerImage", true))
{
try
{
callerImage = MediaStore.Images.Media.getBitmap(getService().getContentResolver(), Uri.parse(photoUri));
}
catch (IOException e)
{
Timber.w("Unable to load contact image!", e);
}
}
}
cursor.close();
}
}
private void processContactImage()
{
Size imageSize = SystemModule.get(getService()).getFullscreenImageSize();
Bitmap processedCallerImage = PebbleImageToolkit.resizeAndCrop(callerImage, imageSize.width, imageSize.height, true);
processedCallerImage = PebbleImageToolkit.multiplyBrightness(processedCallerImage, 0.5f);
processedCallerImage = PebbleImageToolkit.ditherToPebbleTimeColors(processedCallerImage);
callerImageBytes = PebbleImageToolkit.getIndexedPebbleImageBytes(processedCallerImage);
}
@Override
public boolean sendNextMessage()
{
if (updateRequired)
{
sendUpdatePacket();
return true;
}
if (callerNameUpdateRequired)
{
sendCallerName();
return true;
}
if (callerImageNextByte >= 0)
{
sendImagePacket();
return true;
}
return false;
}
private void sendUpdatePacket()
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 1);
data.addUint8(1, (byte) 0);
boolean nameAtBottomWhenImageDisplayed = callerImage != null && getService().getGlobalSettings().getBoolean("bottomCallerName", true);
if (name != null && type != null)
{
data.addString(2, TextUtil.prepareString(type, 30));
data.addString(3, TextUtil.prepareString(number, 30));
}
else
{
data.addString(2, "");
data.addString(3, "");
}
List<Byte> vibrationPattern;
if (vibrating)
{
String vibrationPatternString = getService().getGlobalSettings().getString("vibrationPattern", "100, 100, 100, 1000");
vibrationPattern = PebbleVibrationPattern.parseVibrationPattern(vibrationPatternString);
}
else
{
vibrationPattern = PebbleVibrationPattern.EMPTY_VIBRATION_PATTERN;
}
byte[] parameters = new byte[8 + vibrationPattern.size()];
parameters[0] = (byte) (callState == CallState.ESTABLISHED ? 1 : 0);
parameters[1] = (byte) (nameAtBottomWhenImageDisplayed ? 1 : 0);
parameters[6] = (byte) (identityUpdateRequired ? 1 : 0);
parameters[2] = (byte) getCallAction(getUserSelectedAction(getExtendedButtonId("Up"))).getIcon();
parameters[3] = (byte) getCallAction(getUserSelectedAction(getExtendedButtonId("Select"))).getIcon();
parameters[4] = (byte) getCallAction(getUserSelectedAction(getExtendedButtonId("Down"))).getIcon();
parameters[7] = (byte) vibrationPattern.size();
for (int i = 0; i < vibrationPattern.size(); i++)
parameters[8 + i] = vibrationPattern.get(i);
data.addBytes(4, parameters);
if (callState == CallState.ESTABLISHED)
data.addUint16(5, (short) Math.min(65000, (System.currentTimeMillis() - callStartTime) / 1000));
data.addUint8(999, (byte) 1);
callerImageNextByte = -1;
if (identityUpdateRequired && getService().getPebbleCommunication().getConnectedWatchCapabilities().hasColorScreen())
{
int imageSize = 0;
if (callerImage != null)
{
processContactImage();
imageSize = callerImageBytes.length;
}
data.addUint16(7, (short) imageSize);
if (imageSize != 0)
callerImageNextByte = 0;
Timber.d("Image size: %d", imageSize);
}
getService().getPebbleCommunication().sendToPebble(data);
Timber.d("Sent Call update packet. New identity: %b", identityUpdateRequired);
callerNameUpdateRequired = identityUpdateRequired;
updateRequired = false;
identityUpdateRequired = false;
}
private void sendCallerName()
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 1);
data.addUint8(1, (byte) 1);
String name = TextUtil.prepareString(this.name, 100);
data.addString(2, name == null ? number : name);
getService().getPebbleCommunication().sendToPebble(data);
Timber.d("Sent Caller name packet...");
callerNameUpdateRequired = false;
}
private void sendImagePacket()
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 1);
data.addUint8(1, (byte) 2);
data.addUint16(2, (short) 0); //Image size placeholder
int maxBytesToSend = PebbleUtil.getBytesLeft(data, getService().getPebbleCommunication().getConnectedWatchCapabilities());
int bytesToSend = Math.min(callerImageBytes.length - callerImageNextByte, maxBytesToSend);
byte[] bytes = new byte[bytesToSend];
System.arraycopy(callerImageBytes, callerImageNextByte, bytes, 0, bytesToSend);
data.addUint16(2, (short) bytesToSend); //Image size placeholder
data.addBytes(3, bytes);
getService().getPebbleCommunication().sendToPebble(data);
Timber.d("Sent image packet %d / %d", callerImageNextByte, callerImageBytes.length);
callerNameUpdateRequired = false;
callerImageNextByte += bytesToSend;
if (callerImageNextByte >= callerImageBytes.length)
callerImageNextByte = -1;
}
public void gotMessagePebbleAction(PebbleDictionary data)
{
int button = data.getUnsignedIntegerAsLong(2).intValue();
String extendedButton = getExtendedButtonFromPebbleButton(button);
int action = getUserSelectedAction(extendedButton);
Timber.d("PebbleAction %d %s %d", button, extendedButton, action);
getCallAction(action).executeAction();
}
@Override
public void gotMessageFromPebble(PebbleDictionary message)
{
int id = message.getUnsignedIntegerAsLong(1).intValue();
Timber.d("Incoming call packet %d", id);
switch (id)
{
case 0: //Call action
gotMessagePebbleAction(message);
break;
}
}
@Override
public void pebbleAppOpened() {
if (callState != CallState.NO_CALL)
{
identityUpdateRequired = true;
updateRequired = true;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
}
}
private int getUserSelectedAction(String button)
{
return Integer.parseInt(getService().getGlobalSettings().getString("callButton" + button, Integer.toString(getDefaultAction(button))));
}
private String getExtendedButtonId(String button)
{
switch (callState)
{
case RINGING:
return "Ring" + button;
case ESTABLISHED:
return "Established" + button;
default:
return "Invalid";
}
}
private static int getDefaultAction(String button)
{
switch (button)
{
case "RingUp":
return ToggleRingerAction.TOGGLE_RINGER_ACTION_ID;
case "RingSelect":
return AnswerCallAction.ANSWER_ACTION_ID;
case "RingDown":
return EndCallAction.END_CALL_ACTION_ID;
case "RingUpHold":
return 999;
case "RingSelectHold":
return AnswerCallWithSpeakerAction.ANSWER_WITH_SPEAKER_ACTION_ID;
case "RingDownHold":
return SMSReplyAction.SMS_REPLY_ACTION_ID;
case "RingShake":
return 999;
case "EstablishedUp":
return ToggleMicrophoneAction.TOGGLE_MICROPHONE_ACTION_ID;
case "EstablishedSelect":
return ToggleSpeakerAction.TOGGLE_SPEAKER_ACTION_ID;
case "EstablishedDown":
return EndCallAction.END_CALL_ACTION_ID;
case "EstablishedUpHold":
return 999;
case "EstablishedSelectHold":
return 999;
case "EstablishedDownHold":
return 999;
case "EstablishedShake":
return 999;
default:
return 999;
}
}
private String getExtendedButtonFromPebbleButton(int pebbleButtonId)
{
String button;
switch (pebbleButtonId)
{
case 0:
button = "Up";
break;
case 1:
button = "Select";
break;
case 2:
button = "Down";
break;
case 3:
button = "UpHold";
break;
case 4:
button = "SelectHold";
break;
case 5:
button = "DownHold";
break;
case 6:
button = "Shake";
break;
default:
button = "Invalid";
}
return getExtendedButtonId(button);
}
public CallState getCallState()
{
return callState;
}
public static CallModule get(PebbleTalkerService service)
{
return (CallModule) service.getModule(MODULE_CALL);
}
public static enum CallState
{
NO_CALL,
RINGING,
ESTABLISHED
}
public static boolean isPhoneInDoNotInterrupt()
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
return false;
return JellybeanNotificationListener.isPhoneInDoNotInterrupt();
}
}
| 21,590 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
SystemModule.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/modules/SystemModule.java | package com.matejdro.pebbledialer.modules;
import android.util.SparseArray;
import com.getpebble.android.kit.PebbleKit;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.matejdro.pebblecommons.pebble.CommModule;
import com.matejdro.pebblecommons.pebble.PebbleCommunication;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebblecommons.util.ListSerialization;
import com.matejdro.pebblecommons.util.Size;
import com.matejdro.pebbledialer.PebbleDialerApplication;
import com.matejdro.pebbledialer.ui.ContactGroupsPickerDialog;
import com.matejdro.pebbledialer.pebble.WatchappHandler;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import timber.log.Timber;
/**
* Created by Matej on 29.11.2014.
*/
public class SystemModule extends CommModule
{
public static int MODULE_SYSTEM = 0;
public static final UUID UNKNOWN_UUID = new UUID(0, 0);
public static final UUID MAIN_MENU_UUID = UUID.fromString("dec0424c-0625-4878-b1f2-147e57e83688");
private static final int FALLBACK_CALLER_IMAGE_WIDTH = 144 - 30;
private static final int FALLBACK_CALLER_IMAGE_HEIGHT = 168 - 16;
private Callable<Boolean> runOnNext;
private UUID currentRunningApp;
private List<ContactGroupsPickerDialog.ContactGroup> pickedContactGroups;
private int nextGroupNameToSend = -1;
private int closeTries = 0;
private Integer fullscreenImageWidth;
private Integer fullscreenImageHeight;
public SystemModule(PebbleTalkerService service)
{
super(service);
runOnNext = null;
}
@Override
public boolean sendNextMessage()
{
if (runOnNext != null)
{
Callable<Boolean> oldRunOnNext = runOnNext;
try
{
runOnNext.call();
if (runOnNext == oldRunOnNext)
runOnNext = null;
return true;
} catch (Exception e)
{
e.printStackTrace();
return false;
}
}
if (nextGroupNameToSend != -1)
{
sendGroupNames();
return true;
}
return false;
}
private void sendGroupNames()
{
if (nextGroupNameToSend >= pickedContactGroups.size())
{
nextGroupNameToSend = -1;
return;
}
PebbleDictionary packet = new PebbleDictionary();
packet.addUint8(0, (byte) 0);
packet.addUint8(1, (byte) 2);
packet.addUint8(2, (byte) nextGroupNameToSend);
int num = Math.min(nextGroupNameToSend + 3, pickedContactGroups.size() - 1) - nextGroupNameToSend;
for (int i = 0; i <= num; i++)
{
packet.addString(3 + i, pickedContactGroups.get(nextGroupNameToSend + i).getName());
}
nextGroupNameToSend += 3;
getService().getPebbleCommunication().sendToPebble(packet);
}
private void sendConfig()
{
PebbleDictionary data = new PebbleDictionary();
List<Integer> pickedGroupIds = ListSerialization.loadIntegerList(getService().getGlobalSettings(), "displayedGroupsListNew");
pickedContactGroups = ContactGroupsPickerDialog.getSpecificContactGroups(getService(), pickedGroupIds);
byte[] configBytes = new byte[8];
configBytes[0] = (byte) (WatchappHandler.SUPPORTED_PROTOCOL >>> 0x08);
configBytes[1] = (byte) WatchappHandler.SUPPORTED_PROTOCOL;
boolean callWaiting = CallModule.get(getService()).getCallState() != CallModule.CallState.NO_CALL;
byte flags = 0;
flags |= (byte) (callWaiting ? 0x01 : 0);
flags |= (byte) (getService().getGlobalSettings().getBoolean("closeToLastApp", false) ? 0x02 : 0);
flags |= (byte) (getService().getGlobalSettings().getBoolean("skipGroupFiltering", false) ? 0x04 : 0);
flags |= (byte) (getService().getGlobalSettings().getBoolean("lightOnCallWindow", false) ? 0x08 : 0);
flags |= (byte) (getService().getGlobalSettings().getBoolean("dontVibrateWhenCharging", true) ? 0x10 : 0);
flags |= (byte) (getService().getGlobalSettings().getBoolean("enableCallTimer", true) ? 0x20 : 0);
flags |= (byte) (getService().getGlobalSettings().getBoolean("popupOnOutgoing", true) ? 0x40 : 0);
configBytes[2] = flags;
configBytes[3] = (byte) pickedContactGroups.size();
configBytes[4] = Byte.parseByte(getService().getGlobalSettings().getString("fontTimer", "2"));
configBytes[5] = Byte.parseByte(getService().getGlobalSettings().getString("fontName", "7"));
configBytes[6] = Byte.parseByte(getService().getGlobalSettings().getString("fontNumberType", "2"));
configBytes[7] = Byte.parseByte(getService().getGlobalSettings().getString("fontNumber", "3"));
data.addUint8(0, (byte) 0);
data.addUint8(1, (byte) 0);
data.addBytes(2, configBytes);
Timber.d("Sending config... CallWaiting=%b", callWaiting);
getService().getPebbleCommunication().sendToPebble(data);
if (!callWaiting && pickedContactGroups.size() > 0)
nextGroupNameToSend = 0;
}
private void sendConfigInvalidVersion(int version)
{
PebbleDictionary data = new PebbleDictionary();
byte[] configBytes = new byte[13];
configBytes[0] = (byte) (WatchappHandler.SUPPORTED_PROTOCOL >>> 0x08);
configBytes[1] = (byte) WatchappHandler.SUPPORTED_PROTOCOL;
data.addUint8(0, (byte) 0);
data.addUint8(1, (byte) 0);
data.addBytes(2, configBytes);
Timber.d("Sending version mismatch config...");
getService().getPebbleCommunication().sendToPebble(data);
runOnNext = new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
//Pretend that I sent new message to prevent other modules sending potentially unsupported messages
return true;
}
};
WatchappHandler.showUpdateNotification(getService());
}
/**
* Pre 2.2 watchapp does not have update screen so we display fake call screen
*/
private void sendFakeCall()
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 5);
data.addString(1, "Old PebbleDialer");
data.addString(2, "");
data.addString(3, "Check phone");
byte[] parameters = new byte[4];
parameters[0] = 1;
parameters[3] = 1;
data.addBytes(4, parameters);
data.addUint16(5, (short) 0);
getService().getPebbleCommunication().sendToPebble(data);
runOnNext = new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
//Pretend that I sent new message to prevent other modules sending potentially unsupported messages
return true;
}
};
WatchappHandler.showUpdateNotification(getService());
}
private void gotMessagePebbleOpened(PebbleDictionary message)
{
closeTries = 0;
int version = 0;
if (message.contains(2))
version = message.getUnsignedIntegerAsLong(2).intValue();
final int finalVersion = version;
Timber.d("Version %d", version);
if (version == WatchappHandler.SUPPORTED_PROTOCOL)
{
runOnNext = new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
sendConfig();
return true;
}
};
int pebbleCapabilities = message.getUnsignedIntegerAsLong(3).intValue();
getService().getPebbleCommunication().setConnectedWatchCapabilities(pebbleCapabilities);
fullscreenImageWidth = message.getUnsignedIntegerAsLong(4).intValue();
fullscreenImageHeight = message.getUnsignedIntegerAsLong(5).intValue();
SparseArray<CommModule> modules = getService().getAllModules();
for (int i = 0 ; i < modules.size(); i++)
modules.valueAt(i).pebbleAppOpened();
}
else if (version == 0)
{
runOnNext = new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
sendFakeCall();
return true;
}
};
}
else
{
runOnNext = new Callable<Boolean>()
{
@Override
public Boolean call()
{
sendConfigInvalidVersion(finalVersion);
return true;
}
};
}
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.resetBusy();
communication.sendNext();
}
private void gotMessageMenuItem(PebbleDictionary message)
{
int entry = message.getUnsignedIntegerAsLong(2).intValue();
if (entry == 0) //Call log
CallLogModule.get(getService()).beginSending();
else if (entry == 1) //All contacts
ContactsModule.get(getService()).beginSending(-1);
else //Groups
{
int groupId = entry - 2;
if (pickedContactGroups == null || groupId < 0 || groupId >= pickedContactGroups.size())
{
Timber.w("Got invalid group ID from main menu!");
return;
}
int group = pickedContactGroups.get(groupId).getId();
ContactsModule.get(getService()).beginSending(group);
}
}
@Override
public void gotMessageFromPebble(PebbleDictionary message)
{
int id = 0;
if (message.contains(1)) //Open message from older Pebble app does not have entry at 1.
id = message.getUnsignedIntegerAsLong(1).intValue();
Timber.d("system packet %d", id);
switch (id)
{
case 0: //Pebble opened
gotMessagePebbleOpened(message);
break;
case 1: //Menu entry picked
gotMessageMenuItem(message);
break;
case 2: //Close me
closeApp();
break;
}
}
public void updateCurrentlyRunningApp()
{
UUID newApp = getService().getDeveloperConnection().getCurrentRunningApp();
if (newApp != null && (!newApp.equals(PebbleDialerApplication.WATCHAPP_UUID) || currentRunningApp == null) && !newApp.equals(UNKNOWN_UUID))
{
currentRunningApp = newApp;
}
}
public UUID getCurrentRunningApp()
{
return currentRunningApp;
}
public Size getFullscreenImageSize()
{
if (fullscreenImageWidth == null || fullscreenImageHeight == null)
return new Size(FALLBACK_CALLER_IMAGE_WIDTH, FALLBACK_CALLER_IMAGE_HEIGHT);
else
return new Size(fullscreenImageWidth, fullscreenImageHeight);
}
public void openApp()
{
updateCurrentlyRunningApp();
PebbleKit.startAppOnPebble(getService(), PebbleDialerApplication.WATCHAPP_UUID);
}
public void closeApp()
{
Timber.d("CloseApp %s", currentRunningApp);
if (getService().getGlobalSettings().getBoolean("closeToLastApp", false) && canCloseToApp(currentRunningApp) && closeTries < 2)
PebbleKit.startAppOnPebble(getService(), currentRunningApp);
else
PebbleKit.closeAppOnPebble(getService(), PebbleDialerApplication.WATCHAPP_UUID);
closeTries++;
}
public void startClosing()
{
runOnNext = new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 0);
data.addUint8(1, (byte) 1);
Timber.d("Sending close window packet...");
getService().getPebbleCommunication().sendToPebble(data);
closeApp();
return true;
}
};
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
private static boolean canCloseToApp(UUID uuid)
{
return uuid != null && !uuid.equals(PebbleDialerApplication.WATCHAPP_UUID) && !uuid.equals(MAIN_MENU_UUID) && !uuid.equals(UNKNOWN_UUID);
}
public static SystemModule get(PebbleTalkerService service)
{
return (SystemModule) service.getModule(MODULE_SYSTEM);
}
}
| 12,979 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
CallLogModule.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/modules/CallLogModule.java | package com.matejdro.pebbledialer.modules;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.telecom.Call;
import android.telephony.PhoneNumberUtils;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.matejdro.pebblecommons.pebble.CommModule;
import com.matejdro.pebblecommons.pebble.PebbleCommunication;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import timber.log.Timber;
import com.matejdro.pebblecommons.util.ContactUtils;
import com.matejdro.pebblecommons.util.TextUtil;
public class CallLogModule extends CommModule
{
public static int MODULE_CALL_LOG = 2;
private List<CallLogEntry> entries;
private int nextToSend = -1;
private boolean openWindow = false;
public CallLogModule(PebbleTalkerService service) {
super(service);
entries = new ArrayList<CallLogEntry>();
}
public void beginSending()
{
refreshCallLog();
openWindow = true;
queueSendEntries(0);
}
public void queueSendEntries(int offset)
{
nextToSend = offset;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
public void sendEntriesPacket(int offset)
{
if (entries.size() <= offset)
return;
CallLogEntry callLogEntry = entries.get(offset);
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 2);
data.addUint8(1, (byte) 0);
data.addUint16(2, (short) offset);
data.addUint16(3, (short) entries.size());
data.addUint8(4, (byte) callLogEntry.eventType);
data.addString(6, callLogEntry.date);
if (callLogEntry.name == null)
callLogEntry.name = TextUtil.prepareString(callLogEntry.number);
data.addString(5, callLogEntry.name);
if (callLogEntry.numberType == null)
callLogEntry.numberType = "";
data.addString(7, callLogEntry.numberType);
if (openWindow)
data.addUint8(999, (byte) 1);
getService().getPebbleCommunication().sendToPebble(data);
}
@Override
public boolean sendNextMessage() {
if (nextToSend != -1)
{
sendEntriesPacket(nextToSend);
nextToSend = -1;
openWindow = false;
return true;
}
return false;
}
private void gotMessageEntryPicked(PebbleDictionary message)
{
int index = message.getInteger(2).intValue();
int mode = message.getUnsignedIntegerAsLong(3).intValue();
Timber.d("Picked %d %d", index, mode);
if (entries.size() <= index)
{
Timber.d("Number out of bounds!");
return;
}
CallLogEntry pickedEntry = entries.get(index);
if (mode == 0)
{
ContactUtils.call(pickedEntry.number, getService());
}
else
{
Integer contactId = pickedEntry.contactId;
if (contactId == null)
contactId = getContactId(pickedEntry.number);
NumberPickerModule.get(getService()).showNumberPicker(contactId);
}
}
@Override
public void gotMessageFromPebble(PebbleDictionary message) {
int id = message.getUnsignedIntegerAsLong(1).intValue();
switch (id)
{
case 0: //Request call log entry
int offset = message.getUnsignedIntegerAsLong(2).intValue();
Timber.d("off %d", offset);
queueSendEntries(offset);
break;
case 1:
gotMessageEntryPicked(message);
break;
}
}
private void refreshCallLog()
{
entries.clear();
if (ContextCompat.checkSelfPermission(getService(), Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED)
return;
ContentResolver resolver = getService().getContentResolver();
String sortOrder = CallLog.Calls.DEFAULT_SORT_ORDER + " LIMIT 100";
Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, null, null, null, sortOrder);
if (cursor != null)
{
while (cursor.moveToNext())
{
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String name = TextUtil.prepareString(cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)), 16);
int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
long date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
int numberType = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE));
String customLabel = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL));
if (number == null)
continue;
String numberTypeText = TextUtil.prepareString(ContactUtils.convertNumberType(numberType, customLabel));
CallLogEntry callLogEntry = new CallLogEntry(name, number, numberTypeText, getFormattedDate(date), type);
if (!entries.contains(callLogEntry))
{
if (name == null)
lookupContactInfo(callLogEntry);
entries.add(callLogEntry);
}
}
cursor.close();
}
}
public String getFormattedDate(long date)
{
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getService());
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getService());
Date dateO = new Date(date);
String dateS = dateFormat.format(dateO) + " " + timeFormat.format(dateO);
return TextUtil.prepareString(dateS);
}
private int getContactId(String number)
{
if (number == null)
return -1;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = getService().getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup._ID},null, null, ContactsContract.PhoneLookup._ID + " LIMIT 1");
int id = -1;
if (cursor != null)
{
if (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
return id;
}
private void lookupContactInfo(CallLogEntry callLogEntry)
{
Cursor cursor = null;
try
{
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(callLogEntry.number));
cursor = getService().getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.TYPE, ContactsContract.PhoneLookup.LABEL}, null, null, "contacts_view.last_time_contacted DESC");
} catch (IllegalArgumentException e)
{
//This is sometimes thrown when number is in invalid format, so phone cannot recognize it.
}
catch (SecurityException e)
{
return;
}
if (cursor != null)
{
if (cursor.moveToNext())
{
callLogEntry.contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
callLogEntry.name = TextUtil.prepareString(cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)));
String label = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.LABEL));
int typeId = cursor.getInt(cursor.getColumnIndex(ContactsContract.PhoneLookup.TYPE));
callLogEntry.numberType = TextUtil.prepareString(ContactUtils.convertNumberType(typeId, label));
if (callLogEntry.numberType == null)
callLogEntry.numberType = "Other";
}
cursor.close();
}
}
private static class CallLogEntry
{
public Integer contactId;
public String name;
public String number;
public String numberType;
public String date;
public int eventType;
public CallLogEntry(String name, String number, String numberType, String date, int eventType)
{
this.name = name;
this.number = PhoneNumberUtils.formatNumber(number);
this.numberType = numberType;
this.date = date;
this.eventType = eventType;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CallLogEntry that = (CallLogEntry) o;
return PhoneNumberUtils.compare(number, that.number);
}
@Override
public int hashCode()
{
// Number is not used in hashcode, because it involves complicated comparing method that
// cannot be boiled down to hash.
// Because of this, we can't use hashcode for comparison.
return 0;
}
}
public static CallLogModule get(PebbleTalkerService service)
{
return (CallLogModule) service.getModule(MODULE_CALL_LOG);
}
}
| 9,898 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
ContactsModule.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/modules/ContactsModule.java | package com.matejdro.pebbledialer.modules;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.matejdro.pebblecommons.pebble.CommModule;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebblecommons.pebble.PebbleCommunication;
import com.matejdro.pebblecommons.util.TextUtil;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import timber.log.Timber;
public class ContactsModule extends CommModule
{
public static int MODULE_CONTACTS = 3;
private int nextToSend = -1;
private boolean openWindow = false;
public ContactsModule(PebbleTalkerService service) {
super(service);
names = new ArrayList<String>();
idSet = new HashSet<Integer>();
ids = new ArrayList<Integer>();
filters = new ArrayList<Integer>();
}
private List<Integer> filters;
private List<String> names;
private List<Integer> ids;
private HashSet<Integer> idSet;
private int group = -1;
public static final String queries[] = {"[^GHIghi4JKLjkl6MNOmno6PQRSŠpqrsš7TUVtuv8wWXYZŽxyzž9]", "[GHIghi4JKLjkl6MNOmno6 ]", "[PQRSŠpqrsš7TUVtuv8wWXYZŽxyzž9 ]"};
private boolean filterMode;
public void beginSending(int contactGroup) {
filters.clear();
this.group = contactGroup;
Timber.d("Group %d", group);
filterMode = contactGroup == -1 || !getService().getGlobalSettings().getBoolean("skipGroupFiltering", false);
openWindow = true;
refreshContacts();
queueSendEntries(0);
}
private String buildSelection()
{
if (filters.size() == 0)
return "1";
String selectionHalf = "";
for (int i = 0; i < filters.size(); i++)
selectionHalf = selectionHalf.concat(queries[filters.get(i)]);
String selection = ContactsContract.Contacts.DISPLAY_NAME + " GLOB \"" + selectionHalf + "*\" OR " + ContactsContract.Contacts.DISPLAY_NAME + " GLOB \"* " + selectionHalf + "*\"";
return selection;
}
private void sendContacts(int offset)
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 3);
data.addUint8(1, (byte) 0);
data.addUint16(2, (short) offset);
data.addUint16(3, (short) names.size());
for (int i = 0; i < 3; i++)
{
int listPos = offset + i;
if (listPos >= names.size())
break;
data.addString(i + 4, names.get(i + offset));
}
getService().getPebbleCommunication().sendToPebble(data);
}
private void refreshContacts()
{
if (ContextCompat.checkSelfPermission(getService(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED)
return;
ContentResolver resolver = getService().getContentResolver();
String selection = "( " + buildSelection() + " )";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " ASC";
Uri uri;
String idIndex;
if (group >= 0)
{
uri = ContactsContract.Data.CONTENT_URI;
selection += " AND " + ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + " = " + group;
idIndex = "contact_id";
}
else
{
selection += " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + " = 1";
uri = ContactsContract.Contacts.CONTENT_URI;
sortOrder += " LIMIT " + (filterMode ? "7" : "2000");
idIndex = ContactsContract.Contacts._ID;
}
Cursor cursor = resolver.query(uri, null, selection, null, sortOrder);
names.clear();
ids.clear();
idSet.clear();
if (cursor != null)
{
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int id = cursor.getInt(cursor.getColumnIndex(idIndex));
if (idSet.contains(id))
continue;
if (name == null)
continue;
names.add(TextUtil.prepareString(name));
ids.add(id);
idSet.add(id);
if (ids.size() > (filterMode ? 7 : 2000))
break;
}
cursor.close();
}
Timber.d("Loaded " + names.size() + " contacts.");
}
public void filterContacts(int buttonId)
{
if (buttonId == 3)
filters.clear();
else
filters.add(buttonId);
refreshContacts();
queueSendEntries(0);
}
@Override
public boolean sendNextMessage() {
if (nextToSend != -1)
{
sendContacts(nextToSend);
nextToSend = -1;
openWindow = false;
return true;
}
return false;
}
private void gotMessageRequestContacts(PebbleDictionary message)
{
int offset = message.getUnsignedIntegerAsLong(2).intValue();
if (filterMode && offset > 7)
{
filterMode = false;
refreshContacts();
}
if (offset >= names.size())
{
Timber.w("Received contact offset out of bounds!");
return;
}
queueSendEntries(offset);
}
private void gotMessageContactPicked(PebbleDictionary message)
{
int offset = message.getInteger(2).intValue();
if (offset >= ids.size())
{
Timber.w("Received contact offset out of bounds!");
return;
}
int id = ids.get(offset);
NumberPickerModule.get(getService()).showNumberPicker(id);
}
private void gotMessageFilter(PebbleDictionary message)
{
int button = message.getUnsignedIntegerAsLong(2).intValue();
Timber.d("Offset %d", button);
filterContacts(button);
}
@Override
public void gotMessageFromPebble(PebbleDictionary message) {
int id = message.getUnsignedIntegerAsLong(1).intValue();
switch (id)
{
case 0: //Filter button
gotMessageFilter(message);
break;
case 1: //Request contacts
gotMessageRequestContacts(message);
break;
case 2: //Picked contact
gotMessageContactPicked(message);
break;
}
}
public void queueSendEntries(int offset)
{
nextToSend = offset;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
public static ContactsModule get(PebbleTalkerService service)
{
return (ContactsModule) service.getModule(MODULE_CONTACTS);
}
}
| 6,828 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
NumberPickerModule.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/modules/NumberPickerModule.java | package com.matejdro.pebbledialer.modules;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.telephony.PhoneNumberUtils;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.matejdro.pebblecommons.pebble.CommModule;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebblecommons.pebble.PebbleCommunication;
import com.matejdro.pebblecommons.util.ContactUtils;
import com.matejdro.pebblecommons.util.TextUtil;
import com.matejdro.pebbledialer.callactions.SMSReplyAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import timber.log.Timber;
public class NumberPickerModule extends CommModule
{
public static int MODULE_NUMBER_PICKER = 4;
private List<PebbleNumberEntry> phoneNumbers;
private int nextToSend = -1;
private boolean openWindow = false;
public NumberPickerModule(PebbleTalkerService service) {
super(service);
phoneNumbers = new ArrayList<PebbleNumberEntry>();
}
public void showNumberPicker(int contactId) {
phoneNumbers.clear();
if (ContextCompat.checkSelfPermission(getService(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
{
ContentResolver resolver = getService().getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC LIMIT 2000");
while (cursor.moveToNext())
{
int typeId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String label = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = ContactUtils.convertNumberType(typeId, label);
PebbleNumberEntry numberEntry = new PebbleNumberEntry(number, type);
if (!phoneNumbers.contains(numberEntry))
phoneNumbers.add(numberEntry);
}
cursor.close();
}
else
{
phoneNumbers.add(new PebbleNumberEntry("No permission", "ERROR"));
}
int initialAmount = phoneNumbers.size();
for (int i = 0; i < initialAmount; i++)
{
PebbleNumberEntry originalEntry = phoneNumbers.get(i);
phoneNumbers.add(new PebbleNumberEntry(originalEntry.number, originalEntry.numberType, PebbleNumberEntry.NUMBER_ACTION_SMS));
}
openWindow = true;
sendNumbers(0);
}
public void sendNumbers(int offset)
{
PebbleDictionary data = new PebbleDictionary();
data.addUint8(0, (byte) 4);
data.addUint8(1, (byte) 0);
data.addUint16(2, (short) offset);
data.addUint16(3, (short) phoneNumbers.size());
byte[] numberActions = new byte[2];
for (int i = 0; i < 2; i++)
{
int listPos = offset + i;
if (listPos >= phoneNumbers.size())
break;
PebbleNumberEntry numberEntry = phoneNumbers.get(listPos);
data.addString(i + 4, TextUtil.prepareString(numberEntry.numberType));
data.addString(i + 6, TextUtil.prepareString(numberEntry.number));
numberActions[i] = (byte) numberEntry.numberAction;
}
data.addBytes(8, numberActions);
if (openWindow)
data.addUint8(999, (byte) 1);
Timber.d("sendNumbers %d", offset);
getService().getPebbleCommunication().sendToPebble(data);
}
public void queueSendEntries(int offset)
{
nextToSend = offset;
PebbleCommunication communication = getService().getPebbleCommunication();
communication.queueModulePriority(this);
communication.sendNext();
}
@Override
public boolean sendNextMessage() {
if (nextToSend != -1)
{
sendNumbers(nextToSend);
nextToSend = -1;
openWindow = false;
return true;
}
return false;
}
@Override
public void gotMessageFromPebble(PebbleDictionary message) {
int id = message.getUnsignedIntegerAsLong(1).intValue();
switch (id)
{
case 0:
int offset = message.getUnsignedIntegerAsLong(2).intValue();
queueSendEntries(offset);
break;
case 1:
offset = message.getInteger(2).intValue();
if (offset >= phoneNumbers.size())
break;
PebbleNumberEntry numberEntry = phoneNumbers.get(offset);
if (numberEntry.numberAction == PebbleNumberEntry.NUMBER_ACTION_CALL)
ContactUtils.call(numberEntry.number, getService());
else
SMSReplyModule.get(getService()).startSMSProcess(numberEntry.number);
break;
}
}
public static NumberPickerModule get(PebbleTalkerService service)
{
return (NumberPickerModule) service.getModule(MODULE_NUMBER_PICKER);
}
private static class PebbleNumberEntry
{
public static final int NUMBER_ACTION_CALL = 0;
public static final int NUMBER_ACTION_SMS = 1;
public String number;
public String numberType;
public int numberAction;
public PebbleNumberEntry(String number, String numberType, int numberAction)
{
this.number = number;
this.numberType = numberType;
this.numberAction = numberAction;
}
public PebbleNumberEntry(String number, String numberType)
{
this.number = number;
this.numberType = numberType;
this.numberAction = NUMBER_ACTION_CALL;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PebbleNumberEntry that = (PebbleNumberEntry) o;
if (numberAction != that.numberAction) return false;
return PhoneNumberUtils.compare(number, that.number);
}
@Override
public int hashCode()
{
// Number is not used in hashcode, because it involves complicated comparing method that
// cannot be boiled down to hash.
return numberAction;
}
}
}
| 6,883 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
TaskerMenuFragment.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/tasker/TaskerMenuFragment.java | package com.matejdro.pebbledialer.tasker;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.ui.fragments.settings.CallscreenSettingsFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.GeneralSettingsFragment;
import com.matejdro.pebbledialer.ui.fragments.settings.MessagingSettingsFragment;
public class TaskerMenuFragment extends Fragment
{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_tasker_menu, container, false);
view.findViewById(R.id.general_settings).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onGeneralSettingsClicked();
}
});
view.findViewById(R.id.customize_callscreen).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onCustomizeCallscreenClicked();
}
});
view.findViewById(R.id.sms).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onSmsClicked();
}
});
return view;
}
private void onGeneralSettingsClicked()
{
((TaskerSettingsActivity) getActivity()).swapFragment(new GeneralSettingsFragment());
}
private void onCustomizeCallscreenClicked()
{
((TaskerSettingsActivity) getActivity()).swapFragment(new CallscreenSettingsFragment());
}
private void onSmsClicked()
{
((TaskerSettingsActivity) getActivity()).swapFragment(new MessagingSettingsFragment());
}
}
| 2,040 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
TaskerReceiver.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/tasker/TaskerReceiver.java | package com.matejdro.pebbledialer.tasker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import com.matejdro.pebblecommons.util.BundleSharedPreferences;
public class TaskerReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if (intent == null)
return;
Bundle bundle = intent.getBundleExtra("com.twofortyfouram.locale.intent.extra.BUNDLE");
if (bundle == null)
return;
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
for (String key : bundle.keySet())
{
if (!key.startsWith("setting_"))
continue;
String actualSetting = key.substring(8);
BundleSharedPreferences.writeIntoSharedPreferences(editor, actualSetting, bundle.get(key));
}
editor.apply();
}
}
| 1,086 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
TaskerSettingsActivity.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/tasker/TaskerSettingsActivity.java | package com.matejdro.pebbledialer.tasker;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.annotation.XmlRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.matejdro.pebblecommons.util.BundleSharedPreferences;
import com.matejdro.pebblecommons.util.LogWriter;
import com.matejdro.pebbledialer.R;
import com.matejdro.pebbledialer.ui.PreferenceSource;
import com.matejdro.pebbledialer.ui.fragments.settings.GenericPreferenceScreen;
import com.matejdro.pebbledialer.ui.fragments.settings.PreferenceActivity;
public class TaskerSettingsActivity extends AppCompatActivity implements PreferenceActivity, PreferenceSource
{
private Bundle settingStorageBundle;
private static String KEY_STORAGE_BUNDLE = "StorageBundle";
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
if (savedInstanceState == null)
{
settingStorageBundle = new Bundle();
loadTaskerIntent();
}
else
{
settingStorageBundle = savedInstanceState.getBundle(KEY_STORAGE_BUNDLE);
}
sharedPreferences = new BundleSharedPreferences(PreferenceManager.getDefaultSharedPreferences(this), settingStorageBundle);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasker);
if (savedInstanceState == null)
{
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new TaskerMenuFragment())
.commit();
}
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
outState.putBundle(KEY_STORAGE_BUNDLE, settingStorageBundle);
super.onSaveInstanceState(outState);
}
public void swapFragment(Fragment fragment)
{
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.content_frame, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
public void switchToGenericPreferenceScreen(@XmlRes int xmlRes, String root)
{
Fragment fragment = GenericPreferenceScreen.newInstance(xmlRes, root);
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.content_frame, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
protected void loadTaskerIntent() {
Intent intent = getIntent();
if (intent == null)
return;
Bundle bundle = intent.getBundleExtra("com.twofortyfouram.locale.intent.extra.BUNDLE");
if (bundle == null)
return;
settingStorageBundle.putAll(bundle);
for (String key : bundle.keySet())
{
if (!key.startsWith("setting_"))
{
settingStorageBundle.remove(key);
}
}
}
private void saveTaskerIntent()
{
Intent intent = new Intent();
String description = getString(R.string.tasker_change_settings);
Bundle taskerBundle = new Bundle();
taskerBundle.putAll(settingStorageBundle);
intent.putExtra("com.twofortyfouram.locale.intent.extra.BLURB", description);
intent.putExtra("com.twofortyfouram.locale.intent.extra.BUNDLE", taskerBundle);
setResult(RESULT_OK, intent);
}
@Override
public void onBackPressed()
{
boolean exitingActivity = getFragmentManager().getBackStackEntryCount() == 0;
if (exitingActivity)
saveTaskerIntent();
super.onBackPressed();
}
@Override
public SharedPreferences getCustomPreferences()
{
return sharedPreferences;
}
}
| 4,164 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
WatchappHandler.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/pebble/WatchappHandler.java | package com.matejdro.pebbledialer.pebble;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import com.matejdro.pebbledialer.R;
public class WatchappHandler extends BroadcastReceiver {
public static final int SUPPORTED_PROTOCOL = 11;
public static final String INTENT_UPDATE_WATCHAPP = "com.matejdro.pebbledialer.UPDATE_WATCHAPP";
public static final String WATCHAPP_URL = "https://github.com/matejdro/PebbleDialer-Watchapp/releases/latest";
public static boolean isFirstRun(SharedPreferences settings)
{
boolean firstRun = settings.getBoolean("FirstRun", true);
if (firstRun)
{
Editor editor = settings.edit();
editor.putBoolean("FirstRun", false);
editor.apply();
}
return firstRun;
}
public static void openPebbleStore(Context context)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("pebble://appstore/532323bf60c773c1420000a8"));
try
{
context.startActivity(intent);
}
catch (ActivityNotFoundException e)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.openingPebbleAppFailed).setNegativeButton("OK", null).show();
}
}
public static void showUpdateNotification(Context context)
{
Notification.Builder mBuilder =
new Notification.Builder(context).setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Pebble Dialer watchapp update").setContentText("Click on this notiifcation to open link to the download")
.setContentIntent(PendingIntent.getBroadcast(context, 1, new Intent(INTENT_UPDATE_WATCHAPP), PendingIntent.FLAG_CANCEL_CURRENT));
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.getNotification());
}
public static void openUpdateWebpage(Context context)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(WATCHAPP_URL));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
context.startActivity(intent);
}
catch (ActivityNotFoundException e)
{
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (INTENT_UPDATE_WATCHAPP.equals(intent.getAction()))
{
openUpdateWebpage(context);
}
}
}
| 3,084 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
EndCallAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/EndCallAction.java | package com.matejdro.pebbledialer.callactions;
import android.app.PendingIntent;
import android.content.Context;
import android.telephony.TelephonyManager;
import com.android.internal.telephony.ITelephony;
import com.crashlytics.android.Crashlytics;
import com.matejdro.pebbledialer.modules.CallModule;
import java.io.IOException;
import java.lang.reflect.Method;
import timber.log.Timber;
public class EndCallAction extends CallAction
{
public static final int END_CALL_ACTION_ID = 1;
private PendingIntent notificationEndCallIntent;
private static Method getITelephonyMethod;
public EndCallAction(CallModule callModule)
{
super(callModule);
try {
getITelephonyMethod = TelephonyManager.class.getDeclaredMethod("getITelephony", (Class[]) null);
getITelephonyMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
Timber.e(e, "iTelephony end not supported on your phone!");
} catch (Exception e) {
Timber.e(e, "Error while acquiring iTelephony");
Crashlytics.logException(e);
}
}
public void registerNotificationEndCallIntent(PendingIntent notificationAnswerIntent)
{
this.notificationEndCallIntent = notificationAnswerIntent;
}
@Override
public void executeAction()
{
getCallModule().setCloseAutomaticallyAfterThisCall(true);
if (getCallModule().getService().getGlobalSettings().getBoolean("rootMode", false))
{
Timber.d("Ending call using root method...");
try {
Runtime.getRuntime().exec(new String[] {"su", "-c", "input keyevent 6"});
return;
} catch (IOException e) {
e.printStackTrace();
}
}
if (getCallModule().getCallState() == CallModule.CallState.RINGING && notificationEndCallIntent != null)
{
Timber.d("Ending call using notification method...");
try {
notificationEndCallIntent.send();
return;
} catch (PendingIntent.CanceledException e) {
}
}
if (getITelephonyMethod != null)
{
Timber.d("Ending call using generic iTelephony method...");
try
{
ITelephony iTelephony = (ITelephony) getITelephonyMethod.invoke(getCallModule().getService().getSystemService(Context.TELEPHONY_SERVICE), (Object[]) null);
iTelephony.endCall();
return;
}
catch (SecurityException e)
{
Timber.e("Cannot decline call, no CALL_PHONE permission.");
}
catch (Exception e) {
Timber.e(e, "Error while invoking iTelephony.endCall()");
Crashlytics.logException(e);
}
}
Timber.e("All end call options failed! Nothing is supported.");
}
@Override
public void onCallEnd()
{
notificationEndCallIntent = null; //Reset intent (there will be new intent at next call)
}
@Override
public int getIcon()
{
return CallAction.ICON_BUTTON_END_CALL;
}
public static EndCallAction get(CallModule callModule)
{
return (EndCallAction) callModule.getCallAction(END_CALL_ACTION_ID);
}
}
| 3,373 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
VolumeUpAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/VolumeUpAction.java | package com.matejdro.pebbledialer.callactions;
import android.content.Context;
import android.media.AudioManager;
import com.matejdro.pebbledialer.modules.CallModule;
public class VolumeUpAction extends CallAction
{
public static final int VOLUME_UP_ACTION_ID = 8;
public VolumeUpAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.ESTABLISHED)
return;
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
audioManager.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_RAISE, 0);
}
@Override
public int getIcon()
{
return CallAction.ICON_BUTTON_VOLUME_UP;
}
}
| 850 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
AnswerCallAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/AnswerCallAction.java | package com.matejdro.pebbledialer.callactions;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.session.MediaController;
import android.media.session.MediaSessionManager;
import android.os.Build;
import android.telecom.TelecomManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import com.matejdro.pebbledialer.modules.CallModule;
import com.matejdro.pebbledialer.notifications.JellybeanNotificationListener;
import java.io.IOException;
import java.util.List;
import timber.log.Timber;
public class AnswerCallAction extends CallAction
{
public static final int ANSWER_ACTION_ID = 0;
private PendingIntent notificationAnswerIntent;
public AnswerCallAction(CallModule callModule)
{
super(callModule);
}
public void registerNotificationAnswerIntent(PendingIntent notificationAnswerIntent)
{
this.notificationAnswerIntent = notificationAnswerIntent;
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.RINGING)
return;
if (getCallModule().getService().getGlobalSettings().getBoolean("rootMode", false))
{
Timber.d("Answering using root method...");
try {
Runtime.getRuntime().exec(new String[] {"su", "-c", "input keyevent 5"});
return;
} catch (IOException e) {
e.printStackTrace();
}
}
if (notificationAnswerIntent != null)
{
Timber.d("Answering using notification method...");
try {
notificationAnswerIntent.send();
return;
} catch (PendingIntent.CanceledException e) {
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
answerNativelyOreo();
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
answerUsingMediaServer();
}
else
{
Timber.d("Answering using generic headset hook method...");
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
getCallModule().getService().sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
}
}
@TargetApi(Build.VERSION_CODES.O)
private void answerNativelyOreo() {
TelecomManager telecomManager
= (TelecomManager) getCallModule().getService().getSystemService(Context.TELECOM_SERVICE);
Timber.d("Answering natively with Oreo.");
try {
telecomManager.acceptRingingCall();
} catch (SecurityException e) {
Timber.e("No accept call permission!");
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void answerUsingMediaServer()
{
Timber.d("Answering using media server method...");
MediaSessionManager mediaSessionManager = (MediaSessionManager) getCallModule().getService().getSystemService(Context.MEDIA_SESSION_SERVICE);
try {
List<MediaController> mediaControllerList = mediaSessionManager.getActiveSessions
(new ComponentName(getCallModule().getService(), JellybeanNotificationListener.class));
for (MediaController m : mediaControllerList) {
if ("com.android.server.telecom".equals(m.getPackageName())) {
Timber.d("Found telephony media controller!");
m.dispatchMediaButtonEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
break;
}
}
} catch (SecurityException e) {
Timber.e("Notification service not running!");
}
}
@Override
public void onCallEnd()
{
notificationAnswerIntent = null; //Reset intent (there will be new intent at next call)
}
@Override
public int getIcon()
{
return CallAction.ICON_BUTTON_ANSWER;
}
public static AnswerCallAction get(CallModule callModule)
{
return (AnswerCallAction) callModule.getCallAction(ANSWER_ACTION_ID);
}
}
| 4,437 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
DummyAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/DummyAction.java | package com.matejdro.pebbledialer.callactions;
import com.matejdro.pebbledialer.modules.CallModule;
public class DummyAction extends CallAction
{
public static final int DUMMY_ACTION_ID = 999;
public DummyAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
}
@Override
public int getIcon()
{
return CallAction.ICON_BLANK;
}
public static DummyAction get(CallModule callModule)
{
return (DummyAction) callModule.getCallAction(DUMMY_ACTION_ID);
}
}
| 580 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
ToggleMicrophoneAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/ToggleMicrophoneAction.java | package com.matejdro.pebbledialer.callactions;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import com.matejdro.pebbledialer.modules.CallModule;
import java.io.IOException;
public class ToggleMicrophoneAction extends CallAction
{
public static final int TOGGLE_MICROPHONE_ACTION_ID = 3;
private boolean microphoneMuted = false;
public ToggleMicrophoneAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.ESTABLISHED)
return;
microphoneMuted = !microphoneMuted;
if (getCallModule().getService().getGlobalSettings().getBoolean("rootMode", false))
{
String muteCommand;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
muteCommand = "input keyevent 79";
else
muteCommand = "input keyevent 91";
try {
Runtime.getRuntime().exec(new String[] {"su", "-c", muteCommand});
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMicrophoneMute(microphoneMuted);
}
getCallModule().updatePebble();
}
@Override
public int getIcon()
{
return microphoneMuted ? CallAction.ICON_BUTTON_MIC_OFF : CallAction.ICON_BUTTON_MIC_ON;
}
public static ToggleMicrophoneAction get(CallModule callModule)
{
return (ToggleMicrophoneAction) callModule.getCallAction(TOGGLE_MICROPHONE_ACTION_ID);
}
}
| 1,801 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
SMSReplyAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/SMSReplyAction.java | package com.matejdro.pebbledialer.callactions;
import android.app.PendingIntent;
import android.content.Context;
import android.telephony.TelephonyManager;
import com.android.internal.telephony.ITelephony;
import com.crashlytics.android.Crashlytics;
import com.matejdro.pebbledialer.modules.CallModule;
import com.matejdro.pebbledialer.modules.SMSReplyModule;
import java.io.IOException;
import java.lang.reflect.Method;
import timber.log.Timber;
public class SMSReplyAction extends CallAction
{
public static final int SMS_REPLY_ACTION_ID = 6;
public SMSReplyAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
ToggleRingerAction toggleRingerAction = ToggleRingerAction.get(getCallModule());
toggleRingerAction.mute();
SMSReplyModule smsReplyModule = SMSReplyModule.get(getCallModule().getService());
smsReplyModule.startSMSProcess(getCallModule().getNumber());
getCallModule().setCloseAutomaticallyAfterThisCall(false);
}
@Override
public void onCallEnd()
{
}
@Override
public int getIcon()
{
return CallAction.ICON_BUTTON_END_CALL;
}
public static SMSReplyAction get(CallModule callModule)
{
return (SMSReplyAction) callModule.getCallAction(SMS_REPLY_ACTION_ID);
}
}
| 1,363 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
ToggleRingerAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/ToggleRingerAction.java | package com.matejdro.pebbledialer.callactions;
import android.app.NotificationManager;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.view.KeyEvent;
import com.matejdro.pebbledialer.modules.CallModule;
import java.io.IOException;
import timber.log.Timber;
public class ToggleRingerAction extends CallAction
{
public static final int TOGGLE_RINGER_ACTION_ID = 2;
private boolean isMutedViaAudioManager = false;
private int prevRingerMode = AudioManager.RINGER_MODE_NORMAL;
public ToggleRingerAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.RINGING)
return;
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
getCallModule().setVibration(false);
if (!isMutedViaAudioManager)
{
if (getCallModule().getService().getGlobalSettings().getBoolean("rootMode", false))
{
Timber.d("Muting using root method...");
try {
Runtime.getRuntime().exec(new String[] {"su", "-c", "input keyevent " + KeyEvent.KEYCODE_VOLUME_DOWN});
} catch (IOException e) {
e.printStackTrace();
}
}
else if (canMuteRinger(getCallModule().getService()))
{
isMutedViaAudioManager = true;
prevRingerMode = audioManager.getRingerMode();
audioManager.setStreamSolo(AudioManager.STREAM_MUSIC, true);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
else if (canMuteRinger(getCallModule().getService()))
{
isMutedViaAudioManager = false;
audioManager.setStreamSolo(AudioManager.STREAM_MUSIC, false);
audioManager.setRingerMode(prevRingerMode);
}
getCallModule().updatePebble();
}
public void mute()
{
if (!isMutedViaAudioManager)
executeAction();
}
public static boolean canMuteRinger(Context context)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return true;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager.isNotificationPolicyAccessGranted();
}
@Override
public void onCallEnd()
{ if (isMutedViaAudioManager && canMuteRinger(getCallModule().getService()))
{
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
isMutedViaAudioManager = false;
audioManager.setStreamSolo(AudioManager.STREAM_MUSIC, false);
audioManager.setRingerMode(prevRingerMode);
}
getCallModule().setVibration(true);
}
@Override
public int getIcon()
{
return isMutedViaAudioManager ? CallAction.ICON_BUTTON_SPEAKER_OFF : CallAction.ICON_BUTTON_SPEKAER_ON;
}
public static ToggleRingerAction get(CallModule callModule)
{
return (ToggleRingerAction) callModule.getCallAction(TOGGLE_RINGER_ACTION_ID);
}
}
| 3,397 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
ToggleSpeakerAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/ToggleSpeakerAction.java | package com.matejdro.pebbledialer.callactions;
import android.content.Context;
import android.media.AudioManager;
import com.matejdro.pebbledialer.modules.CallModule;
public class ToggleSpeakerAction extends CallAction
{
public static final int TOGGLE_SPEAKER_ACTION_ID = 4;
private boolean speakerphoneEnabled = false;
public ToggleSpeakerAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.ESTABLISHED)
return;
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
speakerphoneEnabled = !speakerphoneEnabled;
audioManager.setSpeakerphoneOn(speakerphoneEnabled);
getCallModule().updatePebble();
}
public boolean isSpeakerphoneEnabled()
{
return speakerphoneEnabled;
}
private void updateSpeakerphoneEnabled()
{
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
speakerphoneEnabled = audioManager.isSpeakerphoneOn();
}
@Override
public void onPhoneOffhook()
{
updateSpeakerphoneEnabled();
}
@Override
public int getIcon()
{
return speakerphoneEnabled ? ICON_BUTTON_SPEKAER_ON : ICON_BUTTON_SPEAKER_OFF;
}
public static ToggleSpeakerAction get(CallModule callModule)
{
return (ToggleSpeakerAction) callModule.getCallAction(TOGGLE_SPEAKER_ACTION_ID);
}
}
| 1,601 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
VolumeDownAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/VolumeDownAction.java | package com.matejdro.pebbledialer.callactions;
import android.content.Context;
import android.media.AudioManager;
import com.matejdro.pebbledialer.modules.CallModule;
public class VolumeDownAction extends CallAction
{
public static final int VOLUME_DOWN_ACTION_ID = 7;
public VolumeDownAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.ESTABLISHED)
return;
AudioManager audioManager = (AudioManager) getCallModule().getService().getSystemService(Context.AUDIO_SERVICE);
audioManager.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_LOWER, 0);
}
@Override
public int getIcon()
{
return CallAction.ICON_BUTTON_VOLUME_DOWN;
}
}
| 858 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
CallAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/CallAction.java | package com.matejdro.pebbledialer.callactions;
import com.matejdro.pebbledialer.modules.CallModule;
public abstract class CallAction
{
public static final int ICON_BUTTON_ANSWER = 0;
public static final int ICON_BUTTON_END_CALL = 1;
public static final int ICON_BUTTON_MIC_ON = 2;
public static final int ICON_BUTTON_MIC_OFF = 3;
public static final int ICON_BUTTON_SPEKAER_ON = 4;
public static final int ICON_BUTTON_SPEAKER_OFF = 5;
public static final int ICON_BUTTON_VOLUME_DOWN = 6;
public static final int ICON_BUTTON_VOLUME_UP = 7;
public static final int ICON_BLANK = 0xFF;
private CallModule callModule;
public CallAction(CallModule callModule)
{
this.callModule = callModule;
}
public CallModule getCallModule()
{
return callModule;
}
public void onPhoneOffhook()
{
}
public void onCallRinging()
{
}
public void onCallEnd()
{
}
public abstract void executeAction();
public abstract int getIcon();
}
| 1,045 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
AnswerCallWithSpeakerAction.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/callactions/AnswerCallWithSpeakerAction.java | package com.matejdro.pebbledialer.callactions;
import com.matejdro.pebbledialer.modules.CallModule;
public class AnswerCallWithSpeakerAction extends CallAction
{
public static final int ANSWER_WITH_SPEAKER_ACTION_ID = 5;
private boolean enableSpeakerImmediately = false;
public AnswerCallWithSpeakerAction(CallModule callModule)
{
super(callModule);
}
@Override
public void executeAction()
{
if (getCallModule().getCallState() != CallModule.CallState.RINGING)
return;
enableSpeakerImmediately = true;
AnswerCallAction.get(getCallModule()).executeAction();
}
@Override
public void onCallEnd()
{
enableSpeakerImmediately = false; //Reset intent (there will be new intent at next call)
}
@Override
public void onPhoneOffhook()
{
if (enableSpeakerImmediately)
{
ToggleSpeakerAction speakerAction = ToggleSpeakerAction.get(getCallModule());
if (!speakerAction.isSpeakerphoneEnabled())
speakerAction.executeAction();
}
}
@Override
public int getIcon()
{
return CallAction.ICON_BUTTON_ANSWER;
}
public static AnswerCallWithSpeakerAction get(CallModule callModule)
{
return (AnswerCallWithSpeakerAction) callModule.getCallAction(ANSWER_WITH_SPEAKER_ACTION_ID);
}
}
| 1,397 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
NotificationHandler.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/notifications/NotificationHandler.java | package com.matejdro.pebbledialer.notifications;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import com.matejdro.pebblecommons.pebble.PebbleTalkerService;
import com.matejdro.pebbledialer.DialerTalkerService;
import com.matejdro.pebbledialer.modules.CallModule;
import java.lang.reflect.Field;
import timber.log.Timber;
public class NotificationHandler {
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void newNotification(Context context, String pkg, Notification notification)
{
if (pkg.contains("dialer") || pkg.contains("phone") || pkg.contains("call"))
{
Timber.d("Found potentially useful notification from %s", pkg);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String answerText = preferences.getString("callNotificationAnswerButton", "Answer");
String declineText = preferences.getString("callNotificationDeclineButton", "Decline");
Notification.Action[] actions = getActionsField(notification);
if (actions == null)
return;
PendingIntent answerIntent = null;
PendingIntent declineIntent = null;
for (Notification.Action action : actions)
{
Timber.d("Found action %s", action.title);
if (action.title.toString().equalsIgnoreCase(answerText))
answerIntent = action.actionIntent;
else if (action.title.toString().equalsIgnoreCase(declineText))
declineIntent = action.actionIntent;
}
if (answerIntent != null)
{
Intent intent = new Intent(context, DialerTalkerService.class);
intent.setAction(CallModule.INTENT_ACTION_FROM_NOTIFICATION);
intent.putExtra("actionType", 0);
intent.putExtra("action", answerIntent);
context.startService(intent);
}
if (declineIntent != null)
{
Intent intent = new Intent(context, DialerTalkerService.class);
intent.setAction(CallModule.INTENT_ACTION_FROM_NOTIFICATION);
intent.putExtra("actionType", 1);
intent.putExtra("action", declineIntent);
context.startService(intent);
}
}
}
/**
* Get the actions array from a notification using reflection. Actions were present in
* Jellybean notifications, but the field was private until KitKat.
*/
public static Notification.Action[] getActionsField(Notification notif) {
try {
Field actionsField = Notification.class.getDeclaredField("actions");
actionsField.setAccessible(true);
Notification.Action[] actions = (Notification.Action[]) actionsField.get(notif);
return actions;
} catch (IllegalAccessException e) {
} catch (NoSuchFieldException e) {
} catch (IllegalAccessError e)
{
//Weird error that appears on some devices (Only Xiaomi reported so far) and apparently means that Notification.Action on these devices is different than usual Android.
//Unsupported for now.
}
return null;
}
}
| 3,529 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
JellybeanNotificationListener.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/matejdro/pebbledialer/notifications/JellybeanNotificationListener.java | package com.matejdro.pebbledialer.notifications;
import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.os.Build;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import timber.log.Timber;
@TargetApi(value = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class JellybeanNotificationListener extends NotificationListenerService {
private static JellybeanNotificationListener instance = null;
@Override
public void onDestroy() {
Timber.d("Notification Listener stopped...");
super.onDestroy();
instance = null;
}
@Override
public void onCreate() {
Timber.d("Creating Notification Listener...");
super.onCreate();
instance = this;
}
public static boolean isActive()
{
return instance != null;
}
@TargetApi(value = Build.VERSION_CODES.LOLLIPOP)
public static boolean isPhoneInDoNotInterrupt()
{
if (instance == null)
return false;
int interruptionFilter = instance.getCurrentInterruptionFilter();
Timber.d("Interrupt filter: %d", interruptionFilter);
return interruptionFilter != NotificationListenerService.INTERRUPTION_FILTER_ALL && interruptionFilter != 0;
}
@Override
public void onNotificationPosted(final StatusBarNotification sbn) {
Timber.d("Got new jellybean notification");
NotificationHandler.newNotification(JellybeanNotificationListener.this, sbn.getPackageName(), sbn.getNotification());
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
}
}
| 1,587 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
ITelephony.java | /FileExtraction/Java_unseen/matejdro_PebbleDialer-Android/app/src/main/java/com/android/internal/telephony/ITelephony.java | package com.android.internal.telephony;
public interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
} | 155 | Java | .java | matejdro/PebbleDialer-Android | 29 | 16 | 13 | 2013-10-15T18:02:39Z | 2023-01-09T17:34:03Z |
TestInfoViewModel.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/viewmodel/TestInfoViewModel.java | /*
* Copyright 2017, 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 org.akvo.caddisfly.viewmodel;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.databinding.BindingAdapter;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import org.akvo.caddisfly.BuildConfig;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.Constants;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.Reagent;
import org.akvo.caddisfly.model.ReagentType;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.sensor.bluetooth.ReagentLabel;
import org.akvo.caddisfly.util.StringUtil;
import org.akvo.caddisfly.widget.RowView;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestInfoViewModel extends AndroidViewModel {
private static TestInfo testInfo;
private final ObservableField<TestInfo> test = new ObservableField<>();
public TestInfoViewModel(@NonNull Application application) {
super(application);
}
/**
* Sets the content of the view with formatted string.
*
* @param linearLayout the layout
* @param instruction the instruction key
*/
@BindingAdapter("content")
public static void setContent(LinearLayout linearLayout, Instruction instruction) {
if (instruction == null || instruction.section == null) {
return;
}
Context context = linearLayout.getContext();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point size = new Point();
if (windowManager != null) {
windowManager.getDefaultDisplay().getRealSize(size);
}
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
for (int i = 0; i < instruction.section.size(); i++) {
String text = instruction.section.get(i);
Matcher tag = Pattern.compile("~.*?~").matcher(text);
if (tag.find()) {
return;
} else if (text.contains("include:incubation_table")) {
LayoutInflater inflater = (LayoutInflater) linearLayout.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
if (inflater != null) {
view = inflater.inflate(R.layout.incubation_table, linearLayout, false);
linearLayout.addView(view);
}
} else if (text.contains("image:")) {
insertImage(linearLayout, context, size, displayMetrics, i, text);
} else {
RowView rowView = new RowView(context);
Matcher m = Pattern.compile("^(\\d*?[a-zA-Z]{1,3}\\.\\s*)(.*)").matcher(text);
Matcher m1 = Pattern.compile("^(\\d+?\\.\\s*)(.*)").matcher(text);
Matcher m2 = Pattern.compile("^(\\.\\s*)(.*)").matcher(text);
if (m.find()) {
rowView.setNumber(m.group(1).trim());
text = m.group(2).trim();
} else if (m1.find()) {
rowView.setNumber(m1.group(1).trim());
text = m1.group(2).trim();
} else if (m2.find()) {
rowView.setNumber(" ");
text = m2.group(2).trim();
}
String[] sentences = (text + ". ").split("\\.\\s+");
LinearLayout labelView = new LinearLayout(context);
for (int j = 0; j < sentences.length; j++) {
if (j > 0) {
rowView.append(new SpannableString(" "));
}
rowView.append(StringUtil.toInstruction((AppCompatActivity) context,
testInfo, sentences[j].trim()));
String sentence = StringUtil.getStringResourceByName(context, sentences[j]).toString();
if (sentence.contains("[/a]")) {
rowView.enableLinks(true);
}
// Set reagent in the string
replaceReagentTags(labelView, context, sentence);
}
// set an id for the view to be able to find it for unit testing
rowView.setId(i);
linearLayout.addView(rowView);
linearLayout.addView(labelView);
}
}
}
private static void replaceReagentTags(LinearLayout linearLayout, Context context, String sentence) {
linearLayout.setOrientation(LinearLayout.VERTICAL);
for (int j = 1; j < 5; j++) {
Matcher m2 = Pattern.compile("%reagent" + j).matcher(sentence);
while (m2.find()) {
Reagent reagent = testInfo.getReagent(j - 1);
if ((reagent.type == ReagentType.TABLET || testInfo.getReagentType().equals("Tablet"))
&& !reagent.code.isEmpty()) {
ReagentLabel reagentLabel = new ReagentLabel(context, null);
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, (int) (height * 0.19));
layoutParams.bottomMargin = 16;
reagentLabel.setLayoutParams(layoutParams);
reagentLabel.setReagentName(reagent.name);
reagentLabel.setReagentCode(reagent.code);
linearLayout.addView(reagentLabel);
}
}
}
}
private static void insertImage(LinearLayout linearLayout, Context context, Point size,
DisplayMetrics displayMetrics, int i, String text) {
String imageName = text.substring(text.indexOf(":") + 1);
int resourceId = context.getResources().getIdentifier("drawable/in_" + imageName,
"id", BuildConfig.APPLICATION_ID);
if (resourceId > 0) {
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 0, 0, 20);
final AppCompatImageView imageView = new AppCompatImageView(context);
imageView.setImageResource(resourceId);
imageView.setAdjustViewBounds(true);
imageView.setLayoutParams(llp);
imageView.setContentDescription(imageName);
// set an id for the view to be able to find it for unit testing
imageView.setId(i);
linearLayout.addView(imageView);
} else {
String image = Constants.ILLUSTRATION_PATH + imageName + ".webp";
InputStream ims = null;
try {
ims = context.getAssets().open(image);
} catch (IOException e) {
e.printStackTrace();
}
if (ims != null) {
ImageView imageView = new ImageView(linearLayout.getContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageDrawable(Drawable.createFromStream(ims, null));
double divisor = 3.1;
if (displayMetrics.densityDpi > 250) {
divisor = 2.7;
}
if (size.y > displayMetrics.heightPixels) {
divisor += 0.3;
}
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
(int) (displayMetrics.heightPixels / divisor));
llp.setMargins(0, 0, 0, 20);
imageView.setLayoutParams(llp);
imageView.setContentDescription(imageName);
// set an id for the view to be able to find it for unit testing
imageView.setId(i);
linearLayout.addView(imageView);
}
}
}
/**
* Sets the image scale.
*
* @param imageView the image view
* @param scaleType the scale type
*/
@BindingAdapter("imageScale")
public static void setImageScale(ImageView imageView, String scaleType) {
if (scaleType != null) {
imageView.setScaleType("fitCenter".equals(scaleType)
? ImageView.ScaleType.FIT_CENTER : ImageView.ScaleType.CENTER_CROP);
} else {
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
}
@BindingAdapter("imageUrl")
public static void setImageUrl(ImageView imageView, String name) {
setImage(imageView, Constants.BRAND_IMAGE_PATH + name + ".webp");
}
private static void setImage(ImageView imageView, String theName) {
if (theName != null) {
Context context = imageView.getContext();
try {
String name = theName.replace(" ", "-");
InputStream ims = context.getAssets().open(name);
imageView.setImageDrawable(Drawable.createFromStream(ims, null));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void setTest(TestInfo testInfo) {
this.test.set(testInfo);
TestInfoViewModel.testInfo = testInfo;
}
}
| 10,692 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestListViewModel.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/viewmodel/TestListViewModel.java | /*
* Copyright 2017, 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 org.akvo.caddisfly.viewmodel;
import android.app.Application;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.model.TestType;
import org.akvo.caddisfly.repository.TestConfigRepository;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
public class TestListViewModel extends AndroidViewModel {
private final TestConfigRepository testConfigRepository;
public TestListViewModel(@NonNull Application application) {
super(application);
testConfigRepository = new TestConfigRepository();
}
public List<TestInfo> getTests(TestType testType) {
return testConfigRepository.getTests(testType);
}
public TestInfo getTestInfo(String uuid) {
return testConfigRepository.getTestInfo(uuid);
}
public void clearTests() {
testConfigRepository.clear();
}
}
| 1,524 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SentryTree.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/logging/SentryTree.java | package org.akvo.caddisfly.logging;
import android.util.Log;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import io.sentry.Sentry;
import io.sentry.event.BreadcrumbBuilder;
import timber.log.Timber;
public class SentryTree extends Timber.Tree {
@Override
protected void log(int priority, @Nullable String tag, @NotNull String message,
@Nullable Throwable t) {
switch (priority) {
case Log.INFO:
Sentry.getContext().recordBreadcrumb(new BreadcrumbBuilder()
.setMessage(message)
.build());
break;
case Log.ERROR:
if (t == null)
Sentry.capture(message);
else
Sentry.capture(t);
break;
}
}
}
| 879 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SensorConstants.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/common/SensorConstants.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.common;
/**
* Class to hold all public constants used by sensors.
*/
public final class SensorConstants {
/**
* Serialization constants.
*/
public static final String IMAGE = "image";
public static final String IMAGE_BITMAP = "imageBitmap";
public static final String TYPE_NAME = "caddisfly";
public static final String RESOURCE_ID = "caddisflyResourceUuid";
public static final String RESPONSE = "response";
public static final String LANGUAGE = "language";
public static final String QUESTION_TITLE = "questionTitle";
public static final String FLOW_INSTANCE_NAME = "instanceName";
private SensorConstants() {
}
}
| 1,456 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ConstantKey.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/common/ConstantKey.java | package org.akvo.caddisfly.common;
public class ConstantKey {
public static final String CURRENT_PHOTO_PATH = "photo_path";
public static final String CURRENT_IMAGE_FILE_NAME = "image_file_name";
public static final String RESULT_IMAGE_PATH = "result_image_path";
public static final String FRAGMENT_ID = "fragment_id";
public static final String START_MEASURE = "start_measure";
public static final String TEST_PHASE = "test_phase";
private static final String NAMESPACE_PREFIX = "org.akvo.caddisfly.";
public static final String TOP_LEFT = NAMESPACE_PREFIX + "top_left";
public static final String TOP_RIGHT = NAMESPACE_PREFIX + "top_right";
public static final String BOTTOM_LEFT = NAMESPACE_PREFIX + "bottom_left";
public static final String BOTTOM_RIGHT = NAMESPACE_PREFIX + "bottom_right";
public static final String TEST_INFO = NAMESPACE_PREFIX + "testInfo";
public static final String TEST_STAGE = NAMESPACE_PREFIX + "testStage";
public static final String TYPE = NAMESPACE_PREFIX + "type";
}
| 1,060 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ConstantJsonKey.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/common/ConstantJsonKey.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.common;
public class ConstantJsonKey {
public static final String APP = "app";
public static final String BRACKET = "bracket";
public static final String ID = "id";
public static final String IMAGE = "image";
public static final String NAME = "name";
public static final String RESULT = "result";
public static final String TEST_DATE = "testDate";
public static final String TYPE = "type";
public static final String UNIT = "unit";
public static final String UUID = "uuid";
public static final String VALUE = "value";
}
| 1,346 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Constants.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/common/Constants.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.common;
public class Constants {
public static final String BRAND_IMAGE_PATH = "images/brand/";
public static final String ILLUSTRATION_PATH = "images/instructions/";
public static final String TESTS_META_FILENAME = "tests.json";
public static final String FLUORIDE_ID = "d839537b-8106-44e8-953a-6060e4dbe59d";
public static final String CBT_ID = "e40d4764-e73f-46dd-a598-ed4db0fd3386";
public static final String CBT_ID_2 = "5baa9d29-b271-4521-b05f-4bfd645c26cf";
public static final String CBT_ID_3 = "c43b7f5e-c5e3-438a-b4d9-bf80d7197176";
public static final String CBT_ID_4 = "a0467617-cbeb-4c7f-9610-ac22c9afa0ab";
public static final String SWATCH_SELECT_TEST_ID = "520ba67c-233f-4dc7-a2ad-17d86047d7c4";
public static final String MPN_TABLE_FILENAME = "most-probable-number.json";
public static final String MPN_TABLE_FILENAME_AGRICULTURE = "most-probable-number-agriculture.json";
public static final int MIN_CAMERA_MEGA_PIXELS = 5;
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
public static final int DEGREES_90 = 90;
// Automated Testing
public static final String BLUETOOTH_TEST_DATA = "DT01;DT01;DT01;1813246;V012.013.4.003.065;V012.013.4.003.065;191;Ca-hardness 2 T;0-500 mg/l CaCO3;8;0;0;2003-01-01;00:12:26;0;0;0;1;0;4;Overrange; CaCO3;;;; 26;0;0;0;1;0;4;Overrange; CaCO3;;;; 26;0;0;0;1;0;4;Overrange; CaCO3;;;; ";
public static final String BLUETOOTH_TEST_DATA_F = "DT01;1611071;V012.013.4.003.058;V012.013.4.003.058;170;Fluoride L;0.05-2 mg/l F;65;0;0;2003-02-18;19:04:32;3;123;0;1;0;4;Overrange; F;;;;";
// public static final String BLUETOOTH_TEST_DATA = "DT01;1813935;V012.013.4.003.065;V012.013.4.003.065;150;Copper T;0.05-5 mg/l Cu;151;0;0;2003-04-19;23:00:32;0;0;0;3;2;2;Underrange;free Cu;3;8;???;comb. Cu;4;2;Underrange;total Cu;;;;";
// public static final String BLUETOOTH_TEST_DATA = "DT01;1813935;V012.013.4.003.065;V012.013.4.003.065;257;Nickel T;0.1 - 10 mg/l Ni;152;0;0;2003-04-19;23:04:52;0;0;0;1;0;2;Underrange; Ni;;;;";
// public static final String BLUETOOTH_TEST_DATA = "DT01;1813935;V012.013.4.003.065;V012.013.4.003.065;400;Zinc T;0.02-0.9 mg/l Zn;153;0;0;2003-04-19;23:07:41;0;0;0;1;0;2;Underrange; Zn;;;;";
// public static final String BLUETOOTH_TEST_DATA = "DT01;DT01;DT01;1711847;V012.013.4.003.058;V012.013.4.003.058;101;Chlorine L;0.02-4 mg/l Cl2;17;0;0;2003-01-29;03:23:46;4;4;0;3;2;0;0.04;mg/l free Cl2;3;0;0.04;mg/l comb. Cl2;4;0;0.08;mg/l total Cl2;;;; Cl2;4;0;0.08;mg/l total Cl2;;;; Cl2;4;0;0.08;mg/l total Cl2;;;; Cl2;4;0;0.08;mg/l total Cl2;;;; Cl2;4;0;0.08;mg/l total Cl2;;;;";
// public static final String BLUETOOTH_TEST_DATA = "DT01;1013245;V012.013.4.003.065;V012.013.4.003.065;157;Cyanide L;0.01-0.5 mg/l CN;7;0;0;2003-01-01;00:13:13;0;0;0;1;0;2;Underrange; CN;;;;";
// public static final String BLUETOOTH_TEST_DATA = "DT01;1013245;V012.013.4.003.065;V012.013.4.003.065;240;Manganese T;0.2-4 mg/l Mn;8;0;0;2003-01-01;00:20:21;0;0;0;1;0;2;Underrange; Mn;;;;";
}
| 3,818 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SettingsActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/SettingsActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.app.CaddisflyApp;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.util.PreferencesUtil;
import org.akvo.caddisfly.viewmodel.TestListViewModel;
public class SettingsActivity extends BaseActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private ScrollView mScrollView;
private int mScrollPosition;
private void removeAllFragments() {
findViewById(R.id.layoutDiagnostics).setVisibility(View.GONE);
findViewById(R.id.layoutDiagnosticsOptions).setVisibility(View.GONE);
findViewById(R.id.layoutDebugging).setVisibility(View.GONE);
findViewById(R.id.layoutTesting).setVisibility(View.GONE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActivity();
}
@Override
public void onRestart() {
super.onRestart();
setupActivity();
}
@Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext())
.registerOnSharedPreferenceChangeListener(this);
}
private void setupActivity() {
setTitle(R.string.settings);
setContentView(R.layout.activity_settings);
getFragmentManager().beginTransaction()
.replace(R.id.layoutGeneral, new GeneralPreferenceFragment())
.commit();
if (AppPreferences.isDiagnosticMode()) {
getFragmentManager().beginTransaction()
.add(R.id.layoutDiagnostics, new DiagnosticPreferenceFragment())
.commit();
getFragmentManager().beginTransaction()
.add(R.id.layoutDiagnosticsOptions, new DiagnosticOptionsPreferenceFragment())
.commit();
getFragmentManager().beginTransaction()
.add(R.id.layoutDebugging, new DebuggingPreferenceFragment())
.commit();
getFragmentManager().beginTransaction()
.add(R.id.layoutTesting, new TestingPreferenceFragment())
.commit();
findViewById(R.id.layoutDiagnosticsOptions).setVisibility(View.VISIBLE);
findViewById(R.id.layoutDiagnostics).setVisibility(View.VISIBLE);
findViewById(R.id.layoutDebugging).setVisibility(View.VISIBLE);
findViewById(R.id.layoutTesting).setVisibility(View.VISIBLE);
}
mScrollView = findViewById(R.id.scrollViewSettings);
Toolbar toolbar = findViewById(R.id.toolbar);
try {
setSupportActionBar(toolbar);
} catch (Exception ignored) {
//Ignore crash in Samsung
}
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(R.string.settings);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (AppPreferences.isDiagnosticMode()) {
getMenuInflater().inflate(R.menu.menu_settings, menu);
}
return true;
}
public void onDisableDiagnostics(@SuppressWarnings("unused") MenuItem item) {
Toast.makeText(getBaseContext(), getString(R.string.diagnosticModeDisabled),
Toast.LENGTH_SHORT).show();
AppPreferences.disableDiagnosticMode();
changeActionBarStyleBasedOnCurrentMode();
invalidateOptionsMenu();
clearTests();
removeAllFragments();
finish();
}
private void clearTests() {
final TestListViewModel viewModel =
ViewModelProviders.of(this).get(TestListViewModel.class);
viewModel.clearTests();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if (getApplicationContext().getString(R.string.languageKey).equals(s)) {
CaddisflyApp.getApp().setAppLanguage(this, null, false, null);
Intent resultIntent = new Intent(getIntent());
resultIntent.getBooleanExtra("refresh", true);
setResult(RESULT_OK, resultIntent);
PreferencesUtil.setBoolean(this, R.string.refreshKey, true);
PreferencesUtil.setBoolean(this, R.string.refreshAboutKey, true);
recreate();
}
}
@Override
public void onPause() {
int scrollbarPosition = mScrollView.getScrollY();
PreferencesUtil.setInt(this, "settingsScrollPosition", scrollbarPosition);
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext())
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPostResume() {
super.onPostResume();
mScrollPosition = PreferencesUtil.getInt(this, "settingsScrollPosition", 0);
mScrollView.post(() -> mScrollView.scrollTo(0, mScrollPosition));
}
}
| 6,363 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DiagnosticOptionsPreferenceFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/DiagnosticOptionsPreferenceFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.app.Fragment;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.ListViewUtil;
/**
* A simple {@link Fragment} subclass.
*/
public class DiagnosticOptionsPreferenceFragment extends PreferenceFragment {
private ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_diagnostic_options);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_row, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = view.findViewById(android.R.id.list);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListViewUtil.setListViewHeightBasedOnChildren(list, 0);
}
}
| 2,078 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
GeneralPreferenceFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/GeneralPreferenceFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.ListViewUtil;
import androidx.annotation.NonNull;
/**
* Fragment for general preferences section.
*/
public class GeneralPreferenceFragment extends PreferenceFragment {
private ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_row, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = view.findViewById(android.R.id.list);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListViewUtil.setListViewHeightBasedOnChildren(list, 0);
}
}
| 2,035 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DebuggingPreferenceFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/DebuggingPreferenceFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.app.Fragment;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.ListViewUtil;
/**
* A simple {@link Fragment} subclass.
*/
public class DebuggingPreferenceFragment extends PreferenceFragment {
private ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_debugging);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_row, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = view.findViewById(android.R.id.list);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListViewUtil.setListViewHeightBasedOnChildren(list, 0);
}
}
| 2,062 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PreferenceCategoryCustom.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/PreferenceCategoryCustom.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.content.Context;
import android.preference.PreferenceCategory;
import android.util.AttributeSet;
import org.akvo.caddisfly.R;
/**
* A custom category style for the preferences screen.
*/
public class PreferenceCategoryCustom extends PreferenceCategory {
public PreferenceCategoryCustom(Context context) {
super(context);
setLayoutResource(R.layout.preference_category);
}
public PreferenceCategoryCustom(Context context, AttributeSet attrs) {
super(context, attrs);
setLayoutResource(R.layout.preference_category);
}
}
| 1,382 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DiagnosticPreferenceFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/DiagnosticPreferenceFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.app.Fragment;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.ListViewUtil;
/**
* A simple {@link Fragment} subclass.
*/
public class DiagnosticPreferenceFragment extends PreferenceFragment {
private ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_diagnostic);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_row, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = view.findViewById(android.R.id.list);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListViewUtil.setListViewHeightBasedOnChildren(list, 0);
}
}
| 2,063 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AppPreferences.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/AppPreferences.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import org.akvo.caddisfly.BuildConfig;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.app.CaddisflyApp;
import org.akvo.caddisfly.util.PreferencesUtil;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
/**
* Static functions to get or set values of various preferences.
*/
public final class AppPreferences {
private AppPreferences() {
}
public static boolean isDiagnosticMode() {
return PreferencesUtil.getBoolean(CaddisflyApp.getApp(), R.string.diagnosticModeKey, false);
}
public static void enableDiagnosticMode() {
PreferencesUtil.setBoolean(CaddisflyApp.getApp(), R.string.diagnosticModeKey, true);
}
public static void disableDiagnosticMode() {
PreferencesUtil.setBoolean(CaddisflyApp.getApp(), R.string.diagnosticModeKey, false);
PreferencesUtil.setBoolean(CaddisflyApp.getApp(), R.string.testModeOnKey, false);
PreferencesUtil.setBoolean(CaddisflyApp.getApp(), R.string.saveTestImageKey, false);
}
public static boolean isSoundOn() {
return !isDiagnosticMode() || PreferencesUtil.getBoolean(CaddisflyApp.getApp(), R.string.soundOnKey, true);
}
public static boolean getShowDebugInfo() {
return isDiagnosticMode()
&& PreferencesUtil.getBoolean(CaddisflyApp.getApp(), R.string.showDebugMessagesKey, false);
}
public static boolean isTestMode() {
return BuildConfig.TEST_RUNNING || (isDiagnosticMode()
&& PreferencesUtil.getBoolean(CaddisflyApp.getApp(), R.string.testModeOnKey, false));
}
public static boolean isSaveTestImage() {
return (isDiagnosticMode()
&& PreferencesUtil.getBoolean(CaddisflyApp.getApp(), R.string.saveTestImageKey, false));
}
public static boolean ignoreTimeDelays() {
return isDiagnosticMode()
&& PreferencesUtil.getBoolean(CaddisflyApp.getApp(), R.string.ignoreTimeDelaysKey, false);
}
public static void saveLastAppUpdateCheck() {
PreferencesUtil.setLong(CaddisflyApp.getApp(), "lastUpdateCheck",
Calendar.getInstance().getTimeInMillis());
}
public static boolean isAppUpdateCheckRequired() {
if (BuildConfig.TEST_RUNNING) {
return true;
}
long lastCheck = PreferencesUtil.getLong(CaddisflyApp.getApp(), "lastUpdateCheck");
return TimeUnit.MILLISECONDS.toDays(Calendar.getInstance().getTimeInMillis() - lastCheck) > 0;
}
public static boolean analyticsEnabled() {
return !BuildConfig.TEST_RUNNING && !BuildConfig.DEBUG;
}
}
| 3,406 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestingPreferenceFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/preference/TestingPreferenceFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.preference;
import android.app.Fragment;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.AlertUtil;
import org.akvo.caddisfly.util.ListViewUtil;
import org.akvo.caddisfly.util.PreferencesUtil;
import java.util.Calendar;
import timber.log.Timber;
/**
* A simple {@link Fragment} subclass.
*/
public class TestingPreferenceFragment extends PreferenceFragment {
private ListView list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_testing);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.card_row, container, false);
Preference testModeOnPreference = findPreference(getString(R.string.testModeOnKey));
if (testModeOnPreference != null) {
testModeOnPreference.setOnPreferenceClickListener(preference -> true);
}
Preference simulateCrashPreference = findPreference(getString(R.string.simulateCrashKey));
if (simulateCrashPreference != null) {
simulateCrashPreference.setOnPreferenceClickListener(preference -> {
if (Calendar.getInstance().getTimeInMillis() - PreferencesUtil.getLong(getActivity(),
"lastCrashReportSentKey") > 60000) {
AlertUtil.askQuestion(getActivity(), R.string.simulateCrash, R.string.simulateCrash,
R.string.ok, R.string.cancel, true, (dialogInterface, i) -> {
PreferencesUtil.setLong(getActivity(), "lastCrashReportSentKey",
Calendar.getInstance().getTimeInMillis());
try {
throw new Exception("Simulated crash test");
} catch (Exception e) {
Timber.e(e);
}
}, null);
} else {
Toast.makeText(getActivity(), "Wait 1 minute before sending again",
Toast.LENGTH_SHORT).show();
}
return true;
});
}
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = view.findViewById(android.R.id.list);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListViewUtil.setListViewHeightBasedOnChildren(list, 40);
}
}
| 3,832 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
UsbService.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/usb/UsbService.java | package org.akvo.caddisfly.usb;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import com.felhr.usbserial.CDCSerialDevice;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class UsbService extends Service {
public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
private static final int CTS_CHANGE = 1;
private static final int DSR_CHANGE = 2;
private static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
private static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
private static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
private static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
private static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private final IBinder binder = new UsbBinder();
private Context context;
private Handler mHandler;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private final UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] arg0) {
String data = new String(arg0, StandardCharsets.UTF_8);
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
}
};
/*
* State changes in the CTS line will be received here
*/
private final UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
@Override
public void onCTSChanged(boolean state) {
if (mHandler != null)
mHandler.obtainMessage(CTS_CHANGE).sendToTarget();
}
};
/*
* State changes in the DSR line will be received here
*/
private final UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
@Override
public void onDSRChanged(boolean state) {
if (mHandler != null)
mHandler.obtainMessage(DSR_CHANGE).sendToTarget();
}
};
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Different notifications from OS will be received here (USB attached, detached, permission responses...)
* About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
*/
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (arg1.getAction()) {
case ACTION_USB_PERMISSION:
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
try {
connection = usbManager.openDevice(device);
new ConnectionThread().start();
} catch (Exception e) {
Intent intent1 = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent1);
}
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
break;
case ACTION_USB_ATTACHED:
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
break;
case ACTION_USB_DETACHED:
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
if (serialPortConnected) {
serialPort.close();
}
serialPortConnected = false;
break;
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
@Override
public void onCreate() {
this.context = this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003)) {
// There is a device connected to our Android device. Try to open it as a Serial Port.
requestUserPermission();
keep = false;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
if (!keep) {
// There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
/*
* Request user permission. The response will be received in the BroadcastReceiver
*/
private void requestUserPermission() {
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public boolean isUsbConnected() {
return serialPortConnected;
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
/*
* A simple thread to open a serial port.
* Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
*/
private class ConnectionThread extends Thread {
@Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPortConnected = true;
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
/*
Current flow control Options:
UsbSerialInterface.FLOW_CONTROL_OFF
UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
*/
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
serialPort.getCTS(ctsCallback);
serialPort.getDSR(dsrCallback);
//
// Some Arduinos would need some sleep because firmware wait some time to know whether a new sketch is going
// to be uploaded or not
//Thread.sleep(2000); // sleep some. YMMV with different chips.
// Everything went as expected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
// Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
// Send an Intent to Main Activity
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
// No driver for given device, even generic CDC driver could not be loaded
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
| 12,382 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestConfigRepository.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/repository/TestConfigRepository.java | package org.akvo.caddisfly.repository;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.akvo.caddisfly.model.TestConfig;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.model.TestType;
import org.akvo.caddisfly.util.AssetsManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import timber.log.Timber;
public class TestConfigRepository {
private static final HashMap<TestType, List<TestInfo>> testMap = new HashMap<>();
private final AssetsManager assetsManager;
public TestConfigRepository() {
assetsManager = new AssetsManager();
}
/**
* Get list of tests by type of test.
*
* @param testType the test type
* @return the list of tests
*/
public List<TestInfo> getTests(TestType testType) {
List<TestInfo> testInfoList = new ArrayList<>();
if (testMap.containsKey(testType)) {
return testMap.get(testType);
}
try {
testInfoList = new Gson().fromJson(assetsManager.getJson(), TestConfig.class).getTests();
for (int i = testInfoList.size() - 1; i >= 0; i--) {
if (testInfoList.get(i).getSubtype() != testType) {
testInfoList.remove(i);
}
}
if (testType == TestType.BLUETOOTH) {
Collections.sort(testInfoList, (object1, object2) ->
("000000000".substring(object1.getMd610Id().length()) + object1.getMd610Id())
.compareToIgnoreCase(("000000000".substring(object2.getMd610Id().length())
+ object2.getMd610Id())));
} else {
Collections.sort(testInfoList, (object1, object2) ->
object1.getName().compareToIgnoreCase(object2.getName()));
}
} catch (Exception e) {
Timber.e(e);
}
testMap.put(testType, testInfoList);
return testInfoList;
}
/**
* Get the test details from json config.
*
* @param id the test id
* @return the test object
*/
public TestInfo getTestInfo(final String id) {
return getTestInfoItem(assetsManager.getJson(), id);
}
@Nullable
private TestInfo getTestInfoItem(String json, String id) {
List<TestInfo> testInfoList;
try {
TestConfig testConfig = new Gson().fromJson(json, TestConfig.class);
if (testConfig != null) {
testInfoList = testConfig.getTests();
for (TestInfo testInfo : testInfoList) {
if (testInfo.getUuid().equalsIgnoreCase(id)) {
return testInfo;
}
}
}
} catch (JsonSyntaxException e) {
// do nothing
}
return null;
}
public void clear() {
testMap.clear();
}
}
| 3,064 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
UsbConnectionActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/UsbConnectionActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import org.akvo.caddisfly.R;
/**
* A partial_progress dialog to the show that the usb external device is connected.
*/
public class UsbConnectionActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usb_connection);
}
@Override
protected void onStart() {
super.onStart();
final ProgressDialog progressDialog =
new ProgressDialog(this, android.R.style.Theme_DeviceDefault_Light_Dialog);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setTitle(R.string.appName);
progressDialog.setMessage(getString(R.string.deviceConnecting));
progressDialog.setCancelable(false);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && progressDialog.getWindow() != null) {
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
progressDialog.show();
//just a fixed delay so the progress is visible
(new Handler()).postDelayed(() -> {
progressDialog.setMessage(getString(R.string.deviceConnected));
//dismiss after the second message
(new Handler()).postDelayed(() -> {
try {
progressDialog.dismiss();
} catch (Exception ignored) {
// do nothing
}
finish();
}, 1000);
}, 1000);
}
}
| 2,626 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DecodeData.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/models/DecodeData.java | package org.akvo.caddisfly.sensor.striptest.models;
import android.media.Image;
import android.util.SparseArray;
import android.util.SparseIntArray;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.sensor.striptest.decode.DecodeProcessor;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPattern;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPatternInfo;
import org.akvo.caddisfly.sensor.striptest.qrdetector.PerspectiveTransform;
import org.akvo.caddisfly.util.ImageUtil;
import org.apache.commons.math3.linear.RealMatrix;
import java.util.List;
public class DecodeData {
private final SparseIntArray versionNumberMap;
private final SparseArray<float[][][]> stripImageMap;
private Image decodeImage;
private byte[] decodeImageByteArray;
private int decodeWidth;
private int decodeHeight;
private FinderPatternInfo patternInfo;
private List<FinderPattern> finderPatternsFound;
private int tilt;
private boolean distanceOk;
private PerspectiveTransform cardToImageTransform;
private List<float[]> shadowPoints;
private float[][] whitePointArray;
private float[] deltaEStats;
private float[] illuminationData;
private RealMatrix calMatrix;
private int stripPixelWidth;
private TestInfo testInfo;
public DecodeData() {
this.versionNumberMap = new SparseIntArray();
this.stripImageMap = new SparseArray<>();
}
public void addStripImage(float[][][] image, int delay) {
this.stripImageMap.put(delay, image);
}
public SparseArray<float[][][]> getStripImageMap() {
return this.stripImageMap;
}
//put version number in array: number, frequency
public void addVersionNumber(Integer number) {
int versionNumber = versionNumberMap.get(number, -1);
if (versionNumber == -1) {
versionNumberMap.put(number, 1);
} else {
versionNumberMap.put(number, versionNumber + 1);
}
}
public int getMostFrequentVersionNumber() {
int mostFrequent = 0;
int largestValue = -1;
//look for the most frequent value
for (int i = 0; i < versionNumberMap.size(); i++) {
int freq = versionNumberMap.valueAt(i);
if (freq > mostFrequent) {
mostFrequent = freq;
largestValue = versionNumberMap.keyAt(i);
}
}
return largestValue;
}
public boolean isCardVersionEstablished() {
int mostFrequent = 0;
int prevMostFrequent = 0;
//look for the most frequent value
for (int i = 0; i < versionNumberMap.size(); i++) {
int freq = versionNumberMap.valueAt(i);
if (freq > mostFrequent) {
prevMostFrequent = mostFrequent;
mostFrequent = freq;
}
}
// this means we have seen the most frequent version number at least
// 5 times more often than second most frequent.
return mostFrequent - prevMostFrequent > 5;
}
public int getDecodeWidth() {
return decodeWidth;
}
public void setDecodeWidth(int decodeWidth) {
this.decodeWidth = decodeWidth;
}
public int getDecodeHeight() {
return decodeHeight;
}
public void setDecodeHeight(int decodeHeight) {
this.decodeHeight = decodeHeight;
}
public List<FinderPattern> getFinderPatternsFound() {
return finderPatternsFound;
}
public void setFinderPatternsFound(List<FinderPattern> finderPatternsFound) {
this.finderPatternsFound = finderPatternsFound;
}
public FinderPatternInfo getPatternInfo() {
return patternInfo;
}
public void setPatternInfo(FinderPatternInfo patternInfo) {
this.patternInfo = patternInfo;
}
public int getTilt() {
return tilt;
}
public void setTilt(int tilt) {
this.tilt = tilt;
}
public PerspectiveTransform getCardToImageTransform() {
return cardToImageTransform;
}
public void setCardToImageTransform(PerspectiveTransform cardToImageTransform) {
this.cardToImageTransform = cardToImageTransform;
}
public List<float[]> getShadowPoints() {
return shadowPoints;
}
public void setShadowPoints(List<float[]> shadowPoints) {
this.shadowPoints = shadowPoints;
}
public float[][] getWhitePointArray() {
return whitePointArray;
}
public void setWhitePointArray(float[][] whitePointArray) {
this.whitePointArray = whitePointArray;
}
public float[] getDeltaEStats() {
return deltaEStats;
}
public void setDeltaEStats(float[] deltaE2000Stats) {
this.deltaEStats = deltaE2000Stats;
}
public byte[] getDecodeImageByteArray() {
return decodeImageByteArray;
}
public void setDecodeImageByteArray(byte[] decodeImageByteArray) {
this.decodeImageByteArray = decodeImageByteArray;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean getDistanceOk() {
return distanceOk;
}
public void setDistanceOk(boolean distanceOk) {
this.distanceOk = distanceOk;
}
public float[] getIlluminationData() {
return illuminationData;
}
public void setIlluminationData(float[] illuminationData) {
this.illuminationData = illuminationData;
}
public RealMatrix getCalMatrix() {
return calMatrix;
}
public void setCalMatrix(RealMatrix calMatrix) {
this.calMatrix = calMatrix;
}
public TestInfo getTestInfo() {
return testInfo;
}
public void setTestInfo(TestInfo testInfo) {
this.testInfo = testInfo;
}
public int getStripPixelWidth() {
return stripPixelWidth;
}
public void setStripPixelWidth(int stripPixelWidth) {
this.stripPixelWidth = stripPixelWidth;
}
public void clearData() {
if (decodeImage != null) {
decodeImage.close();
}
decodeImage = null;
patternInfo = null;
decodeImageByteArray = null;
shadowPoints = null;
tilt = DecodeProcessor.NO_TILT;
distanceOk = true;
calMatrix = null;
illuminationData = null;
}
public void clearImageMap() {
stripImageMap.clear();
}
public void saveCapturedImage() {
ImageUtil.saveYuvImage(decodeImageByteArray, testInfo.getName());
}
}
| 6,534 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CalibrationCardData.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/models/CalibrationCardData.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.models;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CalibrationCardData {
@NonNull
private final Map<String, Location> locations;
@NonNull
private final Map<String, CalValue> calValues;
@NonNull
private final List<WhiteLine> whiteLines;
@NonNull
private final float[] stripArea;
public float hSize;
public float vSize;
public int version;
private float patchSize;
public CalibrationCardData() {
this.locations = new HashMap<>();
this.calValues = new HashMap<>();
this.whiteLines = new ArrayList<>();
this.stripArea = new float[4];
this.version = 0;
}
public void addLocation(String label, Float x, Float y, Boolean grayPatch) {
Location loc = new Location(x, y, grayPatch);
this.locations.put(label, loc);
}
public void addCal(String label, float l, float a, float b) {
CalValue calVal = new CalValue(l, a, b);
this.calValues.put(label, calVal);
}
public void addWhiteLine(Float x1, Float y1, Float x2, Float y2, Float width) {
WhiteLine line = new WhiteLine(x1, y1, x2, y2, width);
this.whiteLines.add(line);
}
public float getPatchSize() {
return patchSize;
}
public void setPatchSize(float patchSize) {
this.patchSize = patchSize;
}
public float[] getStripArea() {
return stripArea.clone();
}
public void setStripArea(float x1, float y1, float x2, float y2) {
stripArea[0] = x1;
stripArea[1] = y1;
stripArea[2] = x2;
stripArea[3] = y2;
}
@NonNull
public List<WhiteLine> getWhiteLines() {
return whiteLines;
}
@NonNull
public Map<String, Location> getLocations() {
return locations;
}
@NonNull
public Map<String, CalValue> getCalValues() {
return calValues;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public static class Location {
public final Float x;
public final Float y;
private final Boolean grayPatch;
Location(Float x, Float y, Boolean grayPatch) {
this.x = x;
this.y = y;
this.grayPatch = grayPatch;
}
}
public static class CalValue {
private final float X;
private final float Y;
private final float Z;
CalValue(float X, float Y, float Z) {
this.X = X;
this.Y = Y;
this.Z = Z;
}
public float getX() {
return X;
}
public float getY() {
return Y;
}
public float getZ() {
return Z;
}
}
public static class WhiteLine {
@NonNull
private final Float[] p;
private final Float width;
WhiteLine(Float x1, Float y1, Float x2, Float y2, Float width) {
Float[] pArray = new Float[4];
pArray[0] = x1;
pArray[1] = y1;
pArray[2] = x2;
pArray[3] = y2;
this.p = pArray;
this.width = width;
}
public Float[] getPosition() {
return p.clone();
}
public Float getWidth() {
return width;
}
}
}
| 4,268 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TimeDelayDetail.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/models/TimeDelayDetail.java | package org.akvo.caddisfly.sensor.striptest.models;
import androidx.annotation.NonNull;
public class TimeDelayDetail implements Comparable<TimeDelayDetail> {
private final int testStage;
private final int timeDelay;
public TimeDelayDetail(int testStage, int timeDelay) {
this.testStage = testStage;
this.timeDelay = timeDelay;
}
public int getTestStage() {
return testStage;
}
public int getTimeDelay() {
return timeDelay;
}
public int compareTo(@NonNull TimeDelayDetail o) {
int result = Integer.compare(testStage, o.testStage);
if (result == 0) {
return Integer.compare(timeDelay, o.timeDelay);
} else {
return result;
}
}
}
| 763 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PatchResult.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/models/PatchResult.java | package org.akvo.caddisfly.sensor.striptest.models;
import org.akvo.caddisfly.model.Result;
public class PatchResult {
private int id;
private boolean measured;
private float[] Xyz;
private float[] Lab;
private float value;
private String bracket;
private int index;
private String unit;
private Result patch;
private float[][][] image;
// constructor
public PatchResult(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isMeasured() {
return measured;
}
public void setMeasured(boolean measured) {
this.measured = measured;
}
public float[] getXyz() {
return Xyz;
}
public void setXyz(float[] xyz) {
Xyz = xyz;
}
public float[] getLab() {
return Lab;
}
public void setLab(float[] lab) {
Lab = lab;
}
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
public String getBracket() {
return bracket;
}
public void setBracket(String bracket) {
this.bracket = bracket;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Result getPatch() {
return patch;
}
public void setPatch(Result patch) {
this.patch = patch;
}
public float[][][] getImage() {
return this.image;
}
public void setImage(float[][][] image) {
this.image = image;
}
}
| 1,802 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CalibrationCardException.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/models/CalibrationCardException.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.models;
public class CalibrationCardException extends Exception {
public CalibrationCardException(String message) {
super(message);
}
public CalibrationCardException(String message, Throwable e) {
super(message, e);
}
}
| 1,053 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AssetsManager.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/AssetsManager.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.utils;
import android.content.res.AssetManager;
import org.akvo.caddisfly.app.CaddisflyApp;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import timber.log.Timber;
/**
* Created by linda on 8/19/15
*/
public final class AssetsManager {
private static AssetsManager assetsManager;
private final AssetManager manager;
private AssetsManager() {
this.manager = CaddisflyApp.getApp().getApplicationContext().getAssets();
}
public static AssetsManager getInstance() {
if (assetsManager == null) {
assetsManager = new AssetsManager();
}
return assetsManager;
}
String loadJSONFromAsset(String fileName) {
String json;
InputStream is = null;
try {
if (manager == null) {
return null;
}
is = manager.open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
//noinspection ResultOfMethodCallIgnored
is.read(buffer);
json = new String(buffer, StandardCharsets.UTF_8);
} catch (IOException ex) {
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Timber.e(e);
}
}
}
return json;
}
}
| 2,257 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CalibrationUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/CalibrationUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import org.akvo.caddisfly.sensor.striptest.models.CalibrationCardData;
import org.akvo.caddisfly.sensor.striptest.models.DecodeData;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.DecompositionSolver;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import org.apache.commons.math3.linear.SingularValueDecomposition;
import java.util.HashMap;
import java.util.Map;
public class CalibrationUtils {
@SuppressWarnings("SameParameterValue")
private static float capValue(float val, float min, float max) {
if (val > max) {
return max;
}
return val < min ? min : val;
}
public static Map<String, float[]> correctIllumination(Map<String, float[]> patchYUVMap, DecodeData decodeData, CalibrationCardData calCardData) {
float[][] whitePoints = decodeData.getWhitePointArray();
int numRows = whitePoints.length;
RealMatrix coefficient = new Array2DRowRealMatrix(numRows, 6);
RealVector Y = new ArrayRealVector(numRows);
//create constant, x, y, x^2, y^2 and xy terms
float x, y;
for (int i = 0; i < numRows; i++) {
x = whitePoints[i][0];
y = whitePoints[i][1];
coefficient.setEntry(i, 0, x);
coefficient.setEntry(i, 1, y);
coefficient.setEntry(i, 2, x * x);
coefficient.setEntry(i, 3, y * y);
coefficient.setEntry(i, 4, x * y);
coefficient.setEntry(i, 5, 1.0f); // constant term
Y.setEntry(i, whitePoints[i][2]);
}
// solve the least squares problem
DecompositionSolver solver = new SingularValueDecomposition(coefficient).getSolver();
RealVector solutionL = solver.solve(Y);
// get individual coefficients
float Ya = (float) solutionL.getEntry(0); // x
float Yb = (float) solutionL.getEntry(1); // y
float Yc = (float) solutionL.getEntry(2); // x^2
float Yd = (float) solutionL.getEntry(3); // y^2
float Ye = (float) solutionL.getEntry(4); // x y
float Yf = (float) solutionL.getEntry(5); // constant
// we now have a model:
// Y = a x + b y + c x^2 + d y^2 + e x y + constant
// Next step is to choose the Y level we will use for the whole image. For this, we
// compute the mean luminosity of the whole image. To compute this, we compute the volume
// underneath the curve, which gives us the average.
float xMax = calCardData.hSize;
float yMax = calCardData.vSize;
float yMean = (float) (0.5 * Ya * xMax + 0.5 * Yb * yMax + Yc * xMax * xMax / 3.0
+ Yd * yMax * yMax / 3.0 + Ye * 0.25 * xMax * yMax + Yf);
float[] illuminationData = new float[]{Ya, Yb, Yc, Yd, Ye, Yf, yMean};
decodeData.setIlluminationData(illuminationData);
// now we create a new map with corrected values. U and V are unchanged
float yNew;
Map<String, float[]> resultYUVMap = new HashMap<>();
for (String label : calCardData.getCalValues().keySet()) {
CalibrationCardData.Location loc = calCardData.getLocations().get(label);
float[] YUV = patchYUVMap.get(label);
x = loc.x;
y = loc.y;
yNew = capValue(YUV[0] - (Ya * x + Yb * y + Yc * x * x + Yd * y * y
+ Ye * x * y + Yf) + yMean, 0.0f, 255.0f);
resultYUVMap.put(label, new float[]{yNew, YUV[1], YUV[2]});
}
return resultYUVMap;
}
// Calibrates the map using root-polynomial regression.
// following Mackiewicz M, Finlayson GD, Hurlbert AC, Color correction using root-polynomial
// regression, IEEE Transactions on Image processing 2015 24(5) 1460-1470
// Following http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html#solving-linear-least-squares-problems-and-pseudo-inverses
// we will solve P = M x
public static Map<String, float[]> rootPolynomialCalibration(DecodeData decodeData, Map<String, float[]> calibrationXYZMap, Map<String, float[]> patchRGBMap) {
int numPatch = calibrationXYZMap.keySet().size();
RealMatrix coefficient = new Array2DRowRealMatrix(numPatch, 13);
RealMatrix cal = new Array2DRowRealMatrix(numPatch, 3);
int index = 0;
float[] calibrationXYZ, patchRGB;
// create coefficient and calibration vectors
final float ONE_THIRD = 1.0f / 3.0f;
for (String label : calibrationXYZMap.keySet()) {
calibrationXYZ = calibrationXYZMap.get(label);
patchRGB = patchRGBMap.get(label);
coefficient.setEntry(index, 0, patchRGB[0]);
coefficient.setEntry(index, 1, patchRGB[1]);
coefficient.setEntry(index, 2, patchRGB[2]);
coefficient.setEntry(index, 3, Math.sqrt(patchRGB[0] * patchRGB[1])); // sqrt(R * G)
coefficient.setEntry(index, 4, Math.sqrt(patchRGB[1] * patchRGB[2])); // sqrt(G * B)
coefficient.setEntry(index, 5, Math.sqrt(patchRGB[0] * patchRGB[2])); // sqrt(R * B)
coefficient.setEntry(index, 6, Math.pow(patchRGB[0] * patchRGB[1] * patchRGB[1], ONE_THIRD)); // RGG ^ 1/3
coefficient.setEntry(index, 7, Math.pow(patchRGB[1] * patchRGB[2] * patchRGB[2], ONE_THIRD)); // GBB ^ 1/3
coefficient.setEntry(index, 8, Math.pow(patchRGB[0] * patchRGB[2] * patchRGB[2], ONE_THIRD)); // RBB ^ 1/3
coefficient.setEntry(index, 9, Math.pow(patchRGB[1] * patchRGB[0] * patchRGB[0], ONE_THIRD)); // GRR ^ 1/3
coefficient.setEntry(index, 10, Math.pow(patchRGB[2] * patchRGB[1] * patchRGB[1], ONE_THIRD)); // BGG ^ 1/3
coefficient.setEntry(index, 11, Math.pow(patchRGB[2] * patchRGB[0] * patchRGB[0], ONE_THIRD)); // BRR ^ 1/3
coefficient.setEntry(index, 12, Math.pow(patchRGB[0] * patchRGB[1] * patchRGB[2], ONE_THIRD)); // RGB ^ 1/3
cal.setEntry(index, 0, calibrationXYZ[0]);
cal.setEntry(index, 1, calibrationXYZ[1]);
cal.setEntry(index, 2, calibrationXYZ[2]);
index++;
}
// we solve A X = B. First we decompose A, which is the measured patches
DecompositionSolver solver = new SingularValueDecomposition(coefficient).getSolver();
// then we get the solution matrix X, in the case of B = calibrated values of the patches
RealMatrix sol = solver.solve(cal);
decodeData.setCalMatrix(sol);
//use the solution to correct the image
float xNew, YNew, zNew;
Map<String, float[]> resultXYZMap = new HashMap<>();
index = 0;
for (String label : calibrationXYZMap.keySet()) {
xNew = 0;
YNew = 0;
zNew = 0;
for (int i = 0; i <= 12; i++) {
xNew += coefficient.getEntry(index, i) * sol.getEntry(i, 0);
YNew += coefficient.getEntry(index, i) * sol.getEntry(i, 1);
zNew += coefficient.getEntry(index, i) * sol.getEntry(i, 2);
}
resultXYZMap.put(label, new float[]{xNew, YNew, zNew});
index++;
}
return resultXYZMap;
}
}
| 7,380 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ResultUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/ResultUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.model.ColorItem;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.sensor.striptest.models.PatchResult;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import java.util.Locale;
public class ResultUtils {
static final int INTERPOLATION_NUMBER = 10;
private static DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
private static DecimalFormat decimalFormat = new DecimalFormat("#.###", symbols);
public static float[] calculateResultSingle(@Nullable float[] colorValues, @NonNull List<ColorItem> colors) {
double[][] interpolTable = createInterpolTable(colors);
// determine closest value
// create interpolation and extrapolation tables using linear approximation
if (colorValues == null || colorValues.length < 3) {
throw new IllegalArgumentException("invalid color data.");
}
double distance;
int index = 0;
double nearest = Double.MAX_VALUE;
for (int j = 0; j < interpolTable.length; j++) {
// Find the closest point using the E94 distance
// the values are already in the right range, so we don't need to normalize
float[] lab1 = new float[]{colorValues[0], colorValues[1], colorValues[2]};
float[] lab2 = new float[]{(float) interpolTable[j][0], (float) interpolTable[j][1], (float) interpolTable[j][2]};
distance = ColorUtils.deltaE2000(lab1, lab2);
if (distance < nearest) {
nearest = distance;
index = j;
}
}
if (nearest < Constants.MAX_COLOR_DISTANCE) {
// return result only if the color distance is not too big
int leftIndex = Math.max(0, index - INTERPOLATION_NUMBER / 2);
int rightIndex = Math.min(interpolTable.length - 1, index + INTERPOLATION_NUMBER / 2);
float leftBracket = (float) interpolTable[leftIndex][3];
float rightBracket = (float) interpolTable[rightIndex][3];
return new float[]{index, (float) interpolTable[index][3], leftBracket, rightBracket};
} else {
return new float[]{-1, Float.NaN, -1, -1};
}
}
public static float[] calculateResultGroup(List<PatchResult> patchResultList, @NonNull List<Result> patches) {
float[][] colorsValueLab = new float[patches.size()][3];
double[][][] interpolTables = new double[patches.size()][][];
if (patchResultList.size() == 0) {
return new float[]{-1, Float.NaN, -1, -1};
}
// create all interpol tables
for (int p = 0; p < patches.size(); p++) {
PatchResult patchResult = patchResultList.get(p);
colorsValueLab[p] = patchResult.getLab();
List<ColorItem> colors = patches.get(p).getColors();
// create interpol table for this patch
interpolTables[p] = createInterpolTable(colors);
if (colorsValueLab[p] == null || colorsValueLab[p].length < 3) {
throw new IllegalArgumentException("invalid color data.");
}
}
double distance;
int index = 0;
double nearest = Double.MAX_VALUE;
// compute smallest distance, combining all interpolation tables as we want the global minimum
// all interpol tables should have the same length here, so we use the length of the first one
for (int j = 0; j < interpolTables[0].length; j++) {
distance = 0;
for (int p = 0; p < patches.size(); p++) {
float[] lab1 = new float[]{colorsValueLab[p][0], colorsValueLab[p][1], colorsValueLab[p][2]};
float[] lab2 = new float[]{(float) interpolTables[p][j][0], (float) interpolTables[p][j][1], (float) interpolTables[p][j][2]};
distance += ColorUtils.deltaE2000(lab1, lab2);
}
if (distance < nearest) {
nearest = distance;
index = j;
}
}
if (nearest < Constants.MAX_COLOR_DISTANCE * patches.size()) {
// return result only if the color distance is not too big
int leftIndex = Math.max(0, index - INTERPOLATION_NUMBER / 2);
int rightIndex = Math.min(interpolTables[0].length - 1, index + INTERPOLATION_NUMBER / 2);
float leftBracket = (float) interpolTables[0][leftIndex][3];
float rightBracket = (float) interpolTables[0][rightIndex][3];
return new float[]{index, (float) interpolTables[0][index][3], leftBracket, rightBracket};
} else {
return new float[]{-1, Float.NaN, -1, -1};
}
}
private static double[][] createInterpolTable(@NonNull List<ColorItem> colors) {
double resultPatchValueStart, resultPatchValueEnd;
double[] pointStart;
double[] pointEnd;
double lInter, aInter, bInter, vInter;
double[][] interpolTable = new double[(colors.size() - 1) * INTERPOLATION_NUMBER + 1][4];
int count = 0;
for (int i = 0; i < colors.size() - 1; i++) {
List<Double> colorStart = colors.get(i).getLab();
resultPatchValueStart = colors.get(i).getValue();
pointStart = new double[]{colorStart.get(0), colorStart.get(1), colorStart.get(2)};
List<Double> colorEnd = colors.get(i + 1).getLab();
resultPatchValueEnd = colors.get(i + 1).getValue();
pointEnd = new double[]{colorEnd.get(0), colorEnd.get(1), colorEnd.get(2)};
double lStart = pointStart[0];
double aStart = pointStart[1];
double bStart = pointStart[2];
double dL = (pointEnd[0] - pointStart[0]) / INTERPOLATION_NUMBER;
double da = (pointEnd[1] - pointStart[1]) / INTERPOLATION_NUMBER;
double db = (pointEnd[2] - pointStart[2]) / INTERPOLATION_NUMBER;
double dV = (resultPatchValueEnd - resultPatchValueStart) / INTERPOLATION_NUMBER;
// create 10 interpolation points, including the start point,
// but excluding the end point
for (int ii = 0; ii < INTERPOLATION_NUMBER; ii++) {
lInter = lStart + ii * dL;
aInter = aStart + ii * da;
bInter = bStart + ii * db;
vInter = resultPatchValueStart + ii * dV;
interpolTable[count][0] = lInter;
interpolTable[count][1] = aInter;
interpolTable[count][2] = bInter;
interpolTable[count][3] = vInter;
count++;
}
// add final point
List<Double> patchColorValues = colors.get(colors.size() - 1).getLab();
interpolTable[count][0] = patchColorValues.get(0);
interpolTable[count][1] = patchColorValues.get(1);
interpolTable[count][2] = patchColorValues.get(2);
interpolTable[count][3] = colors.get(colors.size() - 1).getValue();
// // add final point
// patchColorValues = colors.getJSONObject(colors.length() - 1).getJSONArray(SensorConstants.LAB);
// interpolTable[count][0] = patchColorValues.getDouble(0);
// interpolTable[count][1] = patchColorValues.getDouble(1);
// interpolTable[count][2] = patchColorValues.getDouble(2);
// interpolTable[count][3] = colors.getJSONObject(colors.length() - 1).getDouble(SensorConstants.VALUE);
}
return interpolTable;
}
// creates formatted string including unit from float value
public static String createValueUnitString(float value, String unit, String defaultString) {
String valueString = defaultString;
if (value > -1) {
valueString = String.format(Locale.US, "%s %s",
decimalFormat.format(value), unit);
}
return valueString.trim();
}
// creates formatted string from float value, for display of colour charts
// here, we use points as decimal separator always, as this is also used
// to format numbers that are returned by json.
public static String createValueString(float value) {
return decimalFormat.format(value);
}
/*
* Restricts number of significant digits depending on size of number
*/
public static double roundSignificant(double value) {
return Double.parseDouble(decimalFormat.format(value));
}
} | 8,682 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ColorUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/ColorUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
public class ColorUtils {
private final static float X_REF = 95.047f;
private final static float Y_REF = 100f;
private final static float Z_REF = 108.883f;
private final static float eps = 0.008856f; //kE
private final static float kappa = 903.3f; // kK
private final static float kappaEps = 8.0f; // kKE
// gamma corrected RGB scaled [0.255] to linear sRGB scaled [0..1]
private static float gammaToLinearRGB(float x) {
float C = x / 255.0f;
if (C < 0.04045) {
C /= 12.92f;
} else {
C = (float) Math.pow((C + 0.055) / 1.055, 2.4);
}
return C;
}
// YCbCr D65 to linear sRGB D65
// according to JPEG standard ITU-T T.871 (05/2011), page 4
// according to http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// and http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// using inverse sRGB companding
// same as https://en.wikipedia.org/wiki/SRGB
// https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.871-201105-I!!PDF-E
public static float[] YUVtoLinearRGB(float[] YUV) {
float rGamma = YUV[0] + 1.402f * YUV[2];
float gGamma = YUV[0] - 0.3441f * YUV[1] - 0.7141f * YUV[2];
float bGamma = YUV[0] + 1.772f * YUV[1];
// make linear and clamp
float rLinear = Math.min(Math.max(0.0f, gammaToLinearRGB(rGamma)), 1.0f);
float gLinear = Math.min(Math.max(0.0f, gammaToLinearRGB(gGamma)), 1.0f);
float bLinear = Math.min(Math.max(0.0f, gammaToLinearRGB(bGamma)), 1.0f);
return new float[]{rLinear, gLinear, bLinear};
}
// linear sRGB D65 scaled [0..1 ]to XYZ D65 scaled [0 .. 100]
// public static float[] linearRGBtoXYZ(float[] RGB) {
//
// // next we apply a transformation matrix to get XYZ D65
// float[] XYZ = new float[3];
// XYZ[0] = 0.4124564f * RGB[0] + 0.3575761f * RGB[1] + 0.1804375f * RGB[2];
// XYZ[1] = 0.2126729f * RGB[0] + 0.7151522f * RGB[1] + 0.0721750f * RGB[2];
// XYZ[2] = 0.0193339f * RGB[0] + 0.1191920f * RGB[1] + 0.9503041f * RGB[2];
//
// // and we scale to 0..100
// XYZ[0] *= 100f;
// XYZ[1] *= 100f;
// XYZ[2] *= 100f;
// return XYZ;
// }
// XYZ D65 to gamma-corrected sRGB D65
// according to http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// and http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
// using sRGB gamma companding
// we assume XYZ is scaled [0..100]
// RGB is scaled to [0..255] and clamped
public static int[] xyzToRgbInt(float[] XYZ) {
float[] xyzScaled = new float[3];
float[] RGB = new float[3];
// first we scale to [0..1]
for (int i = 0; i < 3; i++) {
xyzScaled[i] = XYZ[i] / 100.0f;
}
// next, we apply a matrix:
RGB[0] = 3.2404542f * xyzScaled[0] - 1.5371385f * xyzScaled[1] - 0.4985314f * xyzScaled[2];
RGB[1] = -0.9692660f * xyzScaled[0] + 1.8760108f * xyzScaled[1] + 0.0415560f * xyzScaled[2];
RGB[2] = 0.0556434f * xyzScaled[0] - 0.2040259f * xyzScaled[1] + 1.0572252f * xyzScaled[2];
// next, we apply gamma encoding
for (int i = 0; i < 3; i++) {
if (RGB[i] < 0.0031308) {
RGB[i] = 12.92f * RGB[i];
} else {
RGB[i] = (float) (1.055f * Math.pow(RGB[i], 1 / 2.4)) - 0.055f;
}
}
// next, we scale to [0..255] and clamp
int[] rgbInt = new int[3];
for (int i = 0; i < 3; i++) {
RGB[i] *= 255.0f;
rgbInt[i] = Math.min(Math.max(0, Math.round(RGB[i])), 255);
}
return rgbInt;
}
// XYZ D65 scaled [0..100] to LAB D65
public static float[] XYZtoLAB(float[] XYZ) {
float xr = XYZ[0] / X_REF;
float yr = XYZ[1] / Y_REF;
float zr = XYZ[2] / Z_REF;
float fx, fy, fz;
if (xr > eps) {
fx = (float) Math.pow(xr, 1 / 3.0);
} else {
fx = (float) ((kappa * xr + 16.0) / 116.0);
}
if (yr > eps) {
fy = (float) Math.pow(yr, 1 / 3.0);
} else {
fy = (float) ((kappa * yr + 16.0) / 116.0);
}
if (zr > eps) {
fz = (float) Math.pow(zr, 1 / 3.0);
} else {
fz = (float) ((kappa * zr + 16.0) / 116.0);
}
float CIEL = (float) (116.0 * fy - 16.0);
float CIEa = (500 * (fx - fy));
float CIEb = (200 * (fy - fz));
return new float[]{CIEL, CIEa, CIEb};
}
// Lab D65 to XYZ D65 scaled [0..100]
// http://www.brucelindbloom.com/Eqn_Lab_to_XYZ.html
public static float[] Lab2XYZ(float[] lab) {
float CIEL = lab[0];
float CIEa = lab[1];
float CIEb = lab[2];
float fy = (CIEL + 16.0f) / 116.0f;
float fx = 0.002f * CIEa + fy;
float fz = fy - 0.005f * CIEb;
float fx3 = fx * fx * fx;
float fz3 = fz * fz * fz;
float xr = (fx3 > eps) ? fx3 : ((116.0f * fx - 16.0f) / kappa);
float yr = (float) ((CIEL > kappaEps) ? Math.pow((CIEL + 16.0f) / 116.0f, 3.0f) : (CIEL / kappa));
float zr = (fz3 > eps) ? fz3 : ((116.0f * fz - 16.0f) / kappa);
return new float[]{xr * X_REF, yr * Y_REF, zr * Z_REF};
}
// deltaE2000 colour distance between two lab colour values
public static float deltaE2000(float[] LabRef, float[] LabTarget) {
float dhPrime;
float kL = 1.0f;
float kC = 1.0f;
float kH = 1.0f;
float lBarPrime = 0.5f * (LabRef[0] + LabTarget[0]);
float c1 = (float) Math.sqrt(LabRef[1] * LabRef[1] + LabRef[2] * LabRef[2]);
float c2 = (float) Math.sqrt(LabTarget[1] * LabTarget[1] + LabTarget[2] * LabTarget[2]);
float cBar = 0.5f * (c1 + c2);
float cBar7 = cBar * cBar * cBar * cBar * cBar * cBar * cBar;
float g = (float) (0.5 * (1.0 - Math.sqrt(cBar7 / (cBar7 + 6103515625.0)))); /* 6103515625 = 25^7 */
float a1Prime = LabRef[1] * (1.0f + g);
float a2Prime = LabTarget[1] * (1.0f + g);
float c1Prime = (float) Math.sqrt(a1Prime * a1Prime + LabRef[2] * LabRef[2]);
float c2Prime = (float) Math.sqrt(a2Prime * a2Prime + LabTarget[2] * LabTarget[2]);
float cBarPrime = 0.5f * (c1Prime + c2Prime);
float h1Prime = (float) ((Math.atan2(LabRef[2], a1Prime) * 180.0) / Math.PI);
if (h1Prime < 0.0) {
h1Prime += 360.0;
}
float h2Prime = (float) ((Math.atan2(LabTarget[2], a2Prime) * 180.0) / Math.PI);
if (h2Prime < 0.0) {
h2Prime += 360.0;
}
float hBarPrime = (Math.abs(h1Prime - h2Prime) > 180.0f) ? (0.5f * (h1Prime + h2Prime + 360.0f)) : (0.5f * (h1Prime + h2Prime));
float t = (float) (1.0 -
0.17 * Math.cos(Math.PI * (hBarPrime - 30.0) / 180.0) +
0.24 * Math.cos(Math.PI * (2.0 * hBarPrime) / 180.0) +
0.32 * Math.cos(Math.PI * (3.0 * hBarPrime + 6.0) / 180.0) -
0.20 * Math.cos(Math.PI * (4.0 * hBarPrime - 63.0) / 180.0));
if (Math.abs(h2Prime - h1Prime) <= 180.0) {
dhPrime = h2Prime - h1Prime;
} else {
dhPrime = (h2Prime <= h1Prime) ? (h2Prime - h1Prime + 360.0f) : (h2Prime - h1Prime - 360.0f);
}
float dLPrime = LabTarget[0] - LabRef[0];
float dCPrime = c2Prime - c1Prime;
float dHPrime = (float) (2.0 * Math.sqrt(c1Prime * c2Prime) * Math.sin(Math.PI * (0.5 * dhPrime) / 180.0));
float sL = (float) (1.0 + ((0.015 * (lBarPrime - 50.0) * (lBarPrime - 50.0)) / Math.sqrt(20.0 + (lBarPrime - 50.0) * (lBarPrime - 50.0))));
float sC = 1.0f + 0.045f * cBarPrime;
float sH = 1.0f + 0.015f * cBarPrime * t;
float dTheta = (float) (30.0 * Math.exp(-((hBarPrime - 275.0) / 25.0) * ((hBarPrime - 275.0) / 25.0)));
float cBarPrime7 = cBarPrime * cBarPrime * cBarPrime * cBarPrime * cBarPrime * cBarPrime * cBarPrime;
float rC = (float) (Math.sqrt(cBarPrime7 / (cBarPrime7 + 6103515625.0)));
float rT = (float) (-2.0 * rC * Math.sin(Math.PI * (2.0 * dTheta) / 180.0));
// deltaE2000
return (float) Math.sqrt((dLPrime / (kL * sL)) * (dLPrime / (kL * sL)) +
(dCPrime / (kC * sC)) * (dCPrime / (kC * sC)) +
(dHPrime / (kH * sH)) * (dHPrime / (kH * sH)) +
(dCPrime / (kC * sC)) * (dHPrime / (kH * sH)) * rT);
}
}
| 8,595 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
MessageUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/MessageUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import android.os.Handler;
import android.os.Message;
public class MessageUtils {
public static void sendMessage(Handler handler, int messageId, int data) {
Message message = Message.obtain(handler, messageId);
message.arg1 = data;
message.sendToTarget();
}
}
| 347 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
MathUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/MathUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import java.util.Arrays;
class MathUtils {
// public static float mean(float[] m) {
// float sum = 0;
// for (float aM : m) {
// sum += aM;
// }
// return sum / m.length;
// }
//
// public static float median(float[] m) {
// Arrays.sort(m);
// int middle = m.length / 2;
// if (m.length % 2 == 1) {
// return m[middle];
// } else {
// return (m[middle - 1] + m[middle]) / 2.0f;
// }
// }
public static float[] meanMedianMax(float[] m) {
// compute mean
float sum = 0;
for (float aM : m) {
sum += aM;
}
float mean = sum / m.length;
// sort array
Arrays.sort(m);
// compute median
float median;
int middle = m.length / 2;
if (m.length % 2 == 1) {
median = m[middle];
} else {
median = (m[middle - 1] + m[middle]) / 2.0f;
}
// max (we have already sorted the array)
float max = m[m.length - 1];
return new float[]{mean, median, max};
}
}
| 1,174 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Constants.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/Constants.java | package org.akvo.caddisfly.sensor.striptest.utils;
/**
* Various constants used for configuration and keys.
*/
public final class Constants {
public static final double MAX_LUM_LOWER = 210;
public static final double MAX_LUM_UPPER = 240;
public static final double SHADOW_PERCENTAGE_LIMIT = 90;
// public static final double PERCENT_ILLUMINATION = 1.05;
public static final double CONTRAST_DEVIATION_FRACTION = 0.1;
public static final double CONTRAST_MAX_DEVIATION_FRACTION = 0.20;
public static final double CROP_FINDER_PATTERN_FACTOR = 0.75;
// public static final double FINDER_PATTERN_ASPECT = 0.5662;
public static final float MAX_TILT_DIFF = 0.05f;
public static final float MAX_CLOSER_DIFF = 0.15f;
public static final int COUNT_QUALITY_CHECK_LIMIT = 15;
public static final int PIXEL_PER_MM = 5;
public static final int SKIP_MM_EDGE = 1;
public static final int CALIBRATION_PERCENTAGE_LIMIT = 95;
public static final int MEASURE_TIME_COMPENSATION_MILLIS = 3000;
public static final float STRIP_WIDTH_FRACTION = 0.5f;
public static final int GET_READY_SECONDS = 12;
public static final int MIN_SHOW_TIMER_SECONDS = 5;
public static final int MAX_COLOR_DISTANCE = 23;
private Constants() {
}
}
| 1,296 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CalibrationCardUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/CalibrationCardUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.sensor.striptest.models.CalibrationCardData;
import org.akvo.caddisfly.sensor.striptest.models.CalibrationCardException;
import org.akvo.caddisfly.sensor.striptest.models.DecodeData;
import org.akvo.caddisfly.sensor.striptest.qrdetector.BitMatrix;
import org.akvo.caddisfly.sensor.striptest.qrdetector.Detector;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPattern;
import org.akvo.caddisfly.sensor.striptest.qrdetector.PerspectiveTransform;
import org.akvo.caddisfly.sensor.striptest.qrdetector.ResultPoint;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import timber.log.Timber;
import static org.akvo.caddisfly.sensor.striptest.qrdetector.MathUtils.distance;
import static org.akvo.caddisfly.sensor.striptest.utils.MathUtils.meanMedianMax;
public class CalibrationCardUtils {
private static final int VERSION_NUMBER_NOT_FOUND_CODE = 0;
/*
* Samples known "white" points on the color card, and creates an array
*/
private static final int NUM_SAMPLES_PER_LINE = 10;
private final static float PATCH_SAMPLE_FRACTION = 0.5f;
/**
* find and decode the code of the calibration card
* The code is stored as a simple barcode. It starts 4.5 modules from the center of the bottom left finder pattern
* and extends to module 29.5.
* It has 12 bits, of 2 modules wide each.
* It starts and ends with a 1 bit.
* The remaining 10 bits are interpreted as a 9 bit number with the last bit as parity bit.
* Position barcode:
* _________________________________________________________
* | |
* |________________ |
* ||0 1| |
* || | |
* || | |
* || | |
* || | |
* || b| |
* || b| |
* ||2_____________3| |
* |________________________________________________________|
*/
public static int decodeCalibrationCardCode(@NonNull List<FinderPattern> patternInfo, @NonNull BitMatrix image) {
// patterns are ordered top left, top right, bottom left, bottom right (in portrait mode, with black area to the right)
if (patternInfo.size() == 4) {
ResultPoint bottomLeft = new ResultPoint(patternInfo.get(3).getX(), patternInfo.get(3).getY());
ResultPoint bottomRight = new ResultPoint(patternInfo.get(1).getX(), patternInfo.get(1).getY());
// get estimated module size
Detector detector = new Detector(image);
float modSize = detector.calculateModuleSize(bottomLeft, bottomRight, bottomRight);
// go from one finder pattern to the other,
//because camera is in portrait mode, we need to shift x and y
double lrx = bottomRight.getX() - bottomLeft.getX();
double lry = bottomRight.getY() - bottomLeft.getY();
double hNorm = distance(bottomLeft.getX(), bottomLeft.getY(),
bottomRight.getX(), bottomRight.getY());
// check if left and right are ok
if (lry > 0) {
return VERSION_NUMBER_NOT_FOUND_CODE;
}
// create vector of length 1 pixel, in the direction of the bottomRight finder pattern
lrx /= hNorm;
lry /= hNorm;
// sample line into new row
boolean[] bits = new boolean[image.getHeight()];
int index = 0;
double px = bottomLeft.getX();
double py = bottomLeft.getY();
try {
while (px > 0 && py > 0 && px < image.getWidth() && py < image.getHeight()) {
bits[index] = image.get((int) Math.round(px), (int) Math.round(py));
px += lrx;
py += lry;
index++;
}
} catch (Exception e) {
Timber.d("Error sample line into new row");
return VERSION_NUMBER_NOT_FOUND_CODE;
}
// starting index: 4.5 modules in the direction of the bottom right finder pattern
// end index: our pattern ends at module 17, so we take 25 to be sure.
int startIndex = (int) Math.abs(Math.round(4.5 * modSize / lry));
int endIndex = (int) Math.abs(Math.round(25 * modSize / lry));
// determine qualityChecksOK of pattern: first black bit. Approach from the left
try {
int startI = startIndex;
while (startI < endIndex && !bits[startI]) {
startI++;
}
// determine end of pattern: last black bit. Approach from the right
int endI = endIndex;
while (endI > startI && !bits[endI]) {
endI--;
}
int lengthPattern = endI - startI + 1;
// sanity check on length of pattern.
// We put the minimum size at 20 pixels, which would correspond to a module size of less than 2 pixels,
// which is too small.
if (lengthPattern < 20) {
Timber.d("Length of pattern too small");
return VERSION_NUMBER_NOT_FOUND_CODE;
}
double pWidth = lengthPattern / 12.0;
// determine bits by majority voting
int[] bitVote = new int[12];
for (int i = 0; i < 12; i++) {
bitVote[i] = 0;
}
int bucket;
for (int i = startI; i <= endI; i++) {
bucket = (int) Math.round(Math.floor((i - startI) / pWidth));
bitVote[bucket] += bits[i] ? 1 : -1;
}
// translate into information bits. Skip first and last, which are always 1
boolean[] bitResult = new boolean[10]; // will contain the information bits
for (int i = 1; i < 11; i++) {
bitResult[i - 1] = bitVote[i] > 0;
}
// check parity bit
if (parity(bitResult) != bitResult[9]) {
return VERSION_NUMBER_NOT_FOUND_CODE;
}
// compute result
int code = 0;
int count = 0;
for (int i = 8; i >= 0; i--) {
if (bitResult[i]) {
code += (int) Math.pow(2, count);
}
count++;
}
return code;
} catch (Exception e) {
return VERSION_NUMBER_NOT_FOUND_CODE;
}
} else {
return VERSION_NUMBER_NOT_FOUND_CODE;
}
}
/**
* Compute even parity, where last bit is the even parity bit
*/
private static boolean parity(@NonNull boolean[] bits) {
int oneCount = 0;
for (int i = 0; i < bits.length - 1; i++) { // skip parity bit in calculation of parity
if (bits[i]) {
oneCount++;
}
}
return oneCount % 2 != 0; // returns true if parity is odd
}
public static void readCalibrationFile(CalibrationCardData calCardData, int version) throws CalibrationCardException {
// Log.d(TAG, "reading calibration file");
String calFileName = "calibration-v2-" + version + ".json";
String json = AssetsManager.getInstance().loadJSONFromAsset(calFileName);
// boolean success = false;
if (json != null) {
try {
JSONObject obj = new JSONObject(json);
// general data
//calData.date = obj.getString("date");
// calData.cardVersion = obj.getString("cardVersion");
// calData.unit = obj.getString("unit");
calCardData.version = obj.getInt("cardCode");
// sizes
JSONObject calDataJSON = obj.getJSONObject("calData");
calCardData.setPatchSize((float) calDataJSON.getDouble("patchSize"));
calCardData.hSize = (float) calDataJSON.getDouble("hSize");
calCardData.vSize = (float) calDataJSON.getDouble("vSize");
// locations
JSONArray locJSON = calDataJSON.getJSONArray("locations");
for (int i = 0; i < locJSON.length(); i++) {
JSONObject loc = locJSON.getJSONObject(i);
calCardData.addLocation(loc.getString("l"), (float) loc.getDouble("x"), (float) loc.getDouble("y"), loc.getBoolean("gray"));
}
// colors
JSONArray colJSON = calDataJSON.getJSONArray("calValues");
for (int i = 0; i < colJSON.length(); i++) {
JSONObject cal = colJSON.getJSONObject(i);
// We don't scale the incoming XYZ data, so it has a range [0..100]
calCardData.addCal(cal.getString("l"), (float) cal.getDouble("X"), (float) cal.getDouble("Y"), (float) cal.getDouble("Z"));
}
// white lines
JSONArray linesJSON = obj.getJSONObject("whiteData").getJSONArray("lines");
for (int i = 0; i < linesJSON.length(); i++) {
JSONObject line = linesJSON.getJSONObject(i);
JSONArray p = line.getJSONArray("p");
calCardData.addWhiteLine((float) p.getDouble(0), (float) p.getDouble(1), (float) p.getDouble(2), (float) p.getDouble(3), (float) line.getDouble("width"));
}
// strip area
JSONArray stripArea = obj.getJSONObject("stripAreaData").getJSONArray("area");
calCardData.setStripArea((float) stripArea.getDouble(0), (float) stripArea.getDouble(1), (float) stripArea.getDouble(2), (float) stripArea.getDouble(3));
} catch (JSONException e) {
throw new CalibrationCardException("Error reading calibration card");
}
} else {
throw new CalibrationCardException("Unknown version of calibration card");
}
}
public static float[][] createWhitePointArray(DecodeData decodeData, CalibrationCardData calCardData) {
PerspectiveTransform cardToImageTransform = decodeData.getCardToImageTransform();
byte[] yDataArray = decodeData.getDecodeImageByteArray();
int rowStride = decodeData.getDecodeWidth();
List<CalibrationCardData.WhiteLine> lines = calCardData.getWhiteLines();
int numLines = lines.size() * NUM_SAMPLES_PER_LINE; // on each line, we sample NUM_LINES points
float[][] points = new float[numLines][3];
int index = 0;
float fraction = 1.0f / (NUM_SAMPLES_PER_LINE - 1);
for (CalibrationCardData.WhiteLine line : lines) {
// these coordinates are in the card-space
float xStart = line.getPosition()[0];
float yStart = line.getPosition()[1];
float xEnd = line.getPosition()[2];
float yEnd = line.getPosition()[3];
float xStep = (xEnd - xStart) * fraction;
float yStep = (yEnd - yStart) * fraction;
// sample line
for (int i = 0; i <= NUM_SAMPLES_PER_LINE - 1; i++) {
float xp = xStart + i * xStep;
float yp = yStart + i * yStep;
points[index * NUM_SAMPLES_PER_LINE + i][0] = xp;
points[index * NUM_SAMPLES_PER_LINE + i][1] = yp;
float yVal = getYVal(yDataArray, rowStride, xp, yp, cardToImageTransform);
points[index * NUM_SAMPLES_PER_LINE + i][2] = yVal;
}
index++;
}
return points;
}
// Get the average Y value in a 3x3 area around the central point.
private static float getYVal(byte[] yData, int rowStride, float xp, float yp, PerspectiveTransform cardToImageTransform) {
float totY = 0;
int totNum = 0;
// transform from card-space to image-space
float[] points = new float[]{xp, yp};
cardToImageTransform.transformPoints(points);
for (int i = Math.round(points[0]) - 1; i <= Math.round(points[0]) + 1; i++) {
for (int j = Math.round(points[1]) - 1; j <= Math.round(points[1]) + 1; j++) {
totY += yData[j * rowStride + i] & 0xff;
totNum++;
}
}
return totY / totNum;
}
/*
* measure colour patches on colour card and create an array
*/
public static Map<String, float[]> measurePatches(CalibrationCardData calCardData, DecodeData decodeData) {
PerspectiveTransform cardToImageTransform = decodeData.getCardToImageTransform();
byte[] iDataArray = decodeData.getDecodeImageByteArray();
int rowStride = decodeData.getDecodeWidth();
int frameSize = rowStride * decodeData.getDecodeHeight();
float totY;
float totU;
float totV;
int Y, U, V, uvPos;
int num;
float patchSize = calCardData.getPatchSize();
float halfSampleSize = 0.5f * patchSize * PATCH_SAMPLE_FRACTION;
Map<String, float[]> patchYUVMap = new HashMap<>();
for (String label : calCardData.getCalValues().keySet()) {
//CalibrationCardData.CalValue cal = calCardData.getCalValues().get(label);
CalibrationCardData.Location loc = calCardData.getLocations().get(label);
// upper and lower corners of the sample area, in card coordinates
float[] points = new float[]{loc.x - halfSampleSize, loc.y - halfSampleSize, loc.x + halfSampleSize, loc.y + halfSampleSize};
cardToImageTransform.transformPoints(points);
totY = 0.0f;
totU = 0.0f;
totV = 0.0f;
num = 0;
// follows https://stackoverflow.com/questions/12469730/confusion-on-yuv-nv21-conversion-to-rgb
for (int x = Math.round(points[0]); x <= Math.round(points[2]); x++) {
for (int y = Math.round(points[3]); y <= Math.round(points[1]); y++) {
uvPos = frameSize + (y >> 1) * rowStride;
Y = (0xff & iDataArray[x + y * rowStride]);
V = (0xff & ((int) iDataArray[uvPos + (x & ~1)])) - 128;
U = (0xff & ((int) iDataArray[uvPos + (x & ~1) + 1])) - 128;
totY += Y;
totU += U;
totV += V;
num++;
}
}
float[] patchColYUV = new float[]{totY / num, totU / num, totV / num};
patchYUVMap.put(label, patchColYUV);
}
return patchYUVMap;
}
// Android YUV to sRGB
// RGB has scale [0..255]
public static Map<String, float[]> YUVtoLinearRGB(Map<String, float[]> patchYUVMap) {
Map<String, float[]> patchRGBMap = new HashMap<>();
for (String label : patchYUVMap.keySet()) {
float[] col = patchYUVMap.get(label);
float[] rgb = ColorUtils.YUVtoLinearRGB(col);
patchRGBMap.put(label, rgb);
}
return patchRGBMap;
}
public static Map<String, float[]> calCardXYZ(Map<String, CalibrationCardData.CalValue> calValues) {
Map<String, float[]> patchXYZMap = new HashMap<>();
for (String label : calValues.keySet()) {
CalibrationCardData.CalValue xyzCol = calValues.get(label);
float[] XYZ = new float[3];
XYZ[0] = xyzCol.getX();
XYZ[1] = xyzCol.getY();
XYZ[2] = xyzCol.getZ();
patchXYZMap.put(label, XYZ);
}
return patchXYZMap;
}
public static float[] deltaE2000stats(Map<String, float[]> calibrationXYZMap, Map<String, float[]> patchXYZMap) {
float[] deltaEArray = new float[patchXYZMap.keySet().size()];
int i = 0;
float deltaE2000;
float[] calibrationColXYZ, cardColXYZ, calibrationColLab, cardColLab;
for (String label : patchXYZMap.keySet()) {
calibrationColXYZ = calibrationXYZMap.get(label);
cardColXYZ = patchXYZMap.get(label);
calibrationColLab = ColorUtils.XYZtoLAB(calibrationColXYZ);
cardColLab = ColorUtils.XYZtoLAB(cardColXYZ);
deltaE2000 = ColorUtils.deltaE2000(calibrationColLab, cardColLab);
deltaEArray[i] = deltaE2000;
i++;
}
return meanMedianMax(deltaEArray);
}
}
| 17,163 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ImageUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/ImageUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import org.akvo.caddisfly.sensor.striptest.models.DecodeData;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPattern;
import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoint;
import org.apache.commons.math3.fitting.WeightedObservedPoints;
import java.util.List;
public class ImageUtils {
private static final double LOWER_PERCENTAGE_BOUND = 0.9;
private static final double UPPER_PERCENTAGE_BOUND = 1.1;
public static int maxY(DecodeData decodeData, FinderPattern fp) {
// Compute expected area finder pattern
float x = fp.getX();
float y = fp.getY();
float size = fp.getEstimatedModuleSize();
int halfWidth = (int) (size * 3.5); // one finder pattern has size 7
int xTopLeft = Math.max((int) (x - halfWidth), 0);
int yTopLeft = Math.max((int) (y - halfWidth), 0);
int xBotRight = Math.min((int) (x + halfWidth), decodeData.getDecodeWidth() - 1);
int yBotRight = Math.min((int) (y + halfWidth), decodeData.getDecodeHeight() - 1);
int maxY = 0;
int rowStride = decodeData.getDecodeWidth();
byte[] yDataArray = decodeData.getDecodeImageByteArray();
// iterate over all points and get max Y value
int i;
int j;
int yVal;
for (j = yTopLeft; j <= yBotRight; j++) {
int offset = j * rowStride;
for (i = xTopLeft; i <= xBotRight; i++) {
yVal = yDataArray[offset + i] & 0xff;
if (yVal > maxY) {
maxY = yVal;
}
}
}
return maxY;
}
// detect strip by multi-step method
// returns cut-out and rotated resulting strip as mat
// TODO handle no-strip case
@SuppressWarnings("UnusedParameters")
public static float[][][] detectStrip(float[][][] image, int width, int height,
double stripLength, double ratioPixelPerMm) {
// we need to check if there is a strip on the black area. We
// combine this with computing a first approximation of line through length of the strip,
// as we go through all the points anyway.
final WeightedObservedPoints points = new WeightedObservedPoints();
final WeightedObservedPoints corrPoints = new WeightedObservedPoints();
double tot, yTot;
int totalWhite = 0;
for (int i = 0; i < width; i++) { // iterate over cols
tot = 0;
yTot = 0;
for (int j = 0; j < height; j++) { // iterate over rows
// we check if the Y value in XYZ is larger than 50, which we use as cutoff.
if (image[i][j][1] > 50) {
yTot += j;
tot++;
}
}
if (tot > 0) {
points.add((double) i, yTot / tot);
totalWhite += tot;
}
}
// We should have at least 9% not-black to be sure we have a strip
if (totalWhite < 0.09 * width * height) {
return null;
}
// fit a line through these points
// order of coefficients is (b + ax), so [b, a]
final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(1);
List<WeightedObservedPoint> pointsList = points.toList();
final double[] coefficient = fitter.fit(pointsList);
// second pass, remove outliers
double estimate, actual;
for (int i = 0; i < pointsList.size(); i++) {
estimate = coefficient[1] * pointsList.get(i).getX() + coefficient[0];
actual = pointsList.get(i).getY();
if (actual > LOWER_PERCENTAGE_BOUND * estimate && actual < UPPER_PERCENTAGE_BOUND * estimate) {
//if the point differs less than +/- 10%, keep the point
corrPoints.add(pointsList.get(i).getX(), pointsList.get(i).getY());
}
}
final double[] coefficientCorr = fitter.fit(corrPoints.toList());
double slope = coefficientCorr[1];
double offset = coefficientCorr[0];
// compute rotation angle
double rotAngleRad = Math.atan(slope);
//determine a point on the line, in the middle of strip, in the horizontal middle of the whole image
int midPointX = width / 2;
int midPointY = (int) Math.round(midPointX * slope + offset);
// rotate around the midpoint, to straighten the binary strip
// compute rotation matrix
// cosAngle -sinAngle
// sinAngle cosAngle
float cosAngle = (float) Math.cos(rotAngleRad);
float sinAngle = (float) Math.sin(rotAngleRad);
float xm, ym;
int xt, yt;
float[][][] rotatedImage = new float[width][height][3];
for (int i = 0; i < width; i++) { // iterate over cols
for (int j = 0; j < height; j++) { // iterate over rows
xm = i - midPointX;
ym = j - midPointY;
xt = Math.round(cosAngle * xm - sinAngle * ym + midPointX);
yt = Math.round(sinAngle * xm + cosAngle * ym + midPointY);
if (xt < 0 || xt > width - 1 || yt < 0 || yt > height - 1) {
rotatedImage[i][j][0] = 0; // X
rotatedImage[i][j][1] = 0; // Y
rotatedImage[i][j][2] = 0; // Z
} else {
rotatedImage[i][j][0] = image[xt][yt][0];
rotatedImage[i][j][1] = image[xt][yt][1];
rotatedImage[i][j][2] = image[xt][yt][2];
}
}
}
// Compute white points in each row
int[] rowCount = new int[height];
int rowTot;
for (int j = 0; j < height; j++) { // iterate over rows
rowTot = 0;
for (int i = 0; i < width; i++) { // iterate over cols
if (rotatedImage[i][j][1] > 50) {
rowTot++;
}
}
rowCount[j] = rowTot;
}
// find height of strip by finding top and bottom edges
// find top edge of strip
int topEdge = 0;
double riseVal = 0;
for (int i = 0; i < height - 1; i++) {
int rowDiff = rowCount[i + 1] - rowCount[i];
if (rowDiff > riseVal) {
riseVal = rowDiff;
topEdge = i + 1;
}
}
// find bottom edge of strip
int bottomEdge = 0;
double fallVal = 0;
// start 20 pixels away from top edge when looking for bottom edge
for (int i = height - 1; i >= topEdge + 20; i--) {
int rowDiff = rowCount[i - 1] - rowCount[i];
if (rowDiff > fallVal) {
fallVal = rowDiff;
bottomEdge = i;
}
}
// now find right end of strip
// method: first rising edge
int[] colCount = new int[width];
int colTotal;
for (int i = 0; i < width; i++) { // iterate over cols
colTotal = 0;
for (int j = topEdge; j < bottomEdge; j++) { // iterate over rows
if (rotatedImage[i][j][1] > 50) {
colTotal++;
}
}
colCount[i] = colTotal;
}
// threshold is that half of the rows in a column should be white
int threshold = (bottomEdge - topEdge) / 2;
boolean found = false;
// use known length of strip to determine right side
double posRight = width - 1;
// moving from the right, determine the first point that crosses the threshold
while (!found && posRight > 0) {
if (colCount[(int) posRight] > threshold) {
found = true;
} else {
posRight--;
}
}
// use known length of strip to determine left side
int start = (int) Math.round((posRight - (stripLength * ratioPixelPerMm)));
int end = (int) Math.round(posRight);
// cut out final strip
// here, we also transpose the matrix so the rows correspond to the vertical dimension
float[][][] result = new float[bottomEdge - topEdge + 1][end - start + 1][3];
for (int i = start; i < end; i++) {
for (int j = topEdge; j < bottomEdge; j++) {
result[j - topEdge][i - start][0] = rotatedImage[i][j][0];
result[j - topEdge][i - start][1] = rotatedImage[i][j][1];
result[j - topEdge][i - start][2] = rotatedImage[i][j][2];
}
}
return result;
}
}
| 8,763 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BitmapUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/utils/BitmapUtils.java | package org.akvo.caddisfly.sensor.striptest.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Typeface;
import org.akvo.caddisfly.app.CaddisflyApp;
import org.akvo.caddisfly.model.ColorItem;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.striptest.models.PatchResult;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.Objects;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueString;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueUnitString;
@SuppressWarnings("WeakerAccess")
public class BitmapUtils {
private final static int IMG_WIDTH = 500;
private final static int VALUE_HEIGHT = 40;
private final static int TRIANGLE_WIDTH = 30;
private final static int TRIANGLE_HEIGHT = 30;
private final static int COLOR_DROP_CIRCLE_RADIUS = 20;
private final static int COLOR_BAR_HEIGHT = 50;
private final static int COLOR_BAR_VERTICAL_GAP = 10;
private final static int COLOR_BAR_HORIZONTAL_GAP = 10;
private final static int VAL_BAR_HEIGHT = 25;
private final static int TEXT_SIZE = 20;
private final static int SPACING = 10;
private final static int SPACING_BELOW_STRIP = 40;
// creates image for a strip consisting of one or more individual patches
// creates individual parts of the result image, and concatenates them
public static Bitmap createResultImageSingle(PatchResult patchResult, TestInfo brand) {
Bitmap triangle = createTriangleBitmap(patchResult, brand);
Bitmap strip = createStripBitmap(patchResult);
Bitmap colourDrop = null;
if (!Float.isNaN(patchResult.getValue())) {
colourDrop = createColourDropBitmapSingle(patchResult);
}
Bitmap colourBars = createColourBarsBitmapSingle(patchResult);
return concatAllBitmaps(triangle, strip, colourDrop, colourBars);
}
public static Bitmap RotateBitmap(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
// creates image for a grouped-style strip
// creates individual parts of the result image, and concatenates them
public static Bitmap createResultImageGroup(List<PatchResult> patchResultList) {
Bitmap strip = createStripBitmap(patchResultList.get(0));
Bitmap colourDrop = createColourDropBitmapGroup(patchResultList);
Bitmap colourBars = createColourBarsBitmapGroup(patchResultList);
return concatAllBitmaps(null, strip, colourDrop, colourBars);
}
// Concatenate two bitmaps
public static Bitmap concatTwoBitmapsVertical(Bitmap bmp1, Bitmap bmp2) {
int width = bmp1.getWidth() + bmp2.getWidth() + SPACING;
Bitmap resultImage = Bitmap.createBitmap(width, bmp1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultImage);
canvas.drawBitmap(bmp1, 0f, 0f, null);
canvas.drawBitmap(bmp2, bmp1.getWidth(), 0f, null);
return resultImage;
}
// Concatenate two bitmaps
public static Bitmap concatTwoBitmapsHorizontal(Bitmap bmp1, Bitmap bmp2) {
int height = bmp1.getHeight() + bmp2.getHeight() + SPACING;
Bitmap resultImage = Bitmap.createBitmap(bmp1.getWidth(), height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultImage);
canvas.drawBitmap(bmp1, 0f, 0f, null);
canvas.drawBitmap(bmp2, 0f, bmp1.getHeight(), null);
return resultImage;
}
// Concatenate two bitmaps
public static Bitmap concatTwoBitmaps(Bitmap bmp1, Bitmap bmp2) {
int height = bmp1.getHeight() + bmp2.getHeight() + SPACING;
Bitmap resultImage = Bitmap.createBitmap(IMG_WIDTH, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultImage);
canvas.drawBitmap(bmp1, 0f, 0f, null);
canvas.drawBitmap(bmp2, 0f, bmp1.getHeight() + SPACING, null);
return resultImage;
}
// concatenate all the individual bitmaps
// result is a single bitmap.
public static Bitmap concatAllBitmaps(Bitmap triangle, Bitmap strip, Bitmap colourDrop, Bitmap colourBars) {
int height = strip.getHeight() + colourBars.getHeight() + SPACING;
if (colourDrop == null) {
height += SPACING_BELOW_STRIP;
} else {
height += colourDrop.getHeight();
}
if (triangle != null) {
height += triangle.getHeight();
}
Bitmap resultImage = Bitmap.createBitmap(IMG_WIDTH, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultImage);
int totalHeight = 0;
// paint on all the bitmaps
if (triangle != null) {
canvas.drawBitmap(triangle, 0f, 0f, null);
totalHeight = triangle.getHeight();
}
canvas.drawBitmap(strip, 0f, totalHeight, null);
totalHeight += strip.getHeight() + SPACING;
if (colourDrop != null) {
canvas.drawBitmap(colourDrop, 0f, totalHeight, null);
totalHeight += colourDrop.getHeight();
}
if (colourDrop == null) {
totalHeight += SPACING_BELOW_STRIP;
}
canvas.drawBitmap(colourBars, 0f, totalHeight, null);
return resultImage;
}
// creates bitmap with description, value and unit.
// it is only included when we send the image to the server.
public static Bitmap createValueBitmap(PatchResult patchResult, String defaultString) {
Bitmap resultImage = Bitmap.createBitmap(IMG_WIDTH, VALUE_HEIGHT, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultImage);
String unit = patchResult.getPatch().getUnit();
String valueString = createValueUnitString(patchResult.getValue(), unit, defaultString);
valueString = patchResult.getPatch().getName() + ": " + valueString + " " + patchResult.getBracket();
// create paint
Paint blackText = new Paint();
blackText.setColor(Color.BLACK);
blackText.setTextSize(TEXT_SIZE);
blackText.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
blackText.setTextAlign(Paint.Align.LEFT);
canvas.drawText(valueString, 10, 35, blackText);
return resultImage;
}
// create bitmap from the calibrated strip image
public static Bitmap createStripBitmap(PatchResult patchResult) {
float[][][] xyzImg = patchResult.getImage();
// get dimensions
int rows = xyzImg.length;
int cols = xyzImg[0].length;
// convert to RGB
int[] imgRGB = new int[rows * cols];
int[] RGB;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
RGB = ColorUtils.xyzToRgbInt(xyzImg[i][j]);
imgRGB[i * cols + j] = Color.rgb(RGB[0], RGB[1], RGB[2]);
}
}
int height = Math.round(rows * IMG_WIDTH / cols);
Bitmap bmpRGB = Bitmap.createBitmap(imgRGB, 0, cols, cols, rows, Bitmap.Config.ARGB_8888);
if (AppPreferences.isDiagnosticMode()) {
bmpRGB = convertToMutable(CaddisflyApp.getApp(), bmpRGB);
if (bmpRGB != null) {
Canvas canvas = new Canvas(bmpRGB);
// Initialize a new Paint instance to draw the Rectangle
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
Result patch = patchResult.getPatch();
double stripRatio = 5;
double x = patch.getPatchPos() * stripRatio;
double y = 0.5 * patch.getPatchWidth() * stripRatio;
double halfSize = 0.5 * Constants.STRIP_WIDTH_FRACTION * patch.getPatchWidth();
int tlx = (int) Math.round(x - halfSize);
int tly = (int) Math.round(y - halfSize);
int brx = (int) Math.round(x + halfSize);
int bry = (int) Math.round(y + halfSize);
// Initialize a new Rect object
Rect rectangle = new Rect(tlx, tly, brx, bry);
// Finally, draw the rectangle on the canvas
canvas.drawRect(rectangle, paint);
}
}
// resize
return Bitmap.createScaledBitmap(Objects.requireNonNull(bmpRGB), IMG_WIDTH, height, false);
}
// ----------------------------------------- individual ----------------------------------------
// create bitmap with a black triangle that indicates the position of the patch for this measurement.
public static Bitmap createTriangleBitmap(PatchResult patchResult, TestInfo brand) {
double patchPos = patchResult.getPatch().getPatchPos();
float stripWidth = (float) brand.getStripLength();
float xPos = (float) ((patchPos / stripWidth) * IMG_WIDTH);
Bitmap result = Bitmap.createBitmap(IMG_WIDTH, TRIANGLE_HEIGHT, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint black = new Paint();
black.setColor(Color.BLACK);
black.setStyle(Paint.Style.FILL);
// compute points of triangle:
int halfWidth = TRIANGLE_WIDTH / 2;
Path path = new Path();
path.moveTo(xPos - halfWidth, 0); // top left
path.lineTo(xPos + halfWidth, 0); // top right
path.lineTo(xPos, TRIANGLE_HEIGHT); // bottom
path.lineTo(xPos - halfWidth, 0); // back to top left
path.close();
canvas.drawPath(path, black);
return result;
}
// Create bitmap for coloured 'drop', which indicates the position of the
// measured colour, and has as its own colour the measured colour.
public static Bitmap createColourDropBitmapSingle(PatchResult patchResult) {
Bitmap result = Bitmap.createBitmap(IMG_WIDTH, 3 * COLOR_DROP_CIRCLE_RADIUS, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
float[] xyz = patchResult.getXyz();
int[] rgb = ColorUtils.xyzToRgbInt(xyz);
// compute central location of marker, using the index of the matched colour
List<ColorItem> colors = patchResult.getPatch().getColors();
int numColors = colors.size();
int blockWidth = Math.round((IMG_WIDTH - (numColors - 1) * COLOR_BAR_HORIZONTAL_GAP) / numColors);
int xRange = IMG_WIDTH - blockWidth;
int totIndex = ResultUtils.INTERPOLATION_NUMBER * (numColors - 1) + 1;
int xPos = (blockWidth / 2 + xRange * patchResult.getIndex() / totIndex);
Paint paintColor = new Paint();
paintColor.setStyle(Paint.Style.FILL);
paintColor.setARGB(255, rgb[0], rgb[1], rgb[2]);
// compute points of triangle:
Path path = new Path();
path.moveTo(xPos - COLOR_DROP_CIRCLE_RADIUS, COLOR_DROP_CIRCLE_RADIUS); // top left
path.lineTo(xPos + COLOR_DROP_CIRCLE_RADIUS, COLOR_DROP_CIRCLE_RADIUS); // top right
path.lineTo(xPos, 3 * COLOR_DROP_CIRCLE_RADIUS); // bottom
path.lineTo(xPos - COLOR_DROP_CIRCLE_RADIUS, COLOR_DROP_CIRCLE_RADIUS); // back to top left
path.close();
canvas.drawCircle(xPos, COLOR_DROP_CIRCLE_RADIUS, COLOR_DROP_CIRCLE_RADIUS, paintColor);
canvas.drawPath(path, paintColor);
return result;
}
// Creates bitmap with colour blocks and values.
public static Bitmap createColourBarsBitmapSingle(PatchResult patchResult) {
Bitmap result = Bitmap.createBitmap(IMG_WIDTH, COLOR_BAR_HEIGHT + VAL_BAR_HEIGHT, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
List<ColorItem> colors = patchResult.getPatch().getColors();
int numColors = colors.size();
int[][] rgbCols = new int[numColors][3];
float[] values = new float[numColors];
float[] lab = new float[3];
int[] rgb;
// get lab colours and turn them to RGB
for (int i = 0; i < numColors; i++) {
List<Double> patchColorValues = colors.get(i).getLab();
lab[0] = patchColorValues.get(0).floatValue();
lab[1] = patchColorValues.get(1).floatValue();
lab[2] = patchColorValues.get(2).floatValue();
rgb = ColorUtils.xyzToRgbInt(ColorUtils.Lab2XYZ(lab));
rgbCols[i] = rgb;
values[i] = colors.get(i).getValue().floatValue();
}
// create paints
Paint paintColor = new Paint();
paintColor.setStyle(Paint.Style.FILL);
Paint blackText = new Paint();
blackText.setColor(Color.BLACK);
blackText.setTextSize(TEXT_SIZE);
blackText.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
blackText.setTextAlign(Paint.Align.CENTER);
// cycle over colours and create blocks and value
int blockWidth = Math.round((IMG_WIDTH - (numColors - 1) * COLOR_BAR_HORIZONTAL_GAP) / numColors);
int totWidth = COLOR_BAR_HORIZONTAL_GAP + blockWidth;
for (int i = 0; i < numColors; i++) {
paintColor.setARGB(255, rgbCols[i][0], rgbCols[i][1], rgbCols[i][2]);
canvas.drawRect(i * totWidth, 0, i * totWidth + blockWidth, COLOR_BAR_HEIGHT, paintColor);
String val = createValueString(values[i]);
canvas.drawText(val, i * totWidth + blockWidth / 2, COLOR_BAR_HEIGHT + VAL_BAR_HEIGHT, blackText);
}
return result;
}
// ------------------------------------------ group ---------------------------------------------
// create bitmap for coloured 'drop', which indicates the position of the
// measured colour, and has as its own colours the measured colours.
public static Bitmap createColourDropBitmapGroup(List<PatchResult> patchResultList) {
int numPatches = patchResultList.size();
int[][] rgbCols = new int[numPatches][3];
float index = patchResultList.get(0).getIndex();
float[] xyz;
// get measured RGB colours for all patches
for (int j = 0; j < numPatches; j++) {
xyz = patchResultList.get(j).getXyz();
rgbCols[j] = ColorUtils.xyzToRgbInt(xyz);
}
// compute central location of marker, using the index of the matched colour
List<ColorItem> colors = patchResultList.get(0).getPatch().getColors();
int numColors = colors.size();
int blockWidth = Math.round((IMG_WIDTH - (numColors - 1) * COLOR_BAR_HORIZONTAL_GAP) / numColors);
int halfBlockWidth = blockWidth / 2;
int xRange = IMG_WIDTH - blockWidth;
int totIndex = ResultUtils.INTERPOLATION_NUMBER * (numColors - 1) + 1;
int xPos = (int) (halfBlockWidth + xRange * index / totIndex);
// create empty bitmap
Bitmap result = Bitmap.createBitmap(IMG_WIDTH, (numPatches + 1) * blockWidth, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
// create paint
Paint paintColor = new Paint();
paintColor.setStyle(Paint.Style.FILL);
int yStart;
// iterate over patches and add coloured blocks
for (int j = 0; j < numPatches; j++) {
paintColor.setARGB(255, rgbCols[j][0], rgbCols[j][1], rgbCols[j][2]);
yStart = j * blockWidth;
canvas.drawRect(xPos - halfBlockWidth, yStart, xPos + halfBlockWidth,
yStart + blockWidth, paintColor);
}
// finish with triangle, which is filled with the last colour
yStart = numPatches * blockWidth;
Path path = new Path();
path.moveTo(xPos - halfBlockWidth, yStart); // top left
path.lineTo(xPos + halfBlockWidth, yStart); // top right
path.lineTo(xPos, yStart + blockWidth); // bottom
path.lineTo(xPos - halfBlockWidth, yStart); // back to top left
path.close();
// draw triangle
canvas.drawPath(path, paintColor);
return result;
}
// creates bitmap with colour blocks and values.
public static Bitmap createColourBarsBitmapGroup(List<PatchResult> patchResultList) {
List<ColorItem> colors = patchResultList.get(0).getPatch().getColors();
int numColors = colors.size();
int numPatches = patchResultList.size();
int[][][] rgbCols = new int[numPatches][numColors][3];
float[] values = new float[numColors];
float[] lab = new float[3];
int[] rgb;
// get colors from json, and turn them into sRGB
for (int j = 0; j < numPatches; j++) {
colors = patchResultList.get(j).getPatch().getColors();
// get lab colours and turn them to RGB
for (int i = 0; i < numColors; i++) {
List<Double> patchColorValues = colors.get(i).getLab();
lab[0] = patchColorValues.get(0).floatValue();
lab[1] = patchColorValues.get(1).floatValue();
lab[2] = patchColorValues.get(2).floatValue();
rgb = ColorUtils.xyzToRgbInt(ColorUtils.Lab2XYZ(lab));
rgbCols[j][i] = rgb;
values[i] = colors.get(i).getValue().floatValue();
}
}
// create empty bitmap
Bitmap result = Bitmap.createBitmap(IMG_WIDTH, numPatches * (COLOR_BAR_HEIGHT + COLOR_BAR_VERTICAL_GAP)
+ VAL_BAR_HEIGHT, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
// create paints
Paint paintColor = new Paint();
paintColor.setStyle(Paint.Style.FILL);
Paint blackText = new Paint();
blackText.setColor(Color.BLACK);
blackText.setTextSize(TEXT_SIZE);
blackText.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
blackText.setTextAlign(Paint.Align.CENTER);
int blockWidth = Math.round((IMG_WIDTH - (numColors - 1) * COLOR_BAR_HORIZONTAL_GAP) / numColors);
int totWidth = COLOR_BAR_HORIZONTAL_GAP + blockWidth;
int yStart;
// cycle over patches
for (int j = 0; j < numPatches; j++) {
// cycle over colours and create blocks and value
yStart = j * (COLOR_BAR_HEIGHT + COLOR_BAR_VERTICAL_GAP);
for (int i = 0; i < numColors; i++) {
paintColor.setARGB(255, rgbCols[j][i][0], rgbCols[j][i][1], rgbCols[j][i][2]);
canvas.drawRect(i * totWidth, yStart, i * totWidth + blockWidth,
yStart + COLOR_BAR_HEIGHT, paintColor);
if (i == numColors - 1) {
String val = createValueString(values[i]);
yStart = numColors * (COLOR_BAR_HEIGHT + COLOR_BAR_VERTICAL_GAP) + VAL_BAR_HEIGHT;
canvas.drawText(val, i * totWidth + blockWidth / 2, yStart, blackText);
}
}
}
return result;
}
public static Bitmap convertToMutable(final Context context, final Bitmap imgIn) {
final int width = imgIn.getWidth(), height = imgIn.getHeight();
final Bitmap.Config type = imgIn.getConfig();
File outputFile = null;
final File outputDir = context.getCacheDir();
try {
outputFile = File.createTempFile(Long.toString(System.currentTimeMillis()), null, outputDir);
outputFile.deleteOnExit();
final RandomAccessFile randomAccessFile = new RandomAccessFile(outputFile, "rw");
final FileChannel channel = randomAccessFile.getChannel();
final MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
imgIn.copyPixelsToBuffer(map);
imgIn.recycle();
final Bitmap result = Bitmap.createBitmap(width, height, type);
map.position(0);
result.copyPixelsFromBuffer(map);
channel.close();
randomAccessFile.close();
//noinspection ResultOfMethodCallIgnored
outputFile.delete();
return result;
} catch (final Exception ignored) {
} finally {
if (outputFile != null)
//noinspection ResultOfMethodCallIgnored
outputFile.delete();
}
return null;
}
}
| 20,776 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FinderPatternInfoToJson.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/FinderPatternInfoToJson.java | package org.akvo.caddisfly.sensor.striptest.qrdetector;
import org.akvo.caddisfly.common.ConstantKey;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by linda on 9/13/15
*/
public class FinderPatternInfoToJson {
public static String toJson(FinderPatternInfo info) {
JSONObject jsonObject = new JSONObject();
try {
JSONArray topLeft = new JSONArray();
topLeft.put(info.getTopLeft().getX());
topLeft.put(info.getTopLeft().getY());
jsonObject.put(ConstantKey.TOP_LEFT, topLeft);
JSONArray topRight = new JSONArray();
topRight.put(info.getTopRight().getX());
topRight.put(info.getTopRight().getY());
jsonObject.put(ConstantKey.TOP_RIGHT, topRight);
JSONArray bottomLeft = new JSONArray();
bottomLeft.put(info.getBottomLeft().getX());
bottomLeft.put(info.getBottomLeft().getY());
jsonObject.put(ConstantKey.BOTTOM_LEFT, bottomLeft);
JSONArray bottomRight = new JSONArray();
bottomRight.put(info.getBottomRight().getX());
bottomRight.put(info.getBottomRight().getY());
jsonObject.put(ConstantKey.BOTTOM_RIGHT, bottomRight);
return jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
| 1,446 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DetectorResult.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/DetectorResult.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>Encapsulates the result of detecting a barcode in an image. This includes the raw
* matrix of black/white pixels corresponding to the barcode, and possibly points of interest
* in the image, like the location of finder patterns or corners of the barcode in the image.</p>
*
* @author Sean Owen
*/
public class DetectorResult {
private final BitMatrix bits;
private final ResultPoint[] points;
public DetectorResult(BitMatrix bits, ResultPoint[] points) {
this.bits = bits;
this.points = points;
}
public final BitMatrix getBits() {
return bits;
}
public final ResultPoint[] getPoints() {
return points;
}
} | 1,346 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FormatException.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/FormatException.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* Thrown when a barcode was successfully detected, but some aspect of
* the content did not conform to the barcode's format rules. This could have
* been due to a mis-detection.
*
* @author Sean Owen
*/
public final class FormatException extends ReaderException {
private static final FormatException INSTANCE = new FormatException();
static {
INSTANCE.setStackTrace(NO_TRACE); // since it's meaningless
}
private FormatException() {
}
private FormatException(Throwable cause) {
super(cause);
}
public static FormatException getFormatInstance() {
return isStackTrace ? new FormatException() : INSTANCE;
}
public static FormatException getFormatInstance(Throwable cause) {
return isStackTrace ? new FormatException(cause) : INSTANCE;
}
}
| 1,485 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DecodeHintType.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/DecodeHintType.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
import java.util.List;
/**
* Encapsulates a type of hint that a caller may pass to a barcode reader to help it
* more quickly or accurately decode it. It is up to implementations to decide what,
* if anything, to do with the information that is supplied.
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
*/
public enum DecodeHintType {
/**
* Unspecified, application-specific hint. Maps to an unspecified {@link Object}.
*/
OTHER(Object.class),
/**
* Image is a pure monochrome image of a barcode. Doesn't matter what it maps to;
* use {@link Boolean#TRUE}.
*/
PURE_BARCODE(Void.class),
/**
* Image is known to be of one of a few possible formats.
*/
POSSIBLE_FORMATS(List.class),
/**
* Spend more time to try to find a barcode; optimize for accuracy, not speed.
* Doesn't matter what it maps to; use {@link Boolean#TRUE}.
*/
TRY_HARDER(Void.class),
/**
* Specifies what character encoding to use when decoding, where applicable (type String)
*/
CHARACTER_SET(String.class),
/**
* Allowed lengths of encoded data -- reject anything else. Maps to an {@code int[]}.
*/
ALLOWED_LENGTHS(int[].class),
/**
* Assume Code 39 codes employ a check digit. Doesn't matter what it maps to;
* use {@link Boolean#TRUE}.
*/
ASSUME_CODE_39_CHECK_DIGIT(Void.class),
/**
* Assume the barcode is being processed as a GS1 barcode, and modify behavior as needed.
* For example this affects FNC1 handling for Code 128 (aka GS1-128). Doesn't matter what it maps to;
* use {@link Boolean#TRUE}.
*/
ASSUME_GS1(Void.class),
/**
* If true, return the qualityChecksOK and end digits in a Codabar barcode instead of stripping them. They
* are alpha, whereas the rest are numeric. By default, they are stripped, but this causes them
* to not be. Doesn't matter what it maps to; use {@link Boolean#TRUE}.
*/
RETURN_CODABAR_START_END(Void.class),
/**
* The caller needs to be notified via callback when a possible {@link ResultPoint}
* is found. Maps to a {@link ResultPointCallback}.
*/
NEED_RESULT_POINT_CALLBACK(ResultPointCallback.class),
/**
* Allowed extension lengths for EAN or UPC barcodes. Other formats will ignore this.
* Maps to an {@code int[]} of the allowed extension lengths, for example [2], [5], or [2, 5].
* If it is optional to have an extension, do not set this hint. If this is set,
* and a UPC or EAN barcode is found but an extension is not, then no result will be returned
* at all.
*/
ALLOWED_EAN_EXTENSIONS(int[].class),
// End of enumeration values.
;
/**
* Data type the hint is expecting.
* Among the possible values the {@link Void} stands out as being used for
* hints that do not expect a value to be supplied (flag hints). Such hints
* will possibly have their value ignored, or replaced by a
* {@link Boolean#TRUE}. Hint suppliers should probably use
* {@link Boolean#TRUE} as directed by the actual hint documentation.
*/
private final Class<?> valueType;
DecodeHintType(Class<?> valueType) {
this.valueType = valueType;
}
public Class<?> getValueType() {
return valueType;
}
}
| 4,025 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ErrorCorrectionLevel.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/ErrorCorrectionLevel.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels
* defined by the QR code standard.</p>
*
* @author Sean Owen
*/
public enum ErrorCorrectionLevel {
/**
* L = ~7% correction
*/
L(0x01),
/**
* M = ~15% correction
*/
M(0x00),
/**
* Q = ~25% correction
*/
Q(0x03),
/**
* H = ~30% correction
*/
H(0x02);
private static final ErrorCorrectionLevel[] FOR_BITS = {M, L, H, Q};
private final int bits;
ErrorCorrectionLevel(int bits) {
this.bits = bits;
}
/**
* @param bits int containing the two bits encoding a QR Code's error correction level
* @return ErrorCorrectionLevel representing the encoded error correction level
*/
public static ErrorCorrectionLevel forBits(int bits) {
if (bits < 0 || bits >= FOR_BITS.length) {
throw new IllegalArgumentException();
}
return FOR_BITS[bits];
}
public int getBits() {
return bits;
}
}
| 1,707 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FormatInformation.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/FormatInformation.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>Encapsulates a QR Code's format information, including the data mask used and
* error correction level.</p>
*
* @author Sean Owen
* @see ErrorCorrectionLevel
*/
final class FormatInformation {
private static final int FORMAT_INFO_MASK_QR = 0x5412;
/**
* See ISO 18004:2006, Annex C, Table C.1
*/
private static final int[][] FORMAT_INFO_DECODE_LOOKUP = {
{0x5412, 0x00},
{0x5125, 0x01},
{0x5E7C, 0x02},
{0x5B4B, 0x03},
{0x45F9, 0x04},
{0x40CE, 0x05},
{0x4F97, 0x06},
{0x4AA0, 0x07},
{0x77C4, 0x08},
{0x72F3, 0x09},
{0x7DAA, 0x0A},
{0x789D, 0x0B},
{0x662F, 0x0C},
{0x6318, 0x0D},
{0x6C41, 0x0E},
{0x6976, 0x0F},
{0x1689, 0x10},
{0x13BE, 0x11},
{0x1CE7, 0x12},
{0x19D0, 0x13},
{0x0762, 0x14},
{0x0255, 0x15},
{0x0D0C, 0x16},
{0x083B, 0x17},
{0x355F, 0x18},
{0x3068, 0x19},
{0x3F31, 0x1A},
{0x3A06, 0x1B},
{0x24B4, 0x1C},
{0x2183, 0x1D},
{0x2EDA, 0x1E},
{0x2BED, 0x1F},
};
/**
* Offset i holds the number of 1 bits in the binary representation of i
*/
private static final int[] BITS_SET_IN_HALF_BYTE =
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
private final ErrorCorrectionLevel errorCorrectionLevel;
private final byte dataMask;
private FormatInformation(int formatInfo) {
// Bits 3,4
errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03);
// Bottom 3 bits
dataMask = (byte) (formatInfo & 0x07);
}
static int numBitsDiffering(int a, int b) {
a ^= b; // a now has a 1 bit exactly where its bit differs with b's
// Count bits set quickly with a series of lookups:
return BITS_SET_IN_HALF_BYTE[a & 0x0F] +
BITS_SET_IN_HALF_BYTE[(a >>> 4 & 0x0F)] +
BITS_SET_IN_HALF_BYTE[(a >>> 8 & 0x0F)] +
BITS_SET_IN_HALF_BYTE[(a >>> 12 & 0x0F)] +
BITS_SET_IN_HALF_BYTE[(a >>> 16 & 0x0F)] +
BITS_SET_IN_HALF_BYTE[(a >>> 20 & 0x0F)] +
BITS_SET_IN_HALF_BYTE[(a >>> 24 & 0x0F)] +
BITS_SET_IN_HALF_BYTE[(a >>> 28 & 0x0F)];
}
/**
* @param maskedFormatInfo1 format info indicator, with mask still applied
* @param maskedFormatInfo2 second copy of same info; both are checked at the same time
* to establish best match
* @return information about the format it specifies, or {@code null}
* if doesn't seem to match any known pattern
*/
static FormatInformation decodeFormatInformation(int maskedFormatInfo1, int maskedFormatInfo2) {
FormatInformation formatInfo = doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2);
if (formatInfo != null) {
return formatInfo;
}
// Should return null, but, some QR codes apparently
// do not mask this info. Try again by actually masking the pattern
// first
return doDecodeFormatInformation(maskedFormatInfo1 ^ FORMAT_INFO_MASK_QR,
maskedFormatInfo2 ^ FORMAT_INFO_MASK_QR);
}
private static FormatInformation doDecodeFormatInformation(int maskedFormatInfo1, int maskedFormatInfo2) {
// Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
int bestDifference = Integer.MAX_VALUE;
int bestFormatInfo = 0;
for (int[] decodeInfo : FORMAT_INFO_DECODE_LOOKUP) {
int targetInfo = decodeInfo[0];
if (targetInfo == maskedFormatInfo1 || targetInfo == maskedFormatInfo2) {
// Found an exact match
return new FormatInformation(decodeInfo[1]);
}
int bitsDifference = numBitsDiffering(maskedFormatInfo1, targetInfo);
if (bitsDifference < bestDifference) {
bestFormatInfo = decodeInfo[1];
bestDifference = bitsDifference;
}
if (maskedFormatInfo1 != maskedFormatInfo2) {
// also try the other option
bitsDifference = numBitsDiffering(maskedFormatInfo2, targetInfo);
if (bitsDifference < bestDifference) {
bestFormatInfo = decodeInfo[1];
bestDifference = bitsDifference;
}
}
}
// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
// differing means we found a match
if (bestDifference <= 3) {
return new FormatInformation(bestFormatInfo);
}
return null;
}
ErrorCorrectionLevel getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
byte getDataMask() {
return dataMask;
}
@Override
public int hashCode() {
return (errorCorrectionLevel.ordinal() << 3) | (int) dataMask;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FormatInformation)) {
return false;
}
FormatInformation other = (FormatInformation) o;
return this.errorCorrectionLevel == other.errorCorrectionLevel &&
this.dataMask == other.dataMask;
}
}
| 6,162 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ResultPointCallback.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/ResultPointCallback.java | /*
* Copyright 2009 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* Callback which is invoked when a possible result point (significant
* point in the barcode image such as a corner) is found.
*
* @see DecodeHintType#NEED_RESULT_POINT_CALLBACK
*/
public interface ResultPointCallback {
void foundPossibleResultPoint(ResultPoint point);
}
| 943 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Detector.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/Detector.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
import java.util.Map;
/**
* <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
* is rotated or skewed, or partially obscured.</p>
*
* @author Sean Owen
*/
public class Detector {
private final BitMatrix image;
private ResultPointCallback resultPointCallback;
public Detector(BitMatrix image) {
this.image = image;
}
private static PerspectiveTransform createTransform(ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomLeft,
ResultPoint alignmentPattern,
int dimension) {
float dimMinusThree = (float) dimension - 3.5f;
float bottomRightX;
float bottomRightY;
float sourceBottomRightX;
float sourceBottomRightY;
if (alignmentPattern != null) {
bottomRightX = alignmentPattern.getX();
bottomRightY = alignmentPattern.getY();
sourceBottomRightX = dimMinusThree - 3.0f;
sourceBottomRightY = sourceBottomRightX;
} else {
// Don't have an alignment pattern, just make up the bottom-right point
bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX();
bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY();
sourceBottomRightX = dimMinusThree;
sourceBottomRightY = dimMinusThree;
}
return PerspectiveTransform.quadrilateralToQuadrilateral(
3.5f,
3.5f,
dimMinusThree,
3.5f,
sourceBottomRightX,
sourceBottomRightY,
3.5f,
dimMinusThree,
topLeft.getX(),
topLeft.getY(),
topRight.getX(),
topRight.getY(),
bottomRightX,
bottomRightY,
bottomLeft.getX(),
bottomLeft.getY());
}
private static BitMatrix sampleGrid(BitMatrix image,
PerspectiveTransform transform,
int dimension) throws NotFoundException {
GridSampler sampler = GridSampler.getInstance();
return sampler.sampleGrid(image, dimension, dimension, transform);
}
/**
* <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
* of the finder patterns and estimated module size.</p>
*/
private static int computeDimension(ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomLeft,
float moduleSize) throws NotFoundException {
int topLeftTopRightCenters = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
int topLeftBottomLeftCenters = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
int dimension = ((topLeftTopRightCenters + topLeftBottomLeftCenters) / 2) + 7;
switch (dimension & 0x03) { // mod 4
case 0:
dimension++;
break;
// 1? do nothing
case 2:
dimension--;
break;
case 3:
throw NotFoundException.getNotFoundInstance();
}
return dimension;
}
protected final BitMatrix getImage() {
return image;
}
protected final ResultPointCallback getResultPointCallback() {
return resultPointCallback;
}
/**
* <p>Detects a QR Code in an image.</p>
*
* @return {@link DetectorResult} encapsulating results of detecting a QR Code
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/
public DetectorResult detect() throws NotFoundException, FormatException {
return detect(null);
}
/**
* <p>Detects a QR Code in an image.</p>
*
* @param hints optional hints to detector
* @return {@link DetectorResult} encapsulating results of detecting a QR Code
* @throws NotFoundException if QR Code cannot be found
* @throws FormatException if a QR Code cannot be decoded
*/
public final DetectorResult detect(Map<DecodeHintType, ?> hints) throws NotFoundException, FormatException {
resultPointCallback = hints == null ? null :
(ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
FinderPatternInfo info = finder.find(hints);
return processFinderPatternInfo(info);
}
protected final DetectorResult processFinderPatternInfo(FinderPatternInfo info)
throws NotFoundException, FormatException {
FinderPattern topLeft = info.getTopLeft();
FinderPattern topRight = info.getTopRight();
FinderPattern bottomLeft = info.getBottomLeft();
float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
if (moduleSize < 1.0f) {
throw NotFoundException.getNotFoundInstance();
}
int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
AlignmentPattern alignmentPattern = null;
// Anything above version 1 has an alignment pattern
if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
// Guess where a "bottom right" finder pattern would have been
float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
// Estimate that alignment pattern is closer by 3 modules
// from "bottom right" to known top left location
float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
// Kind of arbitrary -- expand search radius before giving up
for (int i = 4; i <= 16; i <<= 1) {
try {
alignmentPattern = findAlignmentInRegion(moduleSize,
estAlignmentX,
estAlignmentY,
(float) i);
break;
} catch (NotFoundException re) {
// try next round
}
}
// If we didn't find alignment pattern... well try anyway without it
}
PerspectiveTransform transform =
createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
BitMatrix bits = sampleGrid(image, transform, dimension);
ResultPoint[] points;
if (alignmentPattern == null) {
points = new ResultPoint[]{bottomLeft, topLeft, topRight};
} else {
points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
}
return new DetectorResult(bits, points);
}
/**
* <p>Computes an average estimated module size based on estimated derived from the positions
* of the three finder patterns.</p>
*
* @param topLeft detected top-left finder pattern center
* @param topRight detected top-right finder pattern center
* @param bottomLeft detected bottom-left finder pattern center
* @return estimated module size
*/
public final float calculateModuleSize(ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomLeft) {
// Take the average
return (calculateModuleSizeOneWay(topLeft, topRight) +
calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
}
/**
* <p>Estimates module size based on two finder patterns -- it uses
* {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
* width of each, measuring along the axis between their centers.</p>
*/
private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) {
float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
(int) pattern.getY(),
(int) otherPattern.getX(),
(int) otherPattern.getY());
float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(),
(int) otherPattern.getY(),
(int) pattern.getX(),
(int) pattern.getY());
if (Float.isNaN(moduleSizeEst1)) {
return moduleSizeEst2 / 7.0f;
}
if (Float.isNaN(moduleSizeEst2)) {
return moduleSizeEst1 / 7.0f;
}
// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
}
/**
* See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
* a finder pattern by looking for a black-white-black run from the center in the direction
* of another point (another finder pattern center), and in the opposite direction too.
*/
private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
// Now count other way -- don't run off image though of course
float scale = 1.0f;
int otherToX = fromX - (toX - fromX);
if (otherToX < 0) {
scale = (float) fromX / (float) (fromX - otherToX);
otherToX = 0;
} else if (otherToX >= image.getWidth()) {
scale = (float) (image.getWidth() - 1 - fromX) / (float) (otherToX - fromX);
otherToX = image.getWidth() - 1;
}
int otherToY = (int) (fromY - (toY - fromY) * scale);
scale = 1.0f;
if (otherToY < 0) {
scale = (float) fromY / (float) (fromY - otherToY);
otherToY = 0;
} else if (otherToY >= image.getHeight()) {
scale = (float) (image.getHeight() - 1 - fromY) / (float) (otherToY - fromY);
otherToY = image.getHeight() - 1;
}
otherToX = (int) (fromX + (otherToX - fromX) * scale);
result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
// Middle pixel is double-counted this way; subtract 1
return result - 1.0f;
}
/**
* <p>This method traces a line from a point in the image, in the direction towards another point.
* It begins in a black region, and keeps going until it finds white, then black, then white again.
* It reports the distance from the qualityChecksOK to this point.</p>
* <p>
* <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
* may be skewed or rotated.</p>
*/
private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
// Mild variant of Bresenham's algorithm;
// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
if (steep) {
int temp = fromX;
//noinspection SuspiciousNameCombination
fromX = fromY;
fromY = temp;
temp = toX;
//noinspection SuspiciousNameCombination
toX = toY;
toY = temp;
}
int dx = Math.abs(toX - fromX);
int dy = Math.abs(toY - fromY);
int error = -dx / 2;
int xStep = fromX < toX ? 1 : -1;
int yStep = fromY < toY ? 1 : -1;
// In black pixels, looking for white, first or second time.
int state = 0;
// Loop up until x == toX, but not beyond
int xLimit = toX + xStep;
for (int x = fromX, y = fromY; x != xLimit; x += xStep) {
int realX = steep ? y : x;
int realY = steep ? x : y;
// Does current pixel mean we have moved white to black or vice versa?
// Scanning black in state 0,2 and white in state 1, so if we find the wrong
// color, advance to next state or end if we are in state 2 already
if ((state == 1) == image.get(realX, realY)) {
if (state == 2) {
return MathUtils.distance(x, y, fromX, fromY);
}
state++;
}
error += dy;
if (error > 0) {
if (y == toY) {
break;
}
y += yStep;
error -= dx;
}
}
// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
// is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
if (state == 2) {
return MathUtils.distance(toX + xStep, toY, fromX, fromY);
}
// else we didn't find even black-white-black; no estimate is really possible
return Float.NaN;
}
/**
* <p>Attempts to locate an alignment pattern in a limited region of the image, which is
* guessed to contain it. This method uses {@link AlignmentPattern}.</p>
*
* @param overallEstModuleSize estimated module size so far
* @param estAlignmentX x coordinate of center of area probably containing alignment pattern
* @param estAlignmentY y coordinate of above
* @param allowanceFactor number of pixels in all directions to search from the center
* @return {@link AlignmentPattern} if found, or null otherwise
* @throws NotFoundException if an unexpected error occurs during detection
*/
protected final AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
int estAlignmentX,
int estAlignmentY,
float allowanceFactor)
throws NotFoundException {
// Look for an alignment pattern (3 modules in size) around where it
// should be
int allowance = (int) (allowanceFactor * overallEstModuleSize);
int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
throw NotFoundException.getNotFoundInstance();
}
int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {
throw NotFoundException.getNotFoundInstance();
}
AlignmentPatternFinder alignmentFinder =
new AlignmentPatternFinder(
image,
alignmentAreaLeftX,
alignmentAreaTopY,
alignmentAreaRightX - alignmentAreaLeftX,
alignmentAreaBottomY - alignmentAreaTopY,
overallEstModuleSize,
resultPointCallback);
return alignmentFinder.find();
}
}
| 16,885 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
MathUtils.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/MathUtils.java | /*
* Copyright 2012 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* General math-related and numeric utility functions.
*/
public final class MathUtils {
private MathUtils() {
}
/**
* Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its
* argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut
* differ slightly from {@link Math#round(float)} in that half rounds down for negative
* values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.
*
* @param d real value to round
* @return nearest {@code int}
*/
public static int round(float d) {
return (int) (d + (d < 0.0f ? -0.5f : 0.5f));
}
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/
public static float distance(float aX, float aY, float bX, float bY) {
float xDiff = aX - bX;
float yDiff = aY - bY;
return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/
public static float distance(int aX, int aY, int bX, int bY) {
int xDiff = aX - bX;
int yDiff = aY - bY;
return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
| 2,191 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
GridSampler.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/GridSampler.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* Implementations of this class can, given locations of finder patterns for a QR code in an
* image, sample the right points in the image to reconstruct the QR code, accounting for
* perspective distortion. It is abstracted since it is relatively expensive and should be allowed
* to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
* Imaging library, but which may not be available in other environments such as J2ME, and vice
* versa.
* <p>
* The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
* with an instance of a class which implements this interface.
*
* @author Sean Owen
*/
public abstract class GridSampler {
private static GridSampler gridSampler = new DefaultGridSampler();
/**
* Sets the implementation of GridSampler used by the library. One global
* instance is stored, which may sound problematic. But, the implementation provided
* ought to be appropriate for the entire platform, and all uses of this library
* in the whole lifetime of the JVM. For instance, an Android activity can swap in
* an implementation that takes advantage of native platform libraries.
*
* @param newGridSampler The platform-specific object to install.
*/
public static void setGridSampler(GridSampler newGridSampler) {
gridSampler = newGridSampler;
}
/**
* @return the current implementation of GridSampler
*/
public static GridSampler getInstance() {
return gridSampler;
}
/**
* <p>Checks a set of points that have been transformed to sample points on an image against
* the image's dimensions to see if the point are even within the image.</p>
* <p>
* <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
* barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
* patterns in an image where the QR Code runs all the way to the image border.</p>
* <p>
* <p>For efficiency, the method will check points from either end of the line until one is found
* to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
*
* @param image image into which the points should map
* @param points actual points in x1,y1,...,xn,yn form
* @throws NotFoundException if an endpoint is lies outside the image boundaries
*/
protected static void checkAndNudgePoints(BitMatrix image,
float[] points) throws NotFoundException {
int width = image.getWidth();
int height = image.getHeight();
// Check and nudge points from qualityChecksOK until we see some that are OK:
boolean nudged = true;
for (int offset = 0; offset < points.length && nudged; offset += 2) {
int x = (int) points[offset];
int y = (int) points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height) {
throw NotFoundException.getNotFoundInstance();
}
nudged = false;
if (x == -1) {
points[offset] = 0.0f;
nudged = true;
} else if (x == width) {
points[offset] = width - 1;
nudged = true;
}
if (y == -1) {
points[offset + 1] = 0.0f;
nudged = true;
} else if (y == height) {
points[offset + 1] = height - 1;
nudged = true;
}
}
// Check and nudge points from end:
nudged = true;
for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
int x = (int) points[offset];
int y = (int) points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height) {
throw NotFoundException.getNotFoundInstance();
}
nudged = false;
if (x == -1) {
points[offset] = 0.0f;
nudged = true;
} else if (x == width) {
points[offset] = width - 1;
nudged = true;
}
if (y == -1) {
points[offset + 1] = 0.0f;
nudged = true;
} else if (y == height) {
points[offset + 1] = height - 1;
nudged = true;
}
}
}
/**
* Samples an image for a rectangular matrix of bits of the given dimension. The sampling
* transformation is determined by the coordinates of 4 points, in the original and transformed
* image space.
*
* @param image image to sample
* @param dimensionX width of {@link BitMatrix} to sample from image
* @param dimensionY height of {@link BitMatrix} to sample from image
* @param p1ToX point 1 preimage X
* @param p1ToY point 1 preimage Y
* @param p2ToX point 2 preimage X
* @param p2ToY point 2 preimage Y
* @param p3ToX point 3 preimage X
* @param p3ToY point 3 preimage Y
* @param p4ToX point 4 preimage X
* @param p4ToY point 4 preimage Y
* @param p1FromX point 1 image X
* @param p1FromY point 1 image Y
* @param p2FromX point 2 image X
* @param p2FromY point 2 image Y
* @param p3FromX point 3 image X
* @param p3FromY point 3 image Y
* @param p4FromX point 4 image X
* @param p4FromY point 4 image Y
* @return {@link BitMatrix} representing a grid of points sampled from the image within a region
* defined by the "from" parameters
* @throws NotFoundException if image can't be sampled, for example, if the transformation defined
* by the given points is invalid or results in sampling outside the image boundaries
*/
public abstract BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
float p1ToX, float p1ToY,
float p2ToX, float p2ToY,
float p3ToX, float p3ToY,
float p4ToX, float p4ToY,
float p1FromX, float p1FromY,
float p2FromX, float p2FromY,
float p3FromX, float p3FromY,
float p4FromX, float p4FromY) throws NotFoundException;
public abstract BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
PerspectiveTransform transform) throws NotFoundException;
}
| 7,653 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Version.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/Version.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* See ISO 18004:2006 Annex D
*
* @author Sean Owen
*/
public final class Version {
/**
* See ISO 18004:2006 Annex D.
* Element i represents the raw version bits that specify version i + 7
*/
private static final int[] VERSION_DECODE_INFO = {
0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6,
0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78,
0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683,
0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB,
0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250,
0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B,
0x2542E, 0x26A64, 0x27541, 0x28C69
};
private static final Version[] VERSIONS = buildVersions();
private final int versionNumber;
private final int[] alignmentPatternCenters;
private final ECBlocks[] ecBlocks;
private final int totalCodewords;
private Version(int versionNumber,
int[] alignmentPatternCenters,
ECBlocks... ecBlocks) {
this.versionNumber = versionNumber;
this.alignmentPatternCenters = alignmentPatternCenters;
this.ecBlocks = ecBlocks;
int total = 0;
int ecCodewords = ecBlocks[0].getECCodewordsPerBlock();
ECB[] ecbArray = ecBlocks[0].getECBlocks();
for (ECB ecBlock : ecbArray) {
total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords);
}
this.totalCodewords = total;
}
/**
* <p>Deduces version information purely from QR Code dimensions.</p>
*
* @param dimension dimension in modules
* @return Version for a QR Code of that dimension
* @throws FormatException if dimension is not 1 mod 4
*/
public static Version getProvisionalVersionForDimension(int dimension) throws FormatException {
if (dimension % 4 != 1) {
throw FormatException.getFormatInstance();
}
try {
return getVersionForNumber((dimension - 17) / 4);
} catch (IllegalArgumentException ignored) {
throw FormatException.getFormatInstance();
}
}
public static Version getVersionForNumber(int versionNumber) {
if (versionNumber < 1 || versionNumber > 40) {
throw new IllegalArgumentException();
}
return VERSIONS[versionNumber - 1];
}
static Version decodeVersionInformation(int versionBits) {
int bestDifference = Integer.MAX_VALUE;
int bestVersion = 0;
for (int i = 0; i < VERSION_DECODE_INFO.length; i++) {
int targetVersion = VERSION_DECODE_INFO[i];
// Do the version info bits match exactly? done.
if (targetVersion == versionBits) {
return getVersionForNumber(i + 7);
}
// Otherwise see if this is the closest to a real version info bit string
// we have seen so far
int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion);
if (bitsDifference < bestDifference) {
bestVersion = i + 7;
bestDifference = bitsDifference;
}
}
// We can tolerate up to 3 bits of error since no two version info codewords will
// differ in less than 8 bits.
if (bestDifference <= 3) {
return getVersionForNumber(bestVersion);
}
// If we didn't find a close enough match, fail
return null;
}
/**
* See ISO 18004:2006 6.5.1 Table 9
*/
private static Version[] buildVersions() {
return new Version[]{
new Version(1, new int[]{},
new ECBlocks(7, new ECB(1, 19)),
new ECBlocks(10, new ECB(1, 16)),
new ECBlocks(13, new ECB(1, 13)),
new ECBlocks(17, new ECB(1, 9))),
new Version(2, new int[]{6, 18},
new ECBlocks(10, new ECB(1, 34)),
new ECBlocks(16, new ECB(1, 28)),
new ECBlocks(22, new ECB(1, 22)),
new ECBlocks(28, new ECB(1, 16))),
new Version(3, new int[]{6, 22},
new ECBlocks(15, new ECB(1, 55)),
new ECBlocks(26, new ECB(1, 44)),
new ECBlocks(18, new ECB(2, 17)),
new ECBlocks(22, new ECB(2, 13))),
new Version(4, new int[]{6, 26},
new ECBlocks(20, new ECB(1, 80)),
new ECBlocks(18, new ECB(2, 32)),
new ECBlocks(26, new ECB(2, 24)),
new ECBlocks(16, new ECB(4, 9))),
new Version(5, new int[]{6, 30},
new ECBlocks(26, new ECB(1, 108)),
new ECBlocks(24, new ECB(2, 43)),
new ECBlocks(18, new ECB(2, 15),
new ECB(2, 16)),
new ECBlocks(22, new ECB(2, 11),
new ECB(2, 12))),
new Version(6, new int[]{6, 34},
new ECBlocks(18, new ECB(2, 68)),
new ECBlocks(16, new ECB(4, 27)),
new ECBlocks(24, new ECB(4, 19)),
new ECBlocks(28, new ECB(4, 15))),
new Version(7, new int[]{6, 22, 38},
new ECBlocks(20, new ECB(2, 78)),
new ECBlocks(18, new ECB(4, 31)),
new ECBlocks(18, new ECB(2, 14),
new ECB(4, 15)),
new ECBlocks(26, new ECB(4, 13),
new ECB(1, 14))),
new Version(8, new int[]{6, 24, 42},
new ECBlocks(24, new ECB(2, 97)),
new ECBlocks(22, new ECB(2, 38),
new ECB(2, 39)),
new ECBlocks(22, new ECB(4, 18),
new ECB(2, 19)),
new ECBlocks(26, new ECB(4, 14),
new ECB(2, 15))),
new Version(9, new int[]{6, 26, 46},
new ECBlocks(30, new ECB(2, 116)),
new ECBlocks(22, new ECB(3, 36),
new ECB(2, 37)),
new ECBlocks(20, new ECB(4, 16),
new ECB(4, 17)),
new ECBlocks(24, new ECB(4, 12),
new ECB(4, 13))),
new Version(10, new int[]{6, 28, 50},
new ECBlocks(18, new ECB(2, 68),
new ECB(2, 69)),
new ECBlocks(26, new ECB(4, 43),
new ECB(1, 44)),
new ECBlocks(24, new ECB(6, 19),
new ECB(2, 20)),
new ECBlocks(28, new ECB(6, 15),
new ECB(2, 16))),
new Version(11, new int[]{6, 30, 54},
new ECBlocks(20, new ECB(4, 81)),
new ECBlocks(30, new ECB(1, 50),
new ECB(4, 51)),
new ECBlocks(28, new ECB(4, 22),
new ECB(4, 23)),
new ECBlocks(24, new ECB(3, 12),
new ECB(8, 13))),
new Version(12, new int[]{6, 32, 58},
new ECBlocks(24, new ECB(2, 92),
new ECB(2, 93)),
new ECBlocks(22, new ECB(6, 36),
new ECB(2, 37)),
new ECBlocks(26, new ECB(4, 20),
new ECB(6, 21)),
new ECBlocks(28, new ECB(7, 14),
new ECB(4, 15))),
new Version(13, new int[]{6, 34, 62},
new ECBlocks(26, new ECB(4, 107)),
new ECBlocks(22, new ECB(8, 37),
new ECB(1, 38)),
new ECBlocks(24, new ECB(8, 20),
new ECB(4, 21)),
new ECBlocks(22, new ECB(12, 11),
new ECB(4, 12))),
new Version(14, new int[]{6, 26, 46, 66},
new ECBlocks(30, new ECB(3, 115),
new ECB(1, 116)),
new ECBlocks(24, new ECB(4, 40),
new ECB(5, 41)),
new ECBlocks(20, new ECB(11, 16),
new ECB(5, 17)),
new ECBlocks(24, new ECB(11, 12),
new ECB(5, 13))),
new Version(15, new int[]{6, 26, 48, 70},
new ECBlocks(22, new ECB(5, 87),
new ECB(1, 88)),
new ECBlocks(24, new ECB(5, 41),
new ECB(5, 42)),
new ECBlocks(30, new ECB(5, 24),
new ECB(7, 25)),
new ECBlocks(24, new ECB(11, 12),
new ECB(7, 13))),
new Version(16, new int[]{6, 26, 50, 74},
new ECBlocks(24, new ECB(5, 98),
new ECB(1, 99)),
new ECBlocks(28, new ECB(7, 45),
new ECB(3, 46)),
new ECBlocks(24, new ECB(15, 19),
new ECB(2, 20)),
new ECBlocks(30, new ECB(3, 15),
new ECB(13, 16))),
new Version(17, new int[]{6, 30, 54, 78},
new ECBlocks(28, new ECB(1, 107),
new ECB(5, 108)),
new ECBlocks(28, new ECB(10, 46),
new ECB(1, 47)),
new ECBlocks(28, new ECB(1, 22),
new ECB(15, 23)),
new ECBlocks(28, new ECB(2, 14),
new ECB(17, 15))),
new Version(18, new int[]{6, 30, 56, 82},
new ECBlocks(30, new ECB(5, 120),
new ECB(1, 121)),
new ECBlocks(26, new ECB(9, 43),
new ECB(4, 44)),
new ECBlocks(28, new ECB(17, 22),
new ECB(1, 23)),
new ECBlocks(28, new ECB(2, 14),
new ECB(19, 15))),
new Version(19, new int[]{6, 30, 58, 86},
new ECBlocks(28, new ECB(3, 113),
new ECB(4, 114)),
new ECBlocks(26, new ECB(3, 44),
new ECB(11, 45)),
new ECBlocks(26, new ECB(17, 21),
new ECB(4, 22)),
new ECBlocks(26, new ECB(9, 13),
new ECB(16, 14))),
new Version(20, new int[]{6, 34, 62, 90},
new ECBlocks(28, new ECB(3, 107),
new ECB(5, 108)),
new ECBlocks(26, new ECB(3, 41),
new ECB(13, 42)),
new ECBlocks(30, new ECB(15, 24),
new ECB(5, 25)),
new ECBlocks(28, new ECB(15, 15),
new ECB(10, 16))),
new Version(21, new int[]{6, 28, 50, 72, 94},
new ECBlocks(28, new ECB(4, 116),
new ECB(4, 117)),
new ECBlocks(26, new ECB(17, 42)),
new ECBlocks(28, new ECB(17, 22),
new ECB(6, 23)),
new ECBlocks(30, new ECB(19, 16),
new ECB(6, 17))),
new Version(22, new int[]{6, 26, 50, 74, 98},
new ECBlocks(28, new ECB(2, 111),
new ECB(7, 112)),
new ECBlocks(28, new ECB(17, 46)),
new ECBlocks(30, new ECB(7, 24),
new ECB(16, 25)),
new ECBlocks(24, new ECB(34, 13))),
new Version(23, new int[]{6, 30, 54, 78, 102},
new ECBlocks(30, new ECB(4, 121),
new ECB(5, 122)),
new ECBlocks(28, new ECB(4, 47),
new ECB(14, 48)),
new ECBlocks(30, new ECB(11, 24),
new ECB(14, 25)),
new ECBlocks(30, new ECB(16, 15),
new ECB(14, 16))),
new Version(24, new int[]{6, 28, 54, 80, 106},
new ECBlocks(30, new ECB(6, 117),
new ECB(4, 118)),
new ECBlocks(28, new ECB(6, 45),
new ECB(14, 46)),
new ECBlocks(30, new ECB(11, 24),
new ECB(16, 25)),
new ECBlocks(30, new ECB(30, 16),
new ECB(2, 17))),
new Version(25, new int[]{6, 32, 58, 84, 110},
new ECBlocks(26, new ECB(8, 106),
new ECB(4, 107)),
new ECBlocks(28, new ECB(8, 47),
new ECB(13, 48)),
new ECBlocks(30, new ECB(7, 24),
new ECB(22, 25)),
new ECBlocks(30, new ECB(22, 15),
new ECB(13, 16))),
new Version(26, new int[]{6, 30, 58, 86, 114},
new ECBlocks(28, new ECB(10, 114),
new ECB(2, 115)),
new ECBlocks(28, new ECB(19, 46),
new ECB(4, 47)),
new ECBlocks(28, new ECB(28, 22),
new ECB(6, 23)),
new ECBlocks(30, new ECB(33, 16),
new ECB(4, 17))),
new Version(27, new int[]{6, 34, 62, 90, 118},
new ECBlocks(30, new ECB(8, 122),
new ECB(4, 123)),
new ECBlocks(28, new ECB(22, 45),
new ECB(3, 46)),
new ECBlocks(30, new ECB(8, 23),
new ECB(26, 24)),
new ECBlocks(30, new ECB(12, 15),
new ECB(28, 16))),
new Version(28, new int[]{6, 26, 50, 74, 98, 122},
new ECBlocks(30, new ECB(3, 117),
new ECB(10, 118)),
new ECBlocks(28, new ECB(3, 45),
new ECB(23, 46)),
new ECBlocks(30, new ECB(4, 24),
new ECB(31, 25)),
new ECBlocks(30, new ECB(11, 15),
new ECB(31, 16))),
new Version(29, new int[]{6, 30, 54, 78, 102, 126},
new ECBlocks(30, new ECB(7, 116),
new ECB(7, 117)),
new ECBlocks(28, new ECB(21, 45),
new ECB(7, 46)),
new ECBlocks(30, new ECB(1, 23),
new ECB(37, 24)),
new ECBlocks(30, new ECB(19, 15),
new ECB(26, 16))),
new Version(30, new int[]{6, 26, 52, 78, 104, 130},
new ECBlocks(30, new ECB(5, 115),
new ECB(10, 116)),
new ECBlocks(28, new ECB(19, 47),
new ECB(10, 48)),
new ECBlocks(30, new ECB(15, 24),
new ECB(25, 25)),
new ECBlocks(30, new ECB(23, 15),
new ECB(25, 16))),
new Version(31, new int[]{6, 30, 56, 82, 108, 134},
new ECBlocks(30, new ECB(13, 115),
new ECB(3, 116)),
new ECBlocks(28, new ECB(2, 46),
new ECB(29, 47)),
new ECBlocks(30, new ECB(42, 24),
new ECB(1, 25)),
new ECBlocks(30, new ECB(23, 15),
new ECB(28, 16))),
new Version(32, new int[]{6, 34, 60, 86, 112, 138},
new ECBlocks(30, new ECB(17, 115)),
new ECBlocks(28, new ECB(10, 46),
new ECB(23, 47)),
new ECBlocks(30, new ECB(10, 24),
new ECB(35, 25)),
new ECBlocks(30, new ECB(19, 15),
new ECB(35, 16))),
new Version(33, new int[]{6, 30, 58, 86, 114, 142},
new ECBlocks(30, new ECB(17, 115),
new ECB(1, 116)),
new ECBlocks(28, new ECB(14, 46),
new ECB(21, 47)),
new ECBlocks(30, new ECB(29, 24),
new ECB(19, 25)),
new ECBlocks(30, new ECB(11, 15),
new ECB(46, 16))),
new Version(34, new int[]{6, 34, 62, 90, 118, 146},
new ECBlocks(30, new ECB(13, 115),
new ECB(6, 116)),
new ECBlocks(28, new ECB(14, 46),
new ECB(23, 47)),
new ECBlocks(30, new ECB(44, 24),
new ECB(7, 25)),
new ECBlocks(30, new ECB(59, 16),
new ECB(1, 17))),
new Version(35, new int[]{6, 30, 54, 78, 102, 126, 150},
new ECBlocks(30, new ECB(12, 121),
new ECB(7, 122)),
new ECBlocks(28, new ECB(12, 47),
new ECB(26, 48)),
new ECBlocks(30, new ECB(39, 24),
new ECB(14, 25)),
new ECBlocks(30, new ECB(22, 15),
new ECB(41, 16))),
new Version(36, new int[]{6, 24, 50, 76, 102, 128, 154},
new ECBlocks(30, new ECB(6, 121),
new ECB(14, 122)),
new ECBlocks(28, new ECB(6, 47),
new ECB(34, 48)),
new ECBlocks(30, new ECB(46, 24),
new ECB(10, 25)),
new ECBlocks(30, new ECB(2, 15),
new ECB(64, 16))),
new Version(37, new int[]{6, 28, 54, 80, 106, 132, 158},
new ECBlocks(30, new ECB(17, 122),
new ECB(4, 123)),
new ECBlocks(28, new ECB(29, 46),
new ECB(14, 47)),
new ECBlocks(30, new ECB(49, 24),
new ECB(10, 25)),
new ECBlocks(30, new ECB(24, 15),
new ECB(46, 16))),
new Version(38, new int[]{6, 32, 58, 84, 110, 136, 162},
new ECBlocks(30, new ECB(4, 122),
new ECB(18, 123)),
new ECBlocks(28, new ECB(13, 46),
new ECB(32, 47)),
new ECBlocks(30, new ECB(48, 24),
new ECB(14, 25)),
new ECBlocks(30, new ECB(42, 15),
new ECB(32, 16))),
new Version(39, new int[]{6, 26, 54, 82, 110, 138, 166},
new ECBlocks(30, new ECB(20, 117),
new ECB(4, 118)),
new ECBlocks(28, new ECB(40, 47),
new ECB(7, 48)),
new ECBlocks(30, new ECB(43, 24),
new ECB(22, 25)),
new ECBlocks(30, new ECB(10, 15),
new ECB(67, 16))),
new Version(40, new int[]{6, 30, 58, 86, 114, 142, 170},
new ECBlocks(30, new ECB(19, 118),
new ECB(6, 119)),
new ECBlocks(28, new ECB(18, 47),
new ECB(31, 48)),
new ECBlocks(30, new ECB(34, 24),
new ECB(34, 25)),
new ECBlocks(30, new ECB(20, 15),
new ECB(61, 16)))
};
}
public int getVersionNumber() {
return versionNumber;
}
public int[] getAlignmentPatternCenters() {
return alignmentPatternCenters;
}
public int getTotalCodewords() {
return totalCodewords;
}
public int getDimensionForVersion() {
return 17 + 4 * versionNumber;
}
public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) {
return ecBlocks[ecLevel.ordinal()];
}
/**
* See ISO 18004:2006 Annex E
*/
BitMatrix buildFunctionPattern() {
int dimension = getDimensionForVersion();
BitMatrix bitMatrix = new BitMatrix(dimension);
// Top left finder pattern + separator + format
bitMatrix.setRegion(0, 0, 9, 9);
// Top right finder pattern + separator + format
bitMatrix.setRegion(dimension - 8, 0, 8, 9);
// Bottom left finder pattern + separator + format
bitMatrix.setRegion(0, dimension - 8, 9, 8);
// Alignment patterns
int max = alignmentPatternCenters.length;
for (int x = 0; x < max; x++) {
int i = alignmentPatternCenters[x] - 2;
for (int y = 0; y < max; y++) {
if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) {
// No alignment patterns near the three finder patterns
continue;
}
bitMatrix.setRegion(alignmentPatternCenters[y] - 2, i, 5, 5);
}
}
// Vertical timing pattern
bitMatrix.setRegion(6, 9, 1, dimension - 17);
// Horizontal timing pattern
bitMatrix.setRegion(9, 6, dimension - 17, 1);
if (versionNumber > 6) {
// Version info, top right
bitMatrix.setRegion(dimension - 11, 0, 3, 6);
// Version info, bottom left
bitMatrix.setRegion(0, dimension - 11, 6, 3);
}
return bitMatrix;
}
@Override
public String toString() {
return String.valueOf(versionNumber);
}
/**
* <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
* use blocks of differing sizes within one version, so, this encapsulates the parameters for
* each set of blocks. It also holds the number of error-correction codewords per block since it
* will be the same across all blocks within one version.</p>
*/
public static final class ECBlocks {
private final int ecCodewordsPerBlock;
private final ECB[] ecBlocks;
ECBlocks(int ecCodewordsPerBlock, ECB... ecBlocks) {
this.ecCodewordsPerBlock = ecCodewordsPerBlock;
this.ecBlocks = ecBlocks;
}
public int getECCodewordsPerBlock() {
return ecCodewordsPerBlock;
}
public int getNumBlocks() {
int total = 0;
for (ECB ecBlock : ecBlocks) {
total += ecBlock.getCount();
}
return total;
}
public int getTotalECCodewords() {
return ecCodewordsPerBlock * getNumBlocks();
}
public ECB[] getECBlocks() {
return ecBlocks;
}
}
/**
* <p>Encapsulates the parameters for one error-correction block in one symbol version.
* This includes the number of data codewords, and the number of times a block with these
* parameters is used consecutively in the QR code version's format.</p>
*/
public static final class ECB {
private final int count;
private final int dataCodewords;
ECB(int count, int dataCodewords) {
this.count = count;
this.dataCodewords = dataCodewords;
}
public int getCount() {
return count;
}
public int getDataCodewords() {
return dataCodewords;
}
}
}
| 26,279 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FinderPatternInfo.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/FinderPatternInfo.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>Encapsulates information about finder patterns in an image, including the location of
* the three finder patterns, and their estimated module size.</p>
*
* @author Sean Owen
*/
public final class FinderPatternInfo {
private final FinderPattern bottomLeft;
private final FinderPattern bottomRight;
private final FinderPattern topLeft;
private final FinderPattern topRight;
//private final int code;
public FinderPatternInfo(FinderPattern[] patternCenters) {
this.topLeft = patternCenters[0];
this.topRight = patternCenters[1];
this.bottomLeft = patternCenters[2];
this.bottomRight = patternCenters[3];
}
public FinderPattern getBottomLeft() {
return bottomLeft;
}
public FinderPattern getTopLeft() {
return topLeft;
}
public FinderPattern getTopRight() {
return topRight;
}
public FinderPattern getBottomRight() {
return bottomRight;
}
}
| 1,638 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ReaderException.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/ReaderException.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* The general exception class throw when something goes wrong during decoding of a barcode.
* This includes, but is not limited to, failing checksums / error correction algorithms, being
* unable to locate finder timing patterns, and so on.
*
* @author Sean Owen
*/
public abstract class ReaderException extends Exception {
// disable stack traces when not running inside test units
protected static final boolean isStackTrace =
System.getProperty("surefire.test.class.path") != null;
protected static final StackTraceElement[] NO_TRACE = new StackTraceElement[0];
ReaderException() {
// do nothing
}
ReaderException(Throwable cause) {
super(cause);
}
// Prevent stack traces from being taken
// author says: huh, my IDE is saying this is not an override. native methods can't be overridden?
// This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow.
@Override
public final Throwable fillInStackTrace() {
return null;
}
}
| 1,723 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AlignmentPattern.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/AlignmentPattern.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
* all but the simplest QR Codes.</p>
*
* @author Sean Owen
*/
public final class AlignmentPattern extends ResultPoint {
private final float estimatedModuleSize;
AlignmentPattern(float posX, float posY, float estimatedModuleSize) {
super(posX, posY);
this.estimatedModuleSize = estimatedModuleSize;
}
/**
* <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/
boolean aboutEquals(float moduleSize, float i, float j) {
if (Math.abs(i - getY()) <= moduleSize && Math.abs(j - getX()) <= moduleSize) {
float moduleSizeDiff = Math.abs(moduleSize - estimatedModuleSize);
return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize;
}
return false;
}
/**
* Combines this object's current estimate of a finder pattern position and module size
* with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
*/
AlignmentPattern combineEstimate(float i, float j, float newModuleSize) {
float combinedX = (getX() + j) / 2.0f;
float combinedY = (getY() + i) / 2.0f;
float combinedModuleSize = (estimatedModuleSize + newModuleSize) / 2.0f;
return new AlignmentPattern(combinedX, combinedY, combinedModuleSize);
}
} | 2,198 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BitMatrix.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/BitMatrix.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
import java.util.Arrays;
/**
* <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common
* module, x is the column position, and y is the row position. The ordering is always x, y.
* The origin is at the top-left.</p>
* <p>
* <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins
* with a new int. This is done intentionally so that we can copy out a row into a BitArray very
* efficiently.</p>
* <p>
* <p>The ordering of bits is row-major. Within each int, the least significant bits are used first,
* meaning they represent lower x values. This is compatible with BitArray's implementation.</p>
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class BitMatrix implements Cloneable {
private final int width;
private final int height;
private final int rowSize;
private final int[] bits;
// A helper to construct a square matrix.
public BitMatrix(int dimension) {
this(dimension, dimension);
}
public BitMatrix(int width, int height) {
if (width < 1 || height < 1) {
throw new IllegalArgumentException("Both dimensions must be greater than 0");
}
this.width = width;
this.height = height;
this.rowSize = (width + 31) / 32;
bits = new int[rowSize * height];
}
private BitMatrix(int width, int height, int rowSize, int[] bits) {
this.width = width;
this.height = height;
this.rowSize = rowSize;
this.bits = bits;
}
public static BitMatrix parse(String stringRepresentation, String setString, String unsetString) {
if (stringRepresentation == null) {
throw new IllegalArgumentException();
}
boolean[] bits = new boolean[stringRepresentation.length()];
int bitsPos = 0;
int rowStartPos = 0;
int rowLength = -1;
int nRows = 0;
int pos = 0;
while (pos < stringRepresentation.length()) {
if (stringRepresentation.charAt(pos) == '\n' ||
stringRepresentation.charAt(pos) == '\r') {
if (bitsPos > rowStartPos) {
if (rowLength == -1) {
rowLength = bitsPos - rowStartPos;
} else if (bitsPos - rowStartPos != rowLength) {
throw new IllegalArgumentException("row lengths do not match");
}
rowStartPos = bitsPos;
nRows++;
}
pos++;
} else if (stringRepresentation.substring(pos, pos + setString.length()).equals(setString)) {
pos += setString.length();
bits[bitsPos] = true;
bitsPos++;
} else if (stringRepresentation.substring(pos, pos + unsetString.length()).equals(unsetString)) {
pos += unsetString.length();
bits[bitsPos] = false;
bitsPos++;
} else {
throw new IllegalArgumentException(
"illegal character encountered: " + stringRepresentation.substring(pos));
}
}
// no EOL at end?
if (bitsPos > rowStartPos) {
if (rowLength == -1) {
rowLength = bitsPos - rowStartPos;
} else if (bitsPos - rowStartPos != rowLength) {
throw new IllegalArgumentException("row lengths do not match");
}
nRows++;
}
BitMatrix matrix = new BitMatrix(rowLength, nRows);
for (int i = 0; i < bitsPos; i++) {
if (bits[i]) {
matrix.set(i % rowLength, i / rowLength);
}
}
return matrix;
}
/**
* <p>Gets the requested bit, where true means black.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
* @return value of given bit in matrix
*/
public boolean get(int x, int y) {
int offset = y * rowSize + (x >> 5); /* divides by 32 */
return ((bits[offset] >>> (x & 0x1f)) & 1) != 0;
}
/**
* <p>Sets the given bit to true.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/
public void set(int x, int y) {
int offset = y * rowSize + (x >> 5); /* divides by 32 */
bits[offset] |= 1 << (x & 0x1f);
}
public void unset(int x, int y) {
int offset = y * rowSize + (x >> 5); /* divides by 32 */
bits[offset] &= ~(1 << (x & 0x1f));
}
/**
* <p>Flips the given bit.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/
public void flip(int x, int y) {
int offset = y * rowSize + (x / 32);
bits[offset] ^= 1 << (x & 0x1f);
}
/**
* Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
* mask bit is set.
*
* @param mask XOR mask
*/
public void xor(BitMatrix mask) {
if (width != mask.getWidth() || height != mask.getHeight()
|| rowSize != mask.getRowSize()) {
throw new IllegalArgumentException("input matrix dimensions do not match");
}
BitArray rowArray = new BitArray(width / 32 + 1);
for (int y = 0; y < height; y++) {
int offset = y * rowSize;
int[] row = mask.getRow(y, rowArray).getBitArray();
for (int x = 0; x < rowSize; x++) {
bits[offset + x] ^= row[x];
}
}
}
/**
* Clears all bits (sets to false).
*/
public void clear() {
int max = bits.length;
for (int i = 0; i < max; i++) {
bits[i] = 0;
}
}
/**
* <p>Sets a square region of the bit matrix to true.</p>
*
* @param left The horizontal position to begin at (inclusive)
* @param top The vertical position to begin at (inclusive)
* @param width The width of the region
* @param height The height of the region
*/
public void setRegion(int left, int top, int width, int height) {
if (top < 0 || left < 0) {
throw new IllegalArgumentException("Left and top must be non-negative");
}
if (height < 1 || width < 1) {
throw new IllegalArgumentException("Height and width must be at least 1");
}
int right = left + width;
int bottom = top + height;
if (bottom > this.height || right > this.width) {
throw new IllegalArgumentException("The region must fit inside the matrix");
}
for (int y = top; y < bottom; y++) {
int offset = y * rowSize;
for (int x = left; x < right; x++) {
bits[offset + (x / 32)] |= 1 << (x & 0x1f);
}
}
}
/**
* A fast method to retrieve one row of data from the matrix as a BitArray.
*
* @param y The row to retrieve
* @param row An optional caller-allocated BitArray, will be allocated if null or too small
* @return The resulting BitArray - this reference should always be used even when passing
* your own row
*/
public BitArray getRow(int y, BitArray row) {
if (row == null || row.getSize() < width) {
row = new BitArray(width);
} else {
row.clear();
}
int offset = y * rowSize;
for (int x = 0; x < rowSize; x++) {
row.setBulk(x * 32, bits[offset + x]);
}
return row;
}
/**
* @param y row to set
* @param row {@link BitArray} to copy from
*/
public void setRow(int y, BitArray row) {
System.arraycopy(row.getBitArray(), 0, bits, y * rowSize, rowSize);
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
*/
public void rotate180() {
int width = getWidth();
int height = getHeight();
BitArray topRow = new BitArray(width);
BitArray bottomRow = new BitArray(width);
for (int i = 0; i < (height + 1) / 2; i++) {
topRow = getRow(i, topRow);
bottomRow = getRow(height - 1 - i, bottomRow);
topRow.reverse();
bottomRow.reverse();
setRow(i, bottomRow);
setRow(height - 1 - i, topRow);
}
}
/**
* This is useful in detecting the enclosing rectangle of a 'pure' barcode.
*
* @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white
*/
public int[] getEnclosingRectangle() {
int left = width;
int top = height;
int right = -1;
int bottom = -1;
for (int y = 0; y < height; y++) {
for (int x32 = 0; x32 < rowSize; x32++) {
int theBits = bits[y * rowSize + x32];
if (theBits != 0) {
if (y < top) {
top = y;
}
if (y > bottom) {
bottom = y;
}
if (x32 * 32 < left) {
int bit = 0;
while ((theBits << (31 - bit)) == 0) {
bit++;
}
if ((x32 * 32 + bit) < left) {
left = x32 * 32 + bit;
}
}
if (x32 * 32 + 31 > right) {
int bit = 31;
while ((theBits >>> bit) == 0) {
bit--;
}
if ((x32 * 32 + bit) > right) {
right = x32 * 32 + bit;
}
}
}
}
}
int width = right - left;
int height = bottom - top;
if (width < 0 || height < 0) {
return null;
}
return new int[]{left, top, width, height};
}
/**
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white
*/
public int[] getTopLeftOnBit() {
int bitsOffset = 0;
while (bitsOffset < bits.length && bits[bitsOffset] == 0) {
bitsOffset++;
}
if (bitsOffset == bits.length) {
return null;
}
int y = bitsOffset / rowSize;
int x = (bitsOffset % rowSize) * 32;
int theBits = bits[bitsOffset];
int bit = 0;
while ((theBits << (31 - bit)) == 0) {
bit++;
}
x += bit;
return new int[]{x, y};
}
public int[] getBottomRightOnBit() {
int bitsOffset = bits.length - 1;
while (bitsOffset >= 0 && bits[bitsOffset] == 0) {
bitsOffset--;
}
if (bitsOffset < 0) {
return null;
}
int y = bitsOffset / rowSize;
int x = (bitsOffset % rowSize) * 32;
int theBits = bits[bitsOffset];
int bit = 31;
while ((theBits >>> bit) == 0) {
bit--;
}
x += bit;
return new int[]{x, y};
}
/**
* @return The width of the matrix
*/
public int getWidth() {
return width;
}
/**
* @return The height of the matrix
*/
public int getHeight() {
return height;
}
/**
* @return The row size of the matrix
*/
public int getRowSize() {
return rowSize;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BitMatrix)) {
return false;
}
BitMatrix other = (BitMatrix) o;
return width == other.width && height == other.height && rowSize == other.rowSize &&
Arrays.equals(bits, other.bits);
}
@Override
public int hashCode() {
int hash = width;
hash = 31 * hash + width;
hash = 31 * hash + height;
hash = 31 * hash + rowSize;
hash = 31 * hash + Arrays.hashCode(bits);
return hash;
}
/**
* @return string representation using "X" for set and " " for unset bits
*/
@Override
public String toString() {
return toString("X ", " ");
}
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @return string representation of entire matrix utilizing given strings
*/
public String toString(String setString, String unsetString) {
return toString(setString, unsetString, "\n");
}
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @param lineSeparator newline character in string representation
* @return string representation of entire matrix utilizing given strings and line separator
* @deprecated call {@link #toString(String, String)} only, which uses \n line separator always
*/
@Deprecated
public String toString(String setString, String unsetString, String lineSeparator) {
StringBuilder result = new StringBuilder(height * (width + 1));
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
result.append(get(x, y) ? setString : unsetString);
}
result.append(lineSeparator);
}
return result.toString();
}
@Override
public BitMatrix clone() {
return new BitMatrix(width, height, rowSize, bits.clone());
}
}
| 14,556 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FinderPattern.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/FinderPattern.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>Encapsulates a finder pattern, which are the three square patterns found in
* the corners of QR Codes. It also encapsulates a count of similar finder patterns,
* as a convenience to the finder's bookkeeping.</p>
*
* @author Sean Owen
*/
public final class FinderPattern extends ResultPoint {
private final float estimatedModuleSize;
private final int count;
FinderPattern(float posX, float posY, float estimatedModuleSize) {
this(posX, posY, estimatedModuleSize, 1);
}
private FinderPattern(float posX, float posY, float estimatedModuleSize, int count) {
super(posX, posY);
this.estimatedModuleSize = estimatedModuleSize;
this.count = count;
}
public float getEstimatedModuleSize() {
return estimatedModuleSize;
}
int getCount() {
return count;
}
/*
void incrementCount() {
this.count++;
}
*/
/**
* <p>Determines if this finder pattern "about equals" a finder pattern at the stated
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/
boolean aboutEquals(float moduleSize, float i, float j) {
if (Math.abs(i - getY()) <= moduleSize && Math.abs(j - getX()) <= moduleSize) {
float moduleSizeDiff = Math.abs(moduleSize - estimatedModuleSize);
return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize;
}
return false;
}
/**
* Combines this object's current estimate of a finder pattern position and module size
* with a new estimate. It returns a new {@code FinderPattern} containing a weighted average
* based on count.
*/
FinderPattern combineEstimate(float i, float j, float newModuleSize) {
int combinedCount = count + 1;
float combinedX = (count * getX() + j) / combinedCount;
float combinedY = (count * getY() + i) / combinedCount;
float combinedModuleSize = (count * estimatedModuleSize + newModuleSize) / combinedCount;
return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount);
}
}
| 2,799 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AlignmentPatternFinder.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/AlignmentPatternFinder.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
import java.util.ArrayList;
import java.util.List;
/**
* <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
* patterns but are smaller and appear at regular intervals throughout the image.</p>
* <p>
* <p>At the moment this only looks for the bottom-right alignment pattern.</p>
* <p>
* <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
* pasted and stripped down here for maximum performance but does unfortunately duplicate
* some code.</p>
* <p>
* <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
*
* @author Sean Owen
*/
final class AlignmentPatternFinder {
private final BitMatrix image;
private final List<AlignmentPattern> possibleCenters;
private final int startX;
private final int startY;
private final int width;
private final int height;
private final float moduleSize;
private final int[] crossCheckStateCount;
private final ResultPointCallback resultPointCallback;
/**
* <p>Creates a finder that will look in a portion of the whole image.</p>
*
* @param image image to search
* @param startX left column from which to qualityChecksOK searching
* @param startY top row from which to qualityChecksOK searching
* @param width width of region to search
* @param height height of region to search
* @param moduleSize estimated module size so far
*/
AlignmentPatternFinder(BitMatrix image,
int startX,
int startY,
int width,
int height,
float moduleSize,
ResultPointCallback resultPointCallback) {
this.image = image;
this.possibleCenters = new ArrayList<>(5);
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
this.moduleSize = moduleSize;
this.crossCheckStateCount = new int[3];
this.resultPointCallback = resultPointCallback;
}
/**
* Given a count of black/white/black pixels just seen and an end position,
* figures the location of the center of this black/white/black run.
*/
private static float centerFromEnd(int[] stateCount, int end) {
return (float) (end - stateCount[2]) - stateCount[1] / 2.0f;
}
/**
* <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
* it's pretty performance-critical and so is written to be fast foremost.</p>
*
* @return {@link AlignmentPattern} if found
* @throws NotFoundException if not found
*/
AlignmentPattern find() throws NotFoundException {
int startX = this.startX;
int height = this.height;
int maxJ = startX + width;
int middleI = startY + (height / 2);
// We are looking for black/white/black modules in 1:1:1 ratio;
// this tracks the number of black/white/black modules seen so far
int[] stateCount = new int[3];
for (int iGen = 0; iGen < height; iGen++) {
// Search from middle outwards
int i = middleI + ((iGen & 0x01) == 0 ? (iGen + 1) / 2 : -((iGen + 1) / 2));
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
int j = startX;
// Burn off leading white pixels before anything else; if we qualityChecksOK in the middle of
// a white run, it doesn't make sense to count its length, since we don't know if the
// white run continued to the left of the qualityChecksOK point
while (j < maxJ && !image.get(j, i)) {
j++;
}
int currentState = 0;
while (j < maxJ) {
if (image.get(j, i)) {
// Black pixel
if (currentState == 1) { // Counting black pixels
stateCount[currentState]++;
} else { // Counting white pixels
if (currentState == 2) { // A winner?
if (foundPatternCross(stateCount)) { // Yes
AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);
if (confirmed != null) {
return confirmed;
}
}
stateCount[0] = stateCount[2];
stateCount[1] = 1;
stateCount[2] = 0;
currentState = 1;
} else {
stateCount[++currentState]++;
}
}
} else { // White pixel
if (currentState == 1) { // Counting black pixels
currentState++;
}
stateCount[currentState]++;
}
j++;
}
if (foundPatternCross(stateCount)) {
AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ);
if (confirmed != null) {
return confirmed;
}
}
}
// Hmm, nothing we saw was observed and confirmed twice. If we had
// any guess at all, return it.
if (!possibleCenters.isEmpty()) {
return possibleCenters.get(0);
}
throw NotFoundException.getNotFoundInstance();
}
/**
* @param stateCount count of black/white/black pixels just read
* @return true iff the proportions of the counts is close enough to the 1/1/1 ratios
* used by alignment patterns to be considered a match
*/
private boolean foundPatternCross(int[] stateCount) {
float moduleSize = this.moduleSize;
float maxVariance = moduleSize / 2.0f;
for (int i = 0; i < 3; i++) {
if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) {
return false;
}
}
return true;
}
/**
* <p>After a horizontal scan finds a potential alignment pattern, this method
* "cross-checks" by scanning down vertically through the center of the possible
* alignment pattern to see if the same proportion is detected.</p>
*
* @param startI row where an alignment pattern was detected
* @param centerJ center of the section that appears to cross an alignment pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @return vertical center of alignment pattern, or {@link Float#NaN} if not found
*/
private float crossCheckVertical(int startI, int centerJ, int maxCount,
int originalStateCountTotal) {
BitMatrix image = this.image;
int maxI = image.getHeight();
int[] stateCount = crossCheckStateCount;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
// Start counting up from center
int i = startI;
while (i >= 0 && image.get(centerJ, i) && stateCount[1] <= maxCount) {
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount) {
return Float.NaN;
}
while (i >= 0 && !image.get(centerJ, i) && stateCount[0] <= maxCount) {
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image.get(centerJ, i) && stateCount[1] <= maxCount) {
stateCount[1]++;
i++;
}
if (i == maxI || stateCount[1] > maxCount) {
return Float.NaN;
}
while (i < maxI && !image.get(centerJ, i) && stateCount[2] <= maxCount) {
stateCount[2]++;
i++;
}
if (stateCount[2] > maxCount) {
return Float.NaN;
}
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
return Float.NaN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;
}
/**
* <p>This is called when a horizontal scan finds a possible alignment pattern. It will
* cross check with a vertical scan, and if successful, will see if this pattern had been
* found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
* found the alignment pattern.</p>
*
* @param stateCount reading state module counts from horizontal scan
* @param i row where alignment pattern may be found
* @param j end of possible alignment pattern in row
* @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not
*/
private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) {
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
float centerJ = centerFromEnd(stateCount, j);
float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal);
if (!Float.isNaN(centerI)) {
float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;
for (AlignmentPattern center : possibleCenters) {
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
return center.combineEstimate(centerI, centerJ, estimatedModuleSize);
}
}
// Hadn't found this before; save it
AlignmentPattern point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
possibleCenters.add(point);
if (resultPointCallback != null) {
resultPointCallback.foundPossibleResultPoint(point);
}
}
return null;
}
}
| 11,185 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BitArray.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/BitArray.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
import java.util.Arrays;
/**
* <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
*
* @author Sean Owen
*/
public final class BitArray implements Cloneable {
private int[] bits;
private int size;
public BitArray() {
this.size = 0;
this.bits = new int[1];
}
public BitArray(int size) {
this.size = size;
this.bits = makeArray(size);
}
// For testing only
BitArray(int[] bits, int size) {
this.bits = bits;
this.size = size;
}
private static int[] makeArray(int size) {
return new int[(size + 31) / 32];
}
public int getSize() {
return size;
}
public int getSizeInBytes() {
return (size + 7) / 8;
}
private void ensureCapacity(int size) {
if (size > bits.length * 32) {
int[] newBits = makeArray(size);
System.arraycopy(bits, 0, newBits, 0, bits.length);
this.bits = newBits;
}
}
/**
* @param i bit to get
* @return true iff bit i is set
*/
public boolean get(int i) {
return (bits[i / 32] & (1 << (i & 0x1F))) != 0;
}
/**
* Sets bit i.
*
* @param i bit to set
*/
public void set(int i) {
bits[i / 32] |= 1 << (i & 0x1F);
}
/**
* Flips bit i.
*
* @param i bit to set
*/
public void flip(int i) {
bits[i / 32] ^= 1 << (i & 0x1F);
}
/**
* @param from first bit to check
* @return index of first bit that is set, starting from the given index, or size if none are set
* at or beyond this given index
* @see #getNextUnset(int)
*/
public int getNextSet(int from) {
if (from >= size) {
return size;
}
int bitsOffset = from / 32;
int currentBits = bits[bitsOffset];
// mask off lesser bits first
currentBits &= ~((1 << (from & 0x1F)) - 1);
while (currentBits == 0) {
if (++bitsOffset == bits.length) {
return size;
}
currentBits = bits[bitsOffset];
}
int result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);
return result > size ? size : result;
}
/**
* @param from index to qualityChecksOK looking for unset bit
* @return index of next unset bit, or {@code size} if none are unset until the end
* @see #getNextSet(int)
*/
public int getNextUnset(int from) {
if (from >= size) {
return size;
}
int bitsOffset = from / 32;
int currentBits = ~bits[bitsOffset];
// mask off lesser bits first
currentBits &= ~((1 << (from & 0x1F)) - 1);
while (currentBits == 0) {
if (++bitsOffset == bits.length) {
return size;
}
currentBits = ~bits[bitsOffset];
}
int result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);
return result > size ? size : result;
}
/**
* Sets a block of 32 bits, starting at bit i.
*
* @param i first bit to set
* @param newBits the new value of the next 32 bits. Note again that the least-significant bit
* corresponds to bit i, the next-least-significant to i+1, and so on.
*/
public void setBulk(int i, int newBits) {
bits[i / 32] = newBits;
}
/**
* Sets a range of bits.
*
* @param start qualityChecksOK of range, inclusive.
* @param end end of range, exclusive
*/
public void setRange(int start, int end) {
if (end < start) {
throw new IllegalArgumentException();
}
if (end == start) {
return;
}
end--; // will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start / 32;
int lastInt = end / 32;
for (int i = firstInt; i <= lastInt; i++) {
int firstBit = i > firstInt ? 0 : start & 0x1F;
int lastBit = i < lastInt ? 31 : end & 0x1F;
int mask;
if (firstBit == 0 && lastBit == 31) {
mask = -1;
} else {
mask = 0;
for (int j = firstBit; j <= lastBit; j++) {
mask |= 1 << j;
}
}
bits[i] |= mask;
}
}
/**
* Clears all bits (sets to false).
*/
public void clear() {
int max = bits.length;
for (int i = 0; i < max; i++) {
bits[i] = 0;
}
}
/**
* Efficient method to check if a range of bits is set, or not set.
*
* @param start qualityChecksOK of range, inclusive.
* @param end end of range, exclusive
* @param value if true, checks that bits in range are set, otherwise checks that they are not set
* @return true iff all bits are set or not set in range, according to value argument
* @throws IllegalArgumentException if end is less than or equal to qualityChecksOK
*/
public boolean isRange(int start, int end, boolean value) {
if (end < start) {
throw new IllegalArgumentException();
}
if (end == start) {
return true; // empty range matches
}
end--; // will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start / 32;
int lastInt = end / 32;
for (int i = firstInt; i <= lastInt; i++) {
int firstBit = i > firstInt ? 0 : start & 0x1F;
int lastBit = i < lastInt ? 31 : end & 0x1F;
int mask;
if (firstBit == 0 && lastBit == 31) {
mask = -1;
} else {
mask = 0;
for (int j = firstBit; j <= lastBit; j++) {
mask |= 1 << j;
}
}
// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
// equals the mask, or we're looking for 0s and the masked portion is not all 0s
if ((bits[i] & mask) != (value ? mask : 0)) {
return false;
}
}
return true;
}
public void appendBit(boolean bit) {
ensureCapacity(size + 1);
if (bit) {
bits[size / 32] |= 1 << (size & 0x1F);
}
size++;
}
/**
* Appends the least-significant bits, from value, in order from most-significant to
* least-significant. For example, appending 6 bits from 0x000001E will append the bits
* 0, 1, 1, 1, 1, 0 in that order.
*
* @param value {@code int} containing bits to append
* @param numBits bits from value to append
*/
public void appendBits(int value, int numBits) {
if (numBits < 0 || numBits > 32) {
throw new IllegalArgumentException("Num bits must be between 0 and 32");
}
ensureCapacity(size + numBits);
for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) {
appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1);
}
}
public void appendBitArray(BitArray other) {
int otherSize = other.size;
ensureCapacity(size + otherSize);
for (int i = 0; i < otherSize; i++) {
appendBit(other.get(i));
}
}
public void xor(BitArray other) {
if (bits.length != other.bits.length) {
throw new IllegalArgumentException("Sizes don't match");
}
for (int i = 0; i < bits.length; i++) {
// The last byte could be incomplete (i.e. not have 8 bits in
// it) but there is no problem since 0 XOR 0 == 0.
bits[i] ^= other.bits[i];
}
}
/**
* @param bitOffset first bit to qualityChecksOK writing
* @param array array to write into. Bytes are written most-significant byte first. This is the opposite
* of the internal representation, which is exposed by {@link #getBitArray()}
* @param offset position in array to qualityChecksOK writing
* @param numBytes how many bytes to write
*/
public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) {
for (int i = 0; i < numBytes; i++) {
int theByte = 0;
for (int j = 0; j < 8; j++) {
if (get(bitOffset)) {
theByte |= 1 << (7 - j);
}
bitOffset++;
}
array[offset + i] = (byte) theByte;
}
}
/**
* @return underlying array of ints. The first element holds the first 32 bits, and the least
* significant bit is bit 0.
*/
public int[] getBitArray() {
return bits;
}
/**
* Reverses all bits in the array.
*/
public void reverse() {
int[] newBits = new int[bits.length];
// reverse all int's first
int len = ((size - 1) / 32);
int oldBitsLen = len + 1;
for (int i = 0; i < oldBitsLen; i++) {
long x = (long) bits[i];
x = ((x >> 1) & 0x55555555L) | ((x & 0x55555555L) << 1);
x = ((x >> 2) & 0x33333333L) | ((x & 0x33333333L) << 2);
x = ((x >> 4) & 0x0f0f0f0fL) | ((x & 0x0f0f0f0fL) << 4);
x = ((x >> 8) & 0x00ff00ffL) | ((x & 0x00ff00ffL) << 8);
x = ((x >> 16) & 0x0000ffffL) | ((x & 0x0000ffffL) << 16);
newBits[len - i] = (int) x;
}
// now correct the int's if the bit size isn't a multiple of 32
if (size != oldBitsLen * 32) {
int leftOffset = oldBitsLen * 32 - size;
int mask = 1;
for (int i = 0; i < 31 - leftOffset; i++) {
mask = (mask << 1) | 1;
}
int currentInt = (newBits[0] >> leftOffset) & mask;
for (int i = 1; i < oldBitsLen; i++) {
int nextInt = newBits[i];
currentInt |= nextInt << (32 - leftOffset);
newBits[i - 1] = currentInt;
currentInt = (nextInt >> leftOffset) & mask;
}
newBits[oldBitsLen - 1] = currentInt;
}
bits = newBits;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BitArray)) {
return false;
}
BitArray other = (BitArray) o;
return size == other.size && Arrays.equals(bits, other.bits);
}
@Override
public int hashCode() {
return 31 * size + Arrays.hashCode(bits);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(size);
for (int i = 0; i < size; i++) {
if ((i & 0x07) == 0) {
result.append(' ');
}
result.append(get(i) ? 'X' : '.');
}
return result.toString();
}
@Override
public BitArray clone() {
return new BitArray(bits.clone(), size);
}
} | 11,752 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FinderPatternFinder.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/FinderPatternFinder.java | /*
* Copyright 2007 ZXing authors
*
* 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 org.akvo.caddisfly.sensor.striptest.qrdetector;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
* markers at three corners of a QR Code.</p>
* <p>
* <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
*
* @author Sean Owen
*/
public class FinderPatternFinder {
private static final int CENTER_QUORUM = 2;
private static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
private static final int MAX_MODULES = 143; // this is the height of our calibration card (rotated because of the portrait view), so actually the width.
private final BitMatrix image;
private final List<FinderPattern> possibleCenters;
private final int[] crossCheckStateCount;
private final ResultPointCallback resultPointCallback;
private boolean hasSkipped;
/**
* <p>Creates a finder that will search the image for three finder patterns.</p>
*
* @param image image to search
*/
public FinderPatternFinder(BitMatrix image) {
this(image, null);
}
public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) {
this.image = image;
this.possibleCenters = new ArrayList<>();
this.crossCheckStateCount = new int[5];
this.resultPointCallback = resultPointCallback;
}
/**
* Given a count of black/white/black/white/black pixels just seen and an end position,
* figures the location of the center of this run.
*/
private static float centerFromEnd(int[] stateCount, int end) {
return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
}
/**
* @param stateCount count of black/white/black/white/black pixels just read
* @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
* used by finder patterns to be considered a match
*/
private static boolean foundPatternCross(int[] stateCount) {
int totalModuleSize = 0;
for (int i = 0; i < 5; i++) {
int count = stateCount[i];
if (count == 0) {
return false;
}
totalModuleSize += count;
}
if (totalModuleSize < 7) {
return false;
}
float moduleSize = totalModuleSize / 7.0f;
float maxVariance = moduleSize / 1.7f;
// Allow less than 50% variance from 1-1-3-1-1 proportions
return
Math.abs(moduleSize - stateCount[0]) < maxVariance &&
Math.abs(moduleSize - stateCount[1]) < maxVariance &&
Math.abs(3.0f * moduleSize - stateCount[2]) < 3 * maxVariance &&
Math.abs(moduleSize - stateCount[3]) < maxVariance &&
Math.abs(moduleSize - stateCount[4]) < maxVariance;
}
protected final BitMatrix getImage() {
return image;
}
public final List<FinderPattern> getPossibleCenters() {
return possibleCenters;
}
/* Find finder patterns
* The image we have is higher than it is wide, and contains the calibration card rotated:
* ----------
*|o o|
*| |
*| |
*| |
*| |
*| |
*|o________o|
* It contains 4 finder patterns
*/
public final FinderPatternInfo find(Map<DecodeHintType, ?> hints) throws NotFoundException {
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
boolean pureBarcode = hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE);
int maxI = image.getHeight();
int maxJ = image.getWidth();
// We are looking for black/white/black/white/black modules in
// 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
// Let's assume that the maximum version QR Code we support takes up 3/4 the height of the
// image, and then account for the center being 3 modules in size. This gives the smallest
// number of pixels the center could be, so skip this often at the start. When trying harder, look for all
// QR versions regardless of how dense they are.
// states:
// 0: in outer black
// 1: in first inner white
// 2: inside center
// 3: in second inner white
int iSkip = 2;
boolean done = false;
int[] stateCount = new int[5];
for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {
// Get a row of black/white values
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
stateCount[3] = 0;
stateCount[4] = 0;
int currentState = 0;
for (int j = 0; j < maxJ; j++) {
if (image.get(j, i)) { // true means black
// Black pixel
if ((currentState & 1) == 1) { // Selects 1,3: We were counting white pixels
// go to the next state: switch from counting white to counting black
currentState++;
}
stateCount[currentState]++;
} else { // White pixel
if ((currentState & 1) == 0) { // selects 0,2,4: We are counting black pixels. The else clause simply increases the number of white pixels in this run
if (currentState == 4) { // We have just switched from counting black to counting white, while in the second outer black. Is this a winner?
if (foundPatternCross(stateCount)) { // The rations check out, so it looks like a winner. Scan again to make sure
boolean confirmed = handlePossibleCenter(stateCount, i, j, pureBarcode);
if (confirmed) { // it most definitely is a winner
// Start examining every other line. Checking each line turned out to be too
// expensive and didn't improve performance.
iSkip = 2;
// hasSkipped can be set to true if we already have found two finder patterns.
// this can happen only in findRowSkip(), and it means that we have applied a skip already
if (hasSkipped) {
// done becomes true if we have found 4 finder patterns. In that case, we will break out of the row loop the next time around.
done = haveMultiplyConfirmedCenters();
} else {
// see how far we skip. the previous test guarantees we only do it once
int rowSkip = findRowSkip();
// if the rowSkip is larger than the size of the center, apply the rowSkip
if (rowSkip > stateCount[2]) {
// Skip rows between row of lower confirmed center
// and top of presumed third confirmed center
// but back up a bit to get a full chance of detecting
// it, entire width of center of finder pattern
// Skip by rowSkip, but back off by stateCount[2] (size of last center
// of pattern we saw) to be conservative, and also back off by iSkip which
// is about to be re-added
i += rowSkip - stateCount[2] - iSkip;
j = maxJ - 1;
}
}
} else {
stateCount[0] = stateCount[2];
stateCount[1] = stateCount[3];
stateCount[2] = stateCount[4];
stateCount[3] = 1;
stateCount[4] = 0;
currentState = 3;
continue;
}
// Clear state to qualityChecksOK looking again
currentState = 0;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
stateCount[3] = 0;
stateCount[4] = 0;
} else { // No, shift counts back by two
stateCount[0] = stateCount[2];
stateCount[1] = stateCount[3];
stateCount[2] = stateCount[4];
stateCount[3] = 1;
stateCount[4] = 0;
currentState = 3;
}
} else {
stateCount[++currentState]++;
}
} else { // Counting white pixels
stateCount[currentState]++;
}
}
}
if (foundPatternCross(stateCount)) {
boolean confirmed = handlePossibleCenter(stateCount, i, maxJ, pureBarcode);
if (confirmed) {
iSkip = stateCount[0];
if (hasSkipped) {
// Found a third one
done = haveMultiplyConfirmedCenters();
}
}
}
}
// selectBestPatterns also orders the patterns in top left, top right, bottom left, bottom right.
FinderPattern[] patternInfo = selectBestPatterns();
return new FinderPatternInfo(patternInfo);
}
private int[] getCrossCheckStateCount() {
crossCheckStateCount[0] = 0;
crossCheckStateCount[1] = 0;
crossCheckStateCount[2] = 0;
crossCheckStateCount[3] = 0;
crossCheckStateCount[4] = 0;
return crossCheckStateCount;
}
/**
* After a vertical and horizontal scan finds a potential finder pattern, this method
* "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
* finder pattern to see if the same proportion is detected.
*
* @param startI row where a finder pattern was detected
* @param centerJ center of the section that appears to cross a finder pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @param originalStateCountTotal The original state count total.
* @return true if proportions are withing expected limits
*/
private boolean crossCheckDiagonal(int startI, int centerJ, int maxCount, int originalStateCountTotal) {
int[] stateCount = getCrossCheckStateCount();
// Start counting up, left from center finding black center mass
int i = 0;
while (startI >= i && centerJ >= i && image.get(centerJ - i, startI - i)) {
stateCount[2]++;
i++;
}
if (startI < i || centerJ < i) {
return false;
}
// Continue up, left finding white space
while (startI >= i && centerJ >= i && !image.get(centerJ - i, startI - i) &&
stateCount[1] <= maxCount) {
stateCount[1]++;
i++;
}
// If already too many modules in this state or ran off the edge:
if (startI < i || centerJ < i || stateCount[1] > maxCount) {
return false;
}
// Continue up, left finding black border
while (startI >= i && centerJ >= i && image.get(centerJ - i, startI - i) &&
stateCount[0] <= maxCount) {
stateCount[0]++;
i++;
}
if (stateCount[0] > maxCount) {
return false;
}
int maxI = image.getHeight();
int maxJ = image.getWidth();
// Now also count down, right from center
i = 1;
while (startI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, startI + i)) {
stateCount[2]++;
i++;
}
// Ran off the edge?
if (startI + i >= maxI || centerJ + i >= maxJ) {
return false;
}
while (startI + i < maxI && centerJ + i < maxJ && !image.get(centerJ + i, startI + i) &&
stateCount[3] < maxCount) {
stateCount[3]++;
i++;
}
if (startI + i >= maxI || centerJ + i >= maxJ || stateCount[3] >= maxCount) {
return false;
}
while (startI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, startI + i) &&
stateCount[4] < maxCount) {
stateCount[4]++;
i++;
}
if (stateCount[4] >= maxCount) {
return false;
}
// If we found a finder-pattern-like section, but its size is more than 100% different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
return
Math.abs(stateCountTotal - originalStateCountTotal) < 2 * originalStateCountTotal &&
foundPatternCross(stateCount);
}
/**
* <p>After a horizontal scan finds a potential finder pattern, this method
* "cross-checks" by scanning down vertically through the center of the possible
* finder pattern to see if the same proportion is detected.</p>
*
* @param startI row where a finder pattern was detected
* @param centerJ center of the section that appears to cross a finder pattern
* @param maxCount maximum reasonable number of modules that should be
* observed in any reading state, based on the results of the horizontal scan
* @return vertical center of finder pattern, or {@link Float#NaN} if not found
*/
private float crossCheckVertical(int startI, int centerJ, int maxCount,
int originalStateCountTotal) {
BitMatrix image = this.image;
int maxI = image.getHeight();
int[] stateCount = getCrossCheckStateCount();
// Start counting up from center
int i = startI;
while (i >= 0 && image.get(centerJ, i)) {
stateCount[2]++;
i--;
}
if (i < 0) {
return Float.NaN;
}
while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount) {
return Float.NaN;
}
while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image.get(centerJ, i)) {
stateCount[2]++;
i++;
}
if (i == maxI) {
return Float.NaN;
}
while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {
stateCount[3]++;
i++;
}
if (i == maxI || stateCount[3] >= maxCount) {
return Float.NaN;
}
while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {
stateCount[4]++;
i++;
}
if (stateCount[4] >= maxCount) {
return Float.NaN;
}
// If we found a finder-pattern-like section, but its size is more than 40% different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
return Float.NaN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;
}
/**
* <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
* except it reads horizontally instead of vertically. This is used to cross-cross
* check a vertical cross check and locate the real center of the alignment pattern.</p>
*/
private float crossCheckHorizontal(int startJ, int centerI, int maxCount,
int originalStateCountTotal) {
BitMatrix image = this.image;
int maxJ = image.getWidth();
int[] stateCount = getCrossCheckStateCount();
int j = startJ;
while (j >= 0 && image.get(j, centerI)) {
stateCount[2]++;
j--;
}
if (j < 0) {
return Float.NaN;
}
while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {
stateCount[1]++;
j--;
}
if (j < 0 || stateCount[1] > maxCount) {
return Float.NaN;
}
while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {
stateCount[0]++;
j--;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
}
j = startJ + 1;
while (j < maxJ && image.get(j, centerI)) {
stateCount[2]++;
j++;
}
if (j == maxJ) {
return Float.NaN;
}
while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {
stateCount[3]++;
j++;
}
if (j == maxJ || stateCount[3] >= maxCount) {
return Float.NaN;
}
while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {
stateCount[4]++;
j++;
}
if (stateCount[4] >= maxCount) {
return Float.NaN;
}
// If we found a finder-pattern-like section, but its size is significantly different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
return Float.NaN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;
}
/**
* <p>This is called when a horizontal scan finds a possible alignment pattern. It will
* cross check with a vertical scan, and if successful, will, ah, cross-cross-check
* with another horizontal scan. This is needed primarily to locate the real horizontal
* center of the pattern in cases of extreme skew.
* And then we cross-cross-cross check with another diagonal scan.</p>
* <p/>
* <p>If that succeeds the finder pattern location is added to a list that tracks
* the number of times each location has been nearly-matched as a finder pattern.
* Each additional find is more evidence that the location is in fact a finder
* pattern center
*
* @param stateCount reading state module counts from horizontal scan
* @param i row where finder pattern may be found
* @param j end of possible finder pattern in row
* @param pureBarcode true if in "pure barcode" mode
* @return true if a finder pattern candidate was found this time
*/
private boolean handlePossibleCenter(int[] stateCount, int i, int j, boolean pureBarcode) {
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
float centerJ = centerFromEnd(stateCount, j);
float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);
if (!Float.isNaN(centerI)) {
// Re-cross check
centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
if (!Float.isNaN(centerJ) &&
(!pureBarcode || crossCheckDiagonal((int) centerI, (int) centerJ, stateCount[2], stateCountTotal))) {
float estimatedModuleSize = (float) stateCountTotal / 7.0f;
boolean found = false;
for (int index = 0; index < possibleCenters.size(); index++) {
FinderPattern center = possibleCenters.get(index);
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
possibleCenters.set(index, center.combineEstimate(centerI, centerJ, estimatedModuleSize));
found = true;
break;
}
}
if (!found) {
FinderPattern point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
possibleCenters.add(point);
if (resultPointCallback != null) {
resultPointCallback.foundPossibleResultPoint(point);
}
}
return true;
}
}
return false;
}
/**
* @return number of rows we could safely skip during scanning, based on the first
* two finder patterns that have been located. In some cases their position will
* allow us to infer that the third pattern must lie below a certain point farther
* down in the image.
*/
private int findRowSkip() {
int max = possibleCenters.size();
if (max <= 1) {
return 0;
}
ResultPoint firstConfirmedCenter = null;
for (FinderPattern center : possibleCenters) {
if (center.getCount() >= CENTER_QUORUM) {
if (firstConfirmedCenter == null) {
firstConfirmedCenter = center;
} else {
// We have two confirmed centers
// How far down can we skip before resuming looking for the next
// pattern? In the worst case, only the difference between the
// difference in the x / y coordinates of the two centers.
// This is the case where you find top left last.
hasSkipped = true;
// the calibration card has a aspect ration of 1.75, so we can skip this much.
// To be on the safe side, we approximate this by 1.65
return (int) Math.abs(((Math.abs(firstConfirmedCenter.getX() - center.getX()) -
Math.abs(firstConfirmedCenter.getY() - center.getY())) * 1.65));
}
}
}
return 0;
}
/**
* @return true iff we have found at least 4 finder patterns that have been detected
* at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
* candidates is "pretty similar"
*/
private boolean haveMultiplyConfirmedCenters() {
int confirmedCount = 0;
float totalModuleSize = 0.0f;
int max = possibleCenters.size();
for (FinderPattern pattern : possibleCenters) {
if (pattern.getCount() >= CENTER_QUORUM) {
confirmedCount++;
totalModuleSize += pattern.getEstimatedModuleSize();
}
}
if (confirmedCount < 4) {
return false;
}
// OK, we have at least 4 confirmed centers, but, it's possible that one is a "false positive"
// and that we need to keep looking. We detect this by asking if the estimated module sizes
// vary too much. We arbitrarily say that when the total deviation from average exceeds
// 5% of the total module size estimates, it's too much.
float average = totalModuleSize / (float) max;
float totalDeviation = 0.0f;
for (FinderPattern pattern : possibleCenters) {
totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);
}
return totalDeviation <= 0.05f * totalModuleSize;
}
/**
* @return the 4 best {@link FinderPattern}s from our list of candidates. The "best" are
* those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
* size differs from the average among those patterns the least
* @throws NotFoundException if 4 such finder patterns do not exist
*/
private FinderPattern[] selectBestPatterns() throws NotFoundException {
int startSize = possibleCenters.size();
if (startSize < 4) {
// Couldn't find enough finder patterns
// Log.d("Caddisfly", "couldn't find 4 centers");
throw NotFoundException.getNotFoundInstance();
}
// Filter outlier possibilities whose module size is too different
if (startSize > 4) {
// But we can only afford to do so if we have at least 5 possibilities to choose from
float totalModuleSize = 0.0f;
float square = 0.0f;
for (FinderPattern center : possibleCenters) {
float size = center.getEstimatedModuleSize();
totalModuleSize += size;
square += size * size;
}
float average = totalModuleSize / (float) startSize;
float stdDev = (float) Math.sqrt(square / startSize - average * average);
Collections.sort(possibleCenters, new FurthestFromAverageComparator(average));
float limit = Math.max(0.2f * average, stdDev);
for (int i = 0; i < possibleCenters.size() && possibleCenters.size() > 4; i++) {
FinderPattern pattern = possibleCenters.get(i);
if (Math.abs(pattern.getEstimatedModuleSize() - average) > limit) {
possibleCenters.remove(i);
i--;
}
}
}
if (possibleCenters.size() > 4) {
// Throw away all but those first size candidate points we found.
float totalModuleSize = 0.0f;
for (FinderPattern possibleCenter : possibleCenters) {
totalModuleSize += possibleCenter.getEstimatedModuleSize();
}
float average = totalModuleSize / (float) possibleCenters.size();
Collections.sort(possibleCenters, new CenterComparator(average));
possibleCenters.subList(4, possibleCenters.size()).clear();
}
// order the points from top left, top right, bottom left, bottom right
Collections.sort(possibleCenters, new OrderComparator());
return new FinderPattern[]{
possibleCenters.get(0),
possibleCenters.get(1),
possibleCenters.get(2),
possibleCenters.get(3)
};
}
/**
* <p>Orders by furthest from average</p>
*/
private static final class FurthestFromAverageComparator implements Comparator<FinderPattern>, Serializable {
private final float average;
private FurthestFromAverageComparator(float f) {
average = f;
}
@Override
public int compare(FinderPattern center1, FinderPattern center2) {
float dA = Math.abs(center2.getEstimatedModuleSize() - average);
float dB = Math.abs(center1.getEstimatedModuleSize() - average);
return dA < dB ? -1 : dA == dB ? 0 : 1;
}
}
/**
* <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
*/
private static final class CenterComparator implements Comparator<FinderPattern>, Serializable {
private final float average;
private CenterComparator(float f) {
average = f;
}
@Override
public int compare(FinderPattern center1, FinderPattern center2) {
if (center2.getCount() == center1.getCount()) {
float dA = Math.abs(center2.getEstimatedModuleSize() - average);
float dB = Math.abs(center1.getEstimatedModuleSize() - average);
return dA < dB ? 1 : dA == dB ? 0 : -1;
} else {
return center2.getCount() - center1.getCount();
}
}
}
/**
* <p>Orders by x+y coordinates, ascending.</p>
*/
private static final class OrderComparator implements Comparator<FinderPattern>, Serializable {
private OrderComparator() {
}
@Override
public int compare(FinderPattern fp1, FinderPattern fp2) {
return Math.round(fp1.getX() + fp1.getY() - fp2.getX() - fp2.getY());
}
}
}
| 30,371 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.