Refactor to Java 1.8

This commit is contained in:
dgis 2019-07-14 23:15:42 +02:00
parent d8fb3a9ec0
commit 2123f5c45c
5 changed files with 184 additions and 261 deletions

View file

@ -616,13 +616,10 @@ public class PanAndScaleView extends View {
boolean osdAllowed = false; boolean osdAllowed = false;
Handler osdTimerHandler = new Handler(); Handler osdTimerHandler = new Handler();
Runnable osdTimerRunnable = new Runnable() { Runnable osdTimerRunnable = () -> {
@Override // OSD should stop now!
public void run() { osdAllowed = false;
// OSD should stop now! invalidate();
osdAllowed = false;
invalidate();
}
}; };
void startOSDTimer() { void startOSDTimer() {

View file

@ -17,8 +17,6 @@ package org.emulator.calculator;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.util.Log; import android.util.Log;
import java.util.ArrayList;
/** /**
* Based on the free HP82240B Printer Simulator by Christoph Giesselink * Based on the free HP82240B Printer Simulator by Christoph Giesselink
*/ */
@ -26,7 +24,6 @@ public class PrinterSimulator {
private static final String TAG = "PrinterSimulator"; private static final String TAG = "PrinterSimulator";
private boolean debug = false; private boolean debug = false;
private ArrayList<Integer> data = new ArrayList<>();
private StringBuilder m_Text = new StringBuilder(); private StringBuilder m_Text = new StringBuilder();
private StringBuilder textUpdate = new StringBuilder(); private StringBuilder textUpdate = new StringBuilder();
@ -188,8 +185,6 @@ public class PrinterSimulator {
textUpdate.setLength(0); textUpdate.setLength(0);
data.add(byData);
do { do {
// check for begin of ESC sequence // check for begin of ESC sequence
if (byData == ESC && !m_bEsc && m_byGraphLength == 0) { if (byData == ESC && !m_bEsc && m_byGraphLength == 0) {

View file

@ -27,7 +27,6 @@ import android.os.Bundle;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.Window; import android.view.Window;
@ -113,63 +112,55 @@ public class PrinterSimulatorFragment extends AppCompatDialogFragment {
toolbar.setTitle(title); toolbar.setTitle(title);
toolbar.setNavigationIcon(Utils.resId(this, "drawable", "ic_keyboard_backspace_white_24dp")); toolbar.setNavigationIcon(Utils.resId(this, "drawable", "ic_keyboard_backspace_white_24dp"));
toolbar.setNavigationOnClickListener( toolbar.setNavigationOnClickListener(
new View.OnClickListener() { v -> dismiss()
@Override
public void onClick(View v) {
dismiss();
}
}
); );
toolbar.inflateMenu(Utils.resId(this, "menu", "fragment_printer_simulator")); toolbar.inflateMenu(Utils.resId(this, "menu", "fragment_printer_simulator"));
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { toolbar.setOnMenuItemClickListener(item -> {
@Override if(item.getItemId() == Utils.resId(PrinterSimulatorFragment.this, "id", "menu_printer_simulator_share_text")) {
public boolean onMenuItemClick(MenuItem item) { Intent intent = new Intent(Intent.ACTION_SEND);
if(item.getItemId() == Utils.resId(PrinterSimulatorFragment.this, "id", "menu_printer_simulator_share_text")) { intent.setType("text/plain");
Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_SUBJECT, Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_text"));
intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, printerSimulator.getText());
intent.putExtra(Intent.EXTRA_SUBJECT, Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_text")); startActivity(Intent.createChooser(intent, getString(Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_text"))));
intent.putExtra(Intent.EXTRA_TEXT, printerSimulator.getText()); } else if(item.getItemId() == Utils.resId(PrinterSimulatorFragment.this, "id", "menu_printer_simulator_share_graphic")) {
startActivity(Intent.createChooser(intent, getString(Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_text")))); String imageFilename = "HPPrinter-" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US).format(new Date());
} else if(item.getItemId() == Utils.resId(PrinterSimulatorFragment.this, "id", "menu_printer_simulator_share_graphic")) { try {
String imageFilename = "HPPrinter-" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US).format(new Date()); Bitmap paperBitmap = printerSimulator.getImage();
try { Bitmap croppedPaperBitmap = Bitmap.createBitmap(paperBitmap.getWidth(), printerSimulator.getPaperHeight(), Bitmap.Config.ARGB_8888);
Bitmap paperBitmap = printerSimulator.getImage(); Canvas canvas = new Canvas(croppedPaperBitmap);
Bitmap croppedPaperBitmap = Bitmap.createBitmap(paperBitmap.getWidth(), printerSimulator.getPaperHeight(), Bitmap.Config.ARGB_8888); Paint paint = new Paint();
Canvas canvas = new Canvas(croppedPaperBitmap); canvas.drawBitmap(paperBitmap, 0, 0, paint);
Paint paint = new Paint();
canvas.drawBitmap(paperBitmap, 0, 0, paint);
Activity activity = getActivity(); Activity activity = getActivity();
if(activity != null) { if(activity != null) {
File storagePath = new File(activity.getExternalCacheDir(), ""); File storagePath = new File(activity.getExternalCacheDir(), "");
File imageFile = File.createTempFile(imageFilename, ".png", storagePath); File imageFile = File.createTempFile(imageFilename, ".png", storagePath);
FileOutputStream fileOutputStream = new FileOutputStream(imageFile); FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
croppedPaperBitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream); croppedPaperBitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);
fileOutputStream.close(); fileOutputStream.close();
String mimeType = "application/png"; String mimeType = "application/png";
Intent intent = new Intent(android.content.Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(mimeType); intent.setType(mimeType);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_SUBJECT, Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_graphic")); intent.putExtra(Intent.EXTRA_SUBJECT, Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_graphic"));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".provider", imageFile)); intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".provider", imageFile));
startActivity(Intent.createChooser(intent, getString(Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_graphic")))); startActivity(Intent.createChooser(intent, getString(Utils.resId(PrinterSimulatorFragment.this, "string", "message_printer_share_graphic"))));
}
} catch (Exception e) {
e.printStackTrace();
Utils.showAlert(getActivity(), e.getMessage());
}
} else if(item.getItemId() == Utils.resId(PrinterSimulatorFragment.this, "id", "menu_printer_simulator_change_paper")) {
printerSimulator.changePaper();
printerGraphView.updatePaperLayout();
textViewPrinterText.setText("");
if(printerGraphView != null) {
printerGraphView.updatePaperLayout();
printerGraphView.invalidate();
} }
} catch (Exception e) {
e.printStackTrace();
Utils.showAlert(getActivity(), e.getMessage());
}
} else if(item.getItemId() == Utils.resId(PrinterSimulatorFragment.this, "id", "menu_printer_simulator_change_paper")) {
printerSimulator.changePaper();
printerGraphView.updatePaperLayout();
textViewPrinterText.setText("");
if(printerGraphView != null) {
printerGraphView.updatePaperLayout();
printerGraphView.invalidate();
} }
return true;
} }
return true;
}); });
setMenuVisibility(true); setMenuVisibility(true);
@ -235,21 +226,15 @@ public class PrinterSimulatorFragment extends AppCompatDialogFragment {
} }
} }
public void setPrinterSimulator(final PrinterSimulator printerSimulator) { public void setPrinterSimulator(PrinterSimulator printerSimulator) {
this.printerSimulator = printerSimulator; this.printerSimulator = printerSimulator;
this.printerSimulator.setOnPrinterUpdateListener(new PrinterSimulator.OnPrinterUpdateListener() { this.printerSimulator.setOnPrinterUpdateListener(textAppended -> {
@Override Activity activity = getActivity();
public void onPrinterUpdate(final String textAppended) { if(activity != null)
Activity activity = getActivity(); activity.runOnUiThread(() -> {
if(activity != null) if(debug) Log.d(TAG, "onPrinterUpdate(" + textAppended + ")");
activity.runOnUiThread(new Runnable() { updatePaper(textAppended);
@Override });
public void run() {
if(debug) Log.d(TAG, "onPrinterUpdate(" + textAppended + ")");
updatePaper(textAppended);
}
});
}
}); });
} }

View file

@ -74,7 +74,6 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -134,7 +133,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
toolbar.setVisibility(View.GONE); toolbar.setVisibility(View.GONE);
@ -187,19 +186,10 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
fragmentPrinterSimulator.setPrinterSimulator(printerSimulator); fragmentPrinterSimulator.setPrinterSimulator(printerSimulator);
printerSimulator.setOnPrinterOutOfPaperListener(new PrinterSimulator.OnPrinterOutOfPaperListener() { printerSimulator.setOnPrinterOutOfPaperListener((currentLine, maxLine, currentPixelRow, maxPixelRow) -> runOnUiThread(
@Override () -> Toast.makeText(MainActivity.this, String.format(Locale.US, getString(R.string.message_printer_out_of_paper), maxLine, maxPixelRow), Toast.LENGTH_LONG).show()
public void onPrinterOutOfPaper(final int currentLine, final int maxLine, final int currentPixelRow, final int maxPixelRow) { )
runOnUiThread(new Runnable() { );
@Override
public void run() {
Toast.makeText(MainActivity.this, String.format(Locale.US,
getString(R.string.message_printer_out_of_paper),
maxLine, maxPixelRow), Toast.LENGTH_LONG).show();
}
});
}
});
//android.os.Debug.waitForDebugger(); //android.os.Debug.waitForDebugger();
@ -387,15 +377,12 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
String[] mrus = mruLinkedHashMapKeySet.toArray(new String[mruLength]); String[] mrus = mruLinkedHashMapKeySet.toArray(new String[mruLength]);
int mruClickedIndex = id - MRU_ID_START; int mruClickedIndex = id - MRU_ID_START;
final String url = mrus[mruClickedIndex]; String url = mrus[mruClickedIndex];
mruLinkedHashMap.get(url); mruLinkedHashMap.get(url);
ensureDocumentSaved(new Runnable() { ensureDocumentSaved(() -> {
@Override if(onFileOpen(url) != 0) {
public void run() { saveLastDocument(url);
if(onFileOpen(url) != 0) {
saveLastDocument(url);
}
} }
}); });
@ -519,9 +506,9 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
DocumentFile kmlFolderDocumentFile = DocumentFile.fromTreeUri(this, kmlFolderUri); DocumentFile kmlFolderDocumentFile = DocumentFile.fromTreeUri(this, kmlFolderUri);
if(kmlFolderDocumentFile != null) { if(kmlFolderDocumentFile != null) {
for (DocumentFile file : kmlFolderDocumentFile.listFiles()) { for (DocumentFile file : kmlFolderDocumentFile.listFiles()) {
final String url = file.getUri().toString(); String url = file.getUri().toString();
final String name = file.getName(); String name = file.getName();
final String mime = file.getType(); String mime = file.getType();
Log.d(TAG, "url: " + url + ", name: " + name + ", mime: " + mime); Log.d(TAG, "url: " + url + ", name: " + name + ", mime: " + mime);
if(kmlMimeType.equals(mime)) { if(kmlMimeType.equals(mime)) {
calculatorsAssetFilenames.add(url); calculatorsAssetFilenames.add(url);
@ -595,41 +582,34 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
} }
Collections.sort(kmlScripts, new Comparator<KMLScriptItem>() { Collections.sort(kmlScripts, (lhs, rhs) -> lhs.title.compareTo(rhs.title));
@Override
public int compare(KMLScriptItem lhs, KMLScriptItem rhs) {
return lhs.title.compareTo(rhs.title);
}
});
} }
} }
private void ensureDocumentSaved(final Runnable continueCallback) { private void ensureDocumentSaved(Runnable continueCallback) {
ensureDocumentSaved(continueCallback, false); ensureDocumentSaved(continueCallback, false);
} }
private Runnable fileSaveAsCallback = null; private Runnable fileSaveAsCallback = null;
private void ensureDocumentSaved(final Runnable continueCallback, boolean forceRequest) { private void ensureDocumentSaved(Runnable continueCallback, boolean forceRequest) {
if(NativeLib.isDocumentAvailable()) { if(NativeLib.isDocumentAvailable()) {
final String currentFilename = NativeLib.getCurrentFilename(); String currentFilename = NativeLib.getCurrentFilename();
final boolean hasFilename = (currentFilename != null && currentFilename.length() > 0); boolean hasFilename = (currentFilename != null && currentFilename.length() > 0);
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { DialogInterface.OnClickListener onClickListener = (dialog, which) -> {
public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) {
if (which == DialogInterface.BUTTON_POSITIVE) { if (hasFilename) {
if (hasFilename) { if(NativeLib.onFileSave() == 1)
if(NativeLib.onFileSave() == 1) showAlert(getString(R.string.message_state_saved));
showAlert(getString(R.string.message_state_saved)); if (continueCallback != null)
if (continueCallback != null)
continueCallback.run();
} else {
fileSaveAsCallback = continueCallback;
OnFileSaveAs();
}
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
if(continueCallback != null)
continueCallback.run(); continueCallback.run();
} else {
fileSaveAsCallback = continueCallback;
OnFileSaveAs();
} }
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
if(continueCallback != null)
continueCallback.run();
} }
}; };
@ -650,12 +630,7 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
// By default Port1 is set // By default Port1 is set
setPort1Settings(true, true); setPort1Settings(true, true);
ensureDocumentSaved(new Runnable() { ensureDocumentSaved(() -> showKMLPicker(false));
@Override
public void run() {
showKMLPicker(false);
}
});
} }
private void newFileFromKML(String kmlScriptFilename) { private void newFileFromKML(String kmlScriptFilename) {
@ -670,15 +645,12 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
} }
private void OnFileOpen() { private void OnFileOpen() {
ensureDocumentSaved(new Runnable() { ensureDocumentSaved(() -> {
@Override Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
public void run() { intent.addCategory(Intent.CATEGORY_OPENABLE);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.filename) + "-state.e48");
intent.setType("*/*"); startActivityForResult(intent, INTENT_GETOPENFILENAME);
intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.filename) + "-state.e48");
startActivityForResult(intent, INTENT_GETOPENFILENAME);
}
}); });
} }
private void OnFileSave() { private void OnFileSave() {
@ -722,21 +694,14 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
startActivityForResult(intent, INTENT_GETSAVEFILENAME); startActivityForResult(intent, INTENT_GETSAVEFILENAME);
} }
private void OnFileClose() { private void OnFileClose() {
ensureDocumentSaved(new Runnable() { ensureDocumentSaved(() -> {
@Override NativeLib.onFileClose();
public void run() { showCalculatorView(false);
NativeLib.onFileClose(); saveLastDocument("");
showCalculatorView(false); updateNavigationDrawerItems();
saveLastDocument(""); displayFilename("");
updateNavigationDrawerItems(); if(drawer != null) {
displayFilename(""); new android.os.Handler().postDelayed(() -> drawer.openDrawer(GravityCompat.START), 300);
if(drawer != null) {
new android.os.Handler().postDelayed(new Runnable() {
public void run() {
drawer.openDrawer(GravityCompat.START);
}
}, 300);
}
} }
}, true); }, true);
} }
@ -755,11 +720,9 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
private void OnObjectLoad() { private void OnObjectLoad() {
if(sharedPreferences.getBoolean("settings_objectloadwarning", false)) { if(sharedPreferences.getBoolean("settings_objectloadwarning", false)) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { DialogInterface.OnClickListener onClickListener = (dialog, which) -> {
public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) {
if (which == DialogInterface.BUTTON_POSITIVE) { openDocument();
openDocument();
}
} }
}; };
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
@ -812,11 +775,9 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
NativeLib.onStackPaste(); NativeLib.onStackPaste();
} }
private void OnViewReset() { private void OnViewReset() {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { DialogInterface.OnClickListener onClickListener = (dialog, which) -> {
public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) {
if (which == DialogInterface.BUTTON_POSITIVE) { NativeLib.onViewReset();
NativeLib.onViewReset();
}
} }
}; };
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
@ -850,10 +811,10 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
fragmentPrinterSimulator.show(getSupportFragmentManager(), "Hello Fragment"); fragmentPrinterSimulator.show(getSupportFragmentManager(), "Hello Fragment");
} }
private void showKMLPicker(final boolean changeKML) { private void showKMLPicker(boolean changeKML) {
extractKMLScripts(); extractKMLScripts();
final ArrayList<KMLScriptItem> kmlScriptsForCurrentModel; ArrayList<KMLScriptItem> kmlScriptsForCurrentModel;
if(changeKML) { if(changeKML) {
kmlScriptsForCurrentModel = new ArrayList<>(); kmlScriptsForCurrentModel = new ArrayList<>();
char m = (char) NativeLib.getCurrentModel(); char m = (char) NativeLib.getCurrentModel();
@ -866,8 +827,8 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
kmlScriptsForCurrentModel = kmlScripts; kmlScriptsForCurrentModel = kmlScripts;
boolean hasEmbeddedKMLs = getPackageName().contains("org.emulator.forty.eight"); boolean hasEmbeddedKMLs = getPackageName().contains("org.emulator.forty.eight");
final int lastIndex = kmlScriptsForCurrentModel.size(); int lastIndex = kmlScriptsForCurrentModel.size();
final String[] kmlScriptTitles = new String[lastIndex + (hasEmbeddedKMLs ? 2 : 1)]; String[] kmlScriptTitles = new String[lastIndex + (hasEmbeddedKMLs ? 2 : 1)];
for (int i = 0; i < kmlScriptsForCurrentModel.size(); i++) for (int i = 0; i < kmlScriptsForCurrentModel.size(); i++)
kmlScriptTitles[i] = kmlScriptsForCurrentModel.get(i).title; kmlScriptTitles[i] = kmlScriptsForCurrentModel.get(i).title;
kmlScriptTitles[lastIndex] = getResources().getString(R.string.load_custom_kml); kmlScriptTitles[lastIndex] = getResources().getString(R.string.load_custom_kml);
@ -875,45 +836,42 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
kmlScriptTitles[lastIndex + 1] = getResources().getString(R.string.load_default_kml); kmlScriptTitles[lastIndex + 1] = getResources().getString(R.string.load_default_kml);
new AlertDialog.Builder(MainActivity.this) new AlertDialog.Builder(MainActivity.this)
.setTitle(getResources().getString(R.string.pick_calculator)) .setTitle(getResources().getString(R.string.pick_calculator))
.setItems(kmlScriptTitles, new DialogInterface.OnClickListener() { .setItems(kmlScriptTitles, (dialog, which) -> {
@Override if(which == lastIndex) {
public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // < API 21
if(which == lastIndex) { new AlertDialog.Builder(MainActivity.this)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // < API 21 .setTitle(getString(R.string.message_kml_folder_selection_need_api_lollipop))
new AlertDialog.Builder(MainActivity.this) .setMessage(getString(R.string.message_kml_folder_selection_need_api_lollipop_description))
.setTitle(getString(R.string.message_kml_folder_selection_need_api_lollipop)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
.setMessage(getString(R.string.message_kml_folder_selection_need_api_lollipop_description)) public void onClick(DialogInterface dialog, int which) {
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { }
public void onClick(DialogInterface dialog, int which) { }).show();
}
}).show();
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, changeKML ? INTENT_PICK_KML_FOLDER_FOR_CHANGING : INTENT_PICK_KML_FOLDER_FOR_NEW_FILE);
}
} else if(which == lastIndex + 1) {
// Reset to default KML folder
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("settings_kml_default", true);
editor.apply();
updateFromPreferences("settings_kml", true);
if(changeKML)
OnViewScript();
else
OnFileNew();
} else { } else {
String kmlScriptFilename = kmlScriptsForCurrentModel.get(which).filename; Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
if(changeKML) { startActivityForResult(intent, changeKML ? INTENT_PICK_KML_FOLDER_FOR_CHANGING : INTENT_PICK_KML_FOLDER_FOR_NEW_FILE);
int result = NativeLib.onViewScript(kmlScriptFilename);
if(result > 0) {
displayKMLTitle();
showKMLLog();
} else
showKMLLogForce();
updateNavigationDrawerItems();
} else
newFileFromKML(kmlScriptFilename);
} }
} else if(which == lastIndex + 1) {
// Reset to default KML folder
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("settings_kml_default", true);
editor.apply();
updateFromPreferences("settings_kml", true);
if(changeKML)
OnViewScript();
else
OnFileNew();
} else {
String kmlScriptFilename = kmlScriptsForCurrentModel.get(which).filename;
if(changeKML) {
int result = NativeLib.onViewScript(kmlScriptFilename);
if(result > 0) {
displayKMLTitle();
showKMLLog();
} else
showKMLLogForce();
updateNavigationDrawerItems();
} else
newFileFromKML(kmlScriptFilename);
} }
}).show(); }).show();
} }
@ -1172,12 +1130,12 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
} }
private void makeUriPersistable(Intent data, Uri uri) { private void makeUriPersistable(Intent data, Uri uri) {
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
getContentResolver().takePersistableUriPermission(uri, takeFlags); getContentResolver().takePersistableUriPermission(uri, takeFlags);
} }
private void makeUriPersistableReadOnly(Intent data, Uri uri) { private void makeUriPersistableReadOnly(Intent data, Uri uri) {
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION); int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
getContentResolver().takePersistableUriPermission(uri, takeFlags); getContentResolver().takePersistableUriPermission(uri, takeFlags);
} }
@ -1288,8 +1246,8 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
DocumentFile folderDocumentFile = DocumentFile.fromTreeUri(this, folderURI); DocumentFile folderDocumentFile = DocumentFile.fromTreeUri(this, folderURI);
if(folderDocumentFile != null) { if(folderDocumentFile != null) {
for (DocumentFile file : folderDocumentFile.listFiles()) { for (DocumentFile file : folderDocumentFile.listFiles()) {
final String url = file.getUri().toString(); String url = file.getUri().toString();
final String name = file.getName(); String name = file.getName();
//Log.d(TAG, "url: " + url + ", name: " + name); //Log.d(TAG, "url: " + url + ", name: " + name);
if (filename.equals(name)) { if (filename.equals(name)) {
return openFileFromContentResolver(url, writeAccess); return openFileFromContentResolver(url, writeAccess);

View file

@ -122,21 +122,18 @@ public class SettingsActivity extends AppCompatActivity implements SharedPrefere
// final ColorPickerPreferenceCompat preferenceBackgroundCustomColor = (ColorPickerPreferenceCompat)findPreference("settings_background_custom_color"); // final ColorPickerPreferenceCompat preferenceBackgroundCustomColor = (ColorPickerPreferenceCompat)findPreference("settings_background_custom_color");
if(preferenceBackgroundFallbackColor != null /*&& preferenceBackgroundCustomColor != null*/) { if(preferenceBackgroundFallbackColor != null /*&& preferenceBackgroundCustomColor != null*/) {
final String[] stringArrayBackgroundFallbackColor = getResources().getStringArray(R.array.settings_background_fallback_color_item); final String[] stringArrayBackgroundFallbackColor = getResources().getStringArray(R.array.settings_background_fallback_color_item);
Preference.OnPreferenceChangeListener onPreferenceChangeListenerBackgroundFallbackColor = new Preference.OnPreferenceChangeListener() { Preference.OnPreferenceChangeListener onPreferenceChangeListenerBackgroundFallbackColor = (preference, value) -> {
@Override if(value != null) {
public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString();
if(value != null) { int backgroundFallbackColor = -1;
String stringValue = value.toString(); try {
int backgroundFallbackColor = -1; backgroundFallbackColor = Integer.parseInt(stringValue);
try { } catch (NumberFormatException ignored) {}
backgroundFallbackColor = Integer.parseInt(stringValue); if(backgroundFallbackColor >= 0 && backgroundFallbackColor < stringArrayBackgroundFallbackColor.length)
} catch (NumberFormatException ignored) {} preference.setSummary(stringArrayBackgroundFallbackColor[backgroundFallbackColor]);
if(backgroundFallbackColor >= 0 && backgroundFallbackColor < stringArrayBackgroundFallbackColor.length)
preference.setSummary(stringArrayBackgroundFallbackColor[backgroundFallbackColor]);
// preferenceBackgroundCustomColor.setEnabled(backgroundFallbackColor == 2); // preferenceBackgroundCustomColor.setEnabled(backgroundFallbackColor == 2);
}
return true;
} }
return true;
}; };
preferenceBackgroundFallbackColor.setOnPreferenceChangeListener(onPreferenceChangeListenerBackgroundFallbackColor); preferenceBackgroundFallbackColor.setOnPreferenceChangeListener(onPreferenceChangeListenerBackgroundFallbackColor);
onPreferenceChangeListenerBackgroundFallbackColor.onPreferenceChange(preferenceBackgroundFallbackColor, onPreferenceChangeListenerBackgroundFallbackColor.onPreferenceChange(preferenceBackgroundFallbackColor,
@ -161,15 +158,12 @@ public class SettingsActivity extends AppCompatActivity implements SharedPrefere
// Macro // Macro
Preference preferenceMacroRealSpeed = findPreference("settings_macro_real_speed"); Preference preferenceMacroRealSpeed = findPreference("settings_macro_real_speed");
final Preference preferenceMacroManualSpeed = findPreference("settings_macro_manual_speed"); Preference preferenceMacroManualSpeed = findPreference("settings_macro_manual_speed");
if(preferenceMacroRealSpeed != null && preferenceMacroManualSpeed != null) { if(preferenceMacroRealSpeed != null && preferenceMacroManualSpeed != null) {
Preference.OnPreferenceChangeListener onPreferenceChangeListenerMacroRealSpeed = new Preference.OnPreferenceChangeListener() { Preference.OnPreferenceChangeListener onPreferenceChangeListenerMacroRealSpeed = (preference, value) -> {
@Override if(value != null)
public boolean onPreferenceChange(Preference preference, Object value) { preferenceMacroManualSpeed.setEnabled(!(Boolean) value);
if(value != null) return true;
preferenceMacroManualSpeed.setEnabled(!(Boolean) value);
return true;
}
}; };
preferenceMacroRealSpeed.setOnPreferenceChangeListener(onPreferenceChangeListenerMacroRealSpeed); preferenceMacroRealSpeed.setOnPreferenceChangeListener(onPreferenceChangeListenerMacroRealSpeed);
onPreferenceChangeListenerMacroRealSpeed.onPreferenceChange(preferenceMacroRealSpeed, sharedPreferences.getBoolean(preferenceMacroRealSpeed.getKey(), true)); onPreferenceChangeListenerMacroRealSpeed.onPreferenceChange(preferenceMacroRealSpeed, sharedPreferences.getBoolean(preferenceMacroRealSpeed.getKey(), true));
@ -177,51 +171,45 @@ public class SettingsActivity extends AppCompatActivity implements SharedPrefere
// Ports 1 & 2 settings // Ports 1 & 2 settings
final Preference preferencePort1en = findPreference("settings_port1en"); Preference preferencePort1en = findPreference("settings_port1en");
final Preference preferencePort1wr = findPreference("settings_port1wr"); Preference preferencePort1wr = findPreference("settings_port1wr");
final Preference preferencePort2en = findPreference("settings_port2en"); Preference preferencePort2en = findPreference("settings_port2en");
final Preference preferencePort2wr = findPreference("settings_port2wr"); Preference preferencePort2wr = findPreference("settings_port2wr");
preferencePort2load = findPreference("settings_port2load"); preferencePort2load = findPreference("settings_port2load");
if(preferencePort1en != null && preferencePort1wr != null
&& preferencePort2en != null && preferencePort2wr != null
&& preferencePort2load != null) {
boolean enablePortPreferences = NativeLib.isPortExtensionPossible();
final boolean enablePortPreferences = NativeLib.isPortExtensionPossible(); Preference.OnPreferenceChangeListener onPreferenceChangeListenerPort1en = (preference, value) -> {
Preference.OnPreferenceChangeListener onPreferenceChangeListenerPort1en = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
preferencePort1en.setEnabled(enablePortPreferences); preferencePort1en.setEnabled(enablePortPreferences);
preferencePort1wr.setEnabled(enablePortPreferences); preferencePort1wr.setEnabled(enablePortPreferences);
return true; return true;
} };
}; preferencePort1en.setOnPreferenceChangeListener(onPreferenceChangeListenerPort1en);
preferencePort1en.setOnPreferenceChangeListener(onPreferenceChangeListenerPort1en); onPreferenceChangeListenerPort1en.onPreferenceChange(preferencePort1en, sharedPreferences.getBoolean(preferencePort1en.getKey(), false));
onPreferenceChangeListenerPort1en.onPreferenceChange(preferencePort1en, sharedPreferences.getBoolean(preferencePort1en.getKey(), false));
Preference.OnPreferenceChangeListener onPreferenceChangeListenerPort2en = new Preference.OnPreferenceChangeListener() { Preference.OnPreferenceChangeListener onPreferenceChangeListenerPort2en = (preference, value) -> {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
preferencePort2en.setEnabled(enablePortPreferences); preferencePort2en.setEnabled(enablePortPreferences);
preferencePort2wr.setEnabled(enablePortPreferences); preferencePort2wr.setEnabled(enablePortPreferences);
preferencePort2load.setEnabled(enablePortPreferences); preferencePort2load.setEnabled(enablePortPreferences);
return true; return true;
} };
}; preferencePort2en.setOnPreferenceChangeListener(onPreferenceChangeListenerPort2en);
preferencePort2en.setOnPreferenceChangeListener(onPreferenceChangeListenerPort2en); onPreferenceChangeListenerPort2en.onPreferenceChange(preferencePort2en, sharedPreferences.getBoolean(preferencePort2en.getKey(), false));
onPreferenceChangeListenerPort2en.onPreferenceChange(preferencePort2en, sharedPreferences.getBoolean(preferencePort2en.getKey(), false));
updatePort2LoadFilename(sharedPreferences.getString(preferencePort2load.getKey(), "")); updatePort2LoadFilename(sharedPreferences.getString(preferencePort2load.getKey(), ""));
preferencePort2load.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { preferencePort2load.setOnPreferenceClickListener(preference -> {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*"); intent.setType("*/*");
intent.putExtra(Intent.EXTRA_TITLE, "shared.bin"); intent.putExtra(Intent.EXTRA_TITLE, "shared.bin");
Activity activity = getActivity(); Activity activity = getActivity();
if(activity != null) if (activity != null)
activity.startActivityForResult(intent, MainActivity.INTENT_PORT2LOAD); activity.startActivityForResult(intent, MainActivity.INTENT_PORT2LOAD);
return true; return true;
} });
}); }
} }
void updatePort2LoadFilename(String port2Filename) { void updatePort2LoadFilename(String port2Filename) {
@ -259,7 +247,7 @@ public class SettingsActivity extends AppCompatActivity implements SharedPrefere
} }
private void makeUriPersistable(Intent data, Uri uri) { private void makeUriPersistable(Intent data, Uri uri) {
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
getContentResolver().takePersistableUriPermission(uri, takeFlags); getContentResolver().takePersistableUriPermission(uri, takeFlags);
} }