Merge pull request #368 from zod/reformat

Reformat using Android Studio
This commit is contained in:
afischerdev 2021-11-21 11:37:34 +01:00 committed by GitHub
commit a37ee5b3d9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 3034 additions and 3662 deletions

9
.git-blame-ignore-revs Normal file
View file

@ -0,0 +1,9 @@
# Commits which should be ignored by git blame
# You have to instruct git to use this file using either
# `git blame --ignore-revs-file .git-blame-ignore-revs`
# or update you git config to always include those commits
# `git config blame.ignoreRevsFile .git-blame-ignore-revs`
# Reformat brouter-routing-app using Android Studio
54d5c5e9439be2c3df4c95b6fc12d33fdcc9b389

View file

@ -13,34 +13,28 @@ import android.os.Environment;
/**
* static logger interface to be used in the android app
*/
public class AppLogger
{
public class AppLogger {
private static FileWriter debugLogWriter = null;
private static boolean initDone = false;
private static void init()
{
try
{
private static void init() {
try {
// open logfile if existing
File sd = Environment.getExternalStorageDirectory();
if (sd == null) return;
File debugLog = new File(sd, "Android/media/btools.routingapp/brouter/brouterapp.txt");
if ( debugLog.exists() )
{
if (debugLog.exists()) {
debugLogWriter = new FileWriter(debugLog, true);
}
} catch (IOException ioe) {
}
catch( IOException ioe ) {}
}
/**
* log an info trace to the app log file, if any
*/
public static boolean isLogging()
{
if ( !initDone )
{
public static boolean isLogging() {
if (!initDone) {
initDone = true;
init();
log("logging started at " + new Date());
@ -51,18 +45,13 @@ public class AppLogger
/**
* log an info trace to the app log file, if any
*/
public static void log( String msg )
{
if ( isLogging() )
{
try
{
public static void log(String msg) {
if (isLogging()) {
try {
debugLogWriter.write(msg);
debugLogWriter.write('\n');
debugLogWriter.flush();
}
catch( IOException e )
{
} catch (IOException e) {
throw new RuntimeException("cannot write brouterapp.txt: " + e);
}
}
@ -71,8 +60,7 @@ public class AppLogger
/**
* Format an exception using
*/
public static String formatThrowable( Throwable t )
{
public static String formatThrowable(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);

View file

@ -45,7 +45,9 @@ public class BInstallerActivity extends Activity {
}
/** Called when the activity is first created. */
/**
* Called when the activity is first created.
*/
@Override
@SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
@ -105,25 +107,19 @@ public class BInstallerActivity extends Activity {
@Override
@SuppressWarnings("deprecation")
protected Dialog onCreateDialog( int id )
{
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
switch ( id )
{
switch (id) {
case DIALOG_CONFIRM_DELETE_ID:
builder = new AlertDialog.Builder(this);
builder
.setTitle("Confirm Delete")
.setMessage( "Really delete?" ).setPositiveButton( "Yes", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
.setMessage("Really delete?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mBInstallerView.deleteSelectedTiles();
}
} ).setNegativeButton( "No", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
@ -134,17 +130,14 @@ public class BInstallerActivity extends Activity {
}
@SuppressWarnings("deprecation")
public void showConfirmDelete()
{
public void showConfirmDelete() {
showDialog(DIALOG_CONFIRM_DELETE_ID);
}
private Set<Integer> dialogIds = new HashSet<Integer>();
private void showNewDialog( int id )
{
if ( dialogIds.contains( Integer.valueOf( id ) ) )
{
private void showNewDialog(int id) {
if (dialogIds.contains(Integer.valueOf(id))) {
removeDialog(id);
}
dialogIds.add(Integer.valueOf(id));
@ -157,8 +150,7 @@ public class BInstallerActivity extends Activity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return stat.getAvailableBlocksLong() * stat.getBlockSizeLong();
}
else {
} else {
return stat.getAvailableBlocks() * stat.getBlockSize();
}
}

View file

@ -29,14 +29,14 @@ import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import btools.mapaccess.PhysicalFile;
import btools.mapaccess.Rd5DiffManager;
import btools.mapaccess.Rd5DiffTool;
import btools.router.RoutingHelper;
import btools.util.ProgressListener;
public class BInstallerView extends View
{
public class BInstallerView extends View {
private static final int MASK_SELECTED_RD5 = 1;
private static final int MASK_DELETED_RD5 = 2;
private static final int MASK_INSTALLED_RD5 = 4;
@ -86,8 +86,7 @@ public class BInstallerView extends View
Activity mActivity;
protected String baseNameForTile( int tileIndex )
{
protected String baseNameForTile(int tileIndex) {
int lon = (tileIndex % 72) * 5 - 180;
int lat = (tileIndex / 72) * 5 - 90;
String slon = lon < 0 ? "W" + (-lon) : "E" + lon;
@ -95,13 +94,11 @@ public class BInstallerView extends View
return slon + "_" + slat;
}
private int gridPos2Tileindex( int ix, int iy )
{
private int gridPos2Tileindex(int ix, int iy) {
return (35 - iy) * 72 + (ix >= 70 ? ix - 70 : ix + 2);
}
private int tileForBaseName( String basename )
{
private int tileForBaseName(String basename) {
String uname = basename.toUpperCase(Locale.ROOT);
int idx = uname.indexOf("_");
if (idx < 0) return -1;
@ -117,22 +114,18 @@ public class BInstallerView extends View
}
public boolean isDownloadCanceled()
{
public boolean isDownloadCanceled() {
return downloadCanceled;
}
private void toggleDownload()
{
if ( isDownloading )
{
private void toggleDownload() {
if (isDownloading) {
downloadCanceled = true;
downloadAction = "Canceling...";
return;
}
if ( delTiles > 0 )
{
if (delTiles > 0) {
((BInstallerActivity) getContext()).showConfirmDelete();
return;
}
@ -142,17 +135,13 @@ public class BInstallerView extends View
ArrayList<Integer> downloadList = new ArrayList<>();
// prepare download list
for( int ix=0; ix<72; ix++ )
{
for( int iy=0; iy<36; iy++ )
{
for (int ix = 0; ix < 72; ix++) {
for (int iy = 0; iy < 36; iy++) {
int tidx = gridPos2Tileindex(ix, iy);
if ( ( tileStatus[tidx] & MASK_SELECTED_RD5 ) != 0 )
{
if ((tileStatus[tidx] & MASK_SELECTED_RD5) != 0) {
int tilesize = BInstallerSizes.getRd5Size(tidx);
downloadList.add(tidx);
if ( tilesize > 0 && tilesize < min_size )
{
if (tilesize > 0 && tilesize < min_size) {
tidx_min = tidx;
min_size = tilesize;
}
@ -192,11 +181,9 @@ public class BInstallerView extends View
}
public void downloadDone( boolean success )
{
public void downloadDone(boolean success) {
isDownloading = false;
if ( success )
{
if (success) {
scanExistingFiles();
toggleDownload(); // keep on if no error
}
@ -213,79 +200,65 @@ public class BInstallerView extends View
invalidate();
}
private int tileIndex( float x, float y )
{
private int tileIndex(float x, float y) {
int ix = (int) (72.f * x / bmp.getWidth());
int iy = (int) (36.f * y / bmp.getHeight());
if (ix >= 0 && ix < 72 && iy >= 0 && iy < 36) return gridPos2Tileindex(ix, iy);
return -1;
}
private void clearTileSelection( int mask )
{
private void clearTileSelection(int mask) {
// clear selection if zooming out
for (int ix = 0; ix < 72; ix++)
for( int iy=0; iy<36; iy++ )
{
for (int iy = 0; iy < 36; iy++) {
int tidx = gridPos2Tileindex(ix, iy);
tileStatus[tidx] ^= tileStatus[tidx] & mask;
}
}
// get back the current image scale
private float currentScale()
{
private float currentScale() {
testVector[1] = 1.f;
mat.mapVectors(testVector);
return testVector[1] / viewscale;
}
private void deleteRawTracks()
{
private void deleteRawTracks() {
File modeDir = new File(baseDir, "brouter/modes");
String[] fileNames = modeDir.list();
if (fileNames == null) return;
for( String fileName : fileNames )
{
if ( fileName.endsWith( "_rawtrack.dat" ) )
{
for (String fileName : fileNames) {
if (fileName.endsWith("_rawtrack.dat")) {
File f = new File(modeDir, fileName);
f.delete();
}
}
}
private void scanExistingFiles()
{
private void scanExistingFiles() {
clearTileSelection(MASK_INSTALLED_RD5 | MASK_CURRENT_RD5);
scanExistingFiles(new File(baseDir, "brouter/segments4"));
File secondary = RoutingHelper.getSecondarySegmentDir(new File(baseDir, "brouter/segments4"));
if ( secondary != null )
{
if (secondary != null) {
scanExistingFiles(secondary);
}
availableSize = -1;
try
{
try {
availableSize = (long) ((BInstallerActivity) getContext()).getAvailableSpace(baseDir.getAbsolutePath());
//StatFs stat = new StatFs(baseDir.getAbsolutePath ());
//availableSize = (long)stat.getAvailableBlocksLong()*stat.getBlockSizeLong();
}
catch (Exception e) { /* ignore */ }
} catch (Exception e) { /* ignore */ }
}
private void scanExistingFiles( File dir )
{
private void scanExistingFiles(File dir) {
String[] fileNames = dir.list();
if (fileNames == null) return;
String suffix = ".rd5";
for( String fileName : fileNames )
{
if ( fileName.endsWith( suffix ) )
{
for (String fileName : fileNames) {
if (fileName.endsWith(suffix)) {
String basename = fileName.substring(0, fileName.length() - suffix.length());
int tidx = tileForBaseName(basename);
tileStatus[tidx] |= MASK_INSTALLED_RD5;
@ -303,15 +276,12 @@ public class BInstallerView extends View
baseDir = ConfigHelper.getBaseDir(getContext());
segmentDir = new File(baseDir, "brouter/segments4");
try
{
try {
AssetManager assetManager = getContext().getAssets();
InputStream istr = assetManager.open("world.png");
bmp = BitmapFactory.decodeStream(istr);
istr.close();
}
catch( IOException io )
{
} catch (IOException io) {
throw new RuntimeException("cannot read world.png from assets");
}
@ -356,16 +326,13 @@ public class BInstallerView extends View
super.onSizeChanged(w, h, oldw, oldh);
}
private void toast( String msg )
{
private void toast(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_LONG).show();
}
@Override
protected void onDraw(Canvas canvas)
{
if ( !isDownloading )
{
protected void onDraw(Canvas canvas) {
if (!isDownloading) {
canvas.setMatrix(mat);
canvas.drawBitmap(bmp, 0, 0, null);
}
@ -378,18 +345,15 @@ public class BInstallerView extends View
boolean drawGrid = tilesVisible && !isDownloading;
if ( drawGrid )
{
if (drawGrid) {
pnt_1.setColor(Color.GREEN);
for( int ix=1; ix<72; ix++ )
{
for (int ix = 1; ix < 72; ix++) {
float fx = fw * ix;
canvas.drawLine(fx, 0, fx, ih, pnt_1);
}
for( int iy=1; iy<36; iy++ )
{
for (int iy = 1; iy < 36; iy++) {
float fy = fh * iy;
canvas.drawLine(0, fy, iw, fy, pnt_1);
}
@ -422,23 +386,20 @@ public class BInstallerView extends View
long mb = 1024 * 1024;
if ( isDownloading )
{
if (isDownloading) {
String sizeHint = currentDownloadSize > 0 ? " (" + ((currentDownloadSize + mb - 1) / mb) + " MB)" : "";
paint.setTextSize(30);
canvas.drawText(currentDownloadOperation, 30, (imgh / 3) * 2 - 30, paint);
// canvas.drawText( currentDownloadOperation + " " + currentDownloadFile + sizeHint, 30, (imgh/3)*2-30, paint);
canvas.drawText(downloadAction, 30, (imgh / 3) * 2, paint);
}
if ( !tilesVisible && !isDownloading)
{
if (!tilesVisible && !isDownloading) {
paint.setTextSize(35);
canvas.drawText("Touch region to zoom in!", 30, (imgh / 3) * 2, paint);
}
paint.setTextSize(20);
String totmb = ((totalSize + mb - 1) / mb) + " MB";
String freemb = availableSize >= 0 ? ((availableSize + mb - 1) / mb) + " MB" : "?";
canvas.drawText("Selected segments=" + rd5Tiles, 10, 25, paint);
@ -453,8 +414,7 @@ public class BInstallerView extends View
rd5Tiles == 0 &&
RoutingHelper.hasDirectoryAnyDatafiles(segmentDir)) btnText = "Update all";
if ( btnText != null )
{
if (btnText != null) {
canvas.drawLine(imgw - btnw, imgh - btnh, imgw - btnw, imgh - 2, paint);
canvas.drawLine(imgw - btnw, imgh - btnh, imgw - 2, imgh - btnh, paint);
canvas.drawLine(imgw - btnw, imgh - btnh, imgw - btnw, imgh - 2, paint);
@ -470,24 +430,18 @@ public class BInstallerView extends View
float tx, ty;
private void drawSelectedTiles( Canvas canvas, Paint pnt, float fw, float fh, int status, int mask, boolean doCount, boolean cntDel, boolean doDraw )
{
private void drawSelectedTiles(Canvas canvas, Paint pnt, float fw, float fh, int status, int mask, boolean doCount, boolean cntDel, boolean doDraw) {
for (int ix = 0; ix < 72; ix++)
for ( int iy = 0; iy < 36; iy++ )
{
for (int iy = 0; iy < 36; iy++) {
int tidx = gridPos2Tileindex(ix, iy);
if ( ( tileStatus[tidx] & mask ) == status )
{
if ((tileStatus[tidx] & mask) == status) {
int tilesize = BInstallerSizes.getRd5Size(tidx);
if ( tilesize > 0 )
{
if ( doCount )
{
if (tilesize > 0) {
if (doCount) {
rd5Tiles++;
totalSize += BInstallerSizes.getRd5Size(tidx);
}
if ( cntDel )
{
if (cntDel) {
delTiles++;
totalSize += BInstallerSizes.getRd5Size(tidx);
}
@ -507,15 +461,11 @@ float tx, ty;
}
}
public void deleteSelectedTiles()
{
for ( int ix = 0; ix < 72; ix++ )
{
for ( int iy = 0; iy < 36; iy++ )
{
public void deleteSelectedTiles() {
for (int ix = 0; ix < 72; ix++) {
for (int iy = 0; iy < 36; iy++) {
int tidx = gridPos2Tileindex(ix, iy);
if ( ( tileStatus[tidx] & MASK_DELETED_RD5 ) != 0 )
{
if ((tileStatus[tidx] & MASK_DELETED_RD5) != 0) {
new File(baseDir, "brouter/segments4/" + baseNameForTile(tidx) + ".rd5").delete();
}
}
@ -567,8 +517,7 @@ float tx, ty;
float r = (float) Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
float hr = (float) Math.sqrt((hx1 - hx0) * (hx1 - hx0) + (hy1 - hy0) * (hy1 - hy0));
if ( hr > 0. )
{
if (hr > 0.) {
float ratio = r / hr;
float mx = (x1 + x0) / 2.f;
@ -585,8 +534,7 @@ float tx, ty;
mat.postScale(ratio, ratio, mx, my);
boolean tilesv = currentScale() >= 3.f;
if ( tilesVisible && !tilesv )
{
if (tilesVisible && !tilesv) {
clearTileSelection(MASK_SELECTED_RD5 | MASK_DELETED_RD5);
}
tilesVisible = tilesv;
@ -602,24 +550,19 @@ float tx, ty;
long downTime = event.getEventTime() - event.getDownTime();
if ( downTime < 5 || downTime > 500 )
{
if (downTime < 5 || downTime > 500) {
break;
}
if ( Math.abs(lastDownX - event.getX() ) > 10 || Math.abs(lastDownY - event.getY() ) > 10 )
{
if (Math.abs(lastDownX - event.getX()) > 10 || Math.abs(lastDownY - event.getY()) > 10) {
break;
}
// download button?
if ( ( delTiles > 0 || rd5Tiles >= 0 || isDownloading ) && event.getX() > imgwOrig - btnw*scaleOrig && event.getY() > imghOrig-btnh*scaleOrig )
{
if ((delTiles > 0 || rd5Tiles >= 0 || isDownloading) && event.getX() > imgwOrig - btnw * scaleOrig && event.getY() > imghOrig - btnh * scaleOrig) {
if (rd5Tiles == 0) {
for ( int ix = 0; ix < 72; ix++ )
{
for ( int iy = 0; iy < 36; iy++ )
{
for (int ix = 0; ix < 72; ix++) {
for (int iy = 0; iy < 36; iy++) {
int tidx = gridPos2Tileindex(ix, iy);
if (tidx != -1) {
if ((tileStatus[tidx] & MASK_INSTALLED_RD5) != 0) {
@ -635,11 +578,9 @@ float tx, ty;
break;
}
if ( !tilesVisible )
{
if (!tilesVisible) {
float scale = currentScale();
if ( scale > 0f && scale < 5f )
{
if (scale > 0f && scale < 5f) {
float ratio = 5f / scale;
mat.postScale(ratio, ratio, event.getX(), event.getY());
tilesVisible = true;
@ -650,30 +591,22 @@ float tx, ty;
if (isDownloading) break;
Matrix imat = new Matrix();
if ( mat.invert(imat) )
{
if (mat.invert(imat)) {
float[] touchpoint = new float[2];
touchpoint[0] = event.getX();
touchpoint[1] = event.getY();
imat.mapPoints(touchpoint);
int tidx = tileIndex(touchpoint[0], touchpoint[1]);
if ( tidx != -1 )
{
if ( ( tileStatus[tidx] & MASK_SELECTED_RD5 ) != 0 )
{
if (tidx != -1) {
if ((tileStatus[tidx] & MASK_SELECTED_RD5) != 0) {
tileStatus[tidx] ^= MASK_SELECTED_RD5;
if ( ( tileStatus[tidx] & MASK_INSTALLED_RD5 ) != 0 )
{
if ((tileStatus[tidx] & MASK_INSTALLED_RD5) != 0) {
tileStatus[tidx] |= MASK_DELETED_RD5;
}
}
else if ( ( tileStatus[tidx] & MASK_DELETED_RD5 ) != 0 )
{
} else if ((tileStatus[tidx] & MASK_DELETED_RD5) != 0) {
tileStatus[tidx] ^= MASK_DELETED_RD5;
}
else
{
} else {
tileStatus[tidx] ^= MASK_SELECTED_RD5;
}
}
@ -696,5 +629,4 @@ float tx, ty;
}
}

View file

@ -63,11 +63,12 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
private PowerManager mPowerManager;
private WakeLock mWakeLock;
/** Called when the activity is first created. */
/**
* Called when the activity is first created.
*/
@Override
@SuppressWarnings("deprecation")
public void onCreate( Bundle savedInstanceState )
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get an instance of the PowerManager
@ -87,20 +88,16 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
@Override
@SuppressWarnings("deprecation")
protected Dialog onCreateDialog( int id )
{
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
switch ( id )
{
switch (id) {
case DIALOG_SELECTPROFILE_ID:
builder.setTitle("Select a routing profile");
builder.setItems( availableProfiles, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
builder.setItems(availableProfiles, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
selectedProfile = availableProfiles[item];
mBRouterView.startProcessing(selectedProfile);
}
@ -110,10 +107,8 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
builder.setTitle("Select Main Action");
builder
.setItems(new String[]
{ "Download Manager", "BRouter App" }, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
{"Download Manager", "BRouter App"}, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0)
startDownloadManager();
else
@ -121,10 +116,8 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
}
)
.setNegativeButton( "Close", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}
@ -136,18 +129,14 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
.setMessage(
"*** Attention: ***\n\n" + "The Download Manager is used to download routing-data "
+ "files which can be up to 170MB each. Do not start the Download Manager " + "on a cellular data connection without a data plan! "
+ "Download speed is restricted to 4 MBit/s." ).setPositiveButton( "I know", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
+ "Download speed is restricted to 4 MBit/s.").setPositiveButton("I know", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(BRouterActivity.this, BInstallerActivity.class);
startActivity(intent);
// finish();
}
} ).setNegativeButton( "Cancel", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
@ -163,16 +152,12 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
+ "configure the profile mapping. But you will not be able to use nogo-points or do "
+ "long distance calculations. If you know the path to your map-tool, you can manually "
+ "configure it in 'storageconfig.txt'. Or I can do an extended scan searching "
+ "your sd-card for a valid waypoint database" ).setPositiveButton( "Scan", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
+ "your sd-card for a valid waypoint database").setPositiveButton("Scan", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mBRouterView.startWpDatabaseScan();
}
} ).setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
@ -191,10 +176,8 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
+ "very long distance calculations. If you want to get classic mode back, you can manually install "
+ "the APK of the BRouter App from the release page ( http://brouter.de/brouter/revisions.html ), which "
+ "is still built against Android API 10, and does not have these limitations. "
).setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
@ -206,10 +189,8 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
"You successfully repeated a calculation that previously run into a timeout "
+ "when started from your map-tool. If you repeat the same request from your "
+ "maptool, with the exact same destination point and a close-by starting point, "
+ "this request is guaranteed not to time out." ).setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
+ "this request is guaranteed not to time out.").setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
@ -218,16 +199,12 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
builder
.setTitle("Waypoint Database ")
.setMessage("Found Waypoint-Database(s) for maptool-dir: " + maptoolDirCandidate
+ " Configure that?" ).setPositiveButton( "Yes", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
+ " Configure that?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mBRouterView.saveMaptoolDir(maptoolDirCandidate);
}
} ).setNegativeButton( "No", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
@ -240,37 +217,29 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
+ "Before downloading new datafiles made for the new table, "
+ "you have to reset your local setup by 'moving away' (or deleting) "
+ "your <basedir>/brouter directory and start a new setup by calling the " + "BRouter App again.")
.setPositiveButton( "OK", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
return builder.create();
case DIALOG_ROUTINGMODES_ID:
builder.setTitle(message);
builder.setMultiChoiceItems( routingModes, routingModesChecked, new DialogInterface.OnMultiChoiceClickListener()
{
builder.setMultiChoiceItems(routingModes, routingModesChecked, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick( DialogInterface dialog, int which, boolean isChecked )
{
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
routingModesChecked[which] = isChecked;
}
});
builder.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int whichButton )
{
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mBRouterView.configureService(routingModes, routingModesChecked);
}
});
return builder.create();
case DIALOG_EXCEPTION_ID:
builder.setTitle( "An Error occured" ).setMessage( errorMessage ).setPositiveButton( "OK", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
builder.setTitle("An Error occured").setMessage(errorMessage).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mBRouterView.continueProcessing();
}
});
@ -281,10 +250,8 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
final EditText input = new EditText(this);
input.setText(defaultbasedir);
builder.setView(input);
builder.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int whichButton )
{
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String basedir = input.getText().toString();
mBRouterView.startSetup(new File(basedir), true);
}
@ -293,24 +260,17 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
case DIALOG_SELECTBASEDIR_ID:
builder.setTitle("Choose brouter data base dir:");
// builder.setMessage( message );
builder.setSingleChoiceItems( basedirOptions, 0, new DialogInterface.OnClickListener()
{
builder.setSingleChoiceItems(basedirOptions, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int item )
{
public void onClick(DialogInterface dialog, int item) {
selectedBasedir = item;
}
});
builder.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int whichButton )
{
if ( selectedBasedir < availableBasedirs.size() )
{
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (selectedBasedir < availableBasedirs.size()) {
mBRouterView.startSetup(availableBasedirs.get(selectedBasedir), true);
}
else
{
} else {
showDialog(DIALOG_TEXTENTRY_ID);
}
}
@ -318,25 +278,18 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
return builder.create();
case DIALOG_VIASELECT_ID:
builder.setTitle("Check VIA Selection:");
builder.setMultiChoiceItems( availableVias, getCheckedBooleanArray( availableVias.length ), new DialogInterface.OnMultiChoiceClickListener()
{
builder.setMultiChoiceItems(availableVias, getCheckedBooleanArray(availableVias.length), new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick( DialogInterface dialog, int which, boolean isChecked )
{
if ( isChecked )
{
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedVias.add(availableVias[which]);
}
else
{
} else {
selectedVias.remove(availableVias[which]);
}
}
});
builder.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int whichButton )
{
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mBRouterView.updateViaList(selectedVias);
mBRouterView.startProcessing(selectedProfile);
}
@ -348,18 +301,14 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
for (int i = 0; i < nogoList.size(); i++)
nogoNames[i] = nogoList.get(i).name;
final boolean[] nogoEnabled = getCheckedBooleanArray(nogoList.size());
builder.setMultiChoiceItems( nogoNames, getCheckedBooleanArray( nogoNames.length ), new DialogInterface.OnMultiChoiceClickListener()
{
builder.setMultiChoiceItems(nogoNames, getCheckedBooleanArray(nogoNames.length), new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick( DialogInterface dialog, int which, boolean isChecked )
{
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
nogoEnabled[which] = isChecked;
}
});
builder.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int whichButton )
{
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mBRouterView.updateNogoList(nogoEnabled);
mBRouterView.startProcessing(selectedProfile);
}
@ -369,37 +318,23 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
String leftLabel = wpCount < 0 ? (wpCount != -2 ? "Exit" : "Help") : (wpCount == 0 ? "Select from" : "Select to/via");
String rightLabel = wpCount < 2 ? (wpCount == -3 ? "Help" : "Server-Mode") : "Calc Route";
builder.setTitle( title ).setMessage( errorMessage ).setPositiveButton( leftLabel, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
if ( wpCount == -2 )
{
builder.setTitle(title).setMessage(errorMessage).setPositiveButton(leftLabel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (wpCount == -2) {
showWaypointDatabaseHelp();
}
else if ( wpCount == -1 || wpCount == -3 )
{
} else if (wpCount == -1 || wpCount == -3) {
finish();
}
else
{
} else {
mBRouterView.pickWaypoints();
}
}
} ).setNegativeButton( rightLabel, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
if ( wpCount == -3 )
{
}).setNegativeButton(rightLabel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (wpCount == -3) {
showRepeatTimeoutHelp();
}
else if ( wpCount < 2 )
{
} else if (wpCount < 2) {
mBRouterView.startConfigureService();
}
else
{
} else {
mBRouterView.finishWaypointSelection();
mBRouterView.startProcessing(selectedProfile);
}
@ -407,20 +342,16 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
});
return builder.create();
case DIALOG_MODECONFIGOVERVIEW_ID:
builder.setTitle( "Success" ).setMessage( message ).setPositiveButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int id )
{
builder.setTitle("Success").setMessage(message).setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
return builder.create();
case DIALOG_PICKWAYPOINT_ID:
builder.setTitle(wpCount > 0 ? "Select to/via" : "Select from");
builder.setItems( availableWaypoints, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
builder.setItems(availableWaypoints, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mBRouterView.updateWaypointList(availableWaypoints[item]);
mBRouterView.startProcessing(selectedProfile);
}
@ -432,8 +363,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
}
private boolean[] getCheckedBooleanArray( int size )
{
private boolean[] getCheckedBooleanArray(int size) {
boolean[] checked = new boolean[size];
for (int i = 0; i < checked.length; i++) checked[i] = true;
return checked;
@ -461,8 +391,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
private String maptoolDirCandidate;
public boolean isOnline(Context context)
{
public boolean isOnline(Context context) {
boolean result = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@ -486,50 +415,38 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
@SuppressWarnings("deprecation")
public void selectProfile( String[] items )
{
public void selectProfile(String[] items) {
availableProfiles = items;
// if we have internet access, first show the main action dialog
if ( isOnline(this) )
{
if (isOnline(this)) {
showDialog(DIALOG_MAINACTION_ID);
}
else
{
} else {
showDialog(DIALOG_SELECTPROFILE_ID);
}
}
@SuppressWarnings("deprecation")
public void startDownloadManager()
{
if ( !mBRouterView.hasUpToDateLookups() )
{
public void startDownloadManager() {
if (!mBRouterView.hasUpToDateLookups()) {
showDialog(DIALOG_OLDDATAHINT_ID);
}
else
{
} else {
showDialog(DIALOG_SHOW_DM_INFO_ID);
}
}
@SuppressWarnings("deprecation")
public void selectBasedir( ArrayList<File> items, String defaultBasedir, String message )
{
public void selectBasedir(ArrayList<File> items, String defaultBasedir, String message) {
this.defaultbasedir = defaultBasedir;
this.message = message;
availableBasedirs = items;
ArrayList<Long> dirFreeSizes = new ArrayList<Long>();
for ( File f : items )
{
for (File f : items) {
long size = 0L;
try
{
try {
StatFs stat = new StatFs(f.getAbsolutePath());
size = (long) stat.getAvailableBlocks() * stat.getBlockSize();
}
catch (Exception e) { /* ignore */ }
} catch (Exception e) { /* ignore */ }
dirFreeSizes.add(Long.valueOf(size));
}
@ -541,8 +458,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
int bdidx = 0;
DecimalFormat df = new DecimalFormat("###0.00");
for ( int idx = 0; idx < availableBasedirs.size(); idx++ )
{
for (int idx = 0; idx < availableBasedirs.size(); idx++) {
basedirOptions[bdidx++] = availableBasedirs.get(idx) + " (" + df.format(dirFreeSizes.get(idx) / 1024. / 1024. / 1024.) + " GB free)";
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
@ -553,8 +469,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
@SuppressWarnings("deprecation")
public void selectRoutingModes( String[] modes, boolean[] modesChecked, String message )
{
public void selectRoutingModes(String[] modes, boolean[] modesChecked, String message) {
routingModes = modes;
routingModesChecked = modesChecked;
this.message = message;
@ -562,15 +477,13 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
@SuppressWarnings("deprecation")
public void showModeConfigOverview( String message )
{
public void showModeConfigOverview(String message) {
this.message = message;
showDialog(DIALOG_MODECONFIGOVERVIEW_ID);
}
@SuppressWarnings("deprecation")
public void selectVias( String[] items )
{
public void selectVias(String[] items) {
availableVias = items;
selectedVias = new HashSet<String>(availableVias.length);
for (String via : items)
@ -579,51 +492,41 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
@SuppressWarnings("deprecation")
public void selectWaypoint( String[] items )
{
public void selectWaypoint(String[] items) {
availableWaypoints = items;
showNewDialog(DIALOG_PICKWAYPOINT_ID);
}
@SuppressWarnings("deprecation")
public void showWaypointDatabaseHelp()
{
if ( mBRouterView.canAccessSdCard )
{
public void showWaypointDatabaseHelp() {
if (mBRouterView.canAccessSdCard) {
showNewDialog(DIALOG_SHOW_WP_HELP_ID);
}
else
{
} else {
showNewDialog(DIALOG_SHOW_API23_HELP_ID);
}
}
@SuppressWarnings("deprecation")
public void showRepeatTimeoutHelp()
{
public void showRepeatTimeoutHelp() {
showNewDialog(DIALOG_SHOW_REPEAT_TIMEOUT_HELP_ID);
}
@SuppressWarnings("deprecation")
public void showWpDatabaseScanSuccess( String bestGuess )
{
public void showWpDatabaseScanSuccess(String bestGuess) {
maptoolDirCandidate = bestGuess;
showNewDialog(DIALOG_SHOW_WP_SCANRESULT_ID);
}
@SuppressWarnings("deprecation")
public void selectNogos( List<OsmNodeNamed> nogoList )
{
public void selectNogos(List<OsmNodeNamed> nogoList) {
this.nogoList = nogoList;
showDialog(DIALOG_NOGOSELECT_ID);
}
private Set<Integer> dialogIds = new HashSet<Integer>();
private void showNewDialog( int id )
{
if ( dialogIds.contains( Integer.valueOf( id ) ) )
{
private void showNewDialog(int id) {
if (dialogIds.contains(Integer.valueOf(id))) {
removeDialog(id);
}
dialogIds.add(Integer.valueOf(id));
@ -635,15 +538,13 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
private int wpCount;
@SuppressWarnings("deprecation")
public void showErrorMessage( String msg )
{
public void showErrorMessage(String msg) {
errorMessage = msg;
showNewDialog(DIALOG_EXCEPTION_ID);
}
@SuppressWarnings("deprecation")
public void showResultMessage( String title, String msg, int wpCount )
{
public void showResultMessage(String title, String msg, int wpCount) {
errorMessage = msg;
this.title = title;
this.wpCount = wpCount;
@ -651,8 +552,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
@Override
protected void onResume()
{
protected void onResume() {
super.onResume();
/*
* when the activity is resumed, we acquire a wake-lock so that the screen
@ -663,8 +563,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
}
@Override
protected void onPause()
{
protected void onPause() {
super.onPause();
/*
* When the activity is paused, we make sure to stop the router
@ -710,8 +609,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
File sd = Environment.getExternalStorageDirectory();
File testDir = new File(sd, "brouter");
boolean didExist = testDir.isDirectory();
if ( !didExist )
{
if (!didExist) {
testDir.mkdir();
}
File testFile = new File(testDir, "test" + System.currentTimeMillis());
@ -720,8 +618,7 @@ public class BRouterActivity extends Activity implements ActivityCompat.OnReques
testFile.delete();
isWritable = true;
}
}
catch (Throwable t) {
} catch (Throwable t) {
// ignore
}
return isWritable;

View file

@ -33,8 +33,7 @@ import androidx.core.content.ContextCompat;
import btools.router.OsmNodeNamed;
public class BRouterService extends Service
{
public class BRouterService extends Service {
@Override
public IBinder onBind(Intent arg0) {
@ -42,11 +41,9 @@ public class BRouterService extends Service
return myBRouterServiceStub;
}
private IBRouterService.Stub myBRouterServiceStub = new IBRouterService.Stub()
{
private IBRouterService.Stub myBRouterServiceStub = new IBRouterService.Stub() {
@Override
public String getTrackFromParams( Bundle params ) throws RemoteException
{
public String getTrackFromParams(Bundle params) throws RemoteException {
logBundle(params);
BRouterWorker worker = new BRouterWorker();
@ -54,26 +51,23 @@ public class BRouterService extends Service
// get base dir from private file
String baseDir = null;
InputStream configInput = null;
try
{
try {
configInput = openFileInput("config15.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(configInput));
baseDir = br.readLine();
} catch (Exception e) {
} finally {
if (configInput != null) try {
configInput.close();
} catch (Exception ee) {
}
catch (Exception e)
{
}
finally
{
if ( configInput != null ) try { configInput.close(); } catch (Exception ee) {}
}
worker.baseDir = baseDir;
worker.segmentDir = new File(baseDir, "brouter/segments4");
String remoteProfile = params.getString("remoteProfile");
if ( remoteProfile == null )
{
if (remoteProfile == null) {
remoteProfile = checkForTestDummy(baseDir);
}
@ -85,30 +79,26 @@ public class BRouterService extends Service
worker.profileName = profile;
worker.profilePath = baseDir + "/brouter/profiles2/" + profile + ".brf";
worker.rawTrackPath = baseDir + "/brouter/modes/" + profile + "_rawtrack.dat";
if (!new File(worker.profilePath).exists()) errMsg = "Profile " + profile + " does not exists";
if (!new File(worker.profilePath).exists())
errMsg = "Profile " + profile + " does not exists";
try {
readNogos(worker, baseDir);
} catch (Exception e) {
errMsg = e.getLocalizedMessage();
}
}
else {
} else {
errMsg = getConfigFromMode(worker, baseDir, params.getString("v"), params.getString("fast"));
}
if ( errMsg != null )
{
if (errMsg != null) {
return errMsg;
}
boolean canCompress = "true".equals(params.getString("acceptCompressedResult"));
try
{
try {
String gpxMessage = worker.getTrackFromParams(params);
if ( canCompress && gpxMessage.startsWith( "<" ) )
{
try
{
if (canCompress && gpxMessage.startsWith("<")) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write("z64".getBytes(Charset.forName("UTF-8"))); // marker prefix
OutputStream os = new GZIPOutputStream(baos);
@ -119,32 +109,25 @@ public class BRouterService extends Service
os.close();
gpxMessage = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
return gpxMessage;
}
catch( Exception e )
{
} catch (Exception e) {
return "error compressing result";
}
}
return gpxMessage;
}
catch (IllegalArgumentException iae)
{
} catch (IllegalArgumentException iae) {
return iae.getMessage();
}
}
private String getConfigFromMode( BRouterWorker worker, String baseDir, String mode, String fast )
{
private String getConfigFromMode(BRouterWorker worker, String baseDir, String mode, String fast) {
boolean isFast = "1".equals(fast) || "true".equals(fast) || "yes".equals(fast);
String mode_key = mode + "_" + (isFast ? "fast" : "short");
BufferedReader br = null;
try
{
try {
String modesFile = baseDir + "/brouter/modes/serviceconfig.dat";
br = new BufferedReader(new FileReader(modesFile));
for ( ;; )
{
for (; ; ) {
String line = br.readLine();
if (line == null)
break;
@ -159,20 +142,18 @@ public class BRouterService extends Service
return null;
}
}
catch (Exception e)
{
} catch (Exception e) {
return "no brouter service config found, mode " + mode_key;
} finally {
if (br != null) try {
br.close();
} catch (Exception ee) {
}
finally
{
if ( br != null ) try { br.close(); } catch( Exception ee ) {}
}
return "no brouter service config found for mode " + mode_key;
}
private String getConfigForRemoteProfile( BRouterWorker worker, String baseDir, String remoteProfile )
{
private String getConfigForRemoteProfile(BRouterWorker worker, String baseDir, String remoteProfile) {
worker.profileName = "remote";
worker.profilePath = baseDir + "/brouter/profiles2/remote.brf";
worker.rawTrackPath = baseDir + "/brouter/modes/remote_rawtrack.dat";
@ -181,26 +162,22 @@ public class BRouterService extends Service
byte[] profileBytes = remoteProfile.getBytes();
File profileFile = new File(worker.profilePath);
try
{
try {
readNogos(worker, baseDir);
if ( !fileEqual( profileBytes, profileFile ) )
{
if (!fileEqual(profileBytes, profileFile)) {
OutputStream os = null;
try
{
try {
os = new FileOutputStream(profileFile);
os.write(profileBytes);
}
finally
{
if ( os != null ) try { os.close(); } catch( IOException io ) {}
} finally {
if (os != null) try {
os.close();
} catch (IOException io) {
}
}
}
catch( Exception e )
{
} catch (Exception e) {
return "error caching remote profile: " + e;
}
return null;
@ -225,10 +202,8 @@ public class BRouterService extends Service
}
private boolean fileEqual( byte[] fileBytes, File file ) throws Exception
{
if ( !file.exists() )
{
private boolean fileEqual(byte[] fileBytes, File file) throws Exception {
if (!file.exists()) {
return false;
}
int nbytes = fileBytes.length;
@ -236,64 +211,54 @@ public class BRouterService extends Service
int blen = 8192;
byte[] buf = new byte[blen];
InputStream is = null;
try
{
try {
is = new FileInputStream(file);
while( pos < nbytes )
{
while (pos < nbytes) {
int len = is.read(buf, 0, blen);
if (len <= 0) return false;
if (pos + len > nbytes) return false;
for( int j=0; j<len; j++ )
{
if ( fileBytes[pos++] != buf[j] )
{
for (int j = 0; j < len; j++) {
if (fileBytes[pos++] != buf[j]) {
return false;
}
}
}
return true;
} finally {
if (is != null) try {
is.close();
} catch (IOException io) {
}
finally
{
if ( is != null ) try { is.close(); } catch( IOException io ) {}
}
}
private String checkForTestDummy( String baseDir )
{
private String checkForTestDummy(String baseDir) {
File testdummy = new File(baseDir + "/brouter/profiles2/remotetestdummy.brf");
if (!testdummy.exists()) return null;
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try
{
try {
br = new BufferedReader(new FileReader(testdummy));
for ( ;; )
{
for (; ; ) {
String line = br.readLine();
if (line == null)
break;
sb.append(line).append('\n');
}
return sb.toString();
}
catch (Exception e)
{
} catch (Exception e) {
throw new RuntimeException("error reading " + testdummy);
} finally {
if (br != null) try {
br.close();
} catch (Exception ee) {
}
finally
{
if ( br != null ) try { br.close(); } catch( Exception ee ) {}
}
}
private void logBundle( Bundle params )
{
if ( AppLogger.isLogging() )
{
for( String k : params.keySet() )
{
private void logBundle(Bundle params) {
if (AppLogger.isLogging()) {
for (String k : params.keySet()) {
Object val = "remoteProfile".equals(k) ? "<..cut..>" : params.get(k);
String desc = "key=" + k + (val == null ? "" : " class=" + val.getClass() + " val=" + val.toString());
AppLogger.log(desc);
@ -304,15 +269,13 @@ public class BRouterService extends Service
};
@Override
public void onCreate()
{
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(), "onCreate()");
}
@Override
public void onDestroy()
{
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getSimpleName(), "onDestroy()");
}
@ -323,20 +286,17 @@ public class BRouterService extends Service
// method will not be called.
@Override
@SuppressWarnings("deprecation")
public void onStart(Intent intent, int startId)
{
public void onStart(Intent intent, int startId) {
Log.d(getClass().getSimpleName(), "onStart()");
handleStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);
return START_STICKY;
}
void handleStart(Intent intent, int startId)
{
void handleStart(Intent intent, int startId) {
}
}

View file

@ -53,8 +53,7 @@ import btools.router.RoutingEngine;
import btools.router.RoutingHelper;
import btools.util.CheapRuler;
public class BRouterView extends View
{
public class BRouterView extends View {
RoutingEngine cr;
private int imgw;
private int imgh;
@ -98,21 +97,17 @@ public class BRouterView extends View
public boolean canAccessSdCard;
public void stopRouting()
{
public void stopRouting() {
if (cr != null) cr.terminate();
}
public BRouterView( Context context, int memoryClass )
{
public BRouterView(Context context, int memoryClass) {
super(context);
this.memoryClass = memoryClass;
}
public void init()
{
try
{
public void init() {
try {
DisplayMetrics metrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
imgw = metrics.widthPixels;
@ -122,12 +117,10 @@ public class BRouterView extends View
File baseDir = ConfigHelper.getBaseDir(getContext());
// check if valid
boolean bdValid = false;
if ( baseDir != null )
{
if (baseDir != null) {
bdValid = baseDir.isDirectory();
File brd = new File(baseDir, "brouter");
if ( brd.isDirectory() )
{
if (brd.isDirectory()) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q &&
!brd.getAbsolutePath().contains("/Android/media/btools.routingapp")) {
String message = "(previous basedir " + baseDir + " has to migrate )";
@ -148,9 +141,7 @@ public class BRouterView extends View
((BRouterActivity) getContext()).selectBasedir(((BRouterActivity) getContext()).getStorageDirectories(), guessBaseDir(), message);
waitingForSelection = true;
}
catch (Exception e)
{
} catch (Exception e) {
String msg = e instanceof IllegalArgumentException ? e.getMessage() : e.toString();
AppLogger.log(msg);
@ -160,21 +151,17 @@ public class BRouterView extends View
}
}
public void startSetup( File baseDir, boolean storeBasedir )
{
public void startSetup(File baseDir, boolean storeBasedir) {
if (baseDir == null) {
baseDir = retryBaseDir;
retryBaseDir = null;
}
if ( storeBasedir )
{
if (storeBasedir) {
File td = new File(baseDir, "brouter");
try
{
try {
td.mkdirs();
}
catch (Exception e) {
} catch (Exception e) {
Log.d("BRouterView", "Error creating base directory: " + e.getMessage());
e.printStackTrace();
}
@ -190,8 +177,7 @@ public class BRouterView extends View
}
ConfigHelper.writeBaseDir(getContext(), baseDir);
}
try
{
try {
cor = null;
String basedir = baseDir.getAbsolutePath();
@ -202,8 +188,7 @@ public class BRouterView extends View
// create missing directories
assertDirectoryExists("project directory", new File(basedir, "brouter"), null, null);
segmentDir = new File(basedir, "/brouter/segments4");
if ( assertDirectoryExists( "data directory", segmentDir, "segments4.zip", null ) )
{
if (assertDirectoryExists("data directory", segmentDir, "segments4.zip", null)) {
ConfigMigration.tryMigrateStorageConfig(
new File(basedir + "/brouter/segments3/storageconfig.txt"),
new File(basedir + "/brouter/segments4/storageconfig.txt"));
@ -245,38 +230,30 @@ public class BRouterView extends View
needsNogoSelection = nogoList.size() > 0;
needsWaypointSelection = wpList.size() == 0;
if ( cor.tracksdir != null )
{
if (cor.tracksdir != null) {
tracksDir = new File(cor.basedir, cor.tracksdir);
assertDirectoryExists("track directory", tracksDir, null, null);
// output redirect: look for a pointerfile in tracksdir
File tracksDirPointer = new File(tracksDir, "brouter.redirect");
if ( tracksDirPointer.isFile() )
{
if (tracksDirPointer.isFile()) {
String tracksDirStr = readSingleLineFile(tracksDirPointer);
if (tracksDirStr == null)
throw new IllegalArgumentException("redirect pointer file is empty: " + tracksDirPointer);
tracksDir = new File(tracksDirStr);
if (!(tracksDir.isDirectory()))
throw new IllegalArgumentException("redirect pointer file " + tracksDirPointer + " does not point to a directory: " + tracksDir);
}
else
{
} else {
File writeTest = new File(tracksDir + "/brouter.writetest");
try
{
try {
writeTest.createNewFile();
writeTest.delete();
}
catch( Exception e )
{
} catch (Exception e) {
tracksDir = null;
}
}
}
if ( tracksDir == null )
{
if (tracksDir == null) {
tracksDir = new File(basedir, "router"); // fallback
}
@ -284,10 +261,8 @@ public class BRouterView extends View
ArrayList<String> profiles = new ArrayList<String>();
boolean lookupsFound = false;
for ( String fileName : fileNames )
{
if ( fileName.endsWith( ".brf" ) )
{
for (String fileName : fileNames) {
if (fileName.endsWith(".brf")) {
profiles.add(fileName.substring(0, fileName.length() - 4));
}
if (fileName.equals("lookups.dat"))
@ -297,34 +272,28 @@ public class BRouterView extends View
// add a "last timeout" dummy profile
File lastTimeoutFile = new File(modesDir + "/timeoutdata.txt");
long lastTimeoutTime = lastTimeoutFile.lastModified();
if ( lastTimeoutTime > 0 && System.currentTimeMillis() - lastTimeoutTime < 1800000 )
{
if (lastTimeoutTime > 0 && System.currentTimeMillis() - lastTimeoutTime < 1800000) {
BufferedReader br = new BufferedReader(new FileReader(lastTimeoutFile));
String repeatProfile = br.readLine();
br.close();
profiles.add(0, "<repeat:" + repeatProfile + ">");
}
if ( !lookupsFound )
{
if (!lookupsFound) {
throw new IllegalArgumentException("The profile-directory " + profileDir + " does not contain the lookups.dat file."
+ " see brouter.de/brouter for setup instructions.");
}
if ( profiles.size() == 0 )
{
if (profiles.size() == 0) {
throw new IllegalArgumentException("The profile-directory " + profileDir + " contains no routing profiles (*.brf)."
+ " see brouter.de/brouter for setup instructions.");
}
if ( !RoutingHelper.hasDirectoryAnyDatafiles( segmentDir ) )
{
if (!RoutingHelper.hasDirectoryAnyDatafiles(segmentDir)) {
((BRouterActivity) getContext()).startDownloadManager();
waitingForSelection = true;
return;
}
((BRouterActivity) getContext()).selectProfile(profiles.toArray(new String[0]));
}
catch (Exception e)
{
} catch (Exception e) {
String msg = e instanceof IllegalArgumentException ? e.getMessage()
+ (cor == null ? "" : " (coordinate-source: " + cor.basedir + cor.rootdir + ")") : e.toString();
@ -361,8 +330,7 @@ public class BRouterView extends View
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists())
{
if (!dir.exists()) {
dir.mkdirs();
}
@ -387,35 +355,28 @@ public class BRouterView extends View
new File(inputPath + "/" + inputFile).delete();
}
catch (FileNotFoundException fnfe1) {
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
public boolean hasUpToDateLookups()
{
public boolean hasUpToDateLookups() {
BExpressionMetaData meta = new BExpressionMetaData();
meta.readMetaData(new File(profileDir, "lookups.dat"));
return meta.lookupVersion == 10;
}
public void continueProcessing()
{
public void continueProcessing() {
waitingForSelection = false;
invalidate();
}
public void updateViaList( Set<String> selectedVias )
{
public void updateViaList(Set<String> selectedVias) {
ArrayList<OsmNodeNamed> filtered = new ArrayList<OsmNodeNamed>(wpList.size());
for ( OsmNodeNamed n : wpList )
{
for (OsmNodeNamed n : wpList) {
String name = n.name;
if ("from".equals(name) || "to".equals(name) || selectedVias.contains(name))
filtered.add(n);
@ -423,30 +384,22 @@ public class BRouterView extends View
wpList = filtered;
}
public void updateNogoList( boolean[] enabled )
{
for ( int i = nogoList.size() - 1; i >= 0; i-- )
{
if ( enabled[i] )
{
public void updateNogoList(boolean[] enabled) {
for (int i = nogoList.size() - 1; i >= 0; i--) {
if (enabled[i]) {
nogoVetoList.add(nogoList.get(i));
nogoList.remove(i);
}
}
}
public void pickWaypoints()
{
public void pickWaypoints() {
String msg = null;
if ( cor.allpoints == null )
{
try
{
if (cor.allpoints == null) {
try {
cor.readAllPoints();
}
catch (Exception e)
{
} catch (Exception e) {
msg = "Error reading waypoints: " + e.toString();
}
@ -457,12 +410,9 @@ public class BRouterView extends View
msg = "coordinate source contains too much waypoints: " + size + "(please use from/to/via names)";
}
if ( msg != null )
{
if (msg != null) {
((BRouterActivity) getContext()).showErrorMessage(msg);
}
else
{
} else {
String[] wpts = new String[cor.allpoints.size()];
int i = 0;
for (OsmNodeNamed wp : cor.allpoints)
@ -471,17 +421,12 @@ public class BRouterView extends View
}
}
public void updateWaypointList( String waypoint )
{
for( OsmNodeNamed wp : cor.allpoints )
{
if ( wp.name.equals( waypoint ) )
{
if ( wp.ilat != 0 || wp.ilon != 0 )
{
public void updateWaypointList(String waypoint) {
for (OsmNodeNamed wp : cor.allpoints) {
if (wp.name.equals(waypoint)) {
if (wp.ilat != 0 || wp.ilon != 0) {
int nwp = wpList.size();
if ( nwp == 0 || wpList.get( nwp-1 ) != wp )
{
if (nwp == 0 || wpList.get(nwp - 1) != wp) {
wpList.add(wp);
}
}
@ -490,30 +435,25 @@ public class BRouterView extends View
}
}
public void startWpDatabaseScan()
{
public void startWpDatabaseScan() {
dataBaseScanner = new WpDatabaseScanner();
dataBaseScanner.start();
invalidate();
}
public void saveMaptoolDir( String dir )
{
public void saveMaptoolDir(String dir) {
ConfigMigration.saveAdditionalMaptoolDir(segmentDir, dir);
((BRouterActivity) getContext()).showResultMessage("Success", "please restart to use new config", -1);
}
public void finishWaypointSelection()
{
public void finishWaypointSelection() {
needsWaypointSelection = false;
}
private List<OsmNodeNamed> readWpList( BufferedReader br, boolean isNogo ) throws Exception
{
private List<OsmNodeNamed> readWpList(BufferedReader br, boolean isNogo) throws Exception {
int cnt = Integer.parseInt(br.readLine());
List<OsmNodeNamed> res = new ArrayList<OsmNodeNamed>(cnt);
for( int i=0; i<cnt; i++ )
{
for (int i = 0; i < cnt; i++) {
OsmNodeNamed wp = OsmNodeNamed.decodeNogo(br.readLine());
wp.isNogo = isNogo;
res.add(wp);
@ -521,14 +461,11 @@ public class BRouterView extends View
return res;
}
public void startProcessing( String profile )
{
public void startProcessing(String profile) {
rawTrackPath = null;
if ( profile.startsWith( "<repeat" ) )
{
if (profile.startsWith("<repeat")) {
needsViaSelection = needsNogoSelection = needsWaypointSelection = false;
try
{
try {
File lastTimeoutFile = new File(modesDir + "/timeoutdata.txt");
BufferedReader br = new BufferedReader(new FileReader(lastTimeoutFile));
profile = br.readLine();
@ -536,23 +473,18 @@ public class BRouterView extends View
wpList = readWpList(br, false);
nogoList = readWpList(br, true);
br.close();
}
catch( Exception e )
{
} catch (Exception e) {
AppLogger.log(AppLogger.formatThrowable(e));
((BRouterActivity) getContext()).showErrorMessage(e.toString());
}
}
else if ( "remote".equals( profileName ) )
{
} else if ("remote".equals(profileName)) {
rawTrackPath = modesDir + "/remote_rawtrack.dat";
}
profilePath = profileDir + "/" + profile + ".brf";
profileName = profile;
if ( needsViaSelection )
{
if (needsViaSelection) {
needsViaSelection = false;
String[] availableVias = new String[wpList.size() - 2];
for (int viaidx = 0; viaidx < wpList.size() - 2; viaidx++)
@ -561,22 +493,17 @@ public class BRouterView extends View
return;
}
if ( needsNogoSelection )
{
if (needsNogoSelection) {
needsNogoSelection = false;
((BRouterActivity) getContext()).selectNogos(nogoList);
return;
}
if ( needsWaypointSelection )
{
if (needsWaypointSelection) {
String msg;
if ( wpList.size() == 0 )
{
if (wpList.size() == 0) {
msg = "Expecting waypoint selection\n" + sourceHint;
}
else
{
} else {
msg = "current waypoint selection:\n";
for (int i = 0; i < wpList.size(); i++)
msg += (i > 0 ? "->" : "") + wpList.get(i).name;
@ -585,8 +512,7 @@ public class BRouterView extends View
return;
}
try
{
try {
waitingForSelection = false;
RoutingContext rc = new RoutingContext();
@ -601,14 +527,12 @@ public class BRouterView extends View
int minlat = Integer.MAX_VALUE;
OsmNode prev = null;
for ( OsmNode n : wpList )
{
for (OsmNode n : wpList) {
maxlon = Math.max(n.ilon, maxlon);
minlon = Math.min(n.ilon, minlon);
maxlat = Math.max(n.ilat, maxlat);
minlat = Math.min(n.ilat, minlat);
if ( prev != null )
{
if (prev != null) {
plain_distance += n.calcDistance(prev);
}
prev = n;
@ -635,12 +559,9 @@ public class BRouterView extends View
rc.nogopoints = nogoList;
rc.memoryclass = memoryClass;
if ( memoryClass < 16 )
{
if (memoryClass < 16) {
rc.memoryclass = 16;
}
else if ( memoryClass > 256 )
{
} else if (memoryClass > 256) {
rc.memoryclass = 256;
}
@ -652,44 +573,34 @@ public class BRouterView extends View
cr.start();
invalidate();
}
catch (Exception e)
{
} catch (Exception e) {
String msg = e instanceof IllegalArgumentException ? e.getMessage() : e.toString();
toast(msg);
}
}
private boolean assertDirectoryExists( String message, File path, String assetZip, String versionTag )
{
private boolean assertDirectoryExists(String message, File path, String assetZip, String versionTag) {
boolean exists = path.exists();
if ( !exists )
{
if (!exists) {
path.mkdirs();
}
if ( versionTag != null )
{
if (versionTag != null) {
File vtag = new File(path, versionTag);
try
{
try {
exists = !vtag.createNewFile();
}
catch( IOException io ) { } // well..
} catch (IOException io) {
} // well..
}
if ( !exists )
{
if (!exists) {
// default contents from assets archive
if ( assetZip != null )
{
try
{
if (assetZip != null) {
try {
AssetManager assetManager = getContext().getAssets();
InputStream is = assetManager.open(assetZip);
ZipInputStream zis = new ZipInputStream(is);
byte[] data = new byte[1024];
for ( ;; )
{
for (; ; ) {
ZipEntry ze = zis.getNextEntry();
if (ze == null)
break;
@ -698,8 +609,7 @@ public class BRouterView extends View
outfile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(outfile);
for ( ;; )
{
for (; ; ) {
int len = zis.read(data, 0, 1024);
if (len < 0)
break;
@ -709,9 +619,7 @@ public class BRouterView extends View
}
is.close();
return true;
}
catch (IOException io)
{
} catch (IOException io) {
throw new RuntimeException("error expanding " + assetZip + ": " + io);
}
@ -722,32 +630,27 @@ public class BRouterView extends View
return false;
}
private void paintPosition( int ilon, int ilat, int color, int with )
{
private void paintPosition(int ilon, int ilat, int color, int with) {
int lon = ilon - centerLon;
int lat = ilat - centerLat;
int x = imgw / 2 + (int) (scaleLon * lon);
int y = imgh / 2 - (int) (scaleLat * lat);
for (int nx = x - with; nx <= x + with; nx++)
for ( int ny = y - with; ny <= y + with; ny++ )
{
if ( nx >= 0 && nx < imgw && ny >= 0 && ny < imgh )
{
for (int ny = y - with; ny <= y + with; ny++) {
if (nx >= 0 && nx < imgw && ny >= 0 && ny < imgh) {
imgPixels[nx + imgw * ny] = color;
}
}
}
private void paintCircle( Canvas canvas, OsmNodeNamed n, int color, int minradius )
{
private void paintCircle(Canvas canvas, OsmNodeNamed n, int color, int minradius) {
int lon = n.ilon - centerLon;
int lat = n.ilat - centerLat;
int x = imgw / 2 + (int) (scaleLon * lon);
int y = imgh / 2 - (int) (scaleLat * lat);
int ir = (int) (n.radius * scaleMeter2Pixel);
if ( ir > minradius )
{
if (ir > minradius) {
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
@ -755,8 +658,7 @@ public class BRouterView extends View
}
}
private void paintLine( Canvas canvas, final int ilon0, final int ilat0, final int ilon1, final int ilat1, final Paint paint )
{
private void paintLine(Canvas canvas, final int ilon0, final int ilat0, final int ilon1, final int ilat1, final Paint paint) {
final int lon0 = ilon0 - centerLon;
final int lat0 = ilat0 - centerLat;
final int lon1 = ilon1 - centerLon;
@ -768,21 +670,17 @@ public class BRouterView extends View
canvas.drawLine((float) x0, (float) y0, (float) x1, (float) y1, paint);
}
private void paintPolygon( Canvas canvas, OsmNogoPolygon p, int minradius )
{
private void paintPolygon(Canvas canvas, OsmNogoPolygon p, int minradius) {
final int ir = (int) (p.radius * scaleMeter2Pixel);
if ( ir > minradius )
{
if (ir > minradius) {
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
Point p0 = p.isClosed ? p.points.get(p.points.size() - 1) : null;
for ( final Point p1 : p.points )
{
if (p0 != null)
{
for (final Point p1 : p.points) {
if (p0 != null) {
paintLine(canvas, p0.x, p0.y, p1.x, p1.y, paint);
}
p0 = p1;
@ -791,12 +689,10 @@ public class BRouterView extends View
}
@Override
protected void onSizeChanged( int w, int h, int oldw, int oldh )
{
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
}
private void toast( String msg )
{
private void toast(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_LONG).show();
lastDataTime += 4000; // give time for the toast before exiting
}
@ -805,38 +701,27 @@ public class BRouterView extends View
private long startTime = 0L;
@Override
protected void onDraw( Canvas canvas )
{
try
{
protected void onDraw(Canvas canvas) {
try {
_onDraw(canvas);
}
catch (Throwable t)
{
} catch (Throwable t) {
// on out of mem, try to stop the show
if (cr != null)
cr.cleanOnOOM();
cr = null;
try
{
try {
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
} catch (InterruptedException ie) {
}
((BRouterActivity) getContext()).showErrorMessage(t.toString());
waitingForSelection = true;
}
}
private void showDatabaseScanning( Canvas canvas )
{
try
{
private void showDatabaseScanning(Canvas canvas) {
try {
Thread.sleep(100);
}
catch (InterruptedException ie)
{
} catch (InterruptedException ie) {
}
Paint paint1 = new Paint();
paint1.setColor(Color.WHITE);
@ -851,12 +736,9 @@ public class BRouterView extends View
if (currentDir == null) // scan finished
{
if ( bestGuess.length() == 0 )
{
if (bestGuess.length() == 0) {
((BRouterActivity) getContext()).showErrorMessage("scan did not find any possible waypoint database");
}
else
{
} else {
((BRouterActivity) getContext()).showWpDatabaseScanSuccess(bestGuess);
}
cr = null;
@ -875,10 +757,8 @@ public class BRouterView extends View
invalidate();
}
private void _onDraw( Canvas canvas )
{
if ( dataBaseScanner != null )
{
private void _onDraw(Canvas canvas) {
if (dataBaseScanner != null) {
showDatabaseScanning(canvas);
return;
}
@ -892,28 +772,20 @@ public class BRouterView extends View
while (sleeptime < 200)
sleeptime += 500;
try
{
try {
Thread.sleep(sleeptime);
}
catch (InterruptedException ie)
{
} catch (InterruptedException ie) {
}
lastTs = System.currentTimeMillis();
if ( cr == null || cr.isFinished() )
{
if ( cr != null )
{
if ( cr.getErrorMessage() != null )
{
if (cr == null || cr.isFinished()) {
if (cr != null) {
if (cr.getErrorMessage() != null) {
((BRouterActivity) getContext()).showErrorMessage(cr.getErrorMessage());
cr = null;
waitingForSelection = true;
return;
}
else
{
} else {
String memstat = memoryClass + "mb pathPeak " + ((cr.getPathPeak() + 500) / 1000) + "k";
String result = "version = BRouter-" + getContext().getString(R.string.app_version) + "\n" + "mem = " + memstat + "\ndistance = " + cr.getDistance() / 1000. + " km\n" + "filtered ascend = " + cr.getAscend()
+ " m\n" + "plain ascend = " + cr.getPlainAscend() + " m\n" + "estimated time = " + cr.getTime();
@ -921,8 +793,7 @@ public class BRouterView extends View
rawTrack = cr.getFoundRawTrack();
// for profile "remote", always persist referencetrack
if ( cr.getAlternativeIndex() == 0 && rawTrackPath != null )
{
if (cr.getAlternativeIndex() == 0 && rawTrackPath != null) {
writeRawTrackToPath(rawTrackPath);
}
@ -935,33 +806,26 @@ public class BRouterView extends View
waitingForSelection = true;
return;
}
}
else if ( System.currentTimeMillis() > lastDataTime )
{
} else if (System.currentTimeMillis() > lastDataTime) {
System.exit(0);
}
}
else
{
} else {
lastDataTime = System.currentTimeMillis();
imgPixels = new int[imgw * imgh];
int[] openSet = cr.getOpenSet();
for ( int si = 0; si < openSet.length; si += 2 )
{
for (int si = 0; si < openSet.length; si += 2) {
paintPosition(openSet[si], openSet[si + 1], 0xffffff, 1);
}
// paint nogos on top (red)
for ( int ngi = 0; ngi < nogoList.size(); ngi++ )
{
for (int ngi = 0; ngi < nogoList.size(); ngi++) {
OsmNodeNamed n = nogoList.get(ngi);
int color = 0xff0000;
paintPosition(n.ilon, n.ilat, color, 4);
}
// paint start/end/vias on top (yellow/green/blue)
for ( int wpi = 0; wpi < wpList.size(); wpi++ )
{
for (int wpi = 0; wpi < wpList.size(); wpi++) {
OsmNodeNamed n = wpList.get(wpi);
int color = wpi == 0 ? 0xffff00 : wpi < wpList.size() - 1 ? 0xff : 0xff00;
paintPosition(n.ilon, n.ilat, color, 4);
@ -970,15 +834,11 @@ public class BRouterView extends View
canvas.drawBitmap(imgPixels, 0, imgw, (float) 0., (float) 0., imgw, imgh, false, null);
// nogo circles if any
for ( int ngi = 0; ngi < nogoList.size(); ngi++ )
{
for (int ngi = 0; ngi < nogoList.size(); ngi++) {
OsmNodeNamed n = nogoList.get(ngi);
if (n instanceof OsmNogoPolygon)
{
if (n instanceof OsmNogoPolygon) {
paintPolygon(canvas, (OsmNogoPolygon) n, 4);
}
else
{
} else {
int color = 0xff0000;
paintCircle(canvas, n, color, 4);
}
@ -999,76 +859,58 @@ public class BRouterView extends View
invalidate();
}
private String guessBaseDir()
{
private String guessBaseDir() {
File basedir = Environment.getExternalStorageDirectory();
try
{
try {
File bd2 = new File(basedir, "external_sd");
ArrayList<String> basedirGuesses = new ArrayList<String>();
basedirGuesses.add(basedir.getAbsolutePath());
if ( bd2.exists() )
{
if (bd2.exists()) {
basedir = bd2;
basedirGuesses.add(basedir.getAbsolutePath());
}
ArrayList<CoordinateReader> rl = new ArrayList<CoordinateReader>();
for ( String bdg : basedirGuesses )
{
for (String bdg : basedirGuesses) {
rl.add(new CoordinateReaderOsmAnd(bdg));
rl.add(new CoordinateReaderLocus(bdg));
rl.add(new CoordinateReaderOrux(bdg));
}
long tmax = 0;
CoordinateReader cor = null;
for ( CoordinateReader r : rl )
{
for (CoordinateReader r : rl) {
long t = r.getTimeStamp();
if ( t > tmax )
{
if (t > tmax) {
tmax = t;
cor = r;
}
}
if ( cor != null )
{
if (cor != null) {
return cor.basedir;
}
}
catch (Exception e)
{
} catch (Exception e) {
System.out.println("guessBaseDir:" + e);
}
return basedir.getAbsolutePath();
}
private void writeRawTrackToMode( String mode )
{
private void writeRawTrackToMode(String mode) {
writeRawTrackToPath(modesDir + "/" + mode + "_rawtrack.dat");
}
private void writeRawTrackToPath( String rawTrackPath )
{
if ( rawTrack != null )
{
try
{
private void writeRawTrackToPath(String rawTrackPath) {
if (rawTrack != null) {
try {
rawTrack.writeBinary(rawTrackPath);
} catch (Exception e) {
}
catch (Exception e)
{
}
}
else
{
} else {
new File(rawTrackPath).delete();
}
}
public void startConfigureService()
{
public void startConfigureService() {
String[] modes = new String[]
{"foot_short", "foot_fast", "bicycle_short", "bicycle_fast", "motorcar_short", "motorcar_fast"};
boolean[] modesChecked = new boolean[6];
@ -1078,48 +920,35 @@ public class BRouterView extends View
((BRouterActivity) getContext()).selectRoutingModes(modes, modesChecked, msg);
}
public void configureService( String[] routingModes, boolean[] checkedModes )
{
public void configureService(String[] routingModes, boolean[] checkedModes) {
// read in current config
TreeMap<String, ServiceModeConfig> map = new TreeMap<String, ServiceModeConfig>();
BufferedReader br = null;
String modesFile = modesDir + "/serviceconfig.dat";
try
{
try {
br = new BufferedReader(new FileReader(modesFile));
for ( ;; )
{
for (; ; ) {
String line = br.readLine();
if (line == null)
break;
ServiceModeConfig smc = new ServiceModeConfig(line);
map.put(smc.mode, smc);
}
}
catch (Exception e)
{
}
finally
{
} catch (Exception e) {
} finally {
if (br != null)
try
{
try {
br.close();
}
catch (Exception ee)
{
} catch (Exception ee) {
}
}
// replace selected modes
for ( int i = 0; i < 6; i++ )
{
if ( checkedModes[i] )
{
for (int i = 0; i < 6; i++) {
if (checkedModes[i]) {
writeRawTrackToMode(routingModes[i]);
ServiceModeConfig smc = new ServiceModeConfig(routingModes[i], profileName);
for ( OsmNodeNamed nogo : nogoVetoList )
{
for (OsmNodeNamed nogo : nogoVetoList) {
smc.nogoVetos.add(nogo.ilon + "," + nogo.ilat);
}
map.put(smc.mode, smc);
@ -1131,42 +960,30 @@ public class BRouterView extends View
StringBuilder msg = new StringBuilder("Mode mapping is now:\n");
msg.append("( [");
msg.append(nogoVetoList.size() > 0 ? nogoVetoList.size() : "..").append("] counts nogo-vetos)\n");
try
{
try {
bw = new BufferedWriter(new FileWriter(modesFile));
for ( ServiceModeConfig smc : map.values() )
{
for (ServiceModeConfig smc : map.values()) {
bw.write(smc.toLine());
bw.write('\n');
msg.append(smc.toString()).append('\n');
}
}
catch (Exception e)
{
}
finally
{
} catch (Exception e) {
} finally {
if (bw != null)
try
{
try {
bw.close();
}
catch (Exception ee)
{
} catch (Exception ee) {
}
}
((BRouterActivity) getContext()).showModeConfigOverview(msg.toString());
}
private String readSingleLineFile( File f )
{
private String readSingleLineFile(File f) {
try (FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)) {
return br.readLine();
}
catch (Exception e)
{
} catch (Exception e) {
return null;
}
}

View file

@ -17,8 +17,7 @@ import btools.router.OsmTrack;
import btools.router.RoutingContext;
import btools.router.RoutingEngine;
public class BRouterWorker
{
public class BRouterWorker {
private static final int OUTPUT_FORMAT_GPX = 0;
private static final int OUTPUT_FORMAT_KML = 1;
private static final int OUTPUT_FORMAT_JSON = 2;
@ -66,8 +65,7 @@ public class BRouterWorker
}
if ( params.containsKey( "direction" ) )
{
if (params.containsKey("direction")) {
rc.startDirection = params.getInt("direction");
}
if (params.containsKey("alternativeidx")) {
@ -118,11 +116,10 @@ public class BRouterWorker
}
try
{
try {
writeTimeoutData(rc);
} catch (Exception e) {
}
catch( Exception e ) {}
RoutingEngine cr = new RoutingEngine(null, null, segmentDir, waypoints, rc);
cr.quite = true;
@ -130,17 +127,14 @@ public class BRouterWorker
// store new reference track if any
// (can exist for timed-out search)
if ( cr.getFoundRawTrack() != null )
{
try
{
if (cr.getFoundRawTrack() != null) {
try {
cr.getFoundRawTrack().writeBinary(rawTrackPath);
} catch (Exception e) {
}
catch( Exception e ) {}
}
if ( cr.getErrorMessage() != null )
{
if (cr.getErrorMessage() != null) {
return cr.getErrorMessage();
}
@ -152,52 +146,56 @@ public class BRouterWorker
}
OsmTrack track = cr.getFoundTrack();
if ( track != null )
{
if (track != null) {
if (params.containsKey("exportWaypoints")) {
track.exportWaypoints = (params.getInt("exportWaypoints", 0) == 1);
}
if ( pathToFileResult == null )
{
if (pathToFileResult == null) {
switch (writeFromat) {
case OUTPUT_FORMAT_GPX: return track.formatAsGpx();
case OUTPUT_FORMAT_KML: return track.formatAsKml();
case OUTPUT_FORMAT_JSON: return track.formatAsGeoJson();
default: return track.formatAsGpx();
case OUTPUT_FORMAT_GPX:
return track.formatAsGpx();
case OUTPUT_FORMAT_KML:
return track.formatAsKml();
case OUTPUT_FORMAT_JSON:
return track.formatAsGeoJson();
default:
return track.formatAsGpx();
}
}
try
{
try {
switch (writeFromat) {
case OUTPUT_FORMAT_GPX: track.writeGpx(pathToFileResult); break;
case OUTPUT_FORMAT_KML: track.writeKml(pathToFileResult); break;
case OUTPUT_FORMAT_JSON: track.writeJson(pathToFileResult); break;
default: track.writeGpx(pathToFileResult); break;
case OUTPUT_FORMAT_GPX:
track.writeGpx(pathToFileResult);
break;
case OUTPUT_FORMAT_KML:
track.writeKml(pathToFileResult);
break;
case OUTPUT_FORMAT_JSON:
track.writeJson(pathToFileResult);
break;
default:
track.writeGpx(pathToFileResult);
break;
}
}
catch( Exception e )
{
} catch (Exception e) {
return "error writing file: " + e;
}
}
return null;
}
private List<OsmNodeNamed> readPositions( Bundle params )
{
private List<OsmNodeNamed> readPositions(Bundle params) {
List<OsmNodeNamed> wplist = new ArrayList<OsmNodeNamed>();
double[] lats = params.getDoubleArray("lats");
double[] lons = params.getDoubleArray("lons");
if (lats == null || lats.length < 2 || lons == null || lons.length < 2)
{
if (lats == null || lats.length < 2 || lons == null || lons.length < 2) {
throw new IllegalArgumentException("we need two lat/lon points at least!");
}
for( int i=0; i<lats.length && i<lons.length; i++ )
{
for (int i = 0; i < lats.length && i < lons.length; i++) {
OsmNodeNamed n = new OsmNodeNamed();
n.name = "via" + i;
n.ilon = (int) ((lons[i] + 180.) * 1000000. + 0.5);
@ -210,8 +208,7 @@ public class BRouterWorker
return wplist;
}
private List<OsmNodeNamed> readLonlats(Bundle params )
{
private List<OsmNodeNamed> readLonlats(Bundle params) {
List<OsmNodeNamed> wplist = new ArrayList<OsmNodeNamed>();
String lonLats = params.getString("lonlats");
@ -221,8 +218,7 @@ public class BRouterWorker
if (coords.length < 2)
throw new IllegalArgumentException("we need two lat/lon points at least!");
for (int i = 0; i < coords.length; i++)
{
for (int i = 0; i < coords.length; i++) {
String[] lonLat = coords[i].split(",");
if (lonLat.length < 2)
throw new IllegalArgumentException("we need two lat/lon points at least!");
@ -235,16 +231,14 @@ public class BRouterWorker
return wplist;
}
private static OsmNodeNamed readPosition( String vlon, String vlat, String name )
{
private static OsmNodeNamed readPosition(String vlon, String vlat, String name) {
if (vlon == null) throw new IllegalArgumentException("lon " + name + " not found in input");
if (vlat == null) throw new IllegalArgumentException("lat " + name + " not found in input");
return readPosition(Double.parseDouble(vlon), Double.parseDouble(vlat), name);
}
private static OsmNodeNamed readPosition( double lon, double lat, String name )
{
private static OsmNodeNamed readPosition(double lon, double lat, String name) {
OsmNodeNamed n = new OsmNodeNamed();
n.name = name;
n.ilon = (int) ((lon + 180.) * 1000000. + 0.5);
@ -253,8 +247,7 @@ public class BRouterWorker
}
private void readNogos( Bundle params )
{
private void readNogos(Bundle params) {
if (params.containsKey("nogoLats")) {
double[] lats = params.getDoubleArray("nogoLats");
double[] lons = params.getDoubleArray("nogoLons");
@ -282,8 +275,7 @@ public class BRouterWorker
}
}
private List<OsmNodeNamed> readNogoList(Bundle params)
{
private List<OsmNodeNamed> readNogoList(Bundle params) {
// lon,lat,radius|...
String nogos = params.getString("nogos");
if (nogos == null) return null;
@ -291,8 +283,7 @@ public class BRouterWorker
String[] lonLatRadList = nogos.split("\\|");
List<OsmNodeNamed> nogoList = new ArrayList<OsmNodeNamed>();
for (int i = 0; i < lonLatRadList.length; i++)
{
for (int i = 0; i < lonLatRadList.length; i++) {
String[] lonLatRad = lonLatRadList[i].split(",");
String nogoWeight = "NaN";
if (lonLatRad.length > 3) {
@ -304,14 +295,12 @@ public class BRouterWorker
return nogoList;
}
private static OsmNodeNamed readNogo( String lon, String lat, String radius, String nogoWeight )
{
private static OsmNodeNamed readNogo(String lon, String lat, String radius, String nogoWeight) {
double weight = "undefined".equals(nogoWeight) ? Double.NaN : Double.parseDouble(nogoWeight);
return readNogo(Double.parseDouble(lon), Double.parseDouble(lat), Integer.parseInt(radius), weight);
}
private static OsmNodeNamed readNogo( double lon, double lat, int radius, double nogoWeight )
{
private static OsmNodeNamed readNogo(double lon, double lat, int radius, double nogoWeight) {
OsmNodeNamed n = new OsmNodeNamed();
n.name = "nogo" + radius;
n.ilon = (int) ((lon + 180.) * 1000000. + 0.5);
@ -321,30 +310,24 @@ public class BRouterWorker
return n;
}
private List<OsmNodeNamed> readNogoPolygons(Bundle params)
{
private List<OsmNodeNamed> readNogoPolygons(Bundle params) {
List<OsmNodeNamed> result = new ArrayList<OsmNodeNamed>();
parseNogoPolygons(params.getString("polylines"), result, false);
parseNogoPolygons(params.getString("polygons"), result, true);
return result.size() > 0 ? result : null;
}
private static void parseNogoPolygons(String polygons, List<OsmNodeNamed> result, boolean closed )
{
if ( polygons != null )
{
private static void parseNogoPolygons(String polygons, List<OsmNodeNamed> result, boolean closed) {
if (polygons != null) {
OsmNogoPolygon polygon = new OsmNogoPolygon(closed);
polygon.name = "nogopoly";
String nogoWeight = "NaN";
String[] polygonList = polygons.split("\\|");
for (int i = 0; i < polygonList.length; i++)
{
for (int i = 0; i < polygonList.length; i++) {
String[] lonLatList = polygonList[i].split(",");
if ( lonLatList.length > 1 )
{
if (lonLatList.length > 1) {
int j;
for (j = 0; j < 2 * (lonLatList.length / 2) - 1;)
{
for (j = 0; j < 2 * (lonLatList.length / 2) - 1; ) {
String slon = lonLatList[j++];
String slat = lonLatList[j++];
int lon = (int) ((Double.parseDouble(slon) + 180.) * 1000000. + 0.5);
@ -360,29 +343,23 @@ public class BRouterWorker
}
polygon.nogoWeight = Double.parseDouble(nogoWeight);
if ( polygon.points.size() > 0 )
{
if (polygon.points.size() > 0) {
polygon.calcBoundingCircle();
result.add(polygon);
}
}
}
private static void parseNogoPolygons_alt(String polygons, List<OsmNodeNamed> result, boolean closed )
{
if ( polygons != null )
{
private static void parseNogoPolygons_alt(String polygons, List<OsmNodeNamed> result, boolean closed) {
if (polygons != null) {
String[] polygonList = polygons.split("\\|");
for (int i = 0; i < polygonList.length; i++)
{
for (int i = 0; i < polygonList.length; i++) {
String[] lonLatList = polygonList[i].split(",");
if ( lonLatList.length > 1 )
{
if (lonLatList.length > 1) {
OsmNogoPolygon polygon = new OsmNogoPolygon(closed);
polygon.name = "nogo" + i;
int j;
for (j = 0; j < 2 * (lonLatList.length / 2) - 1;)
{
for (j = 0; j < 2 * (lonLatList.length / 2) - 1; ) {
String slon = lonLatList[j++];
String slat = lonLatList[j++];
int lon = (int) ((Double.parseDouble(slon) + 180.) * 1000000. + 0.5);
@ -396,8 +373,7 @@ public class BRouterWorker
}
polygon.nogoWeight = Double.parseDouble(nogoWeight);
if ( polygon.points.size() > 0 )
{
if (polygon.points.size() > 0) {
polygon.calcBoundingCircle();
result.add(polygon);
}
@ -406,8 +382,7 @@ public class BRouterWorker
}
}
private List<OsmNodeNamed> readPoisList(Bundle params )
{
private List<OsmNodeNamed> readPoisList(Bundle params) {
// lon,lat,name|...
String pois = params.getString("pois");
if (pois == null) return null;
@ -415,8 +390,7 @@ public class BRouterWorker
String[] lonLatNameList = pois.split("\\|");
List<OsmNodeNamed> poisList = new ArrayList<OsmNodeNamed>();
for (int i = 0; i < lonLatNameList.length; i++)
{
for (int i = 0; i < lonLatNameList.length; i++) {
String[] lonLatName = lonLatNameList[i].split(",");
OsmNodeNamed n = new OsmNodeNamed();
@ -429,8 +403,7 @@ public class BRouterWorker
return poisList;
}
private void writeTimeoutData( RoutingContext rc ) throws Exception
{
private void writeTimeoutData(RoutingContext rc) throws Exception {
String timeoutFile = baseDir + "/brouter/modes/timeoutdata.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(timeoutFile));
@ -443,11 +416,9 @@ public class BRouterWorker
bw.close();
}
private void writeWPList( BufferedWriter bw, List<OsmNodeNamed> wps ) throws Exception
{
private void writeWPList(BufferedWriter bw, List<OsmNodeNamed> wps) throws Exception {
bw.write(wps.size() + "\n");
for( OsmNodeNamed wp : wps )
{
for (OsmNodeNamed wp : wps) {
bw.write(wp.toString());
bw.write("\n");
}

View file

@ -10,31 +10,25 @@ import java.io.File;
import android.content.Context;
public class ConfigHelper
{
public static File getBaseDir( Context ctx )
{
public class ConfigHelper {
public static File getBaseDir(Context ctx) {
// get base dir from private file
try (InputStream configInput = ctx.openFileInput("config15.dat");
InputStreamReader isr = new InputStreamReader(configInput);
BufferedReader br = new BufferedReader(isr)) {
return new File(br.readLine());
}
catch (Exception e)
{
} catch (Exception e) {
return null;
}
}
public static void writeBaseDir( Context ctx, File baseDir )
{
public static void writeBaseDir(Context ctx, File baseDir) {
try (OutputStream configOutput = ctx.openFileOutput("config15.dat", Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(configOutput);
BufferedWriter bw = new BufferedWriter(osw)) {
bw.write(baseDir.getAbsolutePath());
bw.write('\n');
}
catch (Exception e){ /* ignore */ }
} catch (Exception e) { /* ignore */ }
}
}

View file

@ -8,10 +8,8 @@ import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class ConfigMigration
{
public static void tryMigrateStorageConfig( File srcFile, File dstFile )
{
public class ConfigMigration {
public static void tryMigrateStorageConfig(File srcFile, File dstFile) {
if (!srcFile.exists()) return;
String ssd = null;
@ -19,22 +17,17 @@ public class ConfigMigration
BufferedReader br = null;
BufferedWriter bw = null;
try
{
try {
br = new BufferedReader(new FileReader(srcFile));
for ( ;; )
{
for (; ; ) {
String line = br.readLine();
if (line == null) break;
if ( line.trim().startsWith( "secondary_segment_dir=" ) )
{
if ( !"secondary_segment_dir=../segments2".equals( line ) )
{
if (line.trim().startsWith("secondary_segment_dir=")) {
if (!"secondary_segment_dir=../segments2".equals(line)) {
ssd = line;
}
}
if ( line.trim().startsWith( "additional_maptool_dir=" ) )
{
if (line.trim().startsWith("additional_maptool_dir=")) {
amd = line;
}
}
@ -42,16 +35,13 @@ public class ConfigMigration
List<String> lines = new ArrayList<String>();
br = new BufferedReader(new FileReader(dstFile));
for ( ;; )
{
for (; ; ) {
String line = br.readLine();
if (line == null) break;
if ( ssd != null && line.trim().startsWith( "secondary_segment_dir=" ) )
{
if (ssd != null && line.trim().startsWith("secondary_segment_dir=")) {
line = ssd;
}
if ( amd != null && line.trim().startsWith( "#additional_maptool_dir=" ) )
{
if (amd != null && line.trim().startsWith("#additional_maptool_dir=")) {
line = amd;
}
lines.add(line);
@ -60,54 +50,39 @@ public class ConfigMigration
br = null;
bw = new BufferedWriter(new FileWriter(dstFile));
for( String line: lines )
{
for (String line : lines) {
bw.write(line + "\n");
}
}
catch (Exception e) { /* ignore */ }
finally
{
if ( br != null )
{
try
{
} catch (Exception e) { /* ignore */ } finally {
if (br != null) {
try {
br.close();
} catch (Exception ee) { /* ignore */ }
}
catch (Exception ee) { /* ignore */ }
}
if ( bw != null )
{
try
{
if (bw != null) {
try {
bw.close();
}
catch (Exception ee) { /* ignore */ }
} catch (Exception ee) { /* ignore */ }
}
}
}
public static File saveAdditionalMaptoolDir( File segmentDir, String value )
{
public static File saveAdditionalMaptoolDir(File segmentDir, String value) {
return saveStorageLocation(segmentDir, "additional_maptool_dir=", value);
}
private static File saveStorageLocation( File segmentDir, String tag, String value )
{
private static File saveStorageLocation(File segmentDir, String tag, String value) {
File res = null;
BufferedReader br = null;
BufferedWriter bw = null;
File configFile = new File(segmentDir, "storageconfig.txt");
List<String> lines = new ArrayList<String>();
try
{
try {
br = new BufferedReader(new FileReader(configFile));
for ( ;; )
{
for (; ; ) {
String line = br.readLine();
if (line == null) break;
if ( !line.trim().startsWith( tag ) )
{
if (!line.trim().startsWith(tag)) {
lines.add(line);
}
}
@ -115,29 +90,19 @@ public class ConfigMigration
br.close();
br = null;
bw = new BufferedWriter(new FileWriter(configFile));
for( String line : lines )
{
for (String line : lines) {
bw.write(line + "\r\n");
}
}
catch (Exception e) { /* ignore */ }
finally
{
if ( br != null )
{
try
{
} catch (Exception e) { /* ignore */ } finally {
if (br != null) {
try {
br.close();
} catch (Exception ee) { /* ignore */ }
}
catch (Exception ee) { /* ignore */ }
}
if ( bw != null )
{
try
{
if (bw != null) {
try {
bw.close();
}
catch (Exception ee) { /* ignore */ }
} catch (Exception ee) { /* ignore */ }
}
}
return res;

View file

@ -11,14 +11,14 @@ import java.util.Set;
import java.util.TreeMap;
import android.os.Environment;
import btools.router.OsmNodeNamed;
import btools.router.RoutingHelper;
/**
* Read coordinates from a gpx-file
*/
public abstract class CoordinateReader
{
public abstract class CoordinateReader {
public List<OsmNodeNamed> waypoints;
public List<OsmNodeNamed> nogopoints;
public String basedir;
@ -35,8 +35,7 @@ public abstract class CoordinateReader
protected static String[] posnames
= new String[]{"from", "via1", "via2", "via3", "via4", "via5", "via6", "via7", "via8", "via9", "to"};
public CoordinateReader( String basedir )
{
public CoordinateReader(String basedir) {
this.basedir = basedir;
}
@ -44,27 +43,20 @@ public abstract class CoordinateReader
public abstract int getTurnInstructionMode();
public void readAllPoints() throws Exception
{
public void readAllPoints() throws Exception {
allpointsMap = new TreeMap<String, Map<String, OsmNodeNamed>>();
readFromTo();
allpoints = new ArrayList<OsmNodeNamed>();
Set<String> names = new HashSet<String>();
for( String category : allpointsMap.keySet() )
{
for (String category : allpointsMap.keySet()) {
Map<String, OsmNodeNamed> cat = allpointsMap.get(category);
if ( cat.size() < 101 )
{
for ( OsmNodeNamed wp : cat.values() )
{
if ( names.add( wp.name ) )
{
if (cat.size() < 101) {
for (OsmNodeNamed wp : cat.values()) {
if (names.add(wp.name)) {
allpoints.add(wp);
}
}
}
else
{
} else {
OsmNodeNamed nocatHint = new OsmNodeNamed();
nocatHint.name = "<big category " + category + " supressed>";
allpoints.add(nocatHint);
@ -75,23 +67,18 @@ public abstract class CoordinateReader
/*
* read the from, to and via-positions from a gpx-file
*/
public void readFromTo() throws Exception
{
public void readFromTo() throws Exception {
pointmap = new HashMap<String, OsmNodeNamed>();
waypoints = new ArrayList<OsmNodeNamed>();
nogopoints = new ArrayList<OsmNodeNamed>();
readPointmap();
boolean fromToMissing = false;
for( int i=0; i<posnames.length; i++ )
{
for (int i = 0; i < posnames.length; i++) {
String name = posnames[i];
OsmNodeNamed n = pointmap.get(name);
if ( n != null )
{
if (n != null) {
waypoints.add(n);
}
else
{
} else {
if ("from".equals(name)) fromToMissing = true;
if ("to".equals(name)) fromToMissing = true;
}
@ -99,46 +86,35 @@ public abstract class CoordinateReader
if (fromToMissing) waypoints.clear();
}
protected void checkAddPoint( String category, OsmNodeNamed n )
{
if ( allpointsMap != null )
{
protected void checkAddPoint(String category, OsmNodeNamed n) {
if (allpointsMap != null) {
if (category == null) category = "";
Map<String, OsmNodeNamed> cat = allpointsMap.get(category);
if ( cat == null )
{
if (cat == null) {
cat = new TreeMap<String, OsmNodeNamed>();
allpointsMap.put(category, cat);
}
if ( cat.size() < 101 )
{
if (cat.size() < 101) {
cat.put(n.name, n);
}
return;
}
boolean isKnown = false;
for( int i=0; i<posnames.length; i++ )
{
if ( posnames[i].equals( n.name ) )
{
for (int i = 0; i < posnames.length; i++) {
if (posnames[i].equals(n.name)) {
isKnown = true;
break;
}
}
if ( isKnown )
{
if ( pointmap.put( n.name, n ) != null )
{
if ( !nogosOnly )
{
if (isKnown) {
if (pointmap.put(n.name, n) != null) {
if (!nogosOnly) {
throw new IllegalArgumentException("multiple " + n.name + "-positions!");
}
}
}
else if ( n.name != null && n.name.startsWith( "nogo" ) )
{
} else if (n.name != null && n.name.startsWith("nogo")) {
n.isNogo = true;
n.nogoWeight = Double.NaN;
nogopoints.add(n);
@ -149,13 +125,11 @@ public abstract class CoordinateReader
protected abstract void readPointmap() throws Exception;
public static CoordinateReader obtainValidReader( String basedir, File segmentDir, boolean canAccessSdCard ) throws Exception
{
public static CoordinateReader obtainValidReader(String basedir, File segmentDir, boolean canAccessSdCard) throws Exception {
return obtainValidReader(basedir, segmentDir, canAccessSdCard, false);
}
public static CoordinateReader obtainValidReader( String basedir, File segmentDir, boolean canAccessSdCard, boolean nogosOnly ) throws Exception
{
public static CoordinateReader obtainValidReader(String basedir, File segmentDir, boolean canAccessSdCard, boolean nogosOnly) throws Exception {
CoordinateReader cor = null;
ArrayList<CoordinateReader> rl = new ArrayList<CoordinateReader>();
@ -210,8 +184,7 @@ public abstract class CoordinateReader
}
}
}
if ( cor == null )
{
if (cor == null) {
cor = new CoordinateReaderInternal(basedir);
}
cor.nogosOnly = nogosOnly;

View file

@ -21,26 +21,20 @@ import btools.router.OsmNogoPolygon;
/**
* Read coordinates from a gpx-file
*/
public class CoordinateReaderInternal extends CoordinateReader
{
public class CoordinateReaderInternal extends CoordinateReader {
private String internalDir;
public CoordinateReaderInternal(String basedir )
{
public CoordinateReaderInternal(String basedir) {
this(basedir, false);
}
public CoordinateReaderInternal(String basedir, boolean shortPath )
{
public CoordinateReaderInternal(String basedir, boolean shortPath) {
super(basedir);
if ( shortPath )
{
if (shortPath) {
internalDir = basedir;
tracksdir = "/tracks";
rootdir = "";
}
else
{
} else {
internalDir = basedir + "/brouter/import";
tracksdir = "/brouter/import/tracks";
rootdir = "/brouter/import";
@ -48,16 +42,14 @@ public class CoordinateReaderInternal extends CoordinateReader
}
@Override
public long getTimeStamp() throws Exception
{
public long getTimeStamp() throws Exception {
long t1 = new File(internalDir + "/favourites_bak.gpx").lastModified();
long t2 = new File(internalDir + "/favourites.gpx").lastModified();
return t1 > t2 ? t1 : t2;
}
@Override
public int getTurnInstructionMode()
{
public int getTurnInstructionMode() {
return 4; // comment style
}
@ -66,23 +58,18 @@ public class CoordinateReaderInternal extends CoordinateReader
* (with hardcoded name for now)
*/
@Override
public void readPointmap() throws Exception
{
public void readPointmap() throws Exception {
if (!_readPointmap(internalDir + "/favourites_bak.gpx")) {
_readPointmap(internalDir + "/favourites.gpx");
}
try
{
try {
_readNogoLines(basedir + tracksdir);
}
catch( IOException ioe )
{
} catch (IOException ioe) {
}
}
private boolean _readPointmap( String filename ) throws Exception
{
private boolean _readPointmap(String filename) throws Exception {
BufferedReader br = null;
try {
br = new BufferedReader(
@ -94,15 +81,13 @@ public class CoordinateReaderInternal extends CoordinateReader
}
OsmNodeNamed n = null;
for(;;)
{
for (; ; ) {
String line = br.readLine();
if (line == null) break;
int idx0 = line.indexOf(" lat=\"");
int idx10 = line.indexOf("<name>");
if ( idx0 >= 0 )
{
if (idx0 >= 0) {
n = new OsmNodeNamed();
idx0 += 6;
int idx1 = line.indexOf('"', idx0);
@ -114,12 +99,10 @@ public class CoordinateReaderInternal extends CoordinateReader
n.ilon = (int) ((Double.parseDouble(line.substring(idx2, idx3)) + 180.) * 1000000. + 0.5);
if (idx3 < 0) continue;
}
if ( n != null && idx10 >= 0 )
{
if (n != null && idx10 >= 0) {
idx10 += 6;
int idx11 = line.indexOf("</name>", idx10);
if ( idx11 >= 0 )
{
if (idx11 >= 0) {
n.name = line.substring(idx10, idx11).trim();
checkAddPoint("(one-for-all)", n);
}
@ -129,32 +112,24 @@ public class CoordinateReaderInternal extends CoordinateReader
return true;
}
private void _readNogoLines( String dirname ) throws IOException
{
private void _readNogoLines(String dirname) throws IOException {
File dir = new File(dirname);
if (dir.exists() && dir.isDirectory())
{
for (final File file : dir.listFiles())
{
if (dir.exists() && dir.isDirectory()) {
for (final File file : dir.listFiles()) {
final String name = file.getName();
if (name.startsWith("nogo") && name.endsWith(".gpx"))
{
try
{
if (name.startsWith("nogo") && name.endsWith(".gpx")) {
try {
_readNogoLine(file);
}
catch (Exception e)
{
} catch (Exception e) {
}
}
}
}
}
private void _readNogoLine( File file ) throws Exception
{
private void _readNogoLine(File file) throws Exception {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();

View file

@ -4,23 +4,21 @@ import java.io.File;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import btools.router.OsmNodeNamed;
/**
* Read coordinates from a gpx-file
*/
public class CoordinateReaderLocus extends CoordinateReader
{
public CoordinateReaderLocus( String basedir )
{
public class CoordinateReaderLocus extends CoordinateReader {
public CoordinateReaderLocus(String basedir) {
super(basedir);
tracksdir = "/Locus/mapItems";
rootdir = "/Locus";
}
@Override
public long getTimeStamp() throws Exception
{
public long getTimeStamp() throws Exception {
File f = new File(basedir + "/Locus/data/database/waypoints.db");
long t1 = f.lastModified();
// Android 10 delivers file size but can't read it
@ -29,8 +27,7 @@ public class CoordinateReaderLocus extends CoordinateReader
}
@Override
public int getTurnInstructionMode()
{
public int getTurnInstructionMode() {
return 2; // locus style
}
@ -39,13 +36,11 @@ public class CoordinateReaderLocus extends CoordinateReader
* (with hardcoded name for now)
*/
@Override
public void readPointmap() throws Exception
{
public void readPointmap() throws Exception {
_readPointmap(basedir + "/Locus/data/database/waypoints.db");
}
private void _readPointmap( String filename ) throws Exception
{
private void _readPointmap(String filename) throws Exception {
SQLiteDatabase myDataBase = null;
try {
myDataBase = SQLiteDatabase.openDatabase(filename, null, SQLiteDatabase.OPEN_READONLY);
@ -59,8 +54,7 @@ public class CoordinateReaderLocus extends CoordinateReader
c.close();
c = myDataBase.rawQuery("SELECT c.name, w.name, w.longitude, w.latitude FROM waypoints w, groups c where w.parent_id = c._id;", null);
}
while (c.moveToNext())
{
while (c.moveToNext()) {
OsmNodeNamed n = new OsmNodeNamed();
String category = c.getString(0);
n.name = c.getString(1);

View file

@ -4,23 +4,21 @@ import java.io.File;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import btools.router.OsmNodeNamed;
/**
* Read coordinates from a gpx-file
*/
public class CoordinateReaderOrux extends CoordinateReader
{
public CoordinateReaderOrux( String basedir )
{
public class CoordinateReaderOrux extends CoordinateReader {
public CoordinateReaderOrux(String basedir) {
super(basedir);
tracksdir = "/oruxmaps/tracklogs";
rootdir = "/oruxmaps";
}
@Override
public long getTimeStamp() throws Exception
{
public long getTimeStamp() throws Exception {
File f = new File(basedir + "/oruxmaps/tracklogs/oruxmapstracks.db");
long t1 = f.lastModified();
// Android 10 delivers file size but can't read it
@ -29,8 +27,7 @@ public class CoordinateReaderOrux extends CoordinateReader
}
@Override
public int getTurnInstructionMode()
{
public int getTurnInstructionMode() {
return 0; // none
}
@ -39,13 +36,11 @@ public class CoordinateReaderOrux extends CoordinateReader
* (with hardcoded name for now)
*/
@Override
public void readPointmap() throws Exception
{
public void readPointmap() throws Exception {
_readPointmap(basedir + "/oruxmaps/tracklogs/oruxmapstracks.db");
}
private void _readPointmap( String filename ) throws Exception
{
private void _readPointmap(String filename) throws Exception {
SQLiteDatabase myDataBase = null;
try {
myDataBase = SQLiteDatabase.openDatabase(filename, null, SQLiteDatabase.OPEN_READONLY);
@ -54,8 +49,7 @@ public class CoordinateReaderOrux extends CoordinateReader
return;
}
Cursor c = myDataBase.rawQuery("SELECT poiname, poilon, poilat, poifolder FROM pois", null);
while (c.moveToNext())
{
while (c.moveToNext()) {
OsmNodeNamed n = new OsmNodeNamed();
n.name = c.getString(0);
n.ilon = (int) ((c.getDouble(1) + 180.) * 1000000. + 0.5);

View file

@ -16,26 +16,20 @@ import btools.router.OsmNogoPolygon;
/**
* Read coordinates from a gpx-file
*/
public class CoordinateReaderOsmAnd extends CoordinateReader
{
public class CoordinateReaderOsmAnd extends CoordinateReader {
private String osmandDir;
public CoordinateReaderOsmAnd( String basedir )
{
public CoordinateReaderOsmAnd(String basedir) {
this(basedir, false);
}
public CoordinateReaderOsmAnd( String basedir, boolean shortPath )
{
public CoordinateReaderOsmAnd(String basedir, boolean shortPath) {
super(basedir);
if ( shortPath )
{
if (shortPath) {
osmandDir = basedir;
tracksdir = "/tracks";
rootdir = "";
}
else
{
} else {
osmandDir = basedir + "/osmand";
tracksdir = "/osmand/tracks";
rootdir = "/osmand";
@ -43,8 +37,7 @@ public class CoordinateReaderOsmAnd extends CoordinateReader
}
@Override
public long getTimeStamp() throws Exception
{
public long getTimeStamp() throws Exception {
File f1 = new File(osmandDir + "/favourites_bak.gpx");
File f2 = new File(osmandDir + "/favourites.gpx");
long t1 = f1.canRead() ? f1.lastModified() : 0L;
@ -53,8 +46,7 @@ public class CoordinateReaderOsmAnd extends CoordinateReader
}
@Override
public int getTurnInstructionMode()
{
public int getTurnInstructionMode() {
return 3; // osmand style
}
@ -63,41 +55,31 @@ public class CoordinateReaderOsmAnd extends CoordinateReader
* (with hardcoded name for now)
*/
@Override
public void readPointmap() throws Exception
{
try
{
public void readPointmap() throws Exception {
try {
_readPointmap(osmandDir + "/favourites_bak.gpx");
}
catch( Exception e )
{
} catch (Exception e) {
_readPointmap(osmandDir + "/favourites.gpx");
}
try
{
try {
_readNogoLines(basedir + tracksdir);
}
catch( IOException ioe )
{
} catch (IOException ioe) {
}
}
private void _readPointmap( String filename ) throws Exception
{
private void _readPointmap(String filename) throws Exception {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(filename)));
OsmNodeNamed n = null;
for(;;)
{
for (; ; ) {
String line = br.readLine();
if (line == null) break;
int idx0 = line.indexOf("<wpt lat=\"");
int idx10 = line.indexOf("<name>");
if ( idx0 >= 0 )
{
if (idx0 >= 0) {
n = new OsmNodeNamed();
idx0 += 10;
int idx1 = line.indexOf('"', idx0);
@ -109,12 +91,10 @@ public class CoordinateReaderOsmAnd extends CoordinateReader
n.ilon = (int) ((Double.parseDouble(line.substring(idx2, idx3)) + 180.) * 1000000. + 0.5);
continue;
}
if ( n != null && idx10 >= 0 )
{
if (n != null && idx10 >= 0) {
idx10 += 6;
int idx11 = line.indexOf("</name>", idx10);
if ( idx11 >= 0 )
{
if (idx11 >= 0) {
n.name = line.substring(idx10, idx11).trim();
checkAddPoint("(one-for-all)", n);
}
@ -123,32 +103,24 @@ public class CoordinateReaderOsmAnd extends CoordinateReader
br.close();
}
private void _readNogoLines( String dirname ) throws IOException
{
private void _readNogoLines(String dirname) throws IOException {
File dir = new File(dirname);
if (dir.exists() && dir.isDirectory())
{
for (final File file : dir.listFiles())
{
if (dir.exists() && dir.isDirectory()) {
for (final File file : dir.listFiles()) {
final String name = file.getName();
if (name.startsWith("nogo") && name.endsWith(".gpx"))
{
try
{
if (name.startsWith("nogo") && name.endsWith(".gpx")) {
try {
_readNogoLine(file);
}
catch (Exception e)
{
} catch (Exception e) {
}
}
}
}
}
private void _readNogoLine( File file ) throws Exception
{
private void _readNogoLine(File file) throws Exception {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
@ -176,8 +148,7 @@ public class CoordinateReaderOsmAnd extends CoordinateReader
nogo.calcBoundingCircle();
final String name = file.getName();
nogo.name = name.substring(0, name.length() - 4);
if (numSeg > 0)
{
if (numSeg > 0) {
nogo.name += Integer.toString(numSeg + 1);
}
numSeg++;

View file

@ -81,13 +81,11 @@ public class DownloadService extends Service implements ProgressListener {
mServiceHandler = new ServiceHandler(mServiceLooper);
availableSize = -1;
try
{
try {
availableSize = BInstallerActivity.getAvailableSpace(baseDir);
//StatFs stat = new StatFs(baseDir);
//availableSize = (long)stat.getAvailableBlocksLong()*stat.getBlockSizeLong();
}
catch (Exception e) { /* ignore */ }
} catch (Exception e) { /* ignore */ }
}
@ -166,32 +164,28 @@ public class DownloadService extends Service implements ProgressListener {
}
public void updateProgress( String progress )
{
if ( !newDownloadAction.equals( progress ) )
{
public void updateProgress(String progress) {
if (!newDownloadAction.equals(progress)) {
if (DEBUG) Log.d("BR", "up " + progress);
Intent intent = new Intent(BInstallerActivity.DOWNLOAD_ACTION);
intent.putExtra("txt", progress);
intent.putExtra("ready", bIsDownloading);
sendBroadcast(intent);;
sendBroadcast(intent);
;
newDownloadAction = progress;
mNotificationHelper.progressUpdate(newDownloadAction);
}
}
private String download(int counter, int size, String surl)
{
private String download(int counter, int size, String surl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
File fname = null;
File tmp_file = null;
try
{
try
{
try {
try {
TrafficStats.setThreadStatsTag(1);
int slidx = surl.lastIndexOf("segments4/");
@ -202,8 +196,7 @@ public class DownloadService extends Service implements ProgressListener {
boolean delta = true;
// if (!targetFile.getParentFile().exists()) targetFile.getParentFile().mkdirs();
if ( fname.exists() )
{
if (fname.exists()) {
updateProgress("Calculating local checksum..");
// first check for a delta file
@ -217,16 +210,14 @@ public class DownloadService extends Service implements ProgressListener {
connection.connect();
// 404 kind of expected here, means there's no delta file
if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND )
{
if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
connection = null;
} else {
updateProgress("Connecting.." + surlDelta);
}
}
if ( connection == null )
{
if (connection == null) {
updateProgress("Connecting.." + name);
delta = false;
@ -274,9 +265,7 @@ public class DownloadService extends Service implements ProgressListener {
{
int pct = (int) (total * 100 / fileLength);
updateProgress("Progress " + counter + "/" + size + " .. " + pct + "%");
}
else
{
} else {
updateProgress("Progress (unnown size)");
}
@ -284,28 +273,27 @@ public class DownloadService extends Service implements ProgressListener {
// enforce < 2 Mbit/s
long dt = t0 + total / 524 - System.currentTimeMillis();
if ( dt > 0 )
{
try { Thread.sleep( dt ); } catch( InterruptedException ie ) {}
if (dt > 0) {
try {
Thread.sleep(dt);
} catch (InterruptedException ie) {
}
}
}
output.close();
output = null;
if ( delta )
{
if (delta) {
updateProgress("Applying delta..");
File diffFile = tmp_file;
tmp_file = new File(fname + "_tmp");
Rd5DiffTool.recoverFromDelta(fname, diffFile, tmp_file, this);
diffFile.delete();
}
if (isCanceled())
{
if (isCanceled()) {
return "Canceled!";
}
if ( tmp_file != null )
{
if (tmp_file != null) {
updateProgress("Verifying integrity..");
String check_result = PhysicalFile.checkFileIntegrity(tmp_file);
if (check_result != null) {
@ -315,8 +303,7 @@ public class DownloadService extends Service implements ProgressListener {
return check_result;
}
if (fname.exists()) fname.delete();
if ( !tmp_file.renameTo( fname ) )
{
if (!tmp_file.renameTo(fname)) {
return "Could not rename to " + fname.getAbsolutePath();
}
@ -337,9 +324,7 @@ public class DownloadService extends Service implements ProgressListener {
if (connection != null)
connection.disconnect();
}
}
finally
{
} finally {
if (tmp_file != null) tmp_file.delete(); // just to be sure
}
}
@ -391,10 +376,8 @@ public class DownloadService extends Service implements ProgressListener {
File tmp_file = null;
File targetFile = f;
try
{
try
{
try {
try {
TrafficStats.setThreadStatsTag(1);
URL url = new URL(surl);
@ -463,16 +446,13 @@ public class DownloadService extends Service implements ProgressListener {
output = null;
}
if (isCanceled())
{
if (isCanceled()) {
return "Canceled!";
}
if ( tmp_file != null )
{
if (tmp_file != null) {
f.delete();
if ( !tmp_file.renameTo( f ) )
{
if (!tmp_file.renameTo(f)) {
return "Could not rename to " + f.getName();
}
if (DEBUG) Log.d("BR", "update " + f.getName());
@ -493,9 +473,7 @@ public class DownloadService extends Service implements ProgressListener {
connection.disconnect();
}
}
finally
{
} finally {
if (tmp_file != null) tmp_file.delete(); // just to be sure
}

View file

@ -29,8 +29,7 @@ public class NotificationHelper {
private PendingIntent mContentIntent;
private CharSequence mContentTitle;
public NotificationHelper(Context context)
{
public NotificationHelper(Context context) {
if (DEBUG) Log.d("NH", "init ");
mContext = context;
createNotificationChannels();

View file

@ -7,41 +7,35 @@ import java.util.TreeSet;
/**
* Decsription of a service config
*/
public class ServiceModeConfig
{
public class ServiceModeConfig {
public String mode;
public String profile;
public TreeSet<String> nogoVetos;
public ServiceModeConfig( String line )
{
public ServiceModeConfig(String line) {
StringTokenizer tk = new StringTokenizer(line);
mode = tk.nextToken();
profile = tk.nextToken();
nogoVetos = new TreeSet<String>();
while( tk.hasMoreTokens() )
{
while (tk.hasMoreTokens()) {
nogoVetos.add(tk.nextToken());
}
}
public ServiceModeConfig( String mode, String profile )
{
public ServiceModeConfig(String mode, String profile) {
this.mode = mode;
this.profile = profile;
nogoVetos = new TreeSet<String>();
}
public String toLine()
{
public String toLine() {
StringBuilder sb = new StringBuilder(100);
sb.append(mode).append(' ').append(profile);
for (String veto : nogoVetos) sb.append(' ').append(veto);
return sb.toString();
}
public String toString()
{
public String toString() {
StringBuilder sb = new StringBuilder(100);
sb.append(mode).append("->").append(profile);
sb.append(" [" + nogoVetos.size() + "]");

View file

@ -2,8 +2,7 @@ package btools.routingapp;
import java.io.File;
public class WpDatabaseScanner extends Thread
{
public class WpDatabaseScanner extends Thread {
private String currentDir = "";
private String bestGuess = "";
private String lastError = "";
@ -12,66 +11,49 @@ public class WpDatabaseScanner extends Thread
private long maxtimestamp = 0;
public String getCurrentDir()
{
synchronized (currentDirSync)
{
public String getCurrentDir() {
synchronized (currentDirSync) {
return currentDir;
}
}
private void setCurrentDir( String dir )
{
synchronized (currentDirSync)
{
private void setCurrentDir(String dir) {
synchronized (currentDirSync) {
currentDir = dir;
}
}
public String getBestGuess()
{
synchronized (currentDirSync)
{
public String getBestGuess() {
synchronized (currentDirSync) {
return bestGuess;
}
}
public String getLastError()
{
synchronized (currentDirSync)
{
public String getLastError() {
synchronized (currentDirSync) {
return lastError;
}
}
private void setLastError( String msg )
{
synchronized (currentDirSync)
{
private void setLastError(String msg) {
synchronized (currentDirSync) {
lastError = msg;
}
}
private static String[] vetos = new String[]{"dev", "sys", "system", "proc", "etc", "init", "d", "cache", "acct", "data"};
private void scan( File dir, int level )
{
if ( level > 8 )
{
private void scan(File dir, int level) {
if (level > 8) {
return;
}
try
{
if ( dir.isDirectory() )
{
if ( level == 1 )
{
try {
if (dir.isDirectory()) {
if (level == 1) {
String name = dir.getName();
for( String veto: vetos )
{
if ( veto.equals( name ) )
{
for (String veto : vetos) {
if (veto.equals(name)) {
return;
}
}
@ -79,24 +61,19 @@ public class WpDatabaseScanner extends Thread
testPath(dir.getPath());
File[] childs = dir.listFiles();
if ( childs == null )
{
if (childs == null) {
return;
}
for ( File child : childs )
{
for (File child : childs) {
scan(child, level + 1);
}
}
}
catch (Exception e)
{
} catch (Exception e) {
setLastError(e.toString());
}
}
private void testPath( String path ) throws Exception
{
private void testPath(String path) throws Exception {
setCurrentDir(path);
testReader(new CoordinateReaderOsmAnd(path));
@ -105,23 +82,16 @@ public class WpDatabaseScanner extends Thread
testReader(new CoordinateReaderOrux(path));
}
private void testReader( CoordinateReader cor ) throws Exception
{
private void testReader(CoordinateReader cor) throws Exception {
long ts = cor.getTimeStamp();
if ( ts > maxtimestamp )
{
if (ts > maxtimestamp) {
maxtimestamp = ts;
synchronized (currentDirSync)
{
synchronized (currentDirSync) {
bestGuess = cor.basedir;
}
}
else if ( ts > 0 && ts == maxtimestamp )
{
synchronized (currentDirSync)
{
if ( cor.basedir.length() < bestGuess.length() )
{
} else if (ts > 0 && ts == maxtimestamp) {
synchronized (currentDirSync) {
if (cor.basedir.length() < bestGuess.length()) {
bestGuess = cor.basedir;
}
}
@ -129,8 +99,7 @@ public class WpDatabaseScanner extends Thread
}
@Override
public void run()
{
public void run() {
scan(new File("/"), 0);
setCurrentDir(null);