code
stringlengths
3
1.18M
language
stringclasses
1 value
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation; public class ActionAndTolerance { private final RefreshAction mRefreshAction; private final ToleranceStrategy mToleranceStrategy; public ActionAndTolerance(RefreshAction refreshAction, ToleranceStrategy toleranceStrategy) { mRefreshAction = refreshAction; mToleranceStrategy = toleranceStrategy; } public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) { return mToleranceStrategy.exceedsTolerance(here, azimuth, now); } public void refresh() { mRefreshAction.refresh(); } public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { mToleranceStrategy.updateLastRefreshed(here, azimuth, now); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation; public class LocationTolerance implements ToleranceStrategy { private IGpsLocation mLastRefreshLocation; private final float mLocationTolerance; private final int mMinTimeBetweenRefresh; private long mLastRefreshTime; public LocationTolerance(float locationTolerance, IGpsLocation lastRefreshed, int minTimeBetweenRefresh) { mLocationTolerance = locationTolerance; mLastRefreshLocation = lastRefreshed; mMinTimeBetweenRefresh = minTimeBetweenRefresh; mLastRefreshTime = 0; } public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) { if (now < mLastRefreshTime + mMinTimeBetweenRefresh) return false; final float distanceTo = here.distanceTo(mLastRefreshLocation); // Log.d("GeoBeagle", "distance, tolerance: " + distanceTo + ", " + // mLocationTolerance); final boolean fExceedsTolerance = distanceTo >= mLocationTolerance; return fExceedsTolerance; } public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { // Log.d("GeoBeagle", "updateLastRefreshed here: " + here); mLastRefreshLocation = here; mLastRefreshTime = now; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; public class DistanceUpdater implements RefreshAction { private final GeocacheListAdapter mGeocacheListAdapter; public DistanceUpdater(GeocacheListAdapter geocacheListAdapter) { mGeocacheListAdapter = geocacheListAdapter; } public void refresh() { // Log.d("GeoBeagle", "notifyDataSetChanged"); mGeocacheListAdapter.notifyDataSetChanged(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.R; public class ListTitleFormatter { int getBodyText(int sqlCount) { return sqlCount > 0 ? R.string.no_nearby_caches : R.string.no_caches; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI; import com.google.code.geobeagle.activity.cachelist.model.CacheListData; public class AdapterCachesSorter implements RefreshAction { private final CacheListData mCacheListData; private final LocationControlBuffered mLocationControlBuffered; private final CacheListDelegateDI.Timing mTiming; public AdapterCachesSorter(CacheListData cacheListData, CacheListDelegateDI.Timing timing, LocationControlBuffered locationControlBuffered) { mCacheListData = cacheListData; mTiming = timing; mLocationControlBuffered = locationControlBuffered; } public void refresh() { mLocationControlBuffered.getSortStrategy().sort(mCacheListData.get()); mTiming.lap("sort time"); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.cachelist.actions.context.ContextAction; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.database.FilterNearestCaches; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.ListView; import android.widget.AdapterView.AdapterContextMenuInfo; public class GeocacheListController { public static class CacheListOnCreateContextMenuListener implements OnCreateContextMenuListener { private final GeocacheVectors mGeocacheVectors; public CacheListOnCreateContextMenuListener(GeocacheVectors geocacheVectors) { mGeocacheVectors = geocacheVectors; } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo; if (acmi.position > 0) { menu.setHeaderTitle(mGeocacheVectors.get(acmi.position - 1).getId()); menu.add(0, MENU_VIEW, 0, "View"); menu.add(0, MENU_EDIT, 1, "Edit"); menu.add(0, MENU_DELETE, 2, "Delete"); } } } static final int MENU_DELETE = 0; static final int MENU_VIEW = 1; static final int MENU_EDIT = 2; public static final String SELECT_CACHE = "SELECT_CACHE"; private final CacheListRefresh mCacheListRefresh; private final ContextAction mContextActions[]; private final FilterNearestCaches mFilterNearestCaches; private final MenuActions mMenuActions; private final MenuActionSyncGpx mMenuActionSyncGpx; public GeocacheListController(CacheListRefresh cacheListRefresh, ContextAction[] contextActions, FilterNearestCaches filterNearestCaches, MenuActionSyncGpx menuActionSyncGpx, MenuActions menuActions) { mCacheListRefresh = cacheListRefresh; mContextActions = contextActions; mFilterNearestCaches = filterNearestCaches; mMenuActionSyncGpx = menuActionSyncGpx; mMenuActions = menuActions; } public boolean onContextItemSelected(MenuItem menuItem) { AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo)menuItem .getMenuInfo(); mContextActions[menuItem.getItemId()].act(adapterContextMenuInfo.position - 1); return true; } public boolean onCreateOptionsMenu(Menu menu) { return mMenuActions.onCreateOptionsMenu(menu); } public void onListItemClick(ListView l, View v, int position, long id) { if (position > 0) mContextActions[MENU_VIEW].act(position - 1); else mCacheListRefresh.forceRefresh(); } public boolean onMenuOpened(int featureId, Menu menu) { menu.findItem(R.string.menu_toggle_filter).setTitle(mFilterNearestCaches.getMenuString()); return true; } public boolean onOptionsItemSelected(MenuItem item) { return mMenuActions.act(item.getItemId()); } public void onPause() { mMenuActionSyncGpx.abort(); } public void onResume(CacheListRefresh cacheListRefresh, boolean fImport) { mCacheListRefresh.forceRefresh(); if (fImport) mMenuActionSyncGpx.act(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.view; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.AbsoluteBearingFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.HasDistanceFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class GeocacheSummaryRowInflater implements HasDistanceFormatter { static class RowViews { private final TextView mAttributes; private final TextView mCacheName; private final TextView mDistance; private final ImageView mIcon; private final TextView mId; RowViews(TextView attributes, TextView cacheName, TextView distance, ImageView icon, TextView id) { mAttributes = attributes; mCacheName = cacheName; mDistance = distance; mIcon = icon; mId = id; } void set(GeocacheVector geocacheVector, DistanceFormatter distanceFormatter, BearingFormatter relativeBearingFormatter) { CacheType type = geocacheVector.getGeocache().getCacheType(); mIcon.setImageResource(type.icon()); mId.setText(geocacheVector.getId()); mAttributes.setText(geocacheVector.getFormattedAttributes()); mCacheName.setText(geocacheVector.getName()); mDistance.setText(geocacheVector.getFormattedDistance(distanceFormatter, relativeBearingFormatter)); } } private BearingFormatter mBearingFormatter; private DistanceFormatter mDistanceFormatter; private final GeocacheVectors mGeocacheVectors; private final LayoutInflater mLayoutInflater; public GeocacheSummaryRowInflater(DistanceFormatter distanceFormatter, GeocacheVectors geocacheVectors, LayoutInflater layoutInflater, BearingFormatter relativeBearingFormatter) { mLayoutInflater = layoutInflater; mGeocacheVectors = geocacheVectors; mDistanceFormatter = distanceFormatter; mBearingFormatter = relativeBearingFormatter; } BearingFormatter getBearingFormatter() { return mBearingFormatter; } public View inflate(View convertView) { if (convertView != null) return convertView; //Log.d("GeoBeagle", "SummaryRow::inflate(" + convertView + ")"); View view = mLayoutInflater.inflate(R.layout.cache_row, null); RowViews rowViews = new RowViews((TextView)view.findViewById(R.id.txt_gcattributes), ((TextView)view.findViewById(R.id.txt_cache)), ((TextView)view .findViewById(R.id.distance)), ((ImageView)view .findViewById(R.id.gc_row_icon)), ((TextView)view .findViewById(R.id.txt_gcid))); view.setTag(rowViews); return view; } public void setBearingFormatter(boolean absoluteBearing) { mBearingFormatter = absoluteBearing ? new AbsoluteBearingFormatter() : new RelativeBearingFormatter(); } public void setData(View view, int position) { ((RowViews)view.getTag()).set(mGeocacheVectors.get(position), mDistanceFormatter, mBearingFormatter); } public void setDistanceFormatter(DistanceFormatter distanceFormatter) { mDistanceFormatter = distanceFormatter; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.menu; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.database.FilterNearestCaches; public class MenuActionToggleFilter extends MenuActionBase { private final FilterNearestCaches mFilterNearestCaches; private final CacheListRefresh mMenuActionRefresh; public MenuActionToggleFilter(FilterNearestCaches filterNearestCaches, CacheListRefresh cacheListRefresh) { super(R.string.menu_toggle_filter); mFilterNearestCaches = filterNearestCaches; mMenuActionRefresh = cacheListRefresh; } public void act() { mFilterNearestCaches.toggle(); mMenuActionRefresh.forceRefresh(); } }
Java
package com.google.code.geobeagle.activity.cachelist.actions.menu; public interface Abortable { public void abort(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.menu; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.activity.cachelist.GpxImporterFactory; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.xmlimport.GpxImporter; public class MenuActionSyncGpx extends MenuActionBase { private Abortable mAbortable; private final CacheListRefresh mCacheListRefresh; private final GpxImporterFactory mGpxImporterFactory; private final DbFrontend mDbFrontend; public MenuActionSyncGpx(Abortable abortable, CacheListRefresh cacheListRefresh, GpxImporterFactory gpxImporterFactory, DbFrontend dbFrontend) { super(R.string.menu_sync); mAbortable = abortable; mCacheListRefresh = cacheListRefresh; mGpxImporterFactory = gpxImporterFactory; mDbFrontend = dbFrontend; } public void abort() { mAbortable.abort(); } public void act() { final GpxImporter gpxImporter = mGpxImporterFactory.create(mDbFrontend.getCacheWriter()); mAbortable = gpxImporter; gpxImporter.importGpxs(mCacheListRefresh); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.menu; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.activity.cachelist.model.GeocacheFromMyLocationFactory; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.database.LocationSaver; public class MenuActionMyLocation extends MenuActionBase { private final ErrorDisplayer mErrorDisplayer; private final GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory; private final CacheListRefresh mMenuActionRefresh; private final LocationSaver mLocationSaver; public MenuActionMyLocation(CacheListRefresh cacheListRefresh, ErrorDisplayer errorDisplayer, GeocacheFromMyLocationFactory geocacheFromMyLocationFactory, LocationSaver locationSaver) { super(R.string.menu_add_my_location); mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory; mErrorDisplayer = errorDisplayer; mMenuActionRefresh = cacheListRefresh; mLocationSaver = locationSaver; } @Override public void act() { final Geocache myLocation = mGeocacheFromMyLocationFactory.create(); if (myLocation == null) { mErrorDisplayer.displayError(R.string.current_location_null); return; } mLocationSaver.saveLocation(myLocation); mMenuActionRefresh.forceRefresh(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.context; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.EditCacheActivity; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import android.content.Context; import android.content.Intent; public class ContextActionEdit implements ContextAction { private final Context mContext; private final GeocacheVectors mGeocacheVectors; public ContextActionEdit(GeocacheVectors geocacheVectors, Context context) { mGeocacheVectors = geocacheVectors; mContext = context; } public void act(int position) { Geocache selected = mGeocacheVectors.get(position).getGeocache(); Intent intent = new Intent(mContext, EditCacheActivity.class); intent.putExtra("geocache", selected); mContext.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.context; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import android.content.Context; import android.content.Intent; public class ContextActionView implements ContextAction { private final Context mContext; private final GeocacheVectors mGeocacheVectors; private final Intent mGeoBeagleMainIntent; public ContextActionView(GeocacheVectors geocacheVectors, Context context, Intent intent) { mGeocacheVectors = geocacheVectors; mContext = context; mGeoBeagleMainIntent = intent; } public void act(int position) { mGeoBeagleMainIntent.putExtra("geocache", mGeocacheVectors.get(position).getGeocache()) .setAction(GeocacheListController.SELECT_CACHE); mContext.startActivity(mGeoBeagleMainIntent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.context; public interface ContextAction { public void act(int position); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.context; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater; import com.google.code.geobeagle.database.DbFrontend; import android.widget.BaseAdapter; public class ContextActionDelete implements ContextAction { private final BaseAdapter mGeocacheListAdapter; private final GeocacheVectors mGeocacheVectors; private final TitleUpdater mTitleUpdater; private final DbFrontend mDbFrontend; public ContextActionDelete(BaseAdapter geocacheListAdapter, GeocacheVectors geocacheVectors, TitleUpdater titleUpdater, DbFrontend dbFrontend) { mGeocacheListAdapter = geocacheListAdapter; mGeocacheVectors = geocacheVectors; mTitleUpdater = titleUpdater; mDbFrontend = dbFrontend; } public void act(int position) { mDbFrontend.getCacheWriter().deleteCache(mGeocacheVectors.get(position).getId()); mGeocacheVectors.remove(position); mGeocacheListAdapter.notifyDataSetChanged(); //TODO: How to get correct values? mTitleUpdater.update(mGeocacheVectors.size(), mGeocacheVectors.size()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityType; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter; import com.google.code.geobeagle.database.DbFrontend; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; public class CacheListDelegate { static class ImportIntentManager { static final String INTENT_EXTRA_IMPORT_TRIGGERED = "com.google.code.geabeagle.import_triggered"; private final Activity mActivity; ImportIntentManager(Activity activity) { mActivity = activity; } boolean isImport() { final Intent intent = mActivity.getIntent(); if (intent == null) return false; String action = intent.getAction(); if (action == null) return false; if (!action.equals("android.intent.action.VIEW")) return false; if (intent.getBooleanExtra(INTENT_EXTRA_IMPORT_TRIGGERED, false)) return false; // Need to alter the intent so that the import isn't retriggered if // pause/resume is a result of the phone going to sleep and then // waking up again. intent.putExtra(INTENT_EXTRA_IMPORT_TRIGGERED, true); return true; } } private final ActivitySaver mActivitySaver; private final CacheListRefresh mCacheListRefresh; private final GeocacheListController mController; private final DbFrontend mDbFrontend; private final ImportIntentManager mImportIntentManager; private final GeocacheListPresenter mPresenter; public CacheListDelegate(ImportIntentManager importIntentManager, ActivitySaver activitySaver, CacheListRefresh cacheListRefresh, GeocacheListController geocacheListController, GeocacheListPresenter geocacheListPresenter, DbFrontend dbFrontend) { mActivitySaver = activitySaver; mCacheListRefresh = cacheListRefresh; mController = geocacheListController; mPresenter = geocacheListPresenter; mImportIntentManager = importIntentManager; mDbFrontend = dbFrontend; } public boolean onContextItemSelected(MenuItem menuItem) { return mController.onContextItemSelected(menuItem); } public void onCreate() { mPresenter.onCreate(); } public boolean onCreateOptionsMenu(Menu menu) { return mController.onCreateOptionsMenu(menu); } public void onListItemClick(ListView l, View v, int position, long id) { mController.onListItemClick(l, v, position, id); } public boolean onMenuOpened(int featureId, Menu menu) { return mController.onMenuOpened(featureId, menu); } public boolean onOptionsItemSelected(MenuItem item) { return mController.onOptionsItemSelected(item); } public void onPause() { mPresenter.onPause(); mController.onPause(); mActivitySaver.save(ActivityType.CACHE_LIST); mDbFrontend.closeDatabase(); } public void onResume() { // TODO: No need to re-initialize these mPresenter.onResume(mCacheListRefresh); mController.onResume(mCacheListRefresh, mImportIntentManager.isImport()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.model; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.GeocacheFactory.Source; import android.location.Location; public class GeocacheFromMyLocationFactory { private final GeocacheFactory mGeocacheFactory; private final LocationControlBuffered mLocationControl; public GeocacheFromMyLocationFactory(GeocacheFactory geocacheFactory, LocationControlBuffered locationControl) { mGeocacheFactory = geocacheFactory; mLocationControl = locationControl; } public Geocache create() { Location location = mLocationControl.getLocation(); if (location == null) { return null; } long time = location.getTime(); return mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format( "[%1$tk:%1$tM] My Location", time), location.getLatitude(), location.getLongitude(), Source.MY_LOCATION, null, CacheType.MY_LOCATION, 0, 0, 0); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.model; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import java.util.ArrayList; public class GeocacheVectors { private final ArrayList<GeocacheVector> mGeocacheVectorsList; public GeocacheVectors(ArrayList<GeocacheVector> geocacheVectorsList) { mGeocacheVectorsList = geocacheVectorsList; } public void add(GeocacheVector destinationVector) { mGeocacheVectorsList.add(0, destinationVector); } public void addLocations(ArrayList<Geocache> geocaches, LocationControlBuffered locationControlBuffered) { for (Geocache geocache : geocaches) { add(new GeocacheVector(geocache, locationControlBuffered)); } } public GeocacheVector get(int position) { return mGeocacheVectorsList.get(position); } public ArrayList<GeocacheVector> getGeocacheVectorsList() { return mGeocacheVectorsList; } public void remove(int position) { mGeocacheVectorsList.remove(position); } public void reset(int size) { mGeocacheVectorsList.clear(); mGeocacheVectorsList.ensureCapacity(size); } public int size() { return mGeocacheVectorsList.size(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.model; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.location.Location; import android.util.FloatMath; import java.util.Comparator; public class GeocacheVector { public static class LocationComparator implements Comparator<GeocacheVector> { public int compare(GeocacheVector geocacheVector1, GeocacheVector geocacheVector2) { final float d1 = geocacheVector1.getDistance(); final float d2 = geocacheVector2.getDistance(); if (d1 < d2) return -1; if (d1 > d2) return 1; return 0; } } // From http://www.anddev.org/viewtopic.php?p=20195. public static float calculateDistanceFast(float lat1, float lon1, float lat2, float lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); final float sinDLat = FloatMath.sin((float)(dLat / 2)); final float sinDLon = FloatMath.sin((float)(dLon / 2)); float a = sinDLat * sinDLat + FloatMath.cos((float)Math.toRadians(lat1)) * FloatMath.cos((float)Math.toRadians(lat2)) * sinDLon * sinDLon; float c = (float)(2 * Math.atan2(FloatMath.sqrt(a), FloatMath.sqrt(1 - a))); return 6371000 * c; } // TODO: distance formatter shouldn't be in every object. private final Geocache mGeocache; private float mDistance; private final LocationControlBuffered mLocationControlBuffered; float getDistance() { return mDistance; } public void setDistance(float f) { mDistance = f; } public GeocacheVector(Geocache geocache, LocationControlBuffered locationControlBuffered) { mGeocache = geocache; mLocationControlBuffered = locationControlBuffered; } public float getDistanceFast() { Location here = mLocationControlBuffered.getLocation(); return calculateDistanceFast((float)here.getLatitude(), (float)here.getLongitude(), (float)mGeocache.getLatitude(), (float)mGeocache.getLongitude()); } public CharSequence getFormattedDistance(DistanceFormatter distanceFormatter, BearingFormatter relativeBearingFormatter) { // Use the slower, more accurate distance for display. final float[] distanceAndBearing = mGeocache .calculateDistanceAndBearing(mLocationControlBuffered.getLocation()); if (distanceAndBearing[0] == -1) { return ""; } final float azimuth = mLocationControlBuffered.getAzimuth(); final CharSequence formattedDistance = distanceFormatter .formatDistance(distanceAndBearing[0]); final String formattedBearing = relativeBearingFormatter.formatBearing(distanceAndBearing[1], azimuth); return formattedDistance + " " + formattedBearing; } public Geocache getGeocache() { return mGeocache; } public CharSequence getId() { return mGeocache.getId(); } public CharSequence getName() { return mGeocache.getName(); } public CharSequence getFormattedAttributes() { return mGeocache.getFormattedAttributes(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.model; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import java.util.ArrayList; public class CacheListData { private final GeocacheVectors mGeocacheVectors; public CacheListData(GeocacheVectors geocacheVectors) { mGeocacheVectors = geocacheVectors; } public void add(ArrayList<Geocache> geocaches, LocationControlBuffered locationControlBuffered) { mGeocacheVectors.reset(geocaches.size()); mGeocacheVectors.addLocations(geocaches, locationControlBuffered); } public ArrayList<GeocacheVector> get() { return mGeocacheVectors.getGeocacheVectorsList(); } public int size() { return mGeocacheVectors.size(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory; import com.google.code.geobeagle.activity.cachelist.CacheListActivity; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.main.GeoBeagle; import com.google.code.geobeagle.activity.main.GeocacheFromPreferencesFactory; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; public class ActivityRestorer { static class CacheListRestorer implements Restorer { private final Activity mActivity; public CacheListRestorer(Activity activity) { mActivity = activity; } @Override public void restore() { mActivity.startActivity(new Intent(mActivity, CacheListActivity.class)); mActivity.finish(); } } static class NullRestorer implements Restorer { @Override public void restore() { } } interface Restorer { void restore(); } static class ViewCacheRestorer implements Restorer { private final Activity mActivity; private final GeocacheFromPreferencesFactory mGeocacheFromPreferencesFactory; private final SharedPreferences mSharedPreferences; public ViewCacheRestorer(GeocacheFromPreferencesFactory geocacheFromPreferencesFactory, SharedPreferences sharedPreferences, Activity activity) { mGeocacheFromPreferencesFactory = geocacheFromPreferencesFactory; mSharedPreferences = sharedPreferences; mActivity = activity; } @Override public void restore() { final Geocache geocache = mGeocacheFromPreferencesFactory.create(mSharedPreferences); final Intent intent = new Intent(mActivity, GeoBeagle.class); intent.putExtra("geocache", geocache).setAction(GeocacheListController.SELECT_CACHE); mActivity.startActivity(intent); mActivity.finish(); } } private final ActivityTypeFactory mActivityTypeFactory; private final Restorer[] mRestorers; private final SharedPreferences mSharedPreferences; public ActivityRestorer(Activity activity, GeocacheFromPreferencesFactory geocacheFromPreferencesFactory, ActivityTypeFactory activityTypeFactory, SharedPreferences sharedPreferences) { mActivityTypeFactory = activityTypeFactory; mSharedPreferences = sharedPreferences; final NullRestorer nullRestorer = new NullRestorer(); mRestorers = new Restorer[] { nullRestorer, new CacheListRestorer(activity), nullRestorer, new ViewCacheRestorer(geocacheFromPreferencesFactory, sharedPreferences, activity) }; } public void restore(int flags) { if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) return; final int iLastActivity = mSharedPreferences.getInt(ActivitySaver.LAST_ACTIVITY, ActivityType.NONE.toInt()); final ActivityType activityType = mActivityTypeFactory.fromInt(iLastActivity); mRestorers[activityType.toInt()].restore(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /* * maps.jar doesn't include all its dependencies; fake them out here for testing. */ package android.widget; public class ZoomButtonsController { }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import java.util.ArrayList; class CachesProviderStub implements ICachesProviderArea { private ArrayList<Geocache> mGeocaches = new ArrayList<Geocache>(); private double mLatLow = 0.0; private double mLatHigh = 0.0; private double mLonLow = 0.0; private double mLonHigh = 0.0; private boolean mHasChanged = true; private int mBoundsCalls = 0; private boolean mIsInitialized = false; public CachesProviderStub() { } public CachesProviderStub(ArrayList<Geocache> geocacheList) { mGeocaches = geocacheList; } public void addCache(Geocache geocache) { mGeocaches.add(geocache); } /** maxCount <= 0 means no limit */ private GeocacheListPrecomputed fetchCaches(int maxCount) { if (!mIsInitialized) return new GeocacheListPrecomputed(mGeocaches); ArrayList<Geocache> selection = new ArrayList<Geocache>(); for (Geocache geocache : mGeocaches) { if (geocache.getLatitude() >= mLatLow && geocache.getLatitude() <= mLatHigh && geocache.getLongitude() >= mLonLow && geocache.getLongitude() <= mLonHigh) { selection.add(geocache); if (selection.size() == maxCount) break; } } return new GeocacheListPrecomputed(selection); } @Override public GeocacheListPrecomputed getCaches() { return fetchCaches(-1); } @Override public GeocacheListPrecomputed getCaches(int maxCount) { return fetchCaches(maxCount); } @Override public int getCount() { return fetchCaches(-1).size(); } public int getSetBoundsCalls() { return mBoundsCalls; } @Override public void setBounds(double latLow, double lonLow, double latHigh, double lonHigh) { mBoundsCalls += 1; mLatLow = latLow; mLatHigh = latHigh; mLonLow = lonLow; mLonHigh = lonHigh; mHasChanged = true; mIsInitialized = true; } @Override public boolean hasChanged() { return mHasChanged; } @Override public void resetChanged() { mHasChanged = false; } public void setChanged(boolean changed) { mHasChanged = changed; } @Override public int getTotalCount() { return mGeocaches.size(); } @Override public void clearBounds() { mIsInitialized = false; } }
Java
package com.google.code.geobeagle; import static org.easymock.EasyMock.expect; import org.powermock.api.easymock.PowerMock; public class Common { public static Geocache mockGeocache(double latitude, double longitude) { Geocache geocache = PowerMock.createMock(Geocache.class); expect(geocache.getLatitude()).andReturn(latitude).anyTimes(); expect(geocache.getLongitude()).andReturn(longitude).anyTimes(); return geocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import android.text.Editable; import android.text.InputFilter; class StubEditable implements Editable { private final String mString; public StubEditable(String s) { mString = s; } public Editable append(char arg0) { return null; } public Editable append(CharSequence arg0) { return null; } public Editable append(CharSequence arg0, int arg1, int arg2) { return null; } public char charAt(int index) { return mString.charAt(index); } public void clear() { } public void clearSpans() { } public Editable delete(int arg0, int arg1) { return null; } public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { mString.getChars(srcBegin, srcEnd, dst, dstBegin); } public InputFilter[] getFilters() { return null; } public int getSpanEnd(Object arg0) { return 0; } public int getSpanFlags(Object arg0) { return 0; } public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) { return null; } public int getSpanStart(Object arg0) { return 0; } public Editable insert(int arg0, CharSequence arg1) { return null; } public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) { return null; } public int length() { return mString.length(); } @SuppressWarnings("unchecked") public int nextSpanTransition(int arg0, int arg1, Class arg2) { return 0; } public void removeSpan(Object arg0) { } public Editable replace(int arg0, int arg1, CharSequence arg2) { return null; } public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) { return null; } public void setFilters(InputFilter[] arg0) { } public void setSpan(Object arg0, int arg1, int arg2, int arg3) { } public CharSequence subSequence(int start, int end) { return mString.subSequence(start, end); } @Override public String toString() { return mString; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.test; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.MenuItem; import android.view.SubMenu; import android.view.ContextMenu.ContextMenuInfo; class MenuActionStub implements MenuItem { @Override public char getAlphabeticShortcut() { return 0; } @Override public int getGroupId() { return 0; } @Override public Drawable getIcon() { return null; } @Override public Intent getIntent() { return null; } @Override public int getItemId() { return 7; } @Override public ContextMenuInfo getMenuInfo() { return null; } @Override public char getNumericShortcut() { return 0; } @Override public int getOrder() { return 0; } @Override public SubMenu getSubMenu() { return null; } @Override public CharSequence getTitle() { return null; } @Override public CharSequence getTitleCondensed() { return null; } @Override public boolean hasSubMenu() { return false; } @Override public boolean isCheckable() { return false; } @Override public boolean isChecked() { return false; } @Override public boolean isEnabled() { return false; } @Override public boolean isVisible() { return false; } @Override public MenuItem setAlphabeticShortcut(char alphaChar) { return null; } @Override public MenuItem setCheckable(boolean checkable) { return null; } @Override public MenuItem setChecked(boolean checked) { return null; } @Override public MenuItem setEnabled(boolean enabled) { return null; } @Override public MenuItem setIcon(Drawable icon) { return null; } @Override public MenuItem setIcon(int iconRes) { return null; } @Override public MenuItem setIntent(Intent intent) { return null; } @Override public MenuItem setNumericShortcut(char numericChar) { return null; } @Override public MenuItem setOnMenuItemClickListener( OnMenuItemClickListener menuItemClickListener) { return null; } @Override public MenuItem setShortcut(char numericChar, char alphaChar) { return null; } @Override public MenuItem setTitle(CharSequence title) { return null; } @Override public MenuItem setTitle(int title) { return null; } @Override public MenuItem setTitleCondensed(CharSequence title) { return null; } @Override public MenuItem setVisible(boolean visible) { return null; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.cachedetails.CacheDetailsWriter; import com.google.code.geobeagle.cachedetails.HtmlWriter; import com.google.code.geobeagle.cachedetails.WriterWrapper; import com.google.code.geobeagle.database.CacheWriter; import com.google.code.geobeagle.xmlimport.FileFactory; import com.google.code.geobeagle.xmlimport.CachePersisterFacade.TextHandler; import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import com.google.code.geobeagle.xmlimport.ImportThreadDelegate.ImportThreadHelper; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.code.geobeagle.xmlimport.gpx.GpxFileIterAndZipFileIterFactory; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxAndZipFilenameFilter; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.preference.PreferenceManager; import android.widget.Toast; import java.io.FilenameFilter; import java.util.HashMap; public class GpxImporterDI { // Can't test this due to final methods in base. public static class ImportThread extends Thread { static ImportThread create(MessageHandler messageHandler, GpxLoader gpxLoader, EventHandlers eventHandlers, XmlPullParserWrapper xmlPullParserWrapper, ErrorDisplayer errorDisplayer, Aborter aborter, GeocacheFactory geocacheFactory) { final GpxFilenameFilter gpxFilenameFilter = new GpxFilenameFilter(); final FilenameFilter filenameFilter = new GpxAndZipFilenameFilter(gpxFilenameFilter); final ZipInputFileTester zipInputFileTester = new ZipInputFileTester(gpxFilenameFilter); final GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory = new GpxFileIterAndZipFileIterFactory( zipInputFileTester, aborter); final GpxAndZipFiles gpxAndZipFiles = new GpxAndZipFiles(filenameFilter, gpxFileIterAndZipFileIterFactory); final EventHelperFactory eventHelperFactory = new EventHelperFactory( xmlPullParserWrapper); final ImportThreadHelper importThreadHelper = new ImportThreadHelper(gpxLoader, messageHandler, eventHelperFactory, eventHandlers, errorDisplayer, geocacheFactory); return new ImportThread(gpxAndZipFiles, importThreadHelper, errorDisplayer); } private final ImportThreadDelegate mImportThreadDelegate; public ImportThread(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) { mImportThreadDelegate = new ImportThreadDelegate(gpxAndZipFiles, importThreadHelper, errorDisplayer); } @Override public void run() { mImportThreadDelegate.run(); } } // Wrapper so that containers can follow the "constructors do no work" rule. public static class ImportThreadWrapper { private final Aborter mAborter; private ImportThread mImportThread; private final MessageHandler mMessageHandler; private final XmlPullParserWrapper mXmlPullParserWrapper; public ImportThreadWrapper(MessageHandler messageHandler, XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) { mMessageHandler = messageHandler; mXmlPullParserWrapper = xmlPullParserWrapper; mAborter = aborter; } public boolean isAlive() { if (mImportThread != null) return mImportThread.isAlive(); return false; } public void join() { if (mImportThread != null) try { mImportThread.join(); } catch (InterruptedException e) { // Ignore; we are aborting anyway. } } public void open(CacheListAdapter cacheList, GpxLoader gpxLoader, EventHandlers eventHandlers, ErrorDisplayer mErrorDisplayer, GeocacheFactory geocacheFactory) { mMessageHandler.start(cacheList); mImportThread = ImportThread.create(mMessageHandler, gpxLoader, eventHandlers, mXmlPullParserWrapper, mErrorDisplayer, mAborter, geocacheFactory); } public void start() { if (mImportThread != null) mImportThread.start(); } } // Too hard to test this class due to final methods in base. public static class MessageHandler extends Handler { public static final String GEOBEAGLE = "GeoBeagle"; static final int MSG_DONE = 1; static final int MSG_PROGRESS = 0; public static MessageHandler create(ListActivity listActivity) { final ProgressDialogWrapper progressDialogWrapper = new ProgressDialogWrapper( listActivity); return new MessageHandler(progressDialogWrapper); } private int mCacheCount; private boolean mLoadAborted; private CacheListAdapter mCacheList; private final ProgressDialogWrapper mProgressDialogWrapper; private String mSource; private String mStatus; private String mWaypointId; public MessageHandler(ProgressDialogWrapper progressDialogWrapper) { mProgressDialogWrapper = progressDialogWrapper; } public void abortLoad() { mLoadAborted = true; mProgressDialogWrapper.dismiss(); } @Override public void handleMessage(Message msg) { // Log.d(GEOBEAGLE, "received msg: " + msg.what); switch (msg.what) { case MessageHandler.MSG_PROGRESS: mProgressDialogWrapper.setMessage(mStatus); break; case MessageHandler.MSG_DONE: if (!mLoadAborted) { mProgressDialogWrapper.dismiss(); mCacheList.forceRefresh(); } break; default: break; } } public void loadComplete() { sendEmptyMessage(MessageHandler.MSG_DONE); } public void start(CacheListAdapter cacheList) { mCacheCount = 0; mLoadAborted = false; mCacheList = cacheList; // TODO: move text into resource. mProgressDialogWrapper.show("Syncing caches", "Please wait..."); } public void updateName(String name) { mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name; sendEmptyMessage(MessageHandler.MSG_PROGRESS); } public void updateSource(String text) { mSource = text; mStatus = "Opening: " + mSource + "..."; sendEmptyMessage(MessageHandler.MSG_PROGRESS); } public void updateWaypointId(String wpt) { mWaypointId = wpt; } } // Wrapper so that containers can follow the "constructors do no work" rule. public static class ProgressDialogWrapper { private final Context mContext; private ProgressDialog mProgressDialog; public ProgressDialogWrapper(Context context) { mContext = context; } public void dismiss() { if (mProgressDialog != null) mProgressDialog.dismiss(); } public void setMessage(CharSequence message) { mProgressDialog.setMessage(message); } public void show(String title, String msg) { mProgressDialog = ProgressDialog.show(mContext, title, msg); } } public static class ToastFactory { public void showToast(Context context, int resId, int duration) { Toast.makeText(context, resId, duration).show(); } } public static GpxImporter create(ListActivity listActivity, XmlPullParserWrapper xmlPullParserWrapper, ErrorDisplayer errorDisplayer, GeoFixProvider geoFixProvider, Aborter aborter, MessageHandler messageHandler, CacheWriter cacheWriter, CacheTypeFactory cacheTypeFactory, GeocacheFactory geocacheFactory) { final PowerManager powerManager = (PowerManager)listActivity .getSystemService(Context.POWER_SERVICE); final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Importing"); FileFactory fileFactory = new FileFactory(); WriterWrapper writerWrapper = new WriterWrapper(); HtmlWriter htmlWriter = new HtmlWriter(writerWrapper); CacheDetailsWriter cacheDetailsWriter = new CacheDetailsWriter(htmlWriter); final CacheTagSqlWriter cacheTagSqlWriter = new CacheTagSqlWriter(cacheWriter, cacheTypeFactory); final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(listActivity); final String username = sharedPreferences.getString("username", ""); final CachePersisterFacade cachePersisterFacade = new CachePersisterFacade(cacheTagSqlWriter, fileFactory, cacheDetailsWriter, messageHandler, wakeLock, username); final GpxLoader gpxLoader = GpxLoaderDI.create(cachePersisterFacade, xmlPullParserWrapper, aborter, errorDisplayer, wakeLock); final ToastFactory toastFactory = new ToastFactory(); final ImportThreadWrapper importThreadWrapper = new ImportThreadWrapper(messageHandler, xmlPullParserWrapper, aborter); final HashMap<String, TextHandler> textHandlers = GpxImporterDI.initializeTextHandlers(cachePersisterFacade); final EventHandlerGpx eventHandlerGpx = new EventHandlerGpx(cachePersisterFacade, textHandlers ); final EventHandlerLoc eventHandlerLoc = new EventHandlerLoc(cachePersisterFacade); final EventHandlers eventHandlers = new EventHandlers(); eventHandlers.add(".gpx", eventHandlerGpx); eventHandlers.add(".loc", eventHandlerLoc); return new GpxImporter(geoFixProvider, gpxLoader, listActivity, importThreadWrapper, messageHandler, toastFactory, eventHandlers, errorDisplayer, geocacheFactory); } public static HashMap<String, TextHandler> initializeTextHandlers(CachePersisterFacade cachePersisterFacade) { HashMap<String, TextHandler> textHandlers = new HashMap<String, TextHandler>(); textHandlers.put(EventHandlerGpx.XPATH_WPTNAME, cachePersisterFacade.wptName); textHandlers.put(EventHandlerGpx.XPATH_WPTDESC, cachePersisterFacade.wptDesc); textHandlers.put(EventHandlerGpx.XPATH_GROUNDSPEAKNAME, cachePersisterFacade.groundspeakName); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHENAME, cachePersisterFacade.groundspeakName); textHandlers.put(EventHandlerGpx.XPATH_PLACEDBY, cachePersisterFacade.placedBy); textHandlers.put(EventHandlerGpx.XPATH_LOGDATE, cachePersisterFacade.logDate); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHELOGDATE, cachePersisterFacade.logDate); textHandlers.put(EventHandlerGpx.XPATH_HINT, cachePersisterFacade.hint); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHEHINT, cachePersisterFacade.hint); textHandlers.put(EventHandlerGpx.XPATH_CACHE_TYPE, cachePersisterFacade.cacheType); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_TYPE, cachePersisterFacade.cacheType); textHandlers.put(EventHandlerGpx.XPATH_WAYPOINT_TYPE, cachePersisterFacade.cacheType); textHandlers.put(EventHandlerGpx.XPATH_CACHE_DIFFICULTY, cachePersisterFacade.difficulty); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_DIFFICULTY, cachePersisterFacade.difficulty); textHandlers.put(EventHandlerGpx.XPATH_CACHE_TERRAIN, cachePersisterFacade.terrain); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_TERRAIN, cachePersisterFacade.terrain); textHandlers.put(EventHandlerGpx.XPATH_CACHE_CONTAINER, cachePersisterFacade.container); textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_CONTAINER, cachePersisterFacade.container); return textHandlers; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.xmlimport.EventHandler; import com.google.code.geobeagle.xmlimport.EventHelper; import com.google.code.geobeagle.xmlimport.EventHelper.XmlPathBuilder; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; public class EventHelperDI { public static class EventHelperFactory { private final XmlPullParserWrapper mXmlPullParser; public EventHelperFactory(XmlPullParserWrapper xmlPullParser) { mXmlPullParser = xmlPullParser; } public EventHelper create(EventHandler eventHandler) { final XmlPathBuilder xmlPathBuilder = new XmlPathBuilder(); return new EventHelper(xmlPathBuilder, eventHandler, mXmlPullParser); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.xmlimport.CachePersisterFacade; import com.google.code.geobeagle.xmlimport.GpxLoader; import com.google.code.geobeagle.xmlimport.GpxToCache; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import android.os.PowerManager.WakeLock; public class GpxLoaderDI { public static GpxLoader create(CachePersisterFacade cachePersisterFacade, XmlPullParserWrapper xmlPullParserFactory, Aborter aborter, ErrorDisplayer errorDisplayer, WakeLock wakeLock) { final GpxToCache gpxToCache = new GpxToCache(xmlPullParserFactory, aborter); return new GpxLoader(cachePersisterFacade, errorDisplayer, gpxToCache, wakeLock); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; public class GpxToCacheDI { public static class XmlPullParserWrapper { private String mSource; private XmlPullParser mXmlPullParser; public String getAttributeValue(String namespace, String name) { return mXmlPullParser.getAttributeValue(namespace, name); } public int getEventType() throws XmlPullParserException { return mXmlPullParser.getEventType(); } public String getName() { return mXmlPullParser.getName(); } public String getSource() { return mSource; } public String getText() { return mXmlPullParser.getText(); } public int next() throws XmlPullParserException, IOException { return mXmlPullParser.next(); } public void open(String path, Reader reader) throws XmlPullParserException { final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser(); newPullParser.setInput(reader); mSource = path; mXmlPullParser = newPullParser; } } public static XmlPullParser createPullParser(String path) throws FileNotFoundException, XmlPullParserException { final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser(); final Reader reader = new BufferedReader(new FileReader(path)); newPullParser.setInput(reader); return newPullParser; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import java.io.File; public class FileFactory { public File createFile(String path) { return new File(path); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class WriterWrapper { Writer mWriter; public void close() throws IOException { mWriter.close(); } public void open(String path) throws IOException { mWriter = new BufferedWriter(new FileWriter(path), 4000); } public void write(String str) throws IOException { try { mWriter.write(str); } catch (IOException e) { throw new IOException("Error writing line '" + str + "'"); } } }
Java
package com.google.code.geobeagle; import java.util.Hashtable; public class CacheTypeFactory { private final Hashtable<Integer, CacheType> mCacheTypes = new Hashtable<Integer, CacheType>(CacheType.values().length); public CacheTypeFactory() { for (CacheType cacheType : CacheType.values()) mCacheTypes.put(cacheType.toInt(), cacheType); } public CacheType fromInt(int i) { if (!mCacheTypes.containsKey(i)) return CacheType.NULL; return mCacheTypes.get(i); } public CacheType fromTag(String tag) { String tagLower = tag.toLowerCase(); int longestMatch = 0; CacheType result = CacheType.NULL; for (CacheType cacheType : mCacheTypes.values()) { String cacheTypeTag = cacheType.getTag(); if (tagLower.contains(cacheTypeTag) && cacheTypeTag.length() > longestMatch) { result = cacheType; // Necessary to continue the search to find mega-events and // individual waypoint types. longestMatch = cacheTypeTag.length(); } } return result; } public int container(String container) { if (container.equals("Micro")) { return 1; } else if (container.equals("Small")) { return 2; } else if (container.equals("Regular")) { return 3; } else if (container.equals("Large")) { return 4; } return 0; } public int stars(String stars) { try { return Math.round(Float.parseFloat(stars) * 2); } catch (Exception ex) { return 0; } } }
Java
package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.R; import com.google.code.geobeagle.formatting.DistanceFormatter; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate.TimeProvider; import android.content.Context; import android.os.Handler; import android.view.View; import android.widget.TextView; public class GpsWidgetAndUpdater { private static final class SystemTime implements TimeProvider { @Override public long getTime() { return System.currentTimeMillis(); } } private final GpsStatusWidgetDelegate mGpsStatusWidgetDelegate; private final UpdateGpsWidgetRunnable mUpdateGpsRunnable; public GpsWidgetAndUpdater(Context context, View gpsWidgetView, GeoFixProvider geoFixProvider, DistanceFormatter distanceFormatterMetric) { final Clock clock = new Clock(); final Handler handler = new Handler(); final MeterFormatter meterFormatter = new MeterFormatter(context); final TextView locationViewer = (TextView)gpsWidgetView.findViewById(R.id.location_viewer); final MeterBars meterBars = new MeterBars(locationViewer, meterFormatter); final TextView accuracyView = (TextView)gpsWidgetView.findViewById(R.id.accuracy); final Meter meter = new Meter(meterBars, accuracyView); final TextView lag = (TextView)gpsWidgetView.findViewById(R.id.lag); final TextView status = (TextView)gpsWidgetView.findViewById(R.id.status); final TextView provider = (TextView)gpsWidgetView.findViewById(R.id.provider); final MeterFader meterFader = new MeterFader(gpsWidgetView, meterBars, clock); TimeProvider timeProvider = new SystemTime(); mGpsStatusWidgetDelegate = new GpsStatusWidgetDelegate(geoFixProvider, distanceFormatterMetric, meter, meterFader, provider, context, status, lag, GeoFix.NO_FIX, timeProvider); mUpdateGpsRunnable = new UpdateGpsWidgetRunnable(handler, geoFixProvider, meter, mGpsStatusWidgetDelegate, timeProvider); } public GpsStatusWidgetDelegate getGpsStatusWidgetDelegate() { return mGpsStatusWidgetDelegate; } public UpdateGpsWidgetRunnable getUpdateGpsWidgetRunnable() { return mUpdateGpsRunnable; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.R; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; /** * Displays the GPS status (mAccuracy, availability, etc). * @author sng */ public class InflatedGpsStatusView extends LinearLayout { private GpsStatusWidgetDelegate mGpsStatusWidgetDelegate; public InflatedGpsStatusView(Context context) { super(context); LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true); } public InflatedGpsStatusView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); mGpsStatusWidgetDelegate.paint(); } public void setDelegate(GpsStatusWidgetDelegate gpsStatusWidgetDelegate) { mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate; } }
Java
package com.google.code.geobeagle; import android.app.Activity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class ErrorDisplayerDi { static public ErrorDisplayer createErrorDisplayer(Activity activity) { final OnClickListener mOnClickListener = new OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }; return new ErrorDisplayer(activity, mOnClickListener); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; /** * Database version history: * 12: Adds tables LABELS and CACHELABELS * 13: Replace LABELS and CACHELABELS with TAGS and CACHETAGS */ public class Database { public static final String DATABASE_NAME = "GeoBeagle.db"; public static final int DATABASE_VERSION = 13; public static final String S0_COLUMN_CACHE_TYPE = "CacheType INTEGER NOT NULL Default 0"; public static final String S0_COLUMN_CONTAINER = "Container INTEGER NOT NULL Default 0"; public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1"; public static final String S0_COLUMN_DIFFICULTY = "Difficulty INTEGER NOT NULL Default 0"; public static final String S0_COLUMN_TERRAIN = "Terrain INTEGER NOT NULL Default 0"; public static final String S0_INTENT = "intent"; public static final String SQL_CACHES_DONT_DELETE_ME = "UPDATE CACHES SET DeleteMe = 0 WHERE Source = ?"; public static final String SQL_CLEAR_CACHES = "DELETE FROM CACHES WHERE Source=?"; public static final String SQL_CREATE_CACHE_TABLE_V08 = "CREATE TABLE CACHES (" + "Id VARCHAR PRIMARY KEY, Description VARCHAR, " + "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR);"; public static final String SQL_CREATE_CACHE_TABLE_V10 = "CREATE TABLE CACHES (" + "Id VARCHAR PRIMARY KEY, Description VARCHAR, " + "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ");"; public static final String SQL_CREATE_CACHE_TABLE_V11 = "CREATE TABLE CACHES (" + "Id VARCHAR PRIMARY KEY, Description VARCHAR, " + "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", " + S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY + ", " + S0_COLUMN_TERRAIN + ");"; public static final String SQL_CREATE_GPX_TABLE_V10 = "CREATE TABLE GPX (" + "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL);"; //V12: public static final String SQL_CREATE_TAGS_TABLE_V12 = "CREATE TABLE TAGS (" + "Id VARCHAR PRIMARY KEY NOT NULL, Name VARCHAR NOT NULL, Locked BOOLEAN NOT NULL);"; public static final String SQL_CREATE_CACHETAGS_TABLE_V12 = "CREATE TABLE CACHETAGS (" + "CacheId VARCHAR NOT NULL, TagId INTEGER NOT NULL);"; public static final String SQL_CREATE_IDX_CACHETAGS = "CREATE INDEX IDX_CACHETAGS on CACHETAGS (CacheId, TagId);"; public static final String SQL_CREATE_IDX_LATITUDE = "CREATE INDEX IDX_LATITUDE on CACHES (Latitude);"; public static final String SQL_CREATE_IDX_LONGITUDE = "CREATE INDEX IDX_LONGITUDE on CACHES (Longitude);"; public static final String SQL_CREATE_IDX_SOURCE = "CREATE INDEX IDX_SOURCE on CACHES (Source);"; public static final String SQL_DELETE_CACHE = "DELETE FROM CACHES WHERE Id=?"; public static final String SQL_DELETE_OLD_CACHES = "DELETE FROM CACHES WHERE DeleteMe = 1"; public static final String SQL_DELETE_OLD_GPX = "DELETE FROM GPX WHERE DeleteMe = 1"; public static final String SQL_DELETE_CACHETAG = "DELETE FROM CACHETAGS WHERE CacheId = ? AND TagId = ?"; public static final String SQL_DELETE_ALL_TAGS = "DELETE FROM CACHETAGS WHERE TagId = ?"; public static final String SQL_DELETE_ALL_CACHES = "DELETE FROM CACHES"; public static final String SQL_DELETE_ALL_GPX = "DELETE FROM GPX"; public static final String SQL_DROP_CACHE_TABLE = "DROP TABLE IF EXISTS CACHES"; public static final String SQL_GPX_DONT_DELETE_ME = "UPDATE GPX SET DeleteMe = 0 WHERE Name = ?"; public static final String SQL_MATCH_NAME_AND_EXPORTED_LATER = "Name = ? AND ExportTime >= ?"; public static final String SQL_REPLACE_CACHE = "REPLACE INTO CACHES " + "(Id, Description, Latitude, Longitude, Source, DeleteMe, CacheType, Difficulty, Terrain, Container) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)"; public static final String SQL_REPLACE_GPX = "REPLACE INTO GPX (Name, ExportTime, DeleteMe) VALUES (?, ?, 0)"; public static final String SQL_REPLACE_TAG = "REPLACE INTO TAGS " + "(Id, Name, Locked) VALUES (?, ?, ?)"; public static final String SQL_REPLACE_CACHETAG = "REPLACE INTO CACHETAGS " + "(CacheId, TagId) VALUES (?, ?)"; public static final String SQL_RESET_DELETE_ME_CACHES = "UPDATE CACHES SET DeleteMe = 1 WHERE Source != '" + S0_INTENT + "'"; public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1"; public static final String TBL_CACHES = "CACHES"; public static final String TBL_GPX = "GPX"; public static final String TBL_TAGS = "TAGS"; public static final String TBL_CACHETAGS = "CACHETAGS"; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.GeocacheFactory; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.Arrays; public class DatabaseDI { public static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper { private final OpenHelperDelegate mOpenHelperDelegate; public GeoBeagleSqliteOpenHelper(Context context) { super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION); mOpenHelperDelegate = new OpenHelperDelegate(); } public SQLiteWrapper getWritableSqliteWrapper() { return new SQLiteWrapper(this.getWritableDatabase()); } @Override public void onCreate(SQLiteDatabase db) { final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db); mOpenHelperDelegate.onCreate(sqliteWrapper); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db); mOpenHelperDelegate.onUpgrade(sqliteWrapper, oldVersion); } } public static class SQLiteWrapper implements ISQLiteDatabase { private final SQLiteDatabase mSQLiteDatabase; public SQLiteWrapper(SQLiteDatabase writableDatabase) { mSQLiteDatabase = writableDatabase; } public void beginTransaction() { mSQLiteDatabase.beginTransaction(); } public int countResults(String table, String selection, String... selectionArgs) { Log.d("GeoBeagle", "SQL count results: " + selection + ", " + Arrays.toString(selectionArgs)); Cursor cursor = mSQLiteDatabase.query(table, null, selection, selectionArgs, null, null, null, null); int count = cursor.getCount(); cursor.close(); return count; } public void endTransaction() { mSQLiteDatabase.endTransaction(); } public void execSQL(String sql) { //Log.d("GeoBeagle", "SQL: " + sql); mSQLiteDatabase.execSQL(sql); } public void execSQL(String sql, Object... bindArgs) { //Log.d("GeoBeagle", "SQL: " + sql + ", " + Arrays.toString(bindArgs)); mSQLiteDatabase.execSQL(sql, bindArgs); } public Cursor query(String table, String[] columns, String selection, String groupBy, String having, String orderBy, String limit, String... selectionArgs) { final Cursor query = mSQLiteDatabase.query(table, columns, selection, selectionArgs, groupBy, orderBy, having, limit); //Log.d("GeoBeagle", "limit: " + limit + ", query: " + selection); return query; } public Cursor rawQuery(String sql, String[] selectionArgs) { return mSQLiteDatabase.rawQuery(sql, selectionArgs); } public void setTransactionSuccessful() { mSQLiteDatabase.setTransactionSuccessful(); } public void close() { Log.d("GeoBeagle", "----------closing sqlite------"); mSQLiteDatabase.close(); } public boolean isOpen() { return mSQLiteDatabase.isOpen(); } } public static CacheWriter createCacheWriter(ISQLiteDatabase writableDatabase, GeocacheFactory geocacheFactory, DbFrontend dbFrontend) { final SourceNameTranslator dbToGeocacheAdapter = new SourceNameTranslator(); return new CacheWriter(writableDatabase, dbFrontend, dbToGeocacheAdapter, geocacheFactory); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; public class Clock { public long getCurrentTime() { return System.currentTimeMillis(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; public enum CacheType { NULL(0, R.drawable.cache_default, R.drawable.cache_default_big, R.drawable.pin_default, "null"), MULTI(2, R.drawable.cache_multi, R.drawable.cache_multi_big, R.drawable.pin_multi, "multi"), TRADITIONAL(1, R.drawable.cache_tradi, R.drawable.cache_tradi_big, R.drawable.pin_tradi, "traditional"), UNKNOWN(3, R.drawable.cache_mystery, R.drawable.cache_mystery_big, R.drawable.pin_mystery, "unknown"), MY_LOCATION(4, R.drawable.blue_dot, R.drawable.blue_dot, R.drawable.pin_default, "my location"), //Caches without unique icons EARTHCACHE(5, R.drawable.cache_earth, R.drawable.cache_earth_big, R.drawable.pin_earth, "earth"), VIRTUAL(6, R.drawable.cache_virtual, R.drawable.cache_virtual_big, R.drawable.pin_virtual, "virtual"), LETTERBOX_HYBRID(7, R.drawable.cache_letterbox, R.drawable.cache_letterbox_big, R.drawable.pin_letter, "letterbox"), EVENT(8, R.drawable.cache_event, R.drawable.cache_event_big, R.drawable.pin_event, "event"), WEBCAM(9, R.drawable.cache_webcam, R.drawable.cache_webcam_big, R.drawable.pin_webcam, "webcam"), //Caches without unique icons CITO(10, R.drawable.cache_default, R.drawable.cache_default_big, R.drawable.pin_default, "cache in trash out"), LOCATIONLESS(11, R.drawable.cache_default, R.drawable.cache_default_big, R.drawable.pin_default, "reverse"), APE(12, R.drawable.cache_default, R.drawable.cache_default_big, R.drawable.pin_default, "project ape"), MEGA(13, R.drawable.cache_mega, R.drawable.cache_mega_big, R.drawable.pin_mega, "mega-event"), WHERIGO(14, R.drawable.cache_default, R.drawable.cache_default_big, R.drawable.pin_default, "wherigo"), //Waypoint types WAYPOINT(20, R.drawable.cache_default, R.drawable.cache_default_big, R.drawable.pin_default, "waypoint"), //Not actually seen in GPX... WAYPOINT_PARKING(21, R.drawable.cache_waypoint_p, R.drawable.cache_waypoint_p_big, R.drawable.map_pin2_wp_p, "waypoint|parking area"), WAYPOINT_REFERENCE(22, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big, R.drawable.map_pin2_wp_r, "waypoint|reference point"), WAYPOINT_STAGES(23, R.drawable.cache_waypoint_s, R.drawable.cache_waypoint_s_big, R.drawable.map_pin2_wp_s, "waypoint|stages of a multicache"), WAYPOINT_TRAILHEAD(24, R.drawable.cache_waypoint_t, R.drawable.cache_waypoint_t_big, R.drawable.map_pin2_wp_t, "waypoint|trailhead"), WAYPOINT_FINAL(25, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big, R.drawable.map_pin2_wp_r, "waypoint|final location"); //TODO: Doesn't have unique graphics yet private final int mIconId; private final int mIconIdBig; private final int mIx; private final int mIconIdMap; private final String mTag; CacheType(int ix, int drawableId, int drawableIdBig, int drawableIdMap, String tag) { mIx = ix; mIconId = drawableId; mIconIdBig = drawableIdBig; mIconIdMap = drawableIdMap; mTag = tag; } public int icon() { return mIconId; } public int iconBig() { return mIconIdBig; } public int toInt() { return mIx; } public int iconMap() { return mIconIdMap; } public String getTag() { return mTag; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpx.zip; import com.google.code.geobeagle.xmlimport.gpx.zip.GpxZipInputStream; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipInputStream; public class ZipInputStreamFactory { public GpxZipInputStream create(String filename) throws IOException { return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream( new FileInputStream(filename)))); } }
Java
package com.google.code.geobeagle; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; public class GraphicsGenerator { private final RatingsGenerator mRatingsGenerator; private final IconRenderer mIconRenderer; public GraphicsGenerator(RatingsGenerator ratingsGenerator, IconRenderer iconRenderer) { mRatingsGenerator = ratingsGenerator; mIconRenderer = iconRenderer; } public static class RatingsGenerator { public Drawable createRating(Drawable unselected, Drawable halfSelected, Drawable selected, int rating) { int width = unselected.getIntrinsicWidth(); int height = unselected.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(5 * width, 16, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bitmap); int i = 0; while (i < rating / 2) { draw(width, height, c, i++, selected); } if (rating % 2 == 1) { draw(width, height, c, i++, halfSelected); } while (i < 5) { draw(width, height, c, i++, unselected); } return new BitmapDrawable(bitmap); } private void draw(int width, int height, Canvas c, int i, Drawable drawable) { drawable.setBounds(width * i, 0, width * (i + 1) - 1, height - 1); drawable.draw(c); } } public Drawable[] getRatings(Drawable drawables[], int maxRatings) { Drawable[] ratings = new Drawable[maxRatings]; for (int i = 1; i <= maxRatings; i++) { ratings[i - 1] = mRatingsGenerator.createRating(drawables[0], drawables[1], drawables[2], i); } return ratings; } static interface BitmapCopier { Bitmap copy(Bitmap source); int getBottom(); } static class ListViewBitmapCopier implements BitmapCopier { public Bitmap copy(Bitmap source) { int imageHeight = source.getHeight(); int imageWidth = source.getWidth(); Bitmap copy = Bitmap.createBitmap(imageWidth, imageHeight + 5, Bitmap.Config.ARGB_8888); int[] pixels = new int[imageWidth * imageHeight]; source.getPixels(pixels, 0, imageWidth, 0, 0, imageWidth, imageHeight); copy.setPixels(pixels, 0, imageWidth, 0, 0, imageWidth, imageHeight); return copy; } public int getBottom() { return 0; } } public static class MapViewBitmapCopier implements BitmapCopier { public Bitmap copy(Bitmap source) { return source.copy(Bitmap.Config.ARGB_8888, true); } public int getBottom() { return 3; } } public static class IconRenderer { private final AttributePainter mAttributePainter; public IconRenderer(AttributePainter attributePainter) { mAttributePainter = attributePainter; } Drawable createOverlay(Geocache geocache, int backdropId, Drawable overlayIcon, Resources resources, BitmapCopier bitmapCopier) { Bitmap bitmap = BitmapFactory.decodeResource(resources, backdropId); Bitmap copy = bitmapCopier.copy(bitmap); int imageHeight = copy.getHeight(); int imageWidth = copy.getWidth(); int bottom = bitmapCopier.getBottom(); Canvas canvas = new Canvas(copy); mAttributePainter.drawAttribute(1, bottom, imageHeight, imageWidth, canvas, geocache .getDifficulty(), Color.argb(255, 0x20, 0x20, 0xFF)); mAttributePainter.drawAttribute(0, bottom, imageHeight, imageWidth, canvas, geocache .getTerrain(), Color.argb(255, 0xDB, 0xA1, 0x09)); drawOverlay(overlayIcon, imageWidth, canvas); return new BitmapDrawable(copy); } private void drawOverlay(Drawable overlayIcon, int imageWidth, Canvas canvas) { if (overlayIcon != null) { overlayIcon.setBounds(imageWidth-1-overlayIcon.getIntrinsicWidth(), 0, imageWidth-1, overlayIcon.getIntrinsicHeight()-1); overlayIcon.draw(canvas); } } } public Drawable createIconListView(Geocache geocache, Drawable overlayIcon, Resources resources) { return mIconRenderer.createOverlay(geocache, geocache.getCacheType().icon(), overlayIcon, resources, new ListViewBitmapCopier()); } public Drawable createIconMapView(Geocache geocache, Drawable overlayIcon, Resources resources) { Drawable iconMap = mIconRenderer.createOverlay(geocache, geocache.getCacheType().iconMap(), overlayIcon, resources, new MapViewBitmapCopier()); int width = iconMap.getIntrinsicWidth(); int height = iconMap.getIntrinsicHeight(); iconMap.setBounds(-width / 2, -height, width / 2, 0); return iconMap; } public static class AttributePainter { private final Paint mTempPaint; private final Rect mTempRect; public AttributePainter(Paint tempPaint, Rect tempRect) { mTempPaint = tempPaint; mTempRect = tempRect; } void drawAttribute(int position, int bottom, int imageHeight, int imageWidth, Canvas canvas, double attribute, int color) { final int diffWidth = (int)(imageWidth * (attribute / 10.0)); final int MARGIN = 1; final int THICKNESS = 3; final int base = imageHeight - bottom - MARGIN; final int attributeBottom = base - position * (THICKNESS + 1); final int attributeTop = attributeBottom - THICKNESS; mTempPaint.setColor(color); mTempRect.set(0, attributeTop, diffWidth, attributeBottom); canvas.drawRect(mTempRect, mTempPaint); } } /** Returns a new Drawable that is 'top' over 'bottom'. * Top is assumed to be smaller and is centered over bottom. */ public Drawable superimpose(Drawable top, Drawable bottom) { int width = bottom.getIntrinsicWidth(); int height = bottom.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bitmap); bottom.setBounds(0, 0, width-1, height-1); int topWidth = top.getIntrinsicWidth(); int topHeight = top.getIntrinsicHeight(); top.setBounds(width/2 - topWidth/2, height/2 - topHeight/2, width/2 - topWidth/2 + topWidth, height/2 - topHeight/2 + topHeight); bottom.draw(c); top.draw(c); BitmapDrawable bd = new BitmapDrawable(bitmap); bd.setBounds(-width/2, -height, width/2, 0); //Necessary! return bd; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.code.geobeagle.Geocache.AttributeFormatter; import com.google.code.geobeagle.Geocache.AttributeFormatterImpl; import com.google.code.geobeagle.Geocache.AttributeFormatterNull; import com.google.code.geobeagle.GeocacheFactory.Source.SourceFactory; import com.google.code.geobeagle.database.SourceNameTranslator; import android.database.Cursor; import java.util.WeakHashMap; //TODO: Make GeocacheFactory call DbFrontend and not the other way around. //TODO: Make GeocacheFactory is a global object, common to all Activities of GeoBeagle. Solves GeocacheFactory flushing in other activites when a geocache is changed. public class GeocacheFactory { public static enum Provider { ATLAS_QUEST(0, "LB"), GROUNDSPEAK(1, "GC"), MY_LOCATION(-1, "ML"), OPENCACHING(2, "OC"); private final int mIx; private final String mPrefix; Provider(int ix, String prefix) { mIx = ix; mPrefix = prefix; } public int toInt() { return mIx; } public String getPrefix() { return mPrefix; } } public static Provider ALL_PROVIDERS[] = { Provider.ATLAS_QUEST, Provider.GROUNDSPEAK, Provider.MY_LOCATION, Provider.OPENCACHING }; public static enum Source { GPX(0), LOC(3), MY_LOCATION(1), WEB_URL(2); public final static int MIN_SOURCE = 0; public final static int MAX_SOURCE = 3; public static class SourceFactory { private final Source mSources[] = new Source[values().length]; public SourceFactory() { for (Source source : values()) mSources[source.mIx] = source; } public Source fromInt(int i) { return mSources[i]; } } private final int mIx; Source(int ix) { mIx = ix; } public int toInt() { return mIx; } } static class AttributeFormatterFactory { private AttributeFormatterImpl mAttributeFormatterImpl; private AttributeFormatterNull mAttributeFormatterNull; public AttributeFormatterFactory(AttributeFormatterImpl attributeFormatterImpl, AttributeFormatterNull attributeFormatterNull) { mAttributeFormatterImpl = attributeFormatterImpl; mAttributeFormatterNull = attributeFormatterNull; } AttributeFormatter getAttributeFormatter(Source sourceType) { if (sourceType == Source.GPX) return mAttributeFormatterImpl; return mAttributeFormatterNull; } } private static CacheTypeFactory mCacheTypeFactory; private static SourceFactory mSourceFactory; private AttributeFormatterFactory mAttributeFormatterFactory; public GeocacheFactory() { mSourceFactory = new SourceFactory(); mCacheTypeFactory = new CacheTypeFactory(); mAttributeFormatterFactory = new AttributeFormatterFactory(new AttributeFormatterImpl(), new AttributeFormatterNull()); } public CacheType cacheTypeFromInt(int cacheTypeIx) { return mCacheTypeFactory.fromInt(cacheTypeIx); } /** Mapping from cacheId to Geocache for all loaded geocaches */ private WeakHashMap<CharSequence, Geocache> mGeocaches = new WeakHashMap<CharSequence, Geocache>(); /** @return the geocache if it is already loaded, otherwise null */ public Geocache getFromId(CharSequence id) { return mGeocaches.get(id); } //TODO: This method should only be for creating a new geocache in the database public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container) { if (id.length() < 2) { // ID is missing for waypoints imported from the browser; create a // new id from the time. id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis()); } if (name == null) name = ""; Geocache cached = mGeocaches.get(id); if (cached != null && cached.getName().equals(name) && cached.getLatitude() == latitude && cached.getLongitude() == longitude && cached.getSourceType().equals(sourceType) && cached.getSourceName().equals(sourceName) && cached.getCacheType() == cacheType && cached.getDifficulty() == difficulty && cached.getTerrain() == terrain && cached.getContainer() == container) return cached; final AttributeFormatter attributeFormatter = mAttributeFormatterFactory .getAttributeFormatter(sourceType); cached = new Geocache(id, name, latitude, longitude, sourceType, sourceName, cacheType, difficulty, terrain, container, attributeFormatter); mGeocaches.put(id, cached); return cached; } public Source sourceFromInt(int sourceIx) { return mSourceFactory.fromInt(sourceIx); } /** Remove all cached geocache instances. Future references will reload from the database. */ public void flushCache() { mGeocaches.clear(); } public void flushCacheIcons() { for (Geocache geocache : mGeocaches.values()) { geocache.flushIcons(); } } /** Forces the geocache to be reloaded from the database the next time it is needed. */ public void flushGeocache(CharSequence geocacheId) { mGeocaches.remove(geocacheId.toString()); } public Geocache fromCursor(Cursor cursor, SourceNameTranslator translator) { String sourceName = cursor.getString(4); CacheType cacheType = cacheTypeFromInt(Integer.parseInt(cursor .getString(5))); int difficulty = Integer.parseInt(cursor.getString(6)); int terrain = Integer.parseInt(cursor.getString(7)); int container = Integer.parseInt(cursor.getString(8)); return create(cursor.getString(2), cursor.getString(3), cursor .getDouble(0), cursor.getDouble(1), translator .sourceNameToSourceType(sourceName), sourceName, cacheType, difficulty, terrain, container); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.preference.PreferenceManager; public class LocationControlDi { public static GeoFixProvider create(Activity activity) { if (false) { //Set to true to use fake locations //return new GeoFixProviderFake(GeoFixProviderFake.CAR_JOURNEY); return new GeoFixProviderFake(GeoFixProviderFake.LINKOPING); //return new GeoFixProviderFake(GeoFixProviderFake.TOKYO); //return new GeoFixProviderFake(GeoFixProviderFake.YOKOHAMA); } else { final LocationManager locationManager = (LocationManager)activity .getSystemService(Context.LOCATION_SERVICE); final SensorManager sensorManager = (SensorManager)activity .getSystemService(Context.SENSOR_SERVICE); final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(activity); return new GeoFixProviderLive(locationManager, sensorManager, sharedPreferences); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity; import android.content.Context; public class ActivityDI { public static class ActivityTypeFactory { private final ActivityType mActivityTypes[] = new ActivityType[ActivityType.values().length]; public ActivityTypeFactory() { for (ActivityType activityType : ActivityType.values()) mActivityTypes[activityType.toInt()] = activityType; } public ActivityType fromInt(int i) { return mActivityTypes[i]; } } public static ActivitySaver createActivitySaver(Context context) { return new ActivitySaver(context.getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE) .edit()); } }
Java
//http://www.spectrekking.com/download/FixedMyLocationOverlay.java package com.google.code.geobeagle.activity.map; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.location.Location; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Projection; import com.google.code.geobeagle.R; public class FixedMyLocationOverlay extends MyLocationOverlay { private boolean bugged = false; private Paint accuracyPaint; private Point center; private Point left; private Drawable drawable; private int width; private int height; public FixedMyLocationOverlay(Context context, MapView mapView) { super(context, mapView); } @Override protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc, long when) { if (!bugged) { try { super.drawMyLocation(canvas, mapView, lastFix, myLoc, when); } catch (Exception e) { bugged = true; } } if (bugged) { if (drawable == null) { accuracyPaint = new Paint(); accuracyPaint.setAntiAlias(true); accuracyPaint.setStrokeWidth(2.0f); drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation); width = drawable.getIntrinsicWidth(); height = drawable.getIntrinsicHeight(); center = new Point(); left = new Point(); } Projection projection = mapView.getProjection(); double latitude = lastFix.getLatitude(); double longitude = lastFix.getLongitude(); float accuracy = lastFix.getAccuracy(); float[] result = new float[1]; Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result); float longitudeLineDistance = result[0]; GeoPoint leftGeo = new GeoPoint((int)(latitude * 1e6), (int)((longitude - accuracy / longitudeLineDistance) * 1e6)); projection.toPixels(leftGeo, left); projection.toPixels(myLoc, center); int radius = center.x - left.x; accuracyPaint.setColor(0xff6666ff); accuracyPaint.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); accuracyPaint.setColor(0x186666ff); accuracyPaint.setStyle(Style.FILL); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2); drawable.draw(canvas); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.MapView; import android.content.Context; import android.util.AttributeSet; public class GeoMapView extends MapView { private OverlayManager mOverlayManager; public GeoMapView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); //Log.d("GeoBeagle", "~~~~~~~~~~onLayout " + changed + ", " + left + ", " + top + ", " // + right + ", " + bottom); if (mOverlayManager != null) { mOverlayManager.selectOverlay(); } } public void setScrollListener(OverlayManager overlayManager) { mOverlayManager = overlayManager; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.OverlayItem; import com.google.code.geobeagle.Geocache; class CacheItem extends OverlayItem { private final Geocache mGeocache; CacheItem(GeoPoint geoPoint, Geocache geocache) { super(geoPoint, (String)geocache.getId(), ""); mGeocache = geocache; } Geocache getGeocache() { return mGeocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.GraphicsGenerator; import com.google.code.geobeagle.IToaster; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Toaster; import com.google.code.geobeagle.Toaster.OneTimeToaster; import com.google.code.geobeagle.actions.CacheFilterUpdater; import com.google.code.geobeagle.actions.MenuActionCacheList; import com.google.code.geobeagle.actions.MenuActionEditFilter; import com.google.code.geobeagle.actions.MenuActionFilterListPopup; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import com.google.code.geobeagle.activity.main.GeoUtils; import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch; import com.google.code.geobeagle.activity.map.OverlayManager.OverlaySelector; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.CachesProviderLazyArea; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.PeggedCacheProvider; import com.google.code.geobeagle.database.CachesProviderLazyArea.CoordinateManager; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class GeoMapActivity extends MapActivity { public static Toaster.ToasterFactory peggedCacheProviderToasterFactory = new OneTimeToaster.OneTimeToasterFactory(); static class NullOverlay extends Overlay { } private static final int DEFAULT_ZOOM_LEVEL = 14; private static boolean fZoomed = false; private DbFrontend mDbFrontend; private GeoMapActivityDelegate mGeoMapActivityDelegate; private GeoMapView mMapView; private MyLocationOverlay mMyLocationOverlay; private OverlayManager mOverlayManager; @Override protected boolean isRouteDisplayed() { // This application doesn't use routes return false; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); // Set member variables first, in case anyone after this needs them. mMapView = (GeoMapView)findViewById(R.id.mapview); mDbFrontend = new DbFrontend(this, new GeocacheFactory()); //mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMyLocationOverlay = new FixedMyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); mMapView.setSatellite(false); final Resources resources = getResources(); final Drawable defaultMarker = resources.getDrawable(R.drawable.pin_default); final GraphicsGenerator graphicsGenerator = new GraphicsGenerator( new GraphicsGenerator.RatingsGenerator(), null); final CacheItemFactory cacheItemFactory = new CacheItemFactory(resources, graphicsGenerator, mDbFrontend); final FilterTypeCollection filterTypeCollection = new FilterTypeCollection(this); final List<Overlay> mapOverlays = mMapView.getOverlays(); final Intent intent = getIntent(); final MapController mapController = mMapView.getController(); final double latitude = intent.getFloatExtra("latitude", 0); final double longitude = intent.getFloatExtra("longitude", 0); final Overlay nullOverlay = new NullOverlay(); final GeoPoint nullGeoPoint = new GeoPoint(0, 0); String geocacheId = intent.getStringExtra("geocacheId"); if (geocacheId != null) { Geocache selected = mDbFrontend.loadCacheFromId(geocacheId); cacheItemFactory.setSelectedGeocache(selected); } mapOverlays.add(nullOverlay); mapOverlays.add(mMyLocationOverlay); final List<DensityPatch> densityPatches = new ArrayList<DensityPatch>(); final Toaster toaster = new Toaster(this, R.string.too_many_caches, Toast.LENGTH_SHORT); final CachesProviderDb cachesProviderArea = new CachesProviderDb(mDbFrontend); final IToaster densityOverlayToaster = new OneTimeToaster(toaster); final PeggedCacheProvider peggedCacheProvider = new PeggedCacheProvider( peggedCacheProviderToasterFactory.getToaster(toaster)); final CoordinateManager coordinateManager = new CoordinateManager(1.0); final CachesProviderLazyArea lazyArea = new CachesProviderLazyArea( cachesProviderArea, peggedCacheProvider, coordinateManager); final DensityOverlayDelegate densityOverlayDelegate = DensityOverlay.createDelegate( densityPatches, nullGeoPoint, lazyArea, densityOverlayToaster); final DensityOverlay densityOverlay = new DensityOverlay(densityOverlayDelegate); final CachePinsOverlay cachePinsOverlay = new CachePinsOverlay(cacheItemFactory, this, defaultMarker, GeocacheListPrecomputed.EMPTY); //Pin overlay and Density overlay can't share providers because the provider wouldn't report hasChanged() when switching between them CachesProviderDb cachesProviderAreaPins = new CachesProviderDb(mDbFrontend); final CoordinateManager coordinateManagerPins = new CoordinateManager(1.0); final CachesProviderLazyArea lazyAreaPins = new CachesProviderLazyArea( cachesProviderAreaPins, peggedCacheProvider, coordinateManagerPins); final CachePinsOverlayFactory cachePinsOverlayFactory = new CachePinsOverlayFactory( mMapView, this, defaultMarker, cacheItemFactory, cachePinsOverlay, lazyAreaPins); final GeoPoint center = new GeoPoint((int)(latitude * GeoUtils.MILLION), (int)(longitude * GeoUtils.MILLION)); mapController.setCenter(center); final OverlaySelector overlaySelector = new OverlaySelector(); mOverlayManager = new OverlayManager(mMapView, mapOverlays, densityOverlay, cachePinsOverlayFactory, false, cachesProviderArea, filterTypeCollection, overlaySelector ); mMapView.setScrollListener(mOverlayManager); // *** BUILD MENU *** final MenuActions menuActions = new MenuActions(); menuActions.add(new GeoMapActivityDelegate.MenuActionToggleSatellite(mMapView)); menuActions.add(new GeoMapActivityDelegate.MenuActionCenterLocation(resources, mapController, mMyLocationOverlay)); menuActions.add(new MenuActionCacheList(this, resources)); final List<CachesProviderDb> providers = new ArrayList<CachesProviderDb>(); providers.add(cachesProviderArea); providers.add(cachesProviderAreaPins); final CacheFilterUpdater cacheFilterUpdater = new CacheFilterUpdater(filterTypeCollection, providers); menuActions.add(new MenuActionEditFilter(this, cacheFilterUpdater, mOverlayManager, filterTypeCollection, resources)); menuActions.add(new MenuActionFilterListPopup(this, cacheFilterUpdater, mOverlayManager, filterTypeCollection, resources)); mGeoMapActivityDelegate = new GeoMapActivityDelegate(menuActions); if (!fZoomed) { mapController.setZoom(DEFAULT_ZOOM_LEVEL); fZoomed = true; } mOverlayManager.selectOverlay(); } public OverlayManager getOverlayManager() { return mOverlayManager; } @Override public boolean onCreateOptionsMenu(Menu menu) { return mGeoMapActivityDelegate.onCreateOptionsMenu(menu); } @Override public boolean onMenuOpened(int featureId, Menu menu) { return mGeoMapActivityDelegate.onMenuOpened(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mGeoMapActivityDelegate.onOptionsItemSelected(item); } @Override public void onPause() { mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); mDbFrontend.closeDatabase(); super.onPause(); } @Override public void onResume() { super.onResume(); mOverlayManager.forceRefresh(); //The cache filter might have changed mMyLocationOverlay.enableMyLocation(); mMyLocationOverlay.enableCompass(); mDbFrontend.openDatabase(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.code.geobeagle.IToaster; import com.google.code.geobeagle.Toaster.OneTimeToaster; import com.google.code.geobeagle.database.CachesProviderLazyArea; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import java.util.List; public class DensityOverlay extends Overlay { // Create delegate because it's not possible to test classes that extend // Android classes. public static DensityOverlayDelegate createDelegate(List<DensityMatrix.DensityPatch> patches, GeoPoint nullGeoPoint, CachesProviderLazyArea lazyArea, IToaster densityOverlayToaster) { final Rect patchRect = new Rect(); final Paint paint = new Paint(); paint.setARGB(128, 255, 0, 0); final Point screenLow = new Point(); final Point screenHigh = new Point(); final DensityPatchManager densityPatchManager = new DensityPatchManager(patches, lazyArea, densityOverlayToaster); return new DensityOverlayDelegate(patchRect, paint, screenLow, screenHigh, densityPatchManager); } private DensityOverlayDelegate mDelegate; public DensityOverlay(DensityOverlayDelegate densityOverlayDelegate) { mDelegate = densityOverlayDelegate; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); mDelegate.draw(canvas, mapView, shadow); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.main.GeoBeagle; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import java.util.AbstractList; public class CachePinsOverlay extends ItemizedOverlay<CacheItem> { private final CacheItemFactory mCacheItemFactory; private final Context mContext; private final AbstractList<Geocache> mCacheList; public CachePinsOverlay(CacheItemFactory cacheItemFactory, Context context, Drawable defaultMarker, AbstractList<Geocache> list) { super(boundCenterBottom(defaultMarker)); mContext = context; mCacheItemFactory = cacheItemFactory; mCacheList = list; populate(); } /* (non-Javadoc) * @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean, long) */ @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { return super.draw(canvas, mapView, shadow, when); } @Override protected boolean onTap(int i) { Geocache geocache = getItem(i).getGeocache(); if (geocache == null) return false; final Intent intent = new Intent(mContext, GeoBeagle.class); intent.setAction(GeocacheListController.SELECT_CACHE); intent.putExtra("geocacheId", geocache.getId()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); return true; } @Override protected CacheItem createItem(int i) { return mCacheItemFactory.createCacheItem(mCacheList.get(i)); } @Override public int size() { return mCacheList.size(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.searchonline; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.LocationControlDi; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.ActivityDI; import com.google.code.geobeagle.activity.ActivityRestorer; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory; import com.google.code.geobeagle.activity.ActivityRestorer.CacheListRestorer; import com.google.code.geobeagle.activity.ActivityRestorer.NullRestorer; import com.google.code.geobeagle.activity.ActivityRestorer.Restorer; import com.google.code.geobeagle.activity.ActivityRestorer.ViewCacheRestorer; import com.google.code.geobeagle.activity.cachelist.CacheListActivity; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi; import com.google.code.geobeagle.activity.searchonline.JsInterface.JsInterfaceHelper; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate; import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusView; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; public class SearchOnlineActivity extends Activity { private SearchOnlineActivityDelegate mSearchOnlineActivityDelegate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "SearchOnlineActivity onCreate"); setContentView(R.layout.search); final GeoFixProvider mGeoFixProvider = LocationControlDi.create(this); final InflatedGpsStatusView mGpsStatusWidget = (InflatedGpsStatusView)this .findViewById(R.id.gps_widget_view); final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi .create(this); final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(this, mGpsStatusWidget, mGeoFixProvider, distanceFormatterManager.getFormatter()); final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater .getGpsStatusWidgetDelegate(); gpsWidgetAndUpdater.getUpdateGpsWidgetRunnable().run(); mGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate); mGpsStatusWidget.setBackgroundColor(Color.BLACK); distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate); final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this); final SharedPreferences sharedPreferences = getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE); final ActivityTypeFactory activityTypeFactory = new ActivityTypeFactory(); final NullRestorer nullRestorer = new NullRestorer(); final CacheListRestorer cacheListRestorer = new CacheListRestorer(this); final ViewCacheRestorer viewCacheRestorer = new ViewCacheRestorer(sharedPreferences, this); final Restorer restorers[] = new Restorer[] { nullRestorer, cacheListRestorer, nullRestorer, viewCacheRestorer }; final ActivityRestorer activityRestorer = new ActivityRestorer(activityTypeFactory, sharedPreferences, restorers); mSearchOnlineActivityDelegate = new SearchOnlineActivityDelegate( ((WebView)findViewById(R.id.help_contents)), mGeoFixProvider, distanceFormatterManager, activitySaver); final JsInterfaceHelper jsInterfaceHelper = new JsInterfaceHelper(this); final JsInterface jsInterface = new JsInterface(mGeoFixProvider, jsInterfaceHelper); mSearchOnlineActivityDelegate.configureWebView(jsInterface); activityRestorer.restore(getIntent().getFlags()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_online_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); startActivity(new Intent(this, CacheListActivity.class)); return true; } @Override protected void onResume() { super.onResume(); Log.d("GeoBeagle", "SearchOnlineActivity onResume"); mSearchOnlineActivityDelegate.onResume(); } @Override protected void onPause() { super.onPause(); Log.d("GeoBeagle", "SearchOnlineActivity onPause"); mSearchOnlineActivityDelegate.onPause(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.main.view.EditCache; import com.google.code.geobeagle.database.DbFrontend; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; public class EditCacheActivity extends Activity { private DbFrontend mDbFrontend; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final EditCache.CancelButtonOnClickListener cancelButtonOnClickListener = new EditCache.CancelButtonOnClickListener( this); final GeocacheFactory geocacheFactory = new GeocacheFactory(); mDbFrontend = new DbFrontend(this, geocacheFactory); setContentView(R.layout.cache_edit); final Intent intent = getIntent(); final EditCache editCache = new EditCache(geocacheFactory, (EditText)findViewById(R.id.edit_id), (EditText)findViewById(R.id.edit_name), (EditText)findViewById(R.id.edit_latitude), (EditText)findViewById(R.id.edit_longitude)); EditCache.CacheSaverOnClickListener cacheSaver = new EditCache.CacheSaverOnClickListener( this, editCache, mDbFrontend); ((Button)findViewById(R.id.edit_set)).setOnClickListener(cacheSaver); ((Button)findViewById(R.id.edit_cancel)) .setOnClickListener(cancelButtonOnClickListener); Geocache geocache = mDbFrontend.loadCacheFromId(intent.getStringExtra("geocacheId")); editCache.set(geocache); } @Override protected void onPause() { super.onPause(); mDbFrontend.closeDatabase(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity; public enum ActivityType { // These constants are persisted to the database. They are also used as // indices in ActivityRestorer. CACHE_LIST(1), NONE(0), SEARCH_ONLINE(2), VIEW_CACHE(3); private final int mIx; ActivityType(int i) { mIx = i; } int toInt() { return mIx; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.geobeagle.activity.main; /* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; public class RadarView extends View { private Paint mGridPaint; private Paint mErasePaint; private float mOrientation; private double mTargetLat; private double mTargetLon; private static float KM_PER_METERS = 0.001f; private static float METERS_PER_KM = 1000f; /** * These are the list of choices for the radius of the outer circle on the * screen when using metric units. All items are in kilometers. This array * is used to choose the scale of the radar display. */ private static double mMetricScaleChoices[] = { 100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100, 200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000 }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This * array is for metric measurements.) */ private static float mMetricDisplayUnitsPerKm[] = { METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for metric measurements.) */ private static String mMetricDisplayFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; private static float KM_PER_FEET = 0.0003048f; private static float KM_PER_MILES = 1.609344f; private static float FEET_PER_KM = 3280.8399f; private static float MILES_PER_KM = 0.621371192f; /** * These are the list of choices for the radius of the outer circle on the * screen when using standard units. All items are in kilometers. This array * is used to choose the scale of the radar display. */ private static double mEnglishScaleChoices[] = { 100 * KM_PER_FEET, 200 * KM_PER_FEET, 400 * KM_PER_FEET, 1000 * KM_PER_FEET, 1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES, 20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES, 400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES, 10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This * array is for standard measurements.) */ private static float mEnglishDisplayUnitsPerKm[] = { FEET_PER_KM, FEET_PER_KM, FEET_PER_KM, FEET_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for standard measurements.) */ private static String mEnglishDisplayFormats[] = { "%.0fft", "%.0fft", "%.0fft", "%.0fft", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; private boolean mHaveLocation = false; // True when we have our location private TextView mDistanceView; private double mDistance; // Distance to target, in KM private double mBearing; // Bearing to target, in degrees // Ratio of the distance to the target to the radius of the outermost ring // on the radar screen private float mDistanceRatio; private Bitmap mBlip; // The bitmap used to draw the target // True if the display should use metric units; false if the display should // use standard units private boolean mUseMetric; private TextView mBearingView; private TextView mAccuracyView; private TextView mLagView; private final String mDegreesSymbol; private Path mCompassPath; private final Paint mCompassPaint; private final Paint mArrowPaint; private final Path mArrowPath; private GeoFix mMyLocation; public RadarView(Context context) { this(context, null); } public RadarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RadarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mDegreesSymbol = context.getString(R.string.degrees_symbol); // Paint used for the rings and ring text mGridPaint = new Paint(); mGridPaint.setColor(0xFF00FF00); mGridPaint.setAntiAlias(true); mGridPaint.setStyle(Style.STROKE); mGridPaint.setStrokeWidth(1.0f); mGridPaint.setTextSize(10.0f); mGridPaint.setTextAlign(Align.CENTER); mCompassPaint = new Paint(); mCompassPaint.setColor(0xFF00FF00); mCompassPaint.setAntiAlias(true); mCompassPaint.setStyle(Style.STROKE); mCompassPaint.setStrokeWidth(1.0f); mCompassPaint.setTextSize(10.0f); mCompassPaint.setTextAlign(Align.CENTER); // Paint used to erase the rectangle behind the ring text mErasePaint = new Paint(); mErasePaint.setColor(0xFF191919); mErasePaint.setStyle(Style.FILL); // Paint used for the arrow mArrowPaint = new Paint(); mArrowPaint.setColor(Color.WHITE); mArrowPaint.setAntiAlias(true); mArrowPaint.setStyle(Style.STROKE); mArrowPaint.setStrokeWidth(16); mArrowPaint.setAlpha(228); mArrowPath = new Path(); mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap(); mCompassPath = new Path(); } /** * Sets the target to track on the radar * * @param latE6 Latitude of the target, multiplied by 1,000,000 * @param lonE6 Longitude of the target, multiplied by 1,000,000 */ public void setTarget(int latE6, int lonE6) { mTargetLat = latE6 / (double)GeoUtils.MILLION; mTargetLon = lonE6 / (double)GeoUtils.MILLION; } /** * Sets the view that we will use to report distance * * @param t The text view used to report distance */ public void setDistanceView(TextView d, TextView b, TextView a, TextView lag) { mDistanceView = d; mBearingView = b; mAccuracyView = a; mLagView = lag; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = Math.min(getHeight(), getWidth()) / 2; int radius = center - 8; // Draw the rings final Paint gridPaint = mGridPaint; gridPaint.setAlpha(100); canvas.drawCircle(center, center, radius, gridPaint); canvas.drawCircle(center, center, radius * 3 / 4, gridPaint); canvas.drawCircle(center, center, radius >> 1, gridPaint); canvas.drawCircle(center, center, radius >> 2, gridPaint); int blipRadius = (int)(mDistanceRatio * radius); // Draw horizontal and vertical lines canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint); canvas.drawLine(center, center + (radius >> 2) - 6, center, center + radius + 6, gridPaint); canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint); canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint); if (mHaveLocation) { double northAngle = Math.toRadians(-mOrientation) - (Math.PI / 2); float northX = (float)Math.cos(northAngle); float northY = (float)Math.sin(northAngle); final int compassLength = radius >> 2; float tipX = northX * compassLength, tipY = northY * compassLength; float baseX = northY * 8, baseY = -northX * 8; double bearingToTarget = mBearing - mOrientation; double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2); float cos = (float)Math.cos(drawingAngle); float sin = (float)Math.sin(drawingAngle); mArrowPath.reset(); mArrowPath.moveTo(center - cos * radius, center - sin * radius); mArrowPath.lineTo(center + cos * radius, center + sin * radius); final double arrowRight = drawingAngle + Math.PI / 2; final double arrowLeft = drawingAngle - Math.PI / 2; mArrowPath.moveTo(center + (float)Math.cos(arrowRight) * radius, center + (float)Math.sin(arrowRight) * radius); mArrowPath.lineTo(center + cos * radius, center + sin * radius); mArrowPath.lineTo(center + (float)Math.cos(arrowLeft) * radius, center + (float)Math.sin(arrowLeft) * radius); canvas.drawPath(mArrowPath, mArrowPaint); drawCompassArrow(canvas, center, mCompassPaint, tipX, tipY, baseX, baseY, Color.RED); drawCompassArrow(canvas, center, mCompassPaint, -tipX, -tipY, baseX, baseY, Color.GRAY); gridPaint.setAlpha(255); canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8, center + (sin * blipRadius) - 8, gridPaint); } } private void drawCompassArrow(Canvas canvas, int center, final Paint gridPaint, float tipX, float tipY, float baseX, float baseY, int color) { gridPaint.setStyle(Paint.Style.FILL_AND_STROKE); gridPaint.setColor(color); gridPaint.setAlpha(255); mCompassPath.reset(); mCompassPath.moveTo(center + baseX, center + baseY); mCompassPath.lineTo(center + tipX, center + tipY); mCompassPath.lineTo(center - baseX, center - baseY); mCompassPath.close(); canvas.drawPath(mCompassPath, gridPaint); gridPaint.setStyle(Paint.Style.STROKE); } public void setLocation(GeoFix location, float azimuth) { // Log.d("GeoBeagle", "radarview::onLocationChanged"); mHaveLocation = true; mMyLocation = location; mOrientation = azimuth; double lat = location.getLatitude(); double lon = location.getLongitude(); mDistance = GeoUtils.distanceKm(lat, lon, mTargetLat, mTargetLon); mBearing = GeoUtils.bearing(lat, lon, mTargetLat, mTargetLon); updateDistance(mDistance); double bearingToTarget = mBearing - mOrientation; updateBearing(bearingToTarget); postInvalidate(); } /** * Called when we no longer have a valid location. */ public void handleUnknownLocation() { mHaveLocation = false; mDistanceView.setText(""); mAccuracyView.setText(""); mLagView.setText(""); mBearingView.setText(""); } /** * Update state to reflect whether we are using metric or standard units. * * @param useMetric True if the display should use metric units */ public void setUseImperial(boolean useImperial) { mUseMetric = !useImperial; if (mHaveLocation) { updateDistance(mDistance); } invalidate(); } private void updateBearing(double bearing) { bearing = (bearing + 720) % 360; if (mHaveLocation) { final String sBearing = ((int)bearing / 5) * 5 + mDegreesSymbol; mBearingView.setText(sBearing); } } /** * Update our state to reflect a new distance to the target. This may * require choosing a new scale for the radar rings. * * @param distanceKm The new distance to the target * @param bearing */ private void updateDistance(double distanceKm) { final double[] scaleChoices; final float[] displayUnitsPerKm; final String[] displayFormats; String distanceStr = null; if (mUseMetric) { scaleChoices = mMetricScaleChoices; displayUnitsPerKm = mMetricDisplayUnitsPerKm; displayFormats = mMetricDisplayFormats; } else { scaleChoices = mEnglishScaleChoices; displayUnitsPerKm = mEnglishDisplayUnitsPerKm; displayFormats = mEnglishDisplayFormats; } final int count = scaleChoices.length; for (int i = 0; i < count; i++) { if (distanceKm < scaleChoices[i] || i == (count - 1)) { String format = displayFormats[i]; double distanceDisplay = distanceKm * displayUnitsPerKm[i]; mDistanceRatio = (float)(mDistance / scaleChoices[i]); distanceStr = String.format(format, distanceDisplay); break; } } mDistanceView.setText(distanceStr); String accuracyStr = formatDistance(mMyLocation.getAccuracy(), scaleChoices, displayUnitsPerKm, displayFormats); mAccuracyView.setText(accuracyStr); mLagView.setText(mMyLocation.getLagString(System.currentTimeMillis())); } private static String formatDistance(float accuracy, final double[] scaleChoices, final float[] displayUnitsPerKm, final String[] displayFormats) { if (accuracy == 0.0) return ""; int count = scaleChoices.length; for (int i = 0; i < count; i++) { final float myLocationAccuracyKm = accuracy / 1000; if (myLocationAccuracyKm < scaleChoices[i] || i == (count - 1)) { final String format = displayFormats[i]; return "+/-" + String.format(format, myLocationAccuracyKm * displayUnitsPerKm[i]); } } return ""; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import android.net.Uri; public class UriParser { public Uri parse(String uriString) { return Uri.parse(uriString); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.activity.main.GeoBeagle; import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButton; import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButtons; import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckDetailsButton; import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckWebPageButton; import com.google.code.geobeagle.cachedetails.CacheDetailsLoader; import com.google.code.geobeagle.cachedetails.CacheDetailsLoader.DetailsOpener; import android.app.AlertDialog.Builder; import android.view.LayoutInflater; import android.view.View; public class Misc { public static CacheDetailsOnClickListener createCacheDetailsOnClickListener( GeoBeagle geoBeagle, Builder alertDialogBuilder, LayoutInflater layoutInflater) { final DetailsOpener detailsOpener = new DetailsOpener(geoBeagle); final CacheDetailsLoader cacheDetailsLoader = new CacheDetailsLoader(detailsOpener); return new CacheDetailsOnClickListener(geoBeagle, alertDialogBuilder, layoutInflater, cacheDetailsLoader); } public static WebPageAndDetailsButtonEnabler create(GeoBeagle geoBeagle, View webPageButton, View detailsButton) { final CheckWebPageButton checkWebPageButton = new CheckWebPageButton(webPageButton); final CheckDetailsButton checkDetailsButton = new CheckDetailsButton(detailsButton); final CheckButtons checkButtons = new CheckButtons(new CheckButton[] { checkWebPageButton, checkDetailsButton }); return new WebPageAndDetailsButtonEnabler(geoBeagle, checkButtons); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import java.text.DateFormat; import java.util.Date; public class DateFormatter { private static DateFormat mDateFormat; public DateFormatter(DateFormat dateFormat) { mDateFormat = dateFormat; } public String format(Date date) { return mDateFormat.format(date); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.ErrorDisplayerDi; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GraphicsGenerator; import com.google.code.geobeagle.LocationControlDi; import com.google.code.geobeagle.R; import com.google.code.geobeagle.R.id; import com.google.code.geobeagle.actions.MenuActionSettings; import com.google.code.geobeagle.actions.CacheActionEdit; import com.google.code.geobeagle.actions.CacheActionMap; import com.google.code.geobeagle.actions.CacheActionRadar; import com.google.code.geobeagle.actions.CacheActionViewUri; import com.google.code.geobeagle.actions.MenuAction; import com.google.code.geobeagle.actions.MenuActionCacheList; import com.google.code.geobeagle.actions.CacheActionGoogleMaps; import com.google.code.geobeagle.actions.MenuActionFromCacheAction; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.ActivityDI; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.main.fieldnotes.CacheLogger; import com.google.code.geobeagle.activity.main.DateFormatter; import com.google.code.geobeagle.activity.main.fieldnotes.DialogHelperCommon; import com.google.code.geobeagle.activity.main.fieldnotes.DialogHelperFile; import com.google.code.geobeagle.activity.main.fieldnotes.DialogHelperSms; import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteLogger; import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteStringsFVsDnf; import com.google.code.geobeagle.activity.main.fieldnotes.FileLogger; import com.google.code.geobeagle.activity.main.fieldnotes.SmsLogger; import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteLogger.OnClickCancel; import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteLogger.OnClickOk;import com.google.code.geobeagle.activity.main.GeoBeagleDelegate.LogFindClickListener; import com.google.code.geobeagle.activity.main.GeoBeagleDelegate.OptionsMenu; import com.google.code.geobeagle.activity.main.intents.GeocacheToCachePage; import com.google.code.geobeagle.activity.main.intents.GeocacheToGoogleMap; import com.google.code.geobeagle.activity.main.intents.IntentFactory; import com.google.code.geobeagle.activity.main.view.CacheButtonOnClickListener; import com.google.code.geobeagle.activity.main.view.CacheDetailsOnClickListener; import com.google.code.geobeagle.activity.main.view.FavoriteView; import com.google.code.geobeagle.activity.main.view.GeocacheViewer; import com.google.code.geobeagle.activity.main.view.Misc; import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler; import com.google.code.geobeagle.activity.main.view.GeocacheViewer.AttributeViewer; import com.google.code.geobeagle.activity.main.view.GeocacheViewer.UnlabelledAttributeViewer; import com.google.code.geobeagle.activity.main.view.GeocacheViewer.LabelledAttributeViewer; import com.google.code.geobeagle.activity.main.view.GeocacheViewer.NameViewer; import com.google.code.geobeagle.activity.main.view.GeocacheViewer.ResourceImages; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.Toaster; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; //TODO: Rename to CompassActivity /* * Main Activity for GeoBeagle. */ public class GeoBeagle extends Activity { private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm'Z'"); private GeoBeagleDelegate mGeoBeagleDelegate; private DbFrontend mDbFrontend; private FieldnoteLogger mFieldNoteSender; private OptionsMenu mOptionsMenu; private static final DateFormat mLocalDateFormat = DateFormat .getTimeInstance(DateFormat.MEDIUM); private GeocacheFactory mGeocacheFactory; public Geocache getGeocache() { return mGeoBeagleDelegate.getGeocache(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d("GeoBeagle", "GeoBeagle.onActivityResult"); mGeocacheFactory.flushCache(); if (requestCode == GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE) { Log.d("GeoBeagle", "camera intent has returned."); } else if (resultCode == 0) setIntent(data); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "GeoBeagle onCreate"); setContentView(R.layout.main); final ErrorDisplayer errorDisplayer = ErrorDisplayerDi.createErrorDisplayer(this); final WebPageAndDetailsButtonEnabler webPageButtonEnabler = Misc.create(this, findViewById(R.id.cache_page), findViewById(R.id.cache_details)); final GeoFixProvider geoFixProvider = LocationControlDi.create(this); mGeocacheFactory = new GeocacheFactory(); final TextView gcid = (TextView)findViewById(R.id.gcid); final GraphicsGenerator graphicsGenerator = new GraphicsGenerator( new GraphicsGenerator.RatingsGenerator(), null); final Resources resources = this.getResources(); final Drawable[] pawDrawables = { resources.getDrawable(R.drawable.paw_unselected_dark), resources.getDrawable(R.drawable.paw_half_light), resources.getDrawable(R.drawable.paw_selected_light) }; final Drawable[] pawImages = graphicsGenerator.getRatings(pawDrawables, 10); final Drawable[] ribbonDrawables = { resources.getDrawable(R.drawable.ribbon_unselected_dark), resources.getDrawable(R.drawable.ribbon_half_bright), resources.getDrawable(R.drawable.ribbon_selected_bright) }; final Drawable[] ribbonImages = graphicsGenerator.getRatings(ribbonDrawables, 10); final ImageView difficultyImageView = (ImageView)findViewById(R.id.gc_difficulty); final TextView terrainTextView = (TextView)findViewById(R.id.gc_text_terrain); final ImageView terrainImageView = (ImageView)findViewById(R.id.gc_terrain); final TextView difficultyTextView = (TextView)findViewById(R.id.gc_text_difficulty); final ImageView containerImageView = (ImageView)findViewById(R.id.gccontainer); final UnlabelledAttributeViewer ribbonImagesOnDifficulty = new UnlabelledAttributeViewer( difficultyImageView, ribbonImages); final AttributeViewer gcDifficulty = new LabelledAttributeViewer( difficultyTextView, ribbonImagesOnDifficulty); final UnlabelledAttributeViewer pawImagesOnTerrain = new UnlabelledAttributeViewer( terrainImageView, pawImages); final AttributeViewer gcTerrain = new LabelledAttributeViewer(terrainTextView, pawImagesOnTerrain); final ResourceImages containerImagesOnContainer = new ResourceImages( containerImageView, GeocacheViewer.CONTAINER_IMAGES); final NameViewer gcName = new NameViewer( ((TextView)findViewById(R.id.gcname))); RadarView radar = (RadarView)findViewById(R.id.radarview); radar.setUseImperial(false); radar.setDistanceView((TextView)findViewById(R.id.radar_distance), (TextView)findViewById(R.id.radar_bearing), (TextView)findViewById(R.id.radar_accuracy), (TextView)findViewById(R.id.radar_lag)); FavoriteView favorite = (FavoriteView) findViewById(R.id.gcfavorite); final GeocacheViewer geocacheViewer = new GeocacheViewer(radar, gcid, gcName, (ImageView)findViewById(R.id.gcicon), gcDifficulty, gcTerrain, containerImagesOnContainer/*, favorite*/); //geoFixProvider.onLocationChanged(null); GeoBeagleDelegate.RadarViewRefresher radarViewRefresher = new GeoBeagleDelegate.RadarViewRefresher(radar, geoFixProvider); geoFixProvider.addObserver(radarViewRefresher); final IntentFactory intentFactory = new IntentFactory(new UriParser()); final CacheActionViewUri intentStarterViewUri = new CacheActionViewUri(this, intentFactory, new GeocacheToGoogleMap(this), resources); final LayoutInflater layoutInflater = LayoutInflater.from(this); final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this); mDbFrontend = new DbFrontend(this, mGeocacheFactory); final GeocacheFromIntentFactory geocacheFromIntentFactory = new GeocacheFromIntentFactory( mGeocacheFactory, mDbFrontend); final IncomingIntentHandler incomingIntentHandler = new IncomingIntentHandler( mGeocacheFactory, geocacheFromIntentFactory, mDbFrontend); Geocache geocache = incomingIntentHandler.maybeGetGeocacheFromIntent(getIntent(), null, mDbFrontend); final SharedPreferences defaultSharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); mGeoBeagleDelegate = new GeoBeagleDelegate(activitySaver, this, mGeocacheFactory, geocacheViewer, incomingIntentHandler, mDbFrontend, radar, defaultSharedPreferences, webPageButtonEnabler, geoFixProvider, favorite); final MenuAction[] menuActionArray = { new MenuActionCacheList(this, resources), new MenuActionFromCacheAction(new CacheActionEdit(this, resources), geocache), // new MenuActionLogDnf(this), new MenuActionLogFind(this), //new MenuActionSearchOnline(this), new MenuActionSettings(this, resources), new MenuActionFromCacheAction(new CacheActionGoogleMaps(intentStarterViewUri, resources), geocache), //new MenuActionFromCacheAction(new CacheActionProximity(this, resources), geocache), }; final MenuActions menuActions = new MenuActions(menuActionArray); mOptionsMenu = new GeoBeagleDelegate.OptionsMenu(menuActions); // see http://www.androidguys.com/2008/11/07/rotational-forces-part-two/ if (getLastNonConfigurationInstance() != null) { setIntent((Intent)getLastNonConfigurationInstance()); } final CacheActionMap cacheActionMap = new CacheActionMap(this, resources); final CacheButtonOnClickListener mapsButtonOnClickListener = new CacheButtonOnClickListener(cacheActionMap, this, "Map error", errorDisplayer); findViewById(id.maps).setOnClickListener(mapsButtonOnClickListener); final AlertDialog.Builder cacheDetailsBuilder = new AlertDialog.Builder(this); final CacheDetailsOnClickListener cacheDetailsOnClickListener = Misc .createCacheDetailsOnClickListener(this, cacheDetailsBuilder, layoutInflater); findViewById(R.id.cache_details).setOnClickListener(cacheDetailsOnClickListener); final GeocacheToCachePage geocacheToCachePage = new GeocacheToCachePage(getResources()); final CacheActionViewUri cachePageIntentStarter = new CacheActionViewUri(this, intentFactory, geocacheToCachePage, resources); final CacheButtonOnClickListener cacheButtonOnClickListener = new CacheButtonOnClickListener(cachePageIntentStarter, this, "", errorDisplayer); findViewById(id.cache_page).setOnClickListener(cacheButtonOnClickListener); findViewById(id.radarview).setOnClickListener(new CacheButtonOnClickListener( new CacheActionRadar(this, resources), this, "Please install the Radar application to use Radar.", errorDisplayer)); findViewById(id.menu_log_find).setOnClickListener( new LogFindClickListener(this, id.menu_log_find)); findViewById(id.menu_log_dnf).setOnClickListener( new LogFindClickListener(this, id.menu_log_dnf)); } @Override protected Dialog onCreateDialog(int id) { super.onCreateDialog(id); final FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf = new FieldnoteStringsFVsDnf( getResources()); final Toaster toaster = new Toaster(this, R.string.error_writing_cache_log, Toast.LENGTH_LONG); final DateFormatter dateFormatter = new DateFormatter(simpleDateFormat); final FileLogger fileLogger = new FileLogger(fieldnoteStringsFVsDnf, dateFormatter, toaster); final SmsLogger smsLogger = new SmsLogger(fieldnoteStringsFVsDnf, this); final SharedPreferences defaultSharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); final CacheLogger cacheLogger = new CacheLogger(defaultSharedPreferences, fileLogger, smsLogger); final OnClickCancel onClickCancel = new OnClickCancel(); final LayoutInflater layoutInflater = LayoutInflater.from(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this); final View fieldNoteDialogView = layoutInflater.inflate(R.layout.fieldnote, null); final TextView fieldnoteCaveat = (TextView)fieldNoteDialogView .findViewById(R.id.fieldnote_caveat); final CharSequence geocacheId = mGeoBeagleDelegate.getGeocache().getId(); final boolean fDnf = id == R.id.menu_log_dnf; final EditText editText = (EditText)fieldNoteDialogView.findViewById(R.id.fieldnote); final DialogHelperCommon dialogHelperCommon = new DialogHelperCommon( fieldnoteStringsFVsDnf, editText, fDnf, fieldnoteCaveat); final DialogHelperFile dialogHelperFile = new DialogHelperFile(fieldnoteCaveat, this); final DialogHelperSms dialogHelperSms = new DialogHelperSms(geocacheId.length(), fieldnoteStringsFVsDnf, editText, fDnf, fieldnoteCaveat); mFieldNoteSender = new FieldnoteLogger(dialogHelperCommon, dialogHelperFile, dialogHelperSms); final OnClickOk onClickOk = new OnClickOk(geocacheId, editText, cacheLogger, mDbFrontend, fDnf); builder.setTitle(R.string.field_note_title); builder.setView(fieldNoteDialogView); builder.setNegativeButton(R.string.cancel, onClickCancel); builder.setPositiveButton(R.string.log_cache, onClickOk); return builder.create(); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onCreateDialog(id); final SharedPreferences defaultSharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); mFieldNoteSender.onPrepareDialog(dialog, defaultSharedPreferences, mLocalDateFormat .format(new Date())); } @Override public boolean onCreateOptionsMenu(Menu menu) { return mOptionsMenu.onCreateOptionsMenu(menu); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mGeoBeagleDelegate.onKeyDown(keyCode, event)) return true; return super.onKeyDown(keyCode, event); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mOptionsMenu.onOptionsItemSelected(item); } @Override public void onPause() { super.onPause(); Log.d("GeoBeagle", "GeoBeagle onPause"); mGeoBeagleDelegate.onPause(); } /* * (non-Javadoc) * @see android.app.Activity#onRestoreInstanceState(android.os.Bundle) */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mGeoBeagleDelegate.onRestoreInstanceState(savedInstanceState); } @Override protected void onResume() { super.onResume(); Log.d("GeoBeagle", "GeoBeagle onResume"); mGeoBeagleDelegate.onResume(); } /* * (non-Javadoc) * @see android.app.Activity#onRetainNonConfigurationInstance() */ @Override public Object onRetainNonConfigurationInstance() { return getIntent(); } /* * (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mGeoBeagleDelegate.onSaveInstanceState(outState); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GraphicsGenerator; import com.google.code.geobeagle.IPausable; import com.google.code.geobeagle.LocationControlDi; import com.google.code.geobeagle.R; import com.google.code.geobeagle.GraphicsGenerator.AttributePainter; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.actions.CacheAction; import com.google.code.geobeagle.actions.CacheActionAssignTags; import com.google.code.geobeagle.actions.CacheActionConfirm; import com.google.code.geobeagle.actions.CacheActionDelete; import com.google.code.geobeagle.actions.CacheActionEdit; import com.google.code.geobeagle.actions.CacheActionToggleFavorite; import com.google.code.geobeagle.actions.CacheActionView; import com.google.code.geobeagle.actions.CacheContextMenu; import com.google.code.geobeagle.actions.CacheFilterUpdater; import com.google.code.geobeagle.actions.MenuActionClearTagNew; import com.google.code.geobeagle.actions.MenuActionConfirm; import com.google.code.geobeagle.actions.MenuActionDeleteAll; import com.google.code.geobeagle.actions.MenuActionEditFilter; import com.google.code.geobeagle.actions.MenuActionFilterListPopup; import com.google.code.geobeagle.actions.MenuActionMap; import com.google.code.geobeagle.actions.MenuActionSearchOnline; import com.google.code.geobeagle.actions.MenuActionSettings; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.ActivityDI; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.cachelist.CacheListDelegate.ImportIntentManager; import com.google.code.geobeagle.activity.cachelist.actions.Abortable; import com.google.code.geobeagle.activity.cachelist.actions.MenuActionMyLocation; import com.google.code.geobeagle.activity.cachelist.actions.MenuActionSyncGpx; import com.google.code.geobeagle.activity.cachelist.actions.MenuActionToggleFilter; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListPositionUpdater; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi; import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater; import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater; import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater.RowViews.CacheNameAttributes; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater.TextSelector; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import com.google.code.geobeagle.database.CachesProviderCenterThread; import com.google.code.geobeagle.database.CachesProviderCount; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.CachesProviderSorted; import com.google.code.geobeagle.database.CachesProviderToggler; import com.google.code.geobeagle.database.CachesProviderWaitForInit; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.ICachesProviderCenter; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate; import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusView; import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class CacheListDelegateDI { //TODO: Remove class Timing and replace uses by Clock public static class Timing { private long mStartTime; public void lap(CharSequence msg) { long finishTime = Calendar.getInstance().getTimeInMillis(); Log.d("GeoBeagle", "****** " + msg + ": " + (finishTime - mStartTime)); mStartTime = finishTime; } public void start() { mStartTime = Calendar.getInstance().getTimeInMillis(); } public long getTime() { return Calendar.getInstance().getTimeInMillis(); } } public static CacheListDelegate create(ListActivity listActivity, LayoutInflater layoutInflater) { final OnClickListener onClickListener = new OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }; final ErrorDisplayer errorDisplayer = new ErrorDisplayer(listActivity, onClickListener); final GeoFixProvider geoFixProvider = LocationControlDi.create(listActivity); final GeocacheFactory geocacheFactory = new GeocacheFactory(); final BearingFormatter relativeBearingFormatter = new RelativeBearingFormatter(); final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi .create(listActivity); final XmlPullParserWrapper xmlPullParserWrapper = new XmlPullParserWrapper(); final DbFrontend dbFrontend = new DbFrontend(listActivity, geocacheFactory); final GraphicsGenerator graphicsGenerator = new GraphicsGenerator( new GraphicsGenerator.RatingsGenerator(), new IconRenderer(new AttributePainter(new Paint(), new Rect()))); final CacheNameAttributes cacheNameAttributes = new CacheNameAttributes(); final GeocacheSummaryRowInflater geocacheSummaryRowInflater = new GeocacheSummaryRowInflater( distanceFormatterManager.getFormatter(), layoutInflater, relativeBearingFormatter, listActivity.getResources(), graphicsGenerator, dbFrontend, cacheNameAttributes); final InflatedGpsStatusView inflatedGpsStatusWidget = new InflatedGpsStatusView( listActivity); final LinearLayout gpsStatusWidget = new LinearLayout(listActivity); gpsStatusWidget.addView(inflatedGpsStatusWidget, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(listActivity, gpsStatusWidget, geoFixProvider, distanceFormatterManager.getFormatter()); final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater .getGpsStatusWidgetDelegate(); inflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate); final UpdateGpsWidgetRunnable updateGpsWidgetRunnable = gpsWidgetAndUpdater .getUpdateGpsWidgetRunnable(); updateGpsWidgetRunnable.run(); final FilterTypeCollection filterTypeCollection = new FilterTypeCollection(listActivity); final CachesProviderDb cachesProviderDb = new CachesProviderDb(dbFrontend); final ICachesProviderCenter cachesProviderCount = new CachesProviderWaitForInit(new CachesProviderCount(cachesProviderDb, 15, 30)); final CachesProviderSorted cachesProviderSorted = new CachesProviderSorted(cachesProviderCount); //final CachesProviderLazy cachesProviderLazy = new CachesProviderLazy(cachesProviderSorted, 0.01, 2000, clock); ICachesProviderCenter cachesProviderLazy = cachesProviderSorted; final CachesProviderDb cachesProviderAll = new CachesProviderDb(dbFrontend); final CachesProviderToggler cachesProviderToggler = new CachesProviderToggler(cachesProviderLazy, cachesProviderAll); CachesProviderCenterThread thread = new CachesProviderCenterThread(cachesProviderToggler); final TextSelector textSelector = new TextSelector(); final TitleUpdater titleUpdater = new TitleUpdater(listActivity, cachesProviderToggler, dbFrontend, textSelector); distanceFormatterManager.addHasDistanceFormatter(geocacheSummaryRowInflater); distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate); final CacheListAdapter cacheListAdapter = new CacheListAdapter(cachesProviderToggler, cachesProviderSorted, geocacheSummaryRowInflater, titleUpdater, null); final CacheListPositionUpdater cacheListPositionUpdater = new CacheListPositionUpdater( geoFixProvider, cacheListAdapter, cachesProviderCount, thread /*cachesProviderSorted*/); geoFixProvider.addObserver(cacheListPositionUpdater); geoFixProvider.addObserver(gpsStatusWidgetDelegate); final CacheListAdapter.ScrollListener scrollListener = new CacheListAdapter.ScrollListener( cacheListAdapter); final CacheTypeFactory cacheTypeFactory = new CacheTypeFactory(); final Aborter aborter = new Aborter(); final MessageHandler messageHandler = MessageHandler.create(listActivity); final GpxImporterFactory gpxImporterFactory = new GpxImporterFactory(aborter, errorDisplayer, geoFixProvider, listActivity, messageHandler, xmlPullParserWrapper, cacheTypeFactory, geocacheFactory); final Abortable nullAbortable = new Abortable() { public void abort() { } }; // *** BUILD MENU *** final Resources resources = listActivity.getResources(); final MenuActionSyncGpx menuActionSyncGpx = new MenuActionSyncGpx(nullAbortable, cacheListAdapter, gpxImporterFactory, dbFrontend, resources); final CacheActionEdit cacheActionEdit = new CacheActionEdit(listActivity, resources); final MenuActions menuActions = new MenuActions(); final AlertDialog.Builder builder1 = new AlertDialog.Builder(listActivity); final MenuActionDeleteAll deleteAll = new MenuActionDeleteAll(dbFrontend, resources, cachesProviderAll, cacheListAdapter, titleUpdater, R.string.delete_all_caches); menuActions.add(new MenuActionToggleFilter(cachesProviderToggler, cacheListAdapter, resources)); menuActions.add(new MenuActionSearchOnline(listActivity, resources)); List<CachesProviderDb> providers = new ArrayList<CachesProviderDb>(); providers.add(cachesProviderDb); providers.add(cachesProviderAll); final CacheFilterUpdater cacheFilterUpdater = new CacheFilterUpdater(filterTypeCollection, providers); menuActions.add(new MenuActionMap(listActivity, geoFixProvider, resources)); //menuActions.add(new MenuActionFilterList(listActivity)); menuActions.add(new MenuActionEditFilter(listActivity, cacheFilterUpdater, cacheListAdapter, filterTypeCollection, resources)); menuActions.add(new MenuActionFilterListPopup(listActivity, cacheFilterUpdater, cacheListAdapter, filterTypeCollection, resources)); menuActions.add(new MenuActionClearTagNew(dbFrontend, geocacheFactory, cacheListAdapter)); menuActions.add(new MenuActionMyLocation(errorDisplayer, geocacheFactory, geoFixProvider, dbFrontend, resources, cacheActionEdit)); menuActions.add(menuActionSyncGpx); menuActions.add(new MenuActionConfirm(listActivity, builder1, deleteAll, resources.getString(R.string.delete_all_caches), resources.getString(R.string.confirm_delete_all_caches))); menuActions.add(new MenuActionSettings(listActivity, resources)); // *** BUILD CONTEXT MENU *** final CacheActionView cacheActionView = new CacheActionView(listActivity, resources); final CacheActionToggleFavorite cacheActionToggleFavorite = new CacheActionToggleFavorite(dbFrontend, cacheListAdapter, cacheFilterUpdater); //TODO: It is currently a bug to send cachesProviderDb since cachesProviderAll also need to be notified of db changes. final CacheActionDelete cacheActionDelete = new CacheActionDelete(cacheListAdapter, titleUpdater, dbFrontend, cachesProviderDb, resources); final AlertDialog.Builder builder = new AlertDialog.Builder(listActivity); CacheActionAssignTags cacheActionAssignTags = new CacheActionAssignTags(listActivity, dbFrontend, cacheListAdapter); final CacheActionConfirm cacheActionConfirmDelete = new CacheActionConfirm(listActivity, builder, cacheActionDelete, listActivity.getString(R.string.confirm_delete_title), listActivity.getString(R.string.confirm_delete_body_text)); final CacheAction[] contextActions = new CacheAction[] { cacheActionView, cacheActionToggleFavorite, cacheActionEdit, cacheActionAssignTags, cacheActionConfirmDelete }; final ActivitySaver activitySaver = ActivityDI.createActivitySaver(listActivity); final ImportIntentManager importIntentManager = new ImportIntentManager(listActivity); final CacheContextMenu contextMenu = new CacheContextMenu(cachesProviderToggler, contextActions); final IPausable pausables[] = { geoFixProvider, thread }; final GeocacheListController geocacheListController = new GeocacheListController(cacheListAdapter, menuActionSyncGpx, menuActions, cacheActionView, cacheFilterUpdater); //TODO: It is currently a bug to send cachesProviderDb since cachesProviderAll also need to be notified of db changes. final CacheListDelegate cacheListDelegate = new CacheListDelegate(importIntentManager, activitySaver, geocacheListController, dbFrontend, contextMenu, cacheListAdapter, geocacheSummaryRowInflater, listActivity, distanceFormatterManager, cachesProviderDb, pausables); listActivity.setContentView(R.layout.cache_list); final ListView listView = listActivity.getListView(); listView.addHeaderView(gpsStatusWidget); listActivity.setListAdapter(cacheListAdapter); listView.setOnCreateContextMenuListener(contextMenu); listView.setOnScrollListener(scrollListener); updateGpsWidgetRunnable.run(); return cacheListDelegate; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; public class CacheListActivity extends ListActivity { private CacheListDelegate mCacheListDelegate; // For testing. public CacheListDelegate getCacheListDelegate() { return mCacheListDelegate; } // This is the ctor that Android will use. public CacheListActivity() { } // This is the ctor for testing. public CacheListActivity(CacheListDelegate cacheListDelegate) { mCacheListDelegate = cacheListDelegate; } @Override public boolean onContextItemSelected(MenuItem item) { return mCacheListDelegate.onContextItemSelected(item) || super.onContextItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Log.d("GeoBeagle", "CacheListActivity onCreate"); mCacheListDelegate = CacheListDelegateDI.create(this, getLayoutInflater()); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return mCacheListDelegate.onCreateOptionsMenu(menu); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); mCacheListDelegate.onListItemClick(l, v, position, id); } /* * (non-Javadoc) * @see android.app.Activity#onMenuOpened(int, android.view.Menu) */ @Override public boolean onMenuOpened(int featureId, Menu menu) { super.onMenuOpened(featureId, menu); return mCacheListDelegate.onMenuOpened(featureId, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mCacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override protected void onPause() { //Log.d("GeoBeagle", "CacheListActivity onPause"); super.onPause(); mCacheListDelegate.onPause(); } @Override protected void onResume() { super.onResume(); //Log.d("GeoBeagle", "CacheListActivity onResume"); mCacheListDelegate.onResume(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mCacheListDelegate.onActivityResult(); } }
Java
package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.formatting.DistanceFormatterImperial; import com.google.code.geobeagle.formatting.DistanceFormatterMetric; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class DistanceFormatterManagerDi { public static DistanceFormatterManager create(Context context) { final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); final DistanceFormatterMetric distanceFormatterMetric = new DistanceFormatterMetric(); final DistanceFormatterImperial distanceFormatterImperial = new DistanceFormatterImperial(); return new DistanceFormatterManager(sharedPreferences, distanceFormatterImperial, distanceFormatterMetric); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.database.CacheWriter; import com.google.code.geobeagle.xmlimport.GpxImporter; import com.google.code.geobeagle.xmlimport.GpxImporterDI; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import android.app.ListActivity; public class GpxImporterFactory { private final Aborter mAborter; private final ErrorDisplayer mErrorDisplayer; private final GeoFixProvider mGeoFixProvider; private final ListActivity mListActivity; private final MessageHandler mMessageHandler; private final XmlPullParserWrapper mXmlPullParserWrapper; private final CacheTypeFactory mCacheTypeFactory; private final GeocacheFactory mGeocacheFactory; public GpxImporterFactory(Aborter aborter, ErrorDisplayer errorDisplayer, GeoFixProvider geoFixProvider, ListActivity listActivity, MessageHandler messageHandler, XmlPullParserWrapper xmlPullParserWrapper, CacheTypeFactory cacheTypeFactory, GeocacheFactory geocacheFactory) { mAborter = aborter; mErrorDisplayer = errorDisplayer; mGeoFixProvider = geoFixProvider; mListActivity = listActivity; mMessageHandler = messageHandler; mXmlPullParserWrapper = xmlPullParserWrapper; mCacheTypeFactory = cacheTypeFactory; mGeocacheFactory = geocacheFactory; } public GpxImporter create(CacheWriter cacheWriter) { return GpxImporterDI.create(mListActivity, mXmlPullParserWrapper, mErrorDisplayer, mGeoFixProvider, mAborter, mMessageHandler, cacheWriter, mCacheTypeFactory, mGeocacheFactory); } }
Java
package com.google.code.geobeagle.activity.prox; import android.graphics.Canvas; import android.os.SystemClock; import android.util.Log; import android.view.SurfaceHolder; public class AnimatorThread { public interface IThreadStoppedListener { void OnThreadStopped(); } ////////////////////////////////////////////////////////////// // PRIVATE MEMBERS /** Handle to the surface manager object we interact with */ private SurfaceHolder mSurfaceHolder; /** If the thread should be running */ private boolean mShouldRun = false; private boolean mIsRunning = false; private Thread mThread; private ProximityPainter mWorld; /** Time in milliseconds of the start of this cycle */ private long mCurrentTimeMillis = 0; /** Time in seconds between the last and this cycle */ private double mCurrentTickDelta = 0; /** If non-zero, AdvanceTime will not be called until this time (msec) */ private long mResumeAtTime = 0; void updateTime() { long now = System.currentTimeMillis(); assert (now >= mCurrentTimeMillis); mCurrentTickDelta = (now - mCurrentTimeMillis) / 1000.0; mCurrentTimeMillis = now; if (mCurrentTickDelta > 0.3) { Log.w("GeoBeagle", "Elapsed time " + mCurrentTickDelta + " capped at 0.3 sec"); mCurrentTickDelta = 0.3; } } private class RealThread extends Thread { public void run() { mIsRunning = true; while (mShouldRun) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); if (c == null) { Log.w(this.getClass().getName(), "run(): lockCanvas returned null"); continue; } synchronized (mSurfaceHolder) { updateTime(); if (mCurrentTimeMillis >= mResumeAtTime) { mWorld.advanceTime(mCurrentTickDelta); } mWorld.draw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } mIsRunning = false; } } private double mSecsPerTick = 0; private int mNextTickNo = 0; private class TimingThread extends Thread { private int mRemainingRuns; public TimingThread(int remainingRuns) { mRemainingRuns = remainingRuns; } public void run() { mIsRunning = true; int totalTicksCount = mRemainingRuns; long mStartTimeMillis = SystemClock.uptimeMillis(); while (mShouldRun && mRemainingRuns > 0) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); if (c == null) { Log.w("GeoBeagle", "run(): lockCanvas returned null"); continue; } synchronized (mSurfaceHolder) { mWorld.advanceTime(mSecsPerTick); mWorld.draw(c); mRemainingRuns -= 1; } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } mIsRunning = false; long duration = SystemClock.uptimeMillis() - mStartTimeMillis; int ticksDone = totalTicksCount - mRemainingRuns; if (ticksDone == 1) { Log.d("GeoBeagle", "Iterated tick #" + mNextTickNo + " (@" + mSecsPerTick + "s)"); } else if (ticksDone > 0) { Log.d("GeoBeagle", "Iterated " + ticksDone + " ticks (@" + mSecsPerTick + "s) in " + duration + "ms => " + (ticksDone*1000/duration) + "fps"); } mNextTickNo += ticksDone; } } ////////////////////////////////////////////////////////////// // PUBLIC MEMBERS public AnimatorThread(SurfaceHolder surfaceHolder, ProximityPainter painter) { mSurfaceHolder = surfaceHolder; mWorld = painter; } public void start() { if (mShouldRun) return; Log.d("GeoBeagle", "AnimatorThread.start()"); mCurrentTimeMillis = System.currentTimeMillis() - 1; mResumeAtTime = System.currentTimeMillis() + 200; mShouldRun = true; if (!mIsRunning) { if (mThread == null) mThread = new RealThread(); mThread.start(); } } /** Run the game loop a specific number of times, for testing purposes. */ public void setupTiming(int nrOfTicks, double secondsPerTick) { assert (!mShouldRun && !mIsRunning); assert (nrOfTicks > 0); assert (secondsPerTick > 0); Log.d("GeoBeagle", "setupTiming(" + secondsPerTick + " sec/tick, ticks=" + nrOfTicks + ")"); mResumeAtTime = 0; //mShouldRun = true; mSecsPerTick = secondsPerTick; mThread = new TimingThread(nrOfTicks); //mThread.start(); } /** @param listener is invoked after the thread has stopped or at once if * the thread wasn't running */ public void stop(IThreadStoppedListener listener) { if (!mIsRunning) { if (listener != null) listener.OnThreadStopped(); return; } boolean retry = true; mShouldRun = false; while (retry) { try { mThread.join(); retry = false; mThread = null; listener.OnThreadStopped(); } catch (InterruptedException e) { } } } }
Java
package com.google.code.geobeagle.activity.prox; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceView; public class ProximityView extends SurfaceView { public ProximityView(Context context) { super(context); setFocusable(true); } public ProximityView(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); } public ProximityView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setFocusable(true); } }
Java
package com.google.code.geobeagle.activity.prox; import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.LocationControlDi; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.actions.CacheFilterUpdater; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.CachesProviderCount; import com.google.code.geobeagle.database.DbFrontend; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import java.util.ArrayList; import java.util.List; public class ProximityActivity extends Activity implements SurfaceHolder.Callback { class DataCollector implements Refresher { @Override public void forceRefresh() { refresh(); } @Override public void refresh() { mProximityPainter.setUserDirection(mGeoFixProvider.getAzimuth()); GeoFix location = mGeoFixProvider.getLocation(); mProximityPainter.setUserLocation(location.getLatitude(), location.getLongitude(), location.getAccuracy()); } } private ProximityView mProximityView; ProximityPainter mProximityPainter; DataCollector mDataCollector; private AnimatorThread mAnimatorThread; private boolean mStartWhenSurfaceCreated = false; //TODO: Is mStartWhenSurfaceCreated needed? private DbFrontend mDbFrontend; private GeoFixProvider mGeoFixProvider; private CacheFilterUpdater mCacheFilterUpdater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeocacheFactory geocacheFactory = new GeocacheFactory(); mDbFrontend = new DbFrontend(this, geocacheFactory); final FilterTypeCollection filterTypeCollection = new FilterTypeCollection(this); CachesProviderDb cachesProviderDb = new CachesProviderDb(mDbFrontend); CachesProviderCount cachesProviderCount = new CachesProviderCount(cachesProviderDb, 5, 10); List<CachesProviderDb> list = new ArrayList<CachesProviderDb>(); list.add(cachesProviderDb); mCacheFilterUpdater = new CacheFilterUpdater(filterTypeCollection, list); mProximityPainter = new ProximityPainter(cachesProviderCount); mProximityView = new ProximityView(this); setContentView(mProximityView); } @Override protected void onStart() { super.onStart(); SurfaceHolder holder = mProximityView.getHolder(); holder.addCallback(this); mDataCollector = new DataCollector(); mGeoFixProvider = LocationControlDi.create(this); mGeoFixProvider.addObserver(mDataCollector); } @Override protected void onResume() { super.onResume(); String id = getIntent().getStringExtra("geocacheId"); if (!id.equals("")) { Geocache geocache = mDbFrontend.loadCacheFromId(id); mProximityPainter.setSelectedGeocache(geocache); } mCacheFilterUpdater.loadActiveFilter(); mGeoFixProvider.onResume(); GeoFix location = mGeoFixProvider.getLocation(); mProximityPainter.setUserLocation(location.getLatitude(), location.getLongitude(), location.getAccuracy()); if (mAnimatorThread == null) mStartWhenSurfaceCreated = true; else mAnimatorThread.start(); } @Override protected void onPause() { super.onPause(); mGeoFixProvider.onPause(); if (mAnimatorThread != null) { AnimatorThread.IThreadStoppedListener listener = new AnimatorThread.IThreadStoppedListener() { @Override public void OnThreadStopped() { mDbFrontend.closeDatabase(); } }; mAnimatorThread.stop(listener); } } // *********************************** // ** Implement SurfaceHolder.Callback ** @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d("GeoBeagle", "surfaceChanged called ("+width+"x"+height+")"); } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d("GeoBeagle", "surfaceCreated called"); mAnimatorThread = new AnimatorThread(holder, mProximityPainter); if (mStartWhenSurfaceCreated) { mStartWhenSurfaceCreated = false; mAnimatorThread.start(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d("GeoBeagle", "surfaceDestroyed called"); } }
Java
package com.google.code.geobeagle.activity.filterlist; import com.google.code.geobeagle.activity.filterlist.FilterListActivityDelegate; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ListView; /** * A list of the pre-made filters which the user can choose between by tapping a list item * */ public class FilterListActivity extends ListActivity { private FilterListActivityDelegate mFiltersActivityDelegate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Log.d("GeoBeagle", "CacheListActivity onCreate"); mFiltersActivityDelegate = new FilterListActivityDelegate(); //CacheListDelegateDI.create(this, getLayoutInflater()); mFiltersActivityDelegate.onCreate(this); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); mFiltersActivityDelegate.onListItemClick(l, v, position, id); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.preferences; import com.google.code.geobeagle.R; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.actions.Abortable; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.xmlimport.GpxImporterDI.ImportThreadWrapper; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.xmlimport.GpxImporterDI.ToastFactory; import android.app.ListActivity; import android.widget.Toast; public class GpxImporter implements Abortable { private final ErrorDisplayer mErrorDisplayer; private final EventHandlers mEventHandlers; private final GpxLoader mGpxLoader; private final ImportThreadWrapper mImportThreadWrapper; private final ListActivity mListActivity; private final MessageHandler mMessageHandler; private final ToastFactory mToastFactory; private final GeocacheFactory mGeocacheFactory; GeoFixProvider mGeoFixProvider; GpxImporter(GeoFixProvider geoFixProvider, GpxLoader gpxLoader, ListActivity listActivity, ImportThreadWrapper importThreadWrapper, MessageHandler messageHandler, ToastFactory toastFactory, EventHandlers eventHandlers, ErrorDisplayer errorDisplayer, GeocacheFactory geocacheFactory) { mListActivity = listActivity; mGpxLoader = gpxLoader; mEventHandlers = eventHandlers; mImportThreadWrapper = importThreadWrapper; mMessageHandler = messageHandler; mErrorDisplayer = errorDisplayer; mToastFactory = toastFactory; mGeoFixProvider = geoFixProvider; mGeocacheFactory = geocacheFactory; } public void abort() { mMessageHandler.abortLoad(); mGpxLoader.abort(); if (mImportThreadWrapper.isAlive()) { mImportThreadWrapper.join(); mToastFactory.showToast(mListActivity, R.string.import_canceled, Toast.LENGTH_SHORT); } //TODO: Resume list updates? } public void importGpxs(CacheListAdapter cacheList) { mGeoFixProvider.onPause(); mImportThreadWrapper.open(cacheList, mGpxLoader, mEventHandlers, mErrorDisplayer, mGeocacheFactory); mImportThreadWrapper.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; class EventHandlerLoc implements EventHandler { static final String XPATH_COORD = "/loc/waypoint/coord"; static final String XPATH_GROUNDSPEAKNAME = "/loc/waypoint/name"; static final String XPATH_LOC = "/loc"; static final String XPATH_WPT = "/loc/waypoint"; static final String XPATH_WPTNAME = "/loc/waypoint/name"; private final CachePersisterFacade mCachePersisterFacade; EventHandlerLoc(CachePersisterFacade cachePersisterFacade) { mCachePersisterFacade = cachePersisterFacade; } public void endTag(String previousFullPath) throws IOException { if (previousFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.endCache(Source.LOC); } } public void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException { if (mFullPath.equals(XPATH_COORD)) { mCachePersisterFacade.wpt(mXmlPullParser.getAttributeValue(null, "lat"), mXmlPullParser .getAttributeValue(null, "lon")); } else if (mFullPath.equals(XPATH_WPTNAME)) { mCachePersisterFacade.startCache(); mCachePersisterFacade.wptName.text(mXmlPullParser.getAttributeValue(null, "id")); } } public boolean text(String mFullPath, String text) throws IOException { if (mFullPath.equals(XPATH_WPTNAME)) mCachePersisterFacade.groundspeakName.text(text.trim()); return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilesAndZipFilesIter; import org.xmlpull.v1.XmlPullParserException; import java.io.FileNotFoundException; import java.io.IOException; public class ImportThreadDelegate { public static class ImportThreadHelper { private final ErrorDisplayer mErrorDisplayer; private final EventHandlers mEventHandlers; private final EventHelperFactory mEventHelperFactory; private final GpxLoader mGpxLoader; private boolean mHasFiles; private final MessageHandler mMessageHandler; private final GeocacheFactory mGeocacheFactory; public ImportThreadHelper(GpxLoader gpxLoader, MessageHandler messageHandler, EventHelperFactory eventHelperFactory, EventHandlers eventHandlers, ErrorDisplayer errorDisplayer, GeocacheFactory geocacheFactory) { mErrorDisplayer = errorDisplayer; mGpxLoader = gpxLoader; mMessageHandler = messageHandler; mEventHelperFactory = eventHelperFactory; mEventHandlers = eventHandlers; mHasFiles = false; mGeocacheFactory = geocacheFactory; } public void cleanup() { mMessageHandler.loadComplete(); } public void end() { mGpxLoader.end(); if (!mHasFiles) mErrorDisplayer.displayError(R.string.error_no_gpx_files); mGeocacheFactory.flushCacheIcons(); } /** @return true if we should continue to load files */ public boolean processFile(IGpxReader gpxReader) throws XmlPullParserException, IOException { String filename = gpxReader.getFilename(); mHasFiles = true; mGpxLoader.open(filename, gpxReader.open()); return mGpxLoader.load(mEventHelperFactory.create(mEventHandlers.get(filename))); } public void start() { mGpxLoader.start(); } } private final ErrorDisplayer mErrorDisplayer; private final GpxAndZipFiles mGpxAndZipFiles; private final ImportThreadHelper mImportThreadHelper; public ImportThreadDelegate(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) { mGpxAndZipFiles = gpxAndZipFiles; mImportThreadHelper = importThreadHelper; mErrorDisplayer = errorDisplayer; } public void run() { try { tryRun(); } catch (final FileNotFoundException e) { mErrorDisplayer.displayError(R.string.error_opening_file, e.getMessage()); } catch (IOException e) { mErrorDisplayer.displayError(R.string.error_reading_file, e.getMessage()); } catch (XmlPullParserException e) { mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage()); } finally { mImportThreadHelper.cleanup(); } } protected void tryRun() throws IOException, XmlPullParserException { GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = mGpxAndZipFiles.iterator(); if (gpxFilesAndZipFilesIter == null) { mErrorDisplayer.displayError(R.string.error_cant_read_sd); return; } mImportThreadHelper.start(); while (gpxFilesAndZipFilesIter.hasNext()) { if (!mImportThreadHelper.processFile(gpxFilesAndZipFilesIter.next())) return; } mImportThreadHelper.end(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; public class GpxToCache { public static class Aborter { private static boolean mAborted = false; public Aborter() { mAborted = false; } public void abort() { mAborted = true; } public boolean isAborted() { return mAborted; } public void reset() { mAborted = false; } } @SuppressWarnings("serial") public static class CancelException extends Exception { } private final Aborter mAborter; private final XmlPullParserWrapper mXmlPullParserWrapper; GpxToCache(XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) { mXmlPullParserWrapper = xmlPullParserWrapper; mAborter = aborter; } public void abort() { mAborter.abort(); } public String getSource() { return mXmlPullParserWrapper.getSource(); } /** * @param eventHelper * @return true if this file has already been loaded. * @throws XmlPullParserException * @throws IOException * @throws CancelException */ public boolean load(EventHelper eventHelper) throws XmlPullParserException, IOException, CancelException { int eventType; for (eventType = mXmlPullParserWrapper.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = mXmlPullParserWrapper .next()) { if (mAborter.isAborted()) throw new CancelException(); // File already loaded. if (!eventHelper.handleEvent(eventType)) return true; } // Pick up END_DOCUMENT event as well. eventHelper.handleEvent(eventType); return false; } public void open(String source, Reader reader) throws XmlPullParserException { mXmlPullParserWrapper.open(source, reader); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; interface EventHandler { void endTag(String previousFullPath) throws IOException; void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException; boolean text(String mFullPath, String text) throws IOException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.database.CacheWriter; import android.util.Log; import java.util.Hashtable; /** * @author sng */ public class CacheTagSqlWriter { private final CacheTypeFactory mCacheTypeFactory; private CacheType mCacheType; private final CacheWriter mCacheWriter; private int mContainer; private int mDifficulty; private String mGpxName; private CharSequence mId; private double mLatitude; private double mLongitude; private CharSequence mName; private String mSqlDate; /** An entry here means that the tag is to be removed or added. * Other tags are left as they are. */ private Hashtable<Integer, Boolean> mTags = new Hashtable<Integer, Boolean>(); private int mTerrain; public CacheTagSqlWriter(CacheWriter cacheWriter, CacheTypeFactory cacheTypeFactory) { mCacheWriter = cacheWriter; mCacheTypeFactory = cacheTypeFactory; } public void cacheName(String name) { mName = name; } public void cacheType(String type) { mCacheType = mCacheTypeFactory.fromTag(type); } public void clear() { // TODO: ensure source is not reset mId = mName = null; mLatitude = mLongitude = 0; mCacheType = CacheType.NULL; mDifficulty = 0; mTerrain = 0; mTags.clear(); } public void container(String container) { mContainer = mCacheTypeFactory.container(container); } public void difficulty(String difficulty) { mDifficulty = mCacheTypeFactory.stars(difficulty); } public void end() { mCacheWriter.clearEarlierLoads(); } public void gpxName(String gpxName) { mGpxName = gpxName; } /** * @param gpxTime * @return true if we should load this gpx; false if the gpx is already * loaded. */ public boolean gpxTime(String gpxTime) { mSqlDate = isoTimeToSql(gpxTime); if (mCacheWriter.isGpxAlreadyLoaded(mGpxName, mSqlDate)) { return false; } mCacheWriter.clearCaches(mGpxName); return true; } public void id(CharSequence id) { mId = id; } public String isoTimeToSql(String gpxTime) { return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19); } public void latitudeLongitude(String latitude, String longitude) { mLatitude = Double.parseDouble(latitude); mLongitude = Double.parseDouble(longitude); } public void startWriting() { mSqlDate = "2000-01-01T12:00:00"; mCacheWriter.startWriting(); } public void stopWriting(boolean successfulGpxImport) { mCacheWriter.stopWriting(); if (successfulGpxImport) mCacheWriter.writeGpx(mGpxName, mSqlDate); } public void setTag(int tag, boolean set) { mTags.put(tag, set); } public void terrain(String terrain) { mTerrain = mCacheTypeFactory.stars(terrain); } public void write(Source source) { if (mCacheWriter.isLockedFromUpdating(mId)) { Log.i("GeoBeagle", "Not updating " + mId + " because it is locked"); return; } for (Integer tag : mTags.keySet()) mCacheWriter.updateTag(mId, tag, mTags.get(tag)); boolean changed = mCacheWriter.conditionallyWriteCache(mId, mName, mLatitude, mLongitude, source, mGpxName, mCacheType, mDifficulty, mTerrain, mContainer); if (changed) mCacheWriter.updateTag(mId, Tags.NEW, true); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class GpxAndZipFiles { public static class GpxAndZipFilenameFilter implements FilenameFilter { private final GpxFilenameFilter mGpxFilenameFilter; public GpxAndZipFilenameFilter(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } public boolean accept(File dir, String name) { name = name.toLowerCase(); if (!name.startsWith(".") && name.endsWith(".zip")) return true; return mGpxFilenameFilter.accept(name); } } public static class GpxFilenameFilter { public boolean accept(String name) { name = name.toLowerCase(); return !name.startsWith(".") && (name.endsWith(".gpx") || name.endsWith(".loc")); } } public static class GpxFilesAndZipFilesIter { private final String[] mFileList; private final GpxFileIterAndZipFileIterFactory mGpxAndZipFileIterFactory; private int mIxFileList; private IGpxReaderIter mSubIter; GpxFilesAndZipFilesIter(String[] fileList, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) { mFileList = fileList; mGpxAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; mIxFileList = 0; } public boolean hasNext() throws IOException { // Iterate through actual zip and gpx files on the filesystem. if (mSubIter != null && mSubIter.hasNext()) return true; while (mIxFileList < mFileList.length) { mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]); if (mSubIter.hasNext()) return true; } return false; } public IGpxReader next() throws IOException { return mSubIter.next(); } } public static final String GPX_DIR = "/sdcard/download/"; private final FilenameFilter mFilenameFilter; private final GpxFileIterAndZipFileIterFactory mGpxFileIterAndZipFileIterFactory; public GpxAndZipFiles(FilenameFilter filenameFilter, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) { mFilenameFilter = filenameFilter; mGpxFileIterAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; } public GpxFilesAndZipFilesIter iterator() { String[] fileList = new File(GPX_DIR).list(mFilenameFilter); if (fileList == null) return null; mGpxFileIterAndZipFileIterFactory.resetAborter(); return new GpxFilesAndZipFilesIter(fileList, mGpxFileIterAndZipFileIterFactory); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.gpx.gpx.GpxFileOpener; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester; import java.io.IOException; /** * @author sng Takes a filename and returns an IGpxReaderIter based on the * extension: zip: ZipFileIter gpx/loc: GpxFileIter */ public class GpxFileIterAndZipFileIterFactory { private final Aborter mAborter; private final ZipInputFileTester mZipInputFileTester; public GpxFileIterAndZipFileIterFactory(ZipInputFileTester zipInputFileTester, Aborter aborter) { mAborter = aborter; mZipInputFileTester = zipInputFileTester; } public IGpxReaderIter fromFile(String filename) throws IOException { if (filename.endsWith(".zip")) { return new ZipFileOpener(GpxAndZipFiles.GPX_DIR + filename, new ZipInputStreamFactory(), mZipInputFileTester, mAborter).iterator(); } return new GpxFileOpener(GpxAndZipFiles.GPX_DIR + filename, mAborter).iterator(); } public void resetAborter() { mAborter.reset(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.gpx; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String mFilename; public GpxReader(String filename) { mFilename = filename; } public String getFilename() { return mFilename; } public Reader open() throws FileNotFoundException { return new BufferedReader(new FileReader(mFilename)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.gpx; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; public class GpxFileOpener { public class GpxFileIter implements IGpxReaderIter { public boolean hasNext() { if (mAborter.isAborted()) return false; return mFilename != null; } public IGpxReader next() { final IGpxReader gpxReader = new GpxReader(mFilename); mFilename = null; return gpxReader; } } private Aborter mAborter; private String mFilename; public GpxFileOpener(String filename, Aborter aborter) { mFilename = filename; mAborter = aborter; } public GpxFileIter iterator() { return new GpxFileIter(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.FileNotFoundException; import java.io.Reader; public interface IGpxReader { String getFilename(); Reader open() throws FileNotFoundException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.IOException; public interface IGpxReaderIter { public boolean hasNext() throws IOException; public IGpxReader next() throws IOException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String mFilename; private final Reader mReader; GpxReader(String filename, Reader reader) { mFilename = filename; mReader = reader; } public String getFilename() { return mFilename; } public Reader open() { return mReader; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.ZipEntry; public class ZipFileOpener { public static class ZipFileIter implements IGpxReaderIter { private final Aborter mAborter; private ZipEntry mNextZipEntry; private final ZipInputFileTester mZipInputFileTester; private final GpxZipInputStream mZipInputStream; ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter, ZipInputFileTester zipInputFileTester, ZipEntry nextZipEntry) { mZipInputStream = zipInputStream; mNextZipEntry = nextZipEntry; mAborter = aborter; mZipInputFileTester = zipInputFileTester; } ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter, ZipInputFileTester zipInputFileTester) { mZipInputStream = zipInputStream; mNextZipEntry = null; mAborter = aborter; mZipInputFileTester = zipInputFileTester; } public boolean hasNext() throws IOException { // Iterate through zip file entries. if (mNextZipEntry == null) { do { if (mAborter.isAborted()) break; mNextZipEntry = mZipInputStream.getNextEntry(); } while (mNextZipEntry != null && !mZipInputFileTester.isValid(mNextZipEntry)); } return mNextZipEntry != null; } public IGpxReader next() throws IOException { final String name = mNextZipEntry.getName(); mNextZipEntry = null; return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream())); } } public static class ZipInputFileTester { private final GpxFilenameFilter mGpxFilenameFilter; public ZipInputFileTester(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } public boolean isValid(ZipEntry zipEntry) { return (!zipEntry.isDirectory() && mGpxFilenameFilter.accept(zipEntry.getName())); } } private final Aborter mAborter; private final String mFilename; private final ZipInputFileTester mZipInputFileTester; private final ZipInputStreamFactory mZipInputStreamFactory; public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory, ZipInputFileTester zipInputFileTester, Aborter aborter) { mFilename = filename; mZipInputStreamFactory = zipInputStreamFactory; mAborter = aborter; mZipInputFileTester = zipInputFileTester; } public ZipFileIter iterator() throws IOException { return new ZipFileIter(mZipInputStreamFactory.create(mFilename), mAborter, mZipInputFileTester); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class GpxZipInputStream { private ZipEntry mNextEntry; private final ZipInputStream mZipInputStream; public GpxZipInputStream(ZipInputStream zipInputStream) { mZipInputStream = zipInputStream; } ZipEntry getNextEntry() throws IOException { mNextEntry = mZipInputStream.getNextEntry(); return mNextEntry; } InputStream getStream() { return mZipInputStream; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException; import org.xmlpull.v1.XmlPullParserException; import android.database.sqlite.SQLiteException; import android.os.PowerManager.WakeLock; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; public class GpxLoader { private final CachePersisterFacade mCachePersisterFacade; private final ErrorDisplayer mErrorDisplayer; private final GpxToCache mGpxToCache; private final WakeLock mWakeLock; public static final int WAKELOCK_DURATION = 15000; GpxLoader(CachePersisterFacade cachePersisterFacade, ErrorDisplayer errorDisplayer, GpxToCache gpxToCache, WakeLock wakeLock) { mGpxToCache = gpxToCache; mCachePersisterFacade = cachePersisterFacade; mErrorDisplayer = errorDisplayer; mWakeLock = wakeLock; } public void abort() { mGpxToCache.abort(); } public void end() { mCachePersisterFacade.end(); } /** * @return true if we should continue loading more files, false if we should * terminate. */ public boolean load(EventHelper eventHelper) { boolean markLoadAsComplete = false; boolean continueLoading = false; try { mWakeLock.acquire(WAKELOCK_DURATION); boolean alreadyLoaded = mGpxToCache.load(eventHelper); markLoadAsComplete = !alreadyLoaded; continueLoading = true; } catch (final SQLiteException e) { mErrorDisplayer.displayError(R.string.error_writing_cache, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (XmlPullParserException e) { mErrorDisplayer.displayError(R.string.error_parsing_file, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (FileNotFoundException e) { mErrorDisplayer.displayError(R.string.file_not_found, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (IOException e) { mErrorDisplayer.displayError(R.string.error_reading_file, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (CancelException e) { } mCachePersisterFacade.close(markLoadAsComplete); return continueLoading; } public void open(String path, Reader reader) throws XmlPullParserException { mGpxToCache.open(path, reader); mCachePersisterFacade.open(path); } public void start() { mCachePersisterFacade.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; public class EventHelper { public static class XmlPathBuilder { private String mPath = ""; public void endTag(String currentTag) { mPath = mPath.substring(0, mPath.length() - (currentTag.length() + 1)); } public String getPath() { return mPath; } public void startTag(String mCurrentTag) { mPath += "/" + mCurrentTag; } } private final EventHandler mEventHandler; private final XmlPathBuilder mXmlPathBuilder; private final XmlPullParserWrapper mXmlPullParser; EventHelper(XmlPathBuilder xmlPathBuilder, EventHandler eventHandler, XmlPullParserWrapper xmlPullParser) { mXmlPathBuilder = xmlPathBuilder; mXmlPullParser = xmlPullParser; mEventHandler = eventHandler; } /** @return false if this file has already been loaded */ public boolean handleEvent(int eventType) throws IOException { switch (eventType) { case XmlPullParser.START_TAG: mXmlPathBuilder.startTag(mXmlPullParser.getName()); mEventHandler.startTag(mXmlPathBuilder.getPath(), mXmlPullParser); break; case XmlPullParser.END_TAG: mEventHandler.endTag(mXmlPathBuilder.getPath()); mXmlPathBuilder.endTag(mXmlPullParser.getName()); break; case XmlPullParser.TEXT: return mEventHandler.text(mXmlPathBuilder.getPath(), mXmlPullParser.getText()); } return true; } }
Java
package com.google.code.geobeagle.xmlimport; import java.util.HashMap; public class EventHandlers { private final HashMap<String, EventHandler> mEventHandlers = new HashMap<String, EventHandler>(); public void add(String extension, EventHandler eventHandler) { mEventHandlers.put(extension.toLowerCase(), eventHandler); } public EventHandler get(String filename) { int len = filename.length(); String extension = filename.substring(Math.max(0, len - 4), len); return mEventHandlers.get(extension.toLowerCase()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.xmlimport.CachePersisterFacade.TextHandler; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; import java.util.HashMap; public class EventHandlerGpx implements EventHandler { public static final String XPATH_CACHE_CONTAINER = "/gpx/wpt/groundspeak:cache/groundspeak:container"; public static final String XPATH_CACHE_DIFFICULTY = "/gpx/wpt/groundspeak:cache/groundspeak:difficulty"; public static final String XPATH_CACHE_TERRAIN = "/gpx/wpt/groundspeak:cache/groundspeak:terrain"; public static final String XPATH_CACHE_TYPE = "/gpx/wpt/groundspeak:cache/groundspeak:type"; public static final String XPATH_GEOCACHE_CONTAINER = "/gpx/wpt/geocache/container"; public static final String XPATH_GEOCACHE_DIFFICULTY = "/gpx/wpt/geocache/difficulty"; public static final String XPATH_GEOCACHE_TERRAIN = "/gpx/wpt/geocache/terrain"; public static final String XPATH_GEOCACHE_TYPE = "/gpx/wpt/geocache/type"; public static final String XPATH_GEOCACHEHINT = "/gpx/wpt/geocache/hints"; public static final String XPATH_GEOCACHELOGDATE = "/gpx/wpt/geocache/logs/log/time"; public static final String XPATH_GEOCACHENAME = "/gpx/wpt/geocache/name"; static final String XPATH_GPXNAME = "/gpx/name"; static final String XPATH_GPXTIME = "/gpx/time"; public static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name"; public static final String XPATH_PLACEDBY = "/gpx/wpt/groundspeak:cache/groundspeak:placed_by"; public static final String XPATH_HINT = "/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints"; public static final String XPATH_LOGDATE = "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date"; static final String[] XPATH_PLAINLINES = { "/gpx/wpt/cmt", "/gpx/wpt/desc", "/gpx/wpt/groundspeak:cache/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:container", "/gpx/wpt/groundspeak:cache/groundspeak:short_description", "/gpx/wpt/groundspeak:cache/groundspeak:long_description", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text", /* here are the geocaching.com.au entries */ "/gpx/wpt/geocache/owner", "/gpx/wpt/geocache/type", "/gpx/wpt/geocache/summary", "/gpx/wpt/geocache/description", "/gpx/wpt/geocache/logs/log/geocacher", "/gpx/wpt/geocache/logs/log/type", "/gpx/wpt/geocache/logs/log/text" }; static final String XPATH_SYM = "/gpx/wpt/sym"; static final String XPATH_CACHE = "/gpx/wpt/groundspeak:cache"; static final String XPATH_WPT = "/gpx/wpt"; public static final String XPATH_WPTDESC = "/gpx/wpt/desc"; public static final String XPATH_WPTNAME = "/gpx/wpt/name"; public static final String XPATH_WAYPOINT_TYPE = "/gpx/wpt/type"; private final CachePersisterFacade mCachePersisterFacade; private final HashMap<String, TextHandler> mTextHandlers; public EventHandlerGpx(CachePersisterFacade cachePersisterFacade, HashMap<String, TextHandler> textHandlers) { mCachePersisterFacade = cachePersisterFacade; mTextHandlers = textHandlers; } public void endTag(String previousFullPath) throws IOException { if (previousFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.endCache(Source.GPX); } } public void startTag(String fullPath, XmlPullParserWrapper xmlPullParser) { if (fullPath.equals(XPATH_WPT)) { mCachePersisterFacade.startCache(); mCachePersisterFacade.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser .getAttributeValue(null, "lon")); } else if (fullPath.equals(XPATH_CACHE)) { boolean available = xmlPullParser.getAttributeValue(null, "available").equalsIgnoreCase("true"); boolean archived = xmlPullParser.getAttributeValue(null, "archived").equalsIgnoreCase("true"); mCachePersisterFacade.setTag(Tags.UNAVAILABLE, !available); mCachePersisterFacade.setTag(Tags.ARCHIVED, archived); } } public boolean text(String fullPath, String text) throws IOException { text = text.trim(); if (mTextHandlers.containsKey(fullPath)) mTextHandlers.get(fullPath).text(text); //Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text); if (fullPath.equals(XPATH_GPXTIME)) { return mCachePersisterFacade.gpxTime(text); } else if (fullPath.equals(XPATH_SYM)) { if (text.equals("Geocache Found")) mCachePersisterFacade.setTag(Tags.FOUND, true); } for (String writeLineMatch : XPATH_PLAINLINES) { if (fullPath.equals(writeLineMatch)) { mCachePersisterFacade.line(text); return true; } } return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.cachedetails.CacheDetailsWriter; import com.google.code.geobeagle.xmlimport.FileFactory; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import android.os.PowerManager.WakeLock; import java.io.File; import java.io.IOException; public class CachePersisterFacade { private final CacheDetailsWriter mCacheDetailsWriter; private String mCacheName = ""; private final CacheTagSqlWriter mCacheTagWriter; private final FileFactory mFileFactory; private final MessageHandler mMessageHandler; private final WakeLock mWakeLock; private final String mUsername; static interface TextHandler { public void text(String fullpath) throws IOException; } TextHandler wptName = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheDetailsWriter.open(fullpath); mCacheDetailsWriter.writeWptName(fullpath); mCacheTagWriter.id(fullpath); mMessageHandler.updateWaypointId(fullpath); mWakeLock.acquire(GpxLoader.WAKELOCK_DURATION); } }; TextHandler wptDesc = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheName = fullpath; mCacheTagWriter.cacheName(fullpath); } }; TextHandler logDate = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheDetailsWriter.writeLogDate(fullpath); } }; TextHandler hint = new TextHandler() { @Override public void text(String fullpath) throws IOException { if (!fullpath.equals("")) mCacheDetailsWriter.writeHint(fullpath); } }; TextHandler cacheType = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.cacheType(fullpath); } }; TextHandler difficulty = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.difficulty(fullpath); } }; TextHandler container = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.container(fullpath); } }; TextHandler terrain = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.terrain(fullpath); } }; TextHandler groundspeakName = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.cacheName(fullpath); } }; TextHandler placedBy = new TextHandler() { @Override public void text(String fullpath) throws IOException { boolean isMine = (!mUsername.equals("") && mUsername .equalsIgnoreCase(fullpath)); mCacheTagWriter.setTag(Tags.MINE, isMine); } }; CachePersisterFacade(CacheTagSqlWriter cacheTagSqlWriter, FileFactory fileFactory, CacheDetailsWriter cacheDetailsWriter, MessageHandler messageHandler, WakeLock wakeLock, String username) { mCacheDetailsWriter = cacheDetailsWriter; mCacheTagWriter = cacheTagSqlWriter; mFileFactory = fileFactory; mMessageHandler = messageHandler; mWakeLock = wakeLock; mUsername = username; } void close(boolean success) { mCacheTagWriter.stopWriting(success); } void end() { mCacheTagWriter.end(); } void endCache(Source source) throws IOException { mMessageHandler.updateName(mCacheName); mCacheDetailsWriter.close(); mCacheTagWriter.write(source); } boolean gpxTime(String gpxTime) { return mCacheTagWriter.gpxTime(gpxTime); } void line(String text) throws IOException { mCacheDetailsWriter.writeLine(text); } void open(String path) { mMessageHandler.updateSource(path); mCacheTagWriter.startWriting(); mCacheTagWriter.gpxName(path); } void start() { File file = mFileFactory.createFile(CacheDetailsWriter.GEOBEAGLE_DIR); file.mkdirs(); } void startCache() { mCacheName = ""; mCacheTagWriter.clear(); } public void setTag(int tag, boolean set) { mCacheTagWriter.setTag(tag, set); } void wpt(String latitude, String longitude) { mCacheTagWriter.latitudeLongitude(latitude, longitude); mCacheDetailsWriter.latitudeLongitude(latitude, longitude); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import android.content.Context; import android.widget.Toast; public class Toaster { static public class OneTimeToaster implements IToaster { public static class OneTimeToasterFactory implements Toaster.ToasterFactory { @Override public IToaster getToaster(Toaster toaster) { return new OneTimeToaster(toaster); } } private boolean mHasShownToaster = false; private final Toaster mToaster; public OneTimeToaster(Toaster toaster) { mToaster = toaster; } public void showToast(boolean fCondition) { if (fCondition && !mHasShownToaster) { mToaster.showToast(); mHasShownToaster = true; } } } public static interface ToasterFactory { IToaster getToaster(Toaster toaster); } private final Context mContext; private final int mDuration; private final int mResId; public Toaster(Context context, int resId, int duration) { mContext = context; mResId = resId; mDuration = duration; } public void showToast() { Toast.makeText(mContext, mResId, mDuration).show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import java.io.IOException; public class CacheDetailsWriter { public static final String GEOBEAGLE_DIR = "/sdcard/GeoBeagle"; private final HtmlWriter mHtmlWriter; private String mLatitude; private String mLongitude; public CacheDetailsWriter(HtmlWriter htmlWriter) { mHtmlWriter = htmlWriter; } public void close() throws IOException { mHtmlWriter.writeFooter(); mHtmlWriter.close(); } public void latitudeLongitude(String latitude, String longitude) { mLatitude = latitude; mLongitude = longitude; } public void open(String wpt) throws IOException { final String sanitized = replaceIllegalFileChars(wpt); mHtmlWriter.open(CacheDetailsWriter.GEOBEAGLE_DIR + "/" + sanitized + ".html"); } public static String replaceIllegalFileChars(String wpt) { return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_"); } public void writeHint(String text) throws IOException { mHtmlWriter.write("<br />Hint: <font color=gray>" + text + "</font>"); } public void writeLine(String text) throws IOException { mHtmlWriter.write(text); } public void writeLogDate(String text) throws IOException { mHtmlWriter.writeSeparator(); mHtmlWriter.write(text); } public void writeWptName(String wpt) throws IOException { mHtmlWriter.writeHeader(); mHtmlWriter.write(wpt); mHtmlWriter.write(mLatitude + ", " + mLongitude); mLatitude = mLongitude = null; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.code.geobeagle.R; import android.app.Activity; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class CacheDetailsLoader { static interface Details { String getString(); } static class DetailsError implements Details { private final Activity mActivity; private final String mPath; private final int mResourceId; DetailsError(Activity activity, int resourceId, String path) { mActivity = activity; mResourceId = resourceId; mPath = path; } public String getString() { return mActivity.getString(mResourceId, mPath); } } static class DetailsImpl implements Details { private final byte[] mBuffer; DetailsImpl(byte[] buffer) { mBuffer = buffer; } public String getString() { return new String(mBuffer); } } public static class DetailsOpener { private final Activity mActivity; public DetailsOpener(Activity activity) { mActivity = activity; } DetailsReader open(File file) { FileInputStream fileInputStream; String absolutePath = file.getAbsolutePath(); try { fileInputStream = new FileInputStream(file); } catch (FileNotFoundException e) { return new DetailsReaderFileNotFound(mActivity, e.getMessage()); } byte[] buffer = new byte[(int)file.length()]; return new DetailsReaderImpl(mActivity, absolutePath, fileInputStream, buffer); } } interface DetailsReader { Details read(); } static class DetailsReaderFileNotFound implements DetailsReader { private final Activity mActivity; private final String mPath; DetailsReaderFileNotFound(Activity activity, String path) { mActivity = activity; mPath = path; } public Details read() { return new DetailsError(mActivity, R.string.error_opening_details_file, mPath); } } static class DetailsReaderImpl implements DetailsReader { private final Activity mActivity; private final byte[] mBuffer; private final FileInputStream mFileInputStream; private final String mPath; DetailsReaderImpl(Activity activity, String path, FileInputStream fileInputStream, byte[] buffer) { mActivity = activity; mFileInputStream = fileInputStream; mPath = path; mBuffer = buffer; } public Details read() { try { mFileInputStream.read(mBuffer); mFileInputStream.close(); return new DetailsImpl(mBuffer); } catch (IOException e) { return new DetailsError(mActivity, R.string.error_reading_details_file, mPath); } } } public static final String DETAILS_DIR = "/sdcard/GeoBeagle/"; private final DetailsOpener mDetailsOpener; public CacheDetailsLoader(DetailsOpener detailsOpener) { mDetailsOpener = detailsOpener; } public String load(CharSequence cacheId) { final String sanitized = CacheDetailsWriter.replaceIllegalFileChars(cacheId.toString()); String path = DETAILS_DIR + sanitized + ".html"; File file = new File(path); DetailsReader detailsReader = mDetailsOpener.open(file); Details details = detailsReader.read(); return details.getString(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import java.io.IOException; public class HtmlWriter { private final WriterWrapper mWriter; public HtmlWriter(WriterWrapper writerWrapper) { mWriter = writerWrapper; } public void close() throws IOException { mWriter.close(); } public void open(String path) throws IOException { mWriter.open(path); } public void write(String text) throws IOException { mWriter.write(text + "<br/>\n"); } public void writeFooter() throws IOException { mWriter.write(" </body>\n"); mWriter.write("</html>\n"); } public void writeHeader() throws IOException { mWriter.write("<html>\n"); mWriter.write(" <body>\n"); } public void writeSeparator() throws IOException { mWriter.write("<hr/>\n"); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.android.maps.GeoPoint; import com.google.code.geobeagle.GeocacheFactory.Provider; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.main.GeoUtils; import com.google.code.geobeagle.database.CacheWriter; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.util.FloatMath; /** * Geocache or letterbox description, id, and coordinates. */ public class Geocache { static interface AttributeFormatter { CharSequence formatAttributes(int difficulty, int terrain); } static class AttributeFormatterImpl implements AttributeFormatter { public CharSequence formatAttributes(int difficulty, int terrain) { return (difficulty / 2.0) + " / " + (terrain / 2.0); } } static class AttributeFormatterNull implements AttributeFormatter { public CharSequence formatAttributes(int difficulty, int terrain) { return ""; } } public static final String CACHE_TYPE = "cacheType"; public static final String CONTAINER = "container"; public static final String DIFFICULTY = "difficulty"; public static final String ID = "id"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String NAME = "name"; public static final String SOURCE_NAME = "sourceName"; public static final String SOURCE_TYPE = "sourceType"; public static final String TERRAIN = "terrain"; private final AttributeFormatter mAttributeFormatter; private final CacheType mCacheType; private final int mContainer; /** Difficulty rating * 2 (difficulty=1.5 => mDifficulty=3) */ private final int mDifficulty; private GeoPoint mGeoPoint; private final CharSequence mId; private final double mLatitude; private final double mLongitude; private final CharSequence mName; private final String mSourceName; private final Source mSourceType; private final int mTerrain; private Drawable mIcon = null; //private Drawable mIconBig = null; private Drawable mIconMap = null; public Geocache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container, AttributeFormatter attributeFormatter) { mId = id; mName = name; mLatitude = latitude; mLongitude = longitude; mSourceType = sourceType; mSourceName = sourceName; mCacheType = cacheType; mDifficulty = difficulty; mTerrain = terrain; mContainer = container; mAttributeFormatter = attributeFormatter; } /* public float[] calculateDistanceAndBearing(Location here) { if (here != null) { Location.distanceBetween(here.getLatitude(), here.getLongitude(), getLatitude(), getLongitude(), mDistanceAndBearing); return mDistanceAndBearing; } mDistanceAndBearing[0] = -1; mDistanceAndBearing[1] = -1; return mDistanceAndBearing; } */ public int describeContents() { return 0; } public CacheType getCacheType() { return mCacheType; } public int getContainer() { return mContainer; } public Drawable getIcon(Resources resources, GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) { if (mIcon == null) { Drawable overlayIcon = null; if (dbFrontend.geocacheHasTag(getId(), Tags.MINE)) overlayIcon = resources.getDrawable(R.drawable.overlay_mine_cacheview); else if (dbFrontend.geocacheHasTag(getId(), Tags.FOUND)) overlayIcon = resources.getDrawable(R.drawable.overlay_found_cacheview); else if (dbFrontend.geocacheHasTag(getId(), Tags.DNF)) overlayIcon = resources.getDrawable(R.drawable.overlay_dnf_cacheview); // else if (dbFrontend.geocacheHasTag(getId(), Tags.NEW)) // overlayIcon = resources.getDrawable(R.drawable.overlay_new_cacheview); mIcon = graphicsGenerator.createIconListView(this, overlayIcon, resources); } return mIcon; } public Drawable getIconMap(Resources resources, GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) { if (mIconMap == null) { Drawable overlayIcon = null; if (dbFrontend.geocacheHasTag(getId(), Tags.MINE)) overlayIcon = resources.getDrawable(R.drawable.overlay_mine); else if (dbFrontend.geocacheHasTag(getId(), Tags.FOUND)) overlayIcon = resources.getDrawable(R.drawable.overlay_found); else if (dbFrontend.geocacheHasTag(getId(), Tags.DNF)) overlayIcon = resources.getDrawable(R.drawable.overlay_dnf); else if (dbFrontend.geocacheHasTag(getId(), Tags.NEW)) overlayIcon = resources.getDrawable(R.drawable.overlay_new); mIconMap = graphicsGenerator.createIconMapView(this, overlayIcon, resources); } return mIconMap; } public GeocacheFactory.Provider getContentProvider() { // Must use toString() rather than mId.subSequence(0,2).equals("GC"), // because editing the text in android produces a SpannableString rather // than a String, so the CharSequences won't be equal. String prefix = mId.subSequence(0, 2).toString(); for (Provider provider : GeocacheFactory.ALL_PROVIDERS) { if (prefix.equals(provider.getPrefix())) return provider; } return Provider.GROUNDSPEAK; } public int getDifficulty() { return mDifficulty; } //Formerly calculateDistanceFast public float getDistanceTo(double latitude, double longitude) { double dLat = Math.toRadians(latitude - mLatitude); double dLon = Math.toRadians(longitude - mLongitude); final float sinDLat = FloatMath.sin((float)(dLat / 2)); final float sinDLon = FloatMath.sin((float)(dLon / 2)); float a = sinDLat * sinDLat + FloatMath.cos((float)Math.toRadians(mLatitude)) * FloatMath.cos((float)Math.toRadians(latitude)) * sinDLon * sinDLon; float c = (float)(2 * Math.atan2(FloatMath.sqrt(a), FloatMath.sqrt(1 - a))); return 6371000 * c; } public CharSequence getFormattedAttributes() { return mAttributeFormatter.formatAttributes(mDifficulty, mTerrain); } public GeoPoint getGeoPoint() { if (mGeoPoint == null) { int latE6 = (int)(mLatitude * GeoUtils.MILLION); int lonE6 = (int)(mLongitude * GeoUtils.MILLION); mGeoPoint = new GeoPoint(latE6, lonE6); } return mGeoPoint; } public CharSequence getId() { return mId; } public CharSequence getIdAndName() { if (mId.length() == 0) return mName; else if (mName.length() == 0) return mId; else return mId + ": " + mName; } public double getLatitude() { return mLatitude; } public double getLongitude() { return mLongitude; } public CharSequence getName() { return mName; } public CharSequence getShortId() { if (mId.length() > 2) return mId.subSequence(2, mId.length()); return ""; } public String getSourceName() { return mSourceName; } public Source getSourceType() { return mSourceType; } public int getTerrain() { return mTerrain; } /** @return true if the database needed to be updated */ public boolean saveToDbIfNeeded(DbFrontend dbFrontend) { CacheWriter cacheWriter = dbFrontend.getCacheWriter(); cacheWriter.startWriting(); boolean changed = cacheWriter.conditionallyWriteCache(getId(), getName(), getLatitude(), getLongitude(), getSourceType(), getSourceName(), getCacheType(), getDifficulty(), getTerrain(), getContainer()); cacheWriter.stopWriting(); return changed; } public void saveToDb(DbFrontend dbFrontend) { CacheWriter cacheWriter = dbFrontend.getCacheWriter(); cacheWriter.startWriting(); cacheWriter.insertAndUpdateCache(getId(), getName(), getLatitude(), getLongitude(), getSourceType(), getSourceName(), getCacheType(), getDifficulty(), getTerrain(), getContainer()); cacheWriter.stopWriting(); } /** The icons will be recalculated the next time they are needed. */ public void flushIcons() { mIcon = null; mIconMap = null; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; public interface IToaster { public void showToast(boolean fCondition); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.Clock; import android.view.View; class MeterFader { private long mLastUpdateTime; private final MeterBars mMeterView; private final View mParent; private final Clock mTime; MeterFader(View parent, MeterBars meterBars, Clock time) { mLastUpdateTime = -1; mMeterView = meterBars; mParent = parent; mTime = time; } void paint() { final long currentTime = mTime.getCurrentTime(); if (mLastUpdateTime == -1) mLastUpdateTime = currentTime; long lastUpdateLag = currentTime - mLastUpdateTime; mMeterView.setLag(lastUpdateLag); if (lastUpdateLag < 1000) mParent.postInvalidateDelayed(100); // Log.d("GeoBeagle", "painting " + lastUpdateLag); } void reset() { mLastUpdateTime = -1; mParent.postInvalidate(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate.TimeProvider; import android.os.Handler; /** Updates the Gps widget two times a second */ public class UpdateGpsWidgetRunnable implements Runnable { private final Handler mHandler; private final GeoFixProvider mGeoFixProvider; private final Meter mMeter; private final GpsStatusWidgetDelegate mGpsStatusWidgetDelegate; private final TimeProvider mTimeProvider; UpdateGpsWidgetRunnable(Handler handler, GeoFixProvider geoFixProvider, Meter meter, GpsStatusWidgetDelegate gpsStatusWidgetDelegate, TimeProvider timeProvider) { mMeter = meter; mGeoFixProvider = geoFixProvider; mHandler = handler; mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate; mTimeProvider = timeProvider; } public void run() { // Update the lag time and the orientation. long systemTime = mTimeProvider.getTime(); mGpsStatusWidgetDelegate.updateLagText(systemTime); mMeter.setAzimuth(mGeoFixProvider.getAzimuth()); mHandler.postDelayed(this, 500); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; /* * Displays the accuracy (graphically) and azimuth of the gps. */ import android.graphics.Color; import android.widget.TextView; class MeterBars { private final TextView mBarsAndAzimuth; private final MeterFormatter mMeterFormatter; MeterBars(TextView textView, MeterFormatter meterFormatter) { mBarsAndAzimuth = textView; mMeterFormatter = meterFormatter; } void set(float accuracy, float azimuth) { final String center = String.valueOf((int)azimuth); final int barCount = mMeterFormatter.accuracyToBarCount(accuracy); final String barsToMeterText = mMeterFormatter.barsToMeterText(barCount, center); mBarsAndAzimuth.setText(barsToMeterText); } void setLag(long lag) { mBarsAndAzimuth.setTextColor(Color.argb(mMeterFormatter.lagToAlpha(lag), 147, 190, 38)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.R; import android.content.Context; class MeterFormatter { private static String mMeterLeft; private static String mMeterRight; private static String mDegreesSymbol; private static StringBuilder mStringBuilder; MeterFormatter(Context context) { mMeterLeft = context.getString(R.string.meter_left); mMeterRight = context.getString(R.string.meter_right); mDegreesSymbol = context.getString(R.string.degrees_symbol); mStringBuilder = new StringBuilder(); } int accuracyToBarCount(float accuracy) { return Math.min(mMeterLeft.length(), (int)(Math.log(Math.max(1, accuracy)) / Math.log(2))); } String barsToMeterText(int bars, String center) { mStringBuilder.setLength(0); mStringBuilder.append('[').append(mMeterLeft.substring(mMeterLeft.length() - bars)).append( center + mDegreesSymbol).append(mMeterRight.substring(0, bars)).append(']'); return mStringBuilder.toString(); } int lagToAlpha(long milliseconds) { return Math.max(128, 255 - (int)(milliseconds >> 3)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.widget.TextView; class Meter { private float mAccuracy; private final TextView mAccuracyView; private float mAzimuth; private final MeterBars mMeterView; Meter(MeterBars meterBars, TextView accuracyView) { mAccuracyView = accuracyView; mMeterView = meterBars; } void setAccuracy(float accuracy, DistanceFormatter distanceFormatter) { mAccuracy = accuracy; distanceFormatter.formatDistance(accuracy); mAccuracyView.setText(distanceFormatter.formatDistance(accuracy)); mMeterView.set(accuracy, mAzimuth); } void setAzimuth(float azimuth) { mAzimuth = azimuth; mMeterView.set(mAccuracy, azimuth); } void setDisabled() { mAccuracyView.setText(""); mMeterView.set(Float.MAX_VALUE, 0); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.cachelist.presenter.HasDistanceFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.content.Context; import android.location.LocationProvider; import android.os.Bundle; import android.widget.TextView; public class GpsStatusWidgetDelegate implements HasDistanceFormatter, Refresher { private final Context mContext; private DistanceFormatter mDistanceFormatter; private final GeoFixProvider mGeoFixProvider; private final MeterFader mMeterFader; private final Meter mMeter; private final TextView mProvider; private final TextView mStatus; private final TextView mLagTextView; private GeoFix mGeoFix; private final TimeProvider mTimeProvider; public static interface TimeProvider { long getTime(); } public GpsStatusWidgetDelegate(GeoFixProvider geoFixProvider, DistanceFormatter distanceFormatter, Meter meter, MeterFader meterFader, TextView provider, Context context, TextView status, TextView lagTextView, GeoFix initialGeoFix, TimeProvider timeProvider) { mGeoFixProvider = geoFixProvider; mDistanceFormatter = distanceFormatter; mMeterFader = meterFader; mMeter = meter; mProvider = provider; mContext = context; mStatus = status; mLagTextView = lagTextView; mGeoFix = initialGeoFix; mTimeProvider = timeProvider; } public void onStatusChanged(String provider, int status, Bundle extras) { switch (status) { case LocationProvider.OUT_OF_SERVICE: mStatus.setText(provider + " status: " + mContext.getString(R.string.out_of_service)); break; case LocationProvider.AVAILABLE: mStatus.setText(provider + " status: " + mContext.getString(R.string.available)); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: mStatus.setText(provider + " status: " + mContext.getString(R.string.temporarily_unavailable)); break; } } public void paint() { mMeterFader.paint(); } /** Called when the location changed */ public void refresh() { mGeoFix = mGeoFixProvider.getLocation(); //Log.d("GeoBeagle", "GpsStatusWidget onLocationChanged " + mGeoFix); /* if (!mGeoFixProvider.isProviderEnabled()) { mMeter.setDisabled(); mTextLagUpdater.setDisabled(); return; } */ mProvider.setText(mGeoFix.getProvider()); mMeter.setAccuracy(mGeoFix.getAccuracy(), mDistanceFormatter); mMeterFader.reset(); mLagTextView.setText(mGeoFix.getLagString(mTimeProvider.getTime())); } public void setDistanceFormatter(DistanceFormatter distanceFormatter) { mDistanceFormatter = distanceFormatter; } public void updateLagText(long systemTime) { mLagTextView.setText(mGeoFix.getLagString(systemTime)); } @Override public void forceRefresh() { refresh(); } }
Java