Merge remote-tracking branch 'origin/refactoringDownload'

This commit is contained in:
Victor Shcherb 2015-10-19 23:14:59 +02:00
commit 27dc95a008
41 changed files with 2002 additions and 3268 deletions

View file

@ -1,15 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?>
<cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="com.android.toolchain.gcc.128294115">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="com.android.toolchain.gcc.128294115" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="?attr/ctx_menu_info_view_bg"
android:orientation="vertical">
<include layout="@layout/download_items_list"/>
</LinearLayout>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/ctx_menu_info_view_bg">
<include layout="@layout/download_items_list"/>
</LinearLayout>

View file

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<ExpandableListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:focusable="true"
android:groupIndicator="@android:color/transparent"
android:background="@android:color/transparent"/>

View file

@ -4,8 +4,7 @@
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="net.osmand.plus.download.newimplementation.NewLocalIndexesFragment">
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
@ -19,7 +18,8 @@
android:minHeight="@dimen/dashboard_map_toolbar"
android:theme="?attr/toolbar_theme"
app:contentInsetLeft="72dp"
app:contentInsetStart="72dp"/>
app:contentInsetStart="72dp"
/>
</android.support.design.widget.AppBarLayout>
<include
@ -28,8 +28,15 @@
<include layout="@layout/progress_with_two_texts"/>
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ExpandableListView
android:id="@android:id/list"
style="@style/OsmandListView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginTop="0dp"
android:layout_weight="1"
android:groupIndicator="@android:color/transparent"/>
</LinearLayout>

View file

@ -52,15 +52,6 @@
android:textSize="@dimen/default_sub_text_size"
tools:text="Contour Lines"/>
<TextView
android:id="@+id/mapDateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:maxLines="25"
android:textSize="@dimen/default_sub_text_size"
tools:text="Local version: 10/3/2015"/>
</LinearLayout>
<ProgressBar

View file

@ -13,10 +13,8 @@
<string name="favorite_category_name">Category name</string>
<string name="favorite_category_add_new_title">Add new category</string>
<string name="regions">Regions</string>
<string name="additional_maps">Additional maps</string>
<string name="region_maps">Region maps</string>
<string name="world_maps">World maps</string>
<string name="world_regions">World regions</string>
<string name="hillshade_layer_disabled">Hillshade layer disabled</string>
<string name="srtm_plugin_disabled">Contour lines disabled</string>
<string name="favorite_category_add_new">Add new</string>
@ -2018,7 +2016,7 @@ Afghanistan, Albania, Algeria, Andorra, Angola, Anguilla, Antigua and Barbuda, A
<string name="confirm_download_roadmaps">Are you sure you want to download map of roads, even though you have full map?</string>
<string name="value_downloaded_from_max">%1$.1f from %2$.1f MB</string>
<string name="file_size_in_mb">%.1f MB</string>
<string name="update_all">Update all(%1$s Mb)</string>
<string name="update_all">Update all (%1$s MB)</string>
<string name="free_downloads_used">Free downloads used</string>
<string name="free_downloads_used_description">You can set how many free downloads you have used</string>
</resources>

View file

@ -1,18 +1,18 @@
package net.osmand.plus;
import android.content.res.Resources;
import net.osmand.PlatformUtil;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.download.DownloadActivityType;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.osmand.PlatformUtil;
import net.osmand.map.OsmandRegions;
import net.osmand.util.Algorithms;
import android.content.res.Resources;
public class WorldRegion {
@ -24,46 +24,35 @@ public class WorldRegion {
public static final String NORTH_AMERICA_REGION_ID = "northamerica";
public static final String RUSSIA_REGION_ID = "russia";
public static final String SOUTH_AMERICA_REGION_ID = "southamerica";
public static final String WORLD = "world";
private static final org.apache.commons.logging.Log LOG = PlatformUtil.getLog(WorldRegion.class);
// Region data
private String regionId;
private String downloadsIdPrefix;
private String downloadsId;
private String name;
private Set<DownloadActivityType> resourceTypes;
private String searchText;
// Hierarchy
private WorldRegion superregion;
private List<WorldRegion> subregions;
private List<WorldRegion> flattenedSubregions;
private boolean purchased;
private boolean isInPurchasedArea;
private MapState mapState = MapState.NOT_DOWNLOADED;
public String getRegionId() {
return regionId;
}
public String getDownloadsIdPrefix() {
return downloadsIdPrefix;
public String getDownloadsId() {
return downloadsId;
}
public String getName() {
return name;
}
public Set<DownloadActivityType> getResourceTypes() {
return resourceTypes;
}
public void setResourceTypes(Set<DownloadActivityType> resourceTypes) {
this.resourceTypes = resourceTypes;
}
public WorldRegion getSuperregion() {
return superregion;
}
@ -76,32 +65,6 @@ public class WorldRegion {
return flattenedSubregions;
}
public boolean isPurchased() {
return purchased;
}
public boolean isInPurchasedArea() {
return isInPurchasedArea;
}
public MapState getMapState() {
return mapState;
}
public void processNewMapState(MapState mapState) {
switch (this.mapState) {
case NOT_DOWNLOADED:
this.mapState = mapState;
break;
case DOWNLOADED:
if (mapState == MapState.OUTDATED)
this.mapState = mapState;
break;
case OUTDATED:
break;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -125,7 +88,7 @@ public class WorldRegion {
public void initWorld() {
regionId = "";
downloadsIdPrefix = "world_";
downloadsId = WORLD;
name = "";
superregion = null;
}
@ -133,10 +96,11 @@ public class WorldRegion {
private WorldRegion init(String regionId, OsmandRegions osmandRegions, String name) {
this.regionId = regionId;
String downloadName = osmandRegions.getDownloadName(regionId);
this.searchText = osmandRegions.getDownloadNameIndexLowercase(downloadName);
if (downloadName != null) {
downloadsIdPrefix = downloadName.toLowerCase() + ".";
downloadsId = downloadName.toLowerCase();
} else {
this.downloadsIdPrefix = regionId.toLowerCase() + ".";
downloadsId = regionId.toLowerCase();
}
if (name != null) {
this.name = name;
@ -149,98 +113,69 @@ public class WorldRegion {
return this;
}
private WorldRegion init(String regionId, OsmandRegions osmandRegions) {
this.regionId = regionId;
String downloadName = osmandRegions.getDownloadName(regionId);
if (downloadName != null) {
downloadsIdPrefix = downloadName.toLowerCase() + ".";
} else {
this.downloadsIdPrefix = regionId.toLowerCase() + ".";
}
this.name = osmandRegions.getLocaleNameByFullName(regionId, false);
if (this.name == null) {
this.name = capitalize(regionId.replace('_', ' '));
}
return this;
public String getSearchText() {
return searchText;
}
private WorldRegion init(String regionId, String name) {
this.regionId = regionId;
this.downloadsIdPrefix = regionId.toLowerCase() + ".";
this.name = name;
return this;
}
private void addSubregion(WorldRegion subregion) {
private void addSubregion(WorldRegion subregion, WorldRegion world) {
subregion.superregion = this;
subregions.add(subregion);
propagateSubregionToFlattenedHierarchy(subregion);
}
private void propagateSubregionToFlattenedHierarchy(WorldRegion subregion) {
flattenedSubregions.add(subregion);
if (superregion != null) {
superregion.propagateSubregionToFlattenedHierarchy(subregion);
}
world.flattenedSubregions.add(subregion);
}
public void loadWorldRegions(OsmandApplication app) {
OsmandRegions osmandRegions = app.getRegions();
Map<String, String> loadedItems = osmandRegions.getFullNamesToLowercaseCopy();
if (loadedItems.size() == 0) {
return;
}
HashMap<String, WorldRegion> regionsLookupTable = new HashMap<>(loadedItems.size());
// Create main regions
Resources res = app.getResources();
WorldRegion africaRegion = createRegionAs(AFRICA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_africa));
addSubregion(africaRegion);
addSubregion(africaRegion, this);
regionsLookupTable.put(africaRegion.regionId, africaRegion);
WorldRegion asiaRegion = createRegionAs(ASIA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_asia));
addSubregion(asiaRegion);
addSubregion(asiaRegion, this);
regionsLookupTable.put(asiaRegion.regionId, asiaRegion);
WorldRegion australiaAndOceaniaRegion = createRegionAs(AUSTRALIA_AND_OCEANIA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_oceania));
addSubregion(australiaAndOceaniaRegion);
addSubregion(australiaAndOceaniaRegion, this);
regionsLookupTable.put(australiaAndOceaniaRegion.regionId, australiaAndOceaniaRegion);
WorldRegion centralAmericaRegion = createRegionAs(CENTRAL_AMERICA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_central_america));
addSubregion(centralAmericaRegion);
addSubregion(centralAmericaRegion, this);
regionsLookupTable.put(centralAmericaRegion.regionId, centralAmericaRegion);
WorldRegion europeRegion = createRegionAs(EUROPE_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_europe));
addSubregion(europeRegion);
addSubregion(europeRegion, this);
regionsLookupTable.put(europeRegion.regionId, europeRegion);
WorldRegion northAmericaRegion = createRegionAs(NORTH_AMERICA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_north_america));
addSubregion(northAmericaRegion);
addSubregion(northAmericaRegion, this);
regionsLookupTable.put(northAmericaRegion.regionId, northAmericaRegion);
WorldRegion russiaRegion = createRegionAs(RUSSIA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_russia));
addSubregion(russiaRegion);
addSubregion(russiaRegion, this);
regionsLookupTable.put(russiaRegion.regionId, russiaRegion);
WorldRegion southAmericaRegion = createRegionAs(SOUTH_AMERICA_REGION_ID,
loadedItems, osmandRegions, res.getString(R.string.index_name_south_america));
addSubregion(southAmericaRegion);
addSubregion(southAmericaRegion, this);
regionsLookupTable.put(southAmericaRegion.regionId, southAmericaRegion);
// Process remaining regions
// Process all regions
for (; ; ) {
int processedRegions = 0;
Iterator<Entry<String, String>> iterator = loadedItems.entrySet().iterator();
while (iterator.hasNext()) {
String regionId = iterator.next().getKey();
@ -255,8 +190,8 @@ public class WorldRegion {
continue;
}
WorldRegion newRegion = new WorldRegion().init(regionId, osmandRegions);
parentRegion.addSubregion(newRegion);
WorldRegion newRegion = new WorldRegion().init(regionId, osmandRegions, null);
parentRegion.addSubregion(newRegion, this);
regionsLookupTable.put(newRegion.regionId, newRegion);
// Remove
@ -269,21 +204,35 @@ public class WorldRegion {
break;
}
Comparator<WorldRegion> nameComparator = new Comparator<WorldRegion>() {
@Override
public int compare(WorldRegion w1, WorldRegion w2) {
return w1.getName().compareTo(w2.getName());
}
};
sortSubregions(this, nameComparator);
if (loadedItems.size() > 0) {
LOG.warn("Found orphaned regions: " + loadedItems.size());
for (String regionId : loadedItems.keySet()) {
LOG.warn("FullName = " + regionId + " parent=" + osmandRegions.getParentFullName(regionId));
}
}
private static WorldRegion createRegionAs(String regionId, Map<String, String> loadedItems, OsmandRegions osmandRegions, String localizedName) {
WorldRegion worldRegion;
boolean hasRegion = loadedItems.containsKey(regionId);
if (hasRegion) {
worldRegion = new WorldRegion().init(regionId, osmandRegions, localizedName);
loadedItems.remove(regionId);
} else {
worldRegion = new WorldRegion().init(regionId, localizedName);
}
private void sortSubregions(WorldRegion region, Comparator<WorldRegion> comparator) {
Collections.sort(region.subregions, comparator);
for (WorldRegion r : region.subregions) {
if (r.subregions.size() > 0) {
sortSubregions(r, comparator);
}
}
}
private static WorldRegion createRegionAs(String regionId, Map<String, String> loadedItems,
OsmandRegions osmandRegions, String localizedName) {
WorldRegion worldRegion = new WorldRegion().init(regionId, osmandRegions, localizedName);
loadedItems.remove(regionId);
return worldRegion;
}
@ -291,10 +240,10 @@ public class WorldRegion {
String[] words = s.split(" ");
if (words[0].length() > 0) {
StringBuilder sb = new StringBuilder();
sb.append(Character.toUpperCase(words[0].charAt(0))).append(words[0].subSequence(1, words[0].length()).toString().toLowerCase());
sb.append(Algorithms.capitalizeFirstLetterAndLowercase(words[0]));
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].subSequence(1, words[i].length()).toString().toLowerCase());
sb.append(Algorithms.capitalizeFirstLetterAndLowercase(words[i]));
}
return sb.toString();
} else {
@ -315,9 +264,5 @@ public class WorldRegion {
return null;
}
public enum MapState {
NOT_DOWNLOADED,
DOWNLOADED,
OUTDATED
}
}

View file

@ -16,7 +16,7 @@ import net.osmand.map.TileSourceManager;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.SQLiteTileSource;
import net.osmand.plus.download.LocalIndexesFragment.LoadLocalIndexTask;
import net.osmand.plus.download.ui.LocalIndexesFragment.LoadLocalIndexTask;
import net.osmand.plus.voice.MediaCommandPlayerImpl;
import net.osmand.plus.voice.TTSCommandPlayerImpl;
import net.osmand.util.Algorithms;

View file

@ -3,8 +3,6 @@ package net.osmand.plus.download;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import net.osmand.access.AccessibleToast;
@ -12,9 +10,8 @@ import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.ActionBarProgressActivity;
import net.osmand.plus.download.items.ItemsListBuilder;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
@ -28,9 +25,9 @@ import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.widget.Toast;
public class BaseDownloadActivity extends ActionBarProgressActivity {
public class BaseDownloadActivity extends ActionBarProgressActivity implements DownloadEvents {
protected OsmandSettings settings;
public static DownloadIndexesThread downloadListIndexThread;
private static DownloadIndexesThread downloadListIndexThread;
protected Set<WeakReference<Fragment>> fragSet = new HashSet<>();
public static final int MAXIMUM_AVAILABLE_FREE_DOWNLOADS = 10;
@ -65,64 +62,23 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
}
// FIXME
public void onCategorizationFinished() {
@UiThread
public void downloadInProgress() {
}
@UiThread
public void updateDownloadList() {
public void downloadHasFinished() {
}
@UiThread
public void updateProgress(boolean updateOnlyProgress) {
public void newDownloadIndexes() {
}
public void downloadedIndexes() {
}
public void updateFragments() {
}
public void downloadListUpdated() {
}
/////// FIXME
public OsmandApplication getMyApplication() {
return (OsmandApplication) getApplication();
}
public ItemsListBuilder getItemsBuilder() {
return getItemsBuilder("", false);
}
public ItemsListBuilder getVoicePromptsBuilder() {
return getItemsBuilder("", true);
}
public ItemsListBuilder getItemsBuilder(String regionId, boolean voicePromptsOnly) {
if (downloadListIndexThread.getResourcesByRegions().size() > 0) {
ItemsListBuilder builder = new ItemsListBuilder(getMyApplication(), regionId, downloadListIndexThread.getResourcesByRegions(),
downloadListIndexThread.getVoiceRecItems(), downloadListIndexThread.getVoiceTTSItems());
if (!voicePromptsOnly) {
return builder.build();
} else {
return builder;
}
} else {
return null;
}
}
public List<IndexItem> getIndexItemsByRegion(WorldRegion region) {
if (downloadListIndexThread.getResourcesByRegions().size() > 0) {
return new LinkedList<>(downloadListIndexThread.getResourcesByRegions().get(region).values());
} else {
return new LinkedList<>();
}
}
public void downloadFilesCheck_3_ValidateSpace(final IndexItem... items) {
long szLong = 0;
int i = 0;
@ -155,7 +111,7 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
private void downloadFileCheck_Final_Run(IndexItem[] items) {
downloadListIndexThread.runDownloadFiles(items);
updateFragments();
downloadInProgress();
}

View file

@ -6,36 +6,27 @@ import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.activities.LocalIndexInfo;
import net.osmand.plus.activities.OsmAndListFragment;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.activities.TabActivity;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.items.ActiveDownloadsDialogFragment;
import net.osmand.plus.download.items.DialogDismissListener;
import net.osmand.plus.download.items.RegionItemsFragment;
import net.osmand.plus.download.items.SearchDialogFragment;
import net.osmand.plus.download.items.WorldItemsFragment;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import net.osmand.plus.download.ui.ActiveDownloadsDialogFragment;
import net.osmand.plus.download.ui.DownloadResourceGroupFragment;
import net.osmand.plus.download.ui.LocalIndexesFragment;
import net.osmand.plus.download.ui.UpdatesIndexFragment;
import net.osmand.plus.views.controls.PagerSlidingTabStrip;
import org.apache.commons.logging.Log;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StatFs;
import android.support.annotation.UiThread;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
@ -43,14 +34,11 @@ import android.support.v4.view.ViewPager;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
public class DownloadActivity extends BaseDownloadActivity implements DialogDismissListener {
public class DownloadActivity extends BaseDownloadActivity {
private List<LocalIndexInfo> localIndexInfos = new ArrayList<>();
List<TabActivity.TabItem> mTabs = new ArrayList<TabActivity.TabItem>();
@ -64,15 +52,14 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
public static final MessageFormat formatGb = new MessageFormat("{0, number,#.##} GB", Locale.US);
private BannerAndDownloadFreeVersion visibleBanner;
private ActiveDownloadsDialogFragment activeDownloads;
@Override
protected void onCreate(Bundle savedInstanceState) {
getMyApplication().applyTheme(this);
super.onCreate(savedInstanceState);
if (downloadListIndexThread.getCachedIndexFiles() == null || !downloadListIndexThread.isDownloadedFromInternet()) {
downloadListIndexThread.runReloadIndexFiles();
DownloadResources indexes = getDownloadThread().getIndexes();
if (!indexes.isDownloadedFromInternet) {
getDownloadThread().runReloadIndexFiles();
}
setContentView(R.layout.download);
@ -85,12 +72,13 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
currentTab = 2;
}
}
visibleBanner = new BannerAndDownloadFreeVersion(findViewById(R.id.mainLayout), this);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerSlidingTabStrip mSlidingTabLayout = (PagerSlidingTabStrip) findViewById(R.id.sliding_tabs);
mTabs.add(new TabActivity.TabItem(R.string.download_tab_downloads,
getString(R.string.download_tab_downloads), WorldItemsFragment.class));
getString(R.string.download_tab_downloads), DownloadResourceGroupFragment.class));
mTabs.add(new TabActivity.TabItem(R.string.download_tab_local,
getString(R.string.download_tab_local), LocalIndexesFragment.class));
mTabs.add(new TabActivity.TabItem(R.string.download_tab_updates,
@ -107,19 +95,14 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
final String filter = intent.getExtras().getString(FILTER_KEY);
final String filterCat = intent.getExtras().getString(FILTER_CAT);
}
registerFreeVersionBanner(findViewById(R.id.mainLayout));
}
public Map<String, String> getIndexActivatedFileNames() {
return downloadListIndexThread != null ? downloadListIndexThread.getIndexActivatedFileNames() : null;
}
@Override
protected void onResume() {
super.onResume();
getMyApplication().getAppCustomization().resumeActivity(DownloadActivity.class, this);
updateFragments();
downloadInProgress();
}
@ -150,129 +133,55 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
}
@Override
public void updateProgress(boolean updateOnlyProgress) {
BasicProgressAsyncTask<?, ?, ?, ?> basicProgressAsyncTask =
downloadListIndexThread.getCurrentRunningTask();
if (visibleBanner != null) {
final int countedDownloads = downloadListIndexThread.getCountedDownloads();
visibleBanner.updateProgress(countedDownloads, basicProgressAsyncTask);
}
if (!updateOnlyProgress) {
updateFragments();
}
}
@Override
public void updateDownloadList() {
@UiThread
public void downloadHasFinished() {
visibleBanner.updateBannerInProgress();
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f instanceof UpdatesIndexFragment) {
if (f.isAdded()) {
((UpdatesIndexFragment) f).updateItemsList();
}
if (f instanceof DownloadEvents && f.isAdded()) {
((DownloadEvents) f).downloadHasFinished();
}
}
}
@Override
public void onCategorizationFinished() {
@UiThread
public void downloadInProgress() {
visibleBanner.updateBannerInProgress();
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f instanceof WorldItemsFragment) {
if (f.isAdded()) {
((WorldItemsFragment) f).onCategorizationFinished();
}
} else if (f instanceof SearchDialogFragment) {
if (f.isAdded()) {
((SearchDialogFragment) f).onCategorizationFinished();
}
if (f instanceof DownloadEvents && f.isAdded()) {
((DownloadEvents) f).downloadInProgress();
}
}
}
@Override
public void downloadedIndexes() {
@UiThread
public void newDownloadIndexes() {
visibleBanner.updateBannerInProgress();
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f instanceof LocalIndexesFragment) {
if (f.isAdded()) {
((LocalIndexesFragment) f).reloadData();
}
if (f instanceof DownloadEvents && f.isAdded()) {
((DownloadEvents) f).newDownloadIndexes();
}
}
downloadHasFinished();
}
public void setActiveDownloads(ActiveDownloadsDialogFragment activeDownloads) {
this.activeDownloads = activeDownloads;
}
@Override
public void updateFragments() {
if(activeDownloads != null) {
activeDownloads.refresh();
}
// FIXME
//((DownloadActivity) getActivity()).updateDescriptionTextWithSize(getView());
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
notifyUpdateDataSetChanged(f);
if(f instanceof RegionItemsFragment) {
Fragment innerFragment = ((RegionItemsFragment)f).getChildFragmentManager().findFragmentById(R.id.fragmentContainer);
notifyUpdateDataSetChanged(innerFragment);
}
}
}
private void notifyUpdateDataSetChanged(Fragment f) {
if (f != null && f.isAdded()) {
if(f instanceof OsmandExpandableListFragment) {
ExpandableListAdapter adapter = ((OsmandExpandableListFragment) f).getAdapter();
if(adapter instanceof BaseExpandableListAdapter) {
((BaseExpandableListAdapter)adapter).notifyDataSetChanged();
}
}
if(f instanceof OsmAndListFragment) {
ArrayAdapter<?> adapter = ((OsmAndListFragment) f).getAdapter();
if(adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
}
public boolean isLightActionBar() {
return ((OsmandApplication) getApplication()).getSettings().isLightActionBar();
}
public Map<String, String> getIndexFileNames() {
return downloadListIndexThread != null ? downloadListIndexThread.getIndexFileNames() : null;
}
public List<IndexItem> getIndexFiles() {
return downloadListIndexThread != null ? downloadListIndexThread.getCachedIndexFiles() : null;
}
public void registerFreeVersionBanner(View view) {
visibleBanner = new BannerAndDownloadFreeVersion(view, this);
updateProgress(true);
}
public void showDialog(FragmentActivity activity, DialogFragment fragment) {
fragment.show(activity.getSupportFragmentManager(), "dialog");
}
@Override
public void onDialogDismissed() {
registerFreeVersionBanner(findViewById(R.id.mainLayout));
}
private static class ToggleCollapseFreeVersionBanner implements View.OnClickListener {
private final View freeVersionDescriptionTextView;
private final View buttonsLinearLayout;
@ -310,12 +219,12 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
private final TextView downloadsLeftTextView;
private final View laterButton;
private final FragmentActivity ctx;
private final DownloadActivity ctx;
private final OsmandApplication application;
private final boolean shouldShowFreeVersionBanner;
private final View freeVersionBannerTitle;
public BannerAndDownloadFreeVersion(View view, final FragmentActivity ctx) {
public BannerAndDownloadFreeVersion(View view, final DownloadActivity ctx) {
this.ctx = ctx;
application = (OsmandApplication) ctx.getApplicationContext();
freeVersionBanner = view.findViewById(R.id.freeVersionBanner);
@ -336,6 +245,7 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
initFreeVersionBanner();
updateFreeVersionBanner();
updateBannerInProgress();
downloadProgressLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@ -344,7 +254,13 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
});
}
public void updateProgress(int countedDownloads,
public void updateBannerInProgress() {
BasicProgressAsyncTask<?, ?, ?, ?> basicProgressAsyncTask = ctx.getDownloadThread().getCurrentRunningTask();
final int countedDownloads = ctx.getDownloadThread().getCountedDownloads();
updateProgress(countedDownloads, basicProgressAsyncTask);
}
private void updateProgress(int countedDownloads,
BasicProgressAsyncTask<?, ?, ?, ?> basicProgressAsyncTask) {
final boolean isFinished = basicProgressAsyncTask == null
|| basicProgressAsyncTask.getStatus() == AsyncTask.Status.FINISHED;
@ -397,13 +313,14 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
}
private void updateFreeVersionBanner() {
if (!shouldShowFreeVersionBanner) return;
if (!shouldShowFreeVersionBanner) {
return;
}
setMinimizedFreeVersionBanner(false);
OsmandSettings settings = application.getSettings();
final Integer mapsDownloaded = settings.NUMBER_OF_FREE_DOWNLOADS.get();
downloadsLeftProgressBar.setProgress(mapsDownloaded);
int downloadsLeft = BaseDownloadActivity.MAXIMUM_AVAILABLE_FREE_DOWNLOADS
- mapsDownloaded;
int downloadsLeft = BaseDownloadActivity.MAXIMUM_AVAILABLE_FREE_DOWNLOADS - mapsDownloaded;
downloadsLeft = Math.max(downloadsLeft, 0);
if (downloadsLeft <= 0) {
laterButton.setVisibility(View.GONE);

View file

@ -1,8 +1,15 @@
package net.osmand.plus.download;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import net.osmand.AndroidUtils;
import net.osmand.IndexConstants;
@ -15,18 +22,9 @@ import net.osmand.util.Algorithms;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT;
public class DownloadActivityType implements Parcelable {
public class DownloadActivityType {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
private static Map<String, DownloadActivityType> byTag = new HashMap<>();
@ -64,7 +62,6 @@ public class DownloadActivityType implements Parcelable {
public DownloadActivityType(int stringResource, String tag, int orderIndex) {
this.stringResource = stringResource;
this.tag = tag;
this.orderIndex = orderIndex;
byTag.put(tag, this);
iconResource = R.drawable.ic_map;
}
@ -371,32 +368,4 @@ public class DownloadActivityType implements Parcelable {
return fileName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.stringResource);
dest.writeInt(this.iconResource);
dest.writeString(this.tag);
}
protected DownloadActivityType(Parcel in) {
this.stringResource = in.readInt();
this.iconResource = in.readInt();
this.tag = in.readString();
byTag.put(tag, this);
}
public static final Parcelable.Creator<DownloadActivityType> CREATOR = new Parcelable.Creator<DownloadActivityType>() {
public DownloadActivityType createFromParcel(Parcel source) {
return new DownloadActivityType(source);
}
public DownloadActivityType[] newArray(int size) {
return new DownloadActivityType[size];
}
};
}

View file

@ -1,31 +0,0 @@
package net.osmand.plus.download;
import java.io.File;
public class DownloadEntry {
public long dateModified;
public double sizeMB;
public File targetFile;
public boolean zipStream;
public boolean unzipFolder;
public File fileToDownload;
public String baseName;
public String urlToDownload;
public boolean isAsset;
public String assetName;
public DownloadActivityType type;
public DownloadEntry() {
}
public DownloadEntry(String assetName, String fileName, long dateModified) {
this.dateModified = dateModified;
targetFile = new File(fileName);
this.assetName = assetName;
isAsset = true;
}
}

View file

@ -200,7 +200,7 @@ public class DownloadFileHelper {
return ctx.getSettings().isWifiConnected();
}
public boolean downloadFile(DownloadEntry de, IProgress progress,
public boolean downloadFile(IndexItem.DownloadEntry de, IProgress progress,
List<File> toReIndex, DownloadFileShowWarning showWarningCallback, boolean forceWifi) throws InterruptedException {
try {
final List<InputStream> downloadInputStreams = new ArrayList<InputStream>();
@ -235,7 +235,7 @@ public class DownloadFileHelper {
}
}
private void copyVoiceConfig(DownloadEntry de) {
private void copyVoiceConfig(IndexItem.DownloadEntry de) {
File f = ctx.getAppPath("/voice/" + de.baseName + "/_config.p");
if (f.exists()) try {
InputStream is = ctx.getAssets().open("voice/" + de.baseName + "/config.p");
@ -252,7 +252,7 @@ public class DownloadFileHelper {
}
}
private void unzipFile(DownloadEntry de, IProgress progress, List<InputStream> is) throws IOException {
private void unzipFile(IndexItem.DownloadEntry de, IProgress progress, List<InputStream> is) throws IOException {
CountingMultiInputStream fin = new CountingMultiInputStream(is);
int len = (int) fin.available();
int mb = (int) (len / (1024f*1024f));
@ -308,7 +308,7 @@ public class DownloadFileHelper {
fin.close();
}
private void copyFile(DownloadEntry de, IProgress progress,
private void copyFile(IndexItem.DownloadEntry de, IProgress progress,
CountingMultiInputStream countIS, int length, InputStream toRead, File targetFile)
throws IOException {
targetFile.getParentFile().mkdirs();

View file

@ -1,36 +1,23 @@
package net.osmand.plus.download;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import net.osmand.Collator;
import net.osmand.IndexConstants;
import net.osmand.OsmAndCollator;
import net.osmand.PlatformUtil;
import net.osmand.access.AccessibleToast;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings.OsmandPreference;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.DownloadFileHelper.DownloadFileShowWarning;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.AssetIndexItem;
import net.osmand.plus.helpers.DatabaseHelper;
import net.osmand.plus.resources.ResourceManager;
import net.osmand.util.Algorithms;
@ -57,7 +44,7 @@ public class DownloadIndexesThread {
private final static Log LOG = PlatformUtil.getLog(DownloadIndexesThread.class);
private final Context ctx;
private OsmandApplication app;
private java.text.DateFormat dateFormat;
private BaseDownloadActivity uiActivity = null;
private DatabaseHelper dbHelper;
private DownloadFileHelper downloadFileHelper;
@ -66,33 +53,66 @@ public class DownloadIndexesThread {
private IndexItem currentDownloadingItem = null;
private int currentDownloadingItemProgress = 0;
private DownloadResources indexes;
private DownloadIndexes indexes = new DownloadIndexes();
public static class DownloadIndexes {
Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions = new HashMap<>();
List<IndexItem> voiceRecItems = new LinkedList<>();
List<IndexItem> voiceTTSItems = new LinkedList<>();
IndexFileList indexFiles = null;
public interface DownloadEvents {
void newDownloadIndexes();
void downloadInProgress();
void downloadHasFinished();
}
private Map<String, String> indexFileNames = new LinkedHashMap<>();
private Map<String, String> indexActivatedFileNames = new LinkedHashMap<>();
private List<IndexItem> itemsToUpdate = new ArrayList<>();
public DownloadIndexesThread(Context ctx) {
this.ctx = ctx;
app = (OsmandApplication) ctx.getApplicationContext();
indexes = new DownloadResources(app);
updateLoadedFiles();
downloadFileHelper = new DownloadFileHelper(app);
dateFormat = app.getResourceManager().getDateFormat();
dbHelper = new DatabaseHelper(app);
}
public void updateLoadedFiles() {
indexes.initAlreadyLoadedFiles();
}
/// UI notifications methods
public void setUiActivity(BaseDownloadActivity uiActivity) {
this.uiActivity = uiActivity;
}
@UiThread
protected void downloadInProgress() {
if (uiActivity != null) {
uiActivity.downloadInProgress();
}
}
@UiThread
protected void downloadHasFinished() {
if (uiActivity != null) {
uiActivity.downloadHasFinished();
}
}
@UiThread
protected void newDownloadIndexes() {
if (uiActivity != null) {
uiActivity.newDownloadIndexes();
}
}
// PUBLIC API
public DownloadResources getIndexes() {
return indexes;
}
public List<IndexItem> getCurrentDownloadingItems() {
List<IndexItem> res = new ArrayList<IndexItem>();
IndexItem ii = currentDownloadingItem;
@ -128,163 +148,6 @@ public class DownloadIndexesThread {
return i;
}
// FIXME
public List<IndexItem> getCachedIndexFiles() {
return indexes.indexFiles != null ? indexes.indexFiles.getIndexFiles() : null;
}
// FIXME
public Map<String, String> getIndexFileNames() {
return indexFileNames;
}
// FIXME
public Map<String, String> getIndexActivatedFileNames() {
return indexActivatedFileNames;
}
public void updateLoadedFiles() {
Map<String, String> indexActivatedFileNames = app.getResourceManager().getIndexFileNames();
listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT,
indexActivatedFileNames);
Map<String, String> indexFileNames = app.getResourceManager().getIndexFileNames();
listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT,
indexFileNames);
app.getAppCustomization().updatedLoadedFiles(indexFileNames, indexActivatedFileNames);
listWithAlternatives(dateFormat, app.getAppPath(IndexConstants.TILES_INDEX_DIR),
IndexConstants.SQLITE_EXT, indexFileNames);
app.getResourceManager().getBackupIndexes(indexFileNames);
this.indexFileNames = indexFileNames;
this.indexActivatedFileNames = indexActivatedFileNames;
//updateFilesToDownload();
}
public Map<String, String> getDownloadedIndexFileNames() {
return indexFileNames;
}
public boolean isDownloadedFromInternet() {
return indexes.indexFiles != null && indexes.indexFiles.isDownloadedFromInternet();
}
public List<IndexItem> getItemsToUpdate() {
return itemsToUpdate;
}
public Map<WorldRegion, Map<String, IndexItem>> getResourcesByRegions() {
return indexes.resourcesByRegions;
}
public List<IndexItem> getVoiceRecItems() {
return indexes.voiceRecItems;
}
public List<IndexItem> getVoiceTTSItems() {
return indexes.voiceTTSItems;
}
private boolean prepareData(List<IndexItem> resources,
Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions,
List<IndexItem> voiceRecItems, List<IndexItem> voiceTTSItems) {
List<IndexItem> resourcesInRepository;
if (resources != null) {
resourcesInRepository = resources;
} else {
resourcesInRepository = DownloadActivity.downloadListIndexThread.getCachedIndexFiles();
}
if (resourcesInRepository == null) {
return false;
}
for (WorldRegion region : app.getWorldRegion().getFlattenedSubregions()) {
processRegion(resourcesInRepository, resourcesByRegions, voiceRecItems, voiceTTSItems, false, region);
}
processRegion(resourcesInRepository, resourcesByRegions, voiceRecItems, voiceTTSItems, true, app.getWorldRegion());
final Collator collator = OsmAndCollator.primaryCollator();
final OsmandRegions osmandRegions = app.getRegions();
Collections.sort(voiceRecItems, new Comparator<IndexItem>() {
@Override
public int compare(IndexItem lhs, IndexItem rhs) {
return collator.compare(lhs.getVisibleName(app.getApplicationContext(), osmandRegions),
rhs.getVisibleName(app.getApplicationContext(), osmandRegions));
}
});
Collections.sort(voiceTTSItems, new Comparator<IndexItem>() {
@Override
public int compare(IndexItem lhs, IndexItem rhs) {
return collator.compare(lhs.getVisibleName(app.getApplicationContext(), osmandRegions),
rhs.getVisibleName(app.getApplicationContext(), osmandRegions));
}
});
return true;
}
// FIXME argument list
private void processRegion(List<IndexItem> resourcesInRepository, Map<WorldRegion,
Map<String, IndexItem>> resourcesByRegions,
List<IndexItem> voiceRecItems, List<IndexItem> voiceTTSItems,
boolean processVoiceFiles, WorldRegion region) {
String downloadsIdPrefix = region.getDownloadsIdPrefix();
Map<String, IndexItem> regionResources = new HashMap<>();
Set<DownloadActivityType> typesSet = new TreeSet<>(new Comparator<DownloadActivityType>() {
@Override
public int compare(DownloadActivityType dat1, DownloadActivityType dat2) {
return dat1.getTag().compareTo(dat2.getTag());
}
});
for (IndexItem resource : resourcesInRepository) {
if (processVoiceFiles) {
if (resource.getSimplifiedFileName().endsWith(".voice.zip")) {
voiceRecItems.add(resource);
continue;
} else if (resource.getSimplifiedFileName().contains(".ttsvoice.zip")) {
voiceTTSItems.add(resource);
continue;
}
}
if (!resource.getSimplifiedFileName().startsWith(downloadsIdPrefix)) {
continue;
}
if (resource.type == DownloadActivityType.NORMAL_FILE
|| resource.type == DownloadActivityType.ROADS_FILE) {
if (resource.isAlreadyDownloaded(indexFileNames)) {
region.processNewMapState(checkIfItemOutdated(resource)
? WorldRegion.MapState.OUTDATED : WorldRegion.MapState.DOWNLOADED);
} else {
region.processNewMapState(WorldRegion.MapState.NOT_DOWNLOADED);
}
}
typesSet.add(resource.getType());
regionResources.put(resource.getSimplifiedFileName(), resource);
}
if (region.getSuperregion() != null && region.getSuperregion().getSuperregion() != app.getWorldRegion()) {
if (region.getSuperregion().getResourceTypes() == null) {
region.getSuperregion().setResourceTypes(typesSet);
} else {
region.getSuperregion().getResourceTypes().addAll(typesSet);
}
}
region.setResourceTypes(typesSet);
resourcesByRegions.put(region, regionResources);
}
private boolean checkRunning() {
if (getCurrentRunningTask() != null) {
AccessibleToast.makeText(app, R.string.wait_current_task_finished, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void runReloadIndexFiles() {
if (checkRunning()) {
return;
@ -309,123 +172,11 @@ public class DownloadIndexesThread {
public void cancelDownload(IndexItem item) {
if(currentDownloadingItem == item) {
downloadFileHelper.setInterruptDownloading(true);;
}
// TODO Auto-generated method stub
}
private <P> void execute(BasicProgressAsyncTask<?, P, ?, ?> task, P... indexItems) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, indexItems);
} else {
task.execute(indexItems);
indexItemDownloading.remove(item);
}
}
private void prepareFilesToUpdate() {
List<IndexItem> filtered = getCachedIndexFiles();
if (filtered != null) {
itemsToUpdate.clear();
for (IndexItem item : filtered) {
boolean outdated = checkIfItemOutdated(item);
//include only activated files here
if (outdated && indexActivatedFileNames.containsKey(item.getTargetFileName())) {
itemsToUpdate.add(item);
}
}
}
}
@UiThread
private void notifyFilesToUpdateChanged() {
List<IndexItem> filtered = getCachedIndexFiles();
if (filtered != null) {
if (uiActivity != null) {
uiActivity.updateDownloadList();
}
}
}
public boolean checkIfItemOutdated(IndexItem item) {
boolean outdated = false;
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null &&
!date.equals(indexactivateddate) &&
!date.equals(indexfilesdate)) {
if ((item.getType() == DownloadActivityType.NORMAL_FILE && !item.extra) ||
item.getType() == DownloadActivityType.ROADS_FILE ||
item.getType() == DownloadActivityType.WIKIPEDIA_FILE ||
item.getType() == DownloadActivityType.SRTM_COUNTRY_FILE) {
outdated = true;
} else {
long itemSize = item.getContentSize();
long oldItemSize = 0;
if (item.getType() == DownloadActivityType.VOICE_FILE) {
if (item instanceof AssetIndexItem) {
File file = new File(((AssetIndexItem) item).getDestFile());
oldItemSize = file.length();
} else {
File fl = new File(item.getType().getDownloadFolder(app, item), sfName + "/_config.p");
if (fl.exists()) {
oldItemSize = fl.length();
try {
InputStream is = ctx.getAssets().open("voice/" + sfName + "/config.p");
if (is != null) {
itemSize = is.available();
is.close();
}
} catch (IOException e) {
}
}
}
} else {
oldItemSize = app.getAppPath(item.getTargetFileName()).length();
}
if (itemSize != oldItemSize) {
outdated = true;
}
}
}
return outdated;
}
private void updateFilesToUpdate() {
List<IndexItem> stillUpdate = new ArrayList<IndexItem>();
for (IndexItem item : itemsToUpdate) {
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null &&
!date.equals(indexactivateddate) &&
!date.equals(indexfilesdate) &&
indexActivatedFileNames.containsKey(sfName)) {
stillUpdate.add(item);
}
}
itemsToUpdate = stillUpdate;
if (uiActivity != null) {
uiActivity.updateDownloadList();
}
}
public boolean isDownloadRunning() {
for (int i = 0; i < currentRunningTask.size(); i++) {
if (currentRunningTask.get(i) instanceof DownloadIndexesAsyncTask) {
return true;
}
}
return false;
}
public IndexItem getCurrentDownloadingItem() {
return currentDownloadingItem;
@ -435,7 +186,6 @@ public class DownloadIndexesThread {
return currentDownloadingItemProgress;
}
// FIXME deprecated
public BasicProgressAsyncTask<?, ?, ?, ?> getCurrentRunningTask() {
for (int i = 0; i < currentRunningTask.size(); ) {
if (currentRunningTask.get(i).getStatus() == Status.FINISHED) {
@ -450,6 +200,7 @@ public class DownloadIndexesThread {
return null;
}
@SuppressWarnings("deprecation")
public double getAvailableSpace() {
File dir = app.getAppPath("").getParentFile();
double asz = -1;
@ -460,43 +211,28 @@ public class DownloadIndexesThread {
return asz;
}
/// PRIVATE IMPL
public Map<String, String> listWithAlternatives(final java.text.DateFormat dateFormat, File file, final String ext,
final Map<String, String> files) {
if (file.isDirectory()) {
file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(ext)) {
String date = dateFormat.format(findFileInDir(new File(dir, filename)).lastModified());
files.put(filename, date);
private boolean checkRunning() {
if (getCurrentRunningTask() != null) {
AccessibleToast.makeText(app, R.string.wait_current_task_finished, Toast.LENGTH_SHORT).show();
return true;
} else {
}
return false;
}
}
});
@SuppressWarnings("unchecked")
private <P> void execute(BasicProgressAsyncTask<?, P, ?, ?> task, P... indexItems) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, indexItems);
} else {
task.execute(indexItems);
}
return files;
}
public File findFileInDir(File file) {
if(file.isDirectory()) {
File[] lf = file.listFiles();
if(lf != null) {
for(File f : lf) {
if(f.isFile()) {
return f;
}
}
}
}
return file;
}
public class ReloadIndexesTask extends BasicProgressAsyncTask<Void, Void, Void, DownloadIndexes> {
private class ReloadIndexesTask extends BasicProgressAsyncTask<Void, Void, Void, DownloadResources> {
public ReloadIndexesTask(Context ctx) {
super(ctx);
@ -510,33 +246,26 @@ public class DownloadIndexesThread {
}
@Override
protected DownloadIndexes doInBackground(Void... params) {
DownloadIndexes result = new DownloadIndexes();
IndexFileList indexFileList = DownloadOsmandIndexesHelper.getIndexesList(ctx);
result.indexFiles = indexFileList;
protected DownloadResources doInBackground(Void... params) {
DownloadResources result = new DownloadResources(app);
DownloadOsmandIndexesHelper.IndexFileList indexFileList = DownloadOsmandIndexesHelper.getIndexesList(ctx);
if (indexFileList != null) {
updateLoadedFiles();
prepareFilesToUpdate();
prepareData(indexFileList.getIndexFiles(), result.resourcesByRegions, result.voiceRecItems, result.voiceTTSItems);
result.isDownloadedFromInternet = indexFileList.isDownloadedFromInternet();
result.mapVersionIsIncreased = indexFileList.isIncreasedMapVersion();
result.prepareData(indexFileList.getIndexFiles());
}
return result;
}
protected void onPostExecute(DownloadIndexes result) {
protected void onPostExecute(DownloadResources result) {
indexes = result;
notifyFilesToUpdateChanged();
if (result.indexFiles != null) {
if (result.indexFiles.isIncreasedMapVersion()) {
if (result.mapVersionIsIncreased) {
showWarnDialog();
}
} else {
} else if (!result.isDownloadedFromInternet) {
AccessibleToast.makeText(ctx, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
currentRunningTask.remove(this);
if (uiActivity != null) {
uiActivity.updateProgress(false);
uiActivity.onCategorizationFinished();
}
newDownloadIndexes();
}
private void showWarnDialog() {
@ -564,15 +293,12 @@ public class DownloadIndexesThread {
@Override
protected void updateProgress(boolean updateOnlyProgress, Void tag) {
if (uiActivity != null) {
uiActivity.updateProgress(updateOnlyProgress);
}
downloadInProgress();
}
}
public class DownloadIndexesAsyncTask extends BasicProgressAsyncTask<IndexItem, IndexItem, Object, String> implements DownloadFileShowWarning {
private class DownloadIndexesAsyncTask extends BasicProgressAsyncTask<IndexItem, IndexItem, Object, String> implements DownloadFileShowWarning {
private OsmandPreference<Integer> downloads;
@ -594,10 +320,9 @@ public class DownloadIndexesThread {
protected void onProgressUpdate(Object... values) {
for (Object o : values) {
if (o instanceof IndexItem) {
if (uiActivity != null) {
uiActivity.updateFragments();
IndexItem item = (IndexItem) o;
String name = item.getBasename();
item.setDownloaded(true);
long count = dbHelper.getCount(name, DatabaseHelper.DOWNLOAD_ENTRY) + 1;
DatabaseHelper.HistoryDownloadEntry entry = new DatabaseHelper.HistoryDownloadEntry(name, count);
if (count == 1) {
@ -605,7 +330,6 @@ public class DownloadIndexesThread {
} else {
dbHelper.update(entry, DatabaseHelper.DOWNLOAD_ENTRY);
}
}
} else if (o instanceof String) {
String message = (String) o;
if (!message.equals("I/O error occurred : Interrupted")) {
@ -613,13 +337,10 @@ public class DownloadIndexesThread {
!message.equals(uiActivity.getString(R.string.shared_string_download_successful))) {
AccessibleToast.makeText(ctx, message, Toast.LENGTH_LONG).show();
}
} else {
if (uiActivity != null) {
uiActivity.updateProgress(true);
}
}
}
}
downloadInProgress();
super.onProgressUpdate(values);
}
@ -647,16 +368,15 @@ public class DownloadIndexesThread {
if (mainView != null) {
mainView.setKeepScreenOn(false);
}
uiActivity.downloadedIndexes();
}
currentRunningTask.remove(this);
if (uiActivity != null) {
uiActivity.updateProgress(false);
}
updateFilesToUpdate();
downloadHasFinished();
indexes.updateFilesToUpdate();
}
@Override
protected String doInBackground(IndexItem... filesToDownload) {
try {
@ -699,7 +419,6 @@ public class DownloadIndexesThread {
currentDownloadingItemProgress = 0;
}
String warn = reindexFiles(filesToReindex);
updateLoadedFiles();
return warn;
} catch (InterruptedException e) {
LOG.info("Download Interrupted");
@ -777,7 +496,7 @@ public class DownloadIndexesThread {
public boolean downloadFile(IndexItem item, List<File> filesToReindex, boolean forceWifi)
throws InterruptedException {
downloadFileHelper.setInterruptDownloading(false);
DownloadEntry de = item.createDownloadEntry(app);
IndexItem.DownloadEntry de = item.createDownloadEntry(app);
boolean res = false;
if(de == null) {
return res;
@ -804,7 +523,7 @@ public class DownloadIndexesThread {
@Override
protected void updateProgress(boolean updateOnlyProgress, IndexItem tag) {
currentDownloadingItemProgress = getProgressPercentage();
uiActivity.updateProgress(true);
downloadInProgress();
}
}

View file

@ -1,28 +1,28 @@
package net.osmand.plus.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import net.osmand.AndroidUtils;
import net.osmand.IndexConstants;
import net.osmand.PlatformUtil;
import net.osmand.osm.io.NetworkUtils;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
@ -32,6 +32,79 @@ import android.content.res.AssetManager;
public class DownloadOsmandIndexesHelper {
private final static Log log = PlatformUtil.getLog(DownloadOsmandIndexesHelper.class);
public static class IndexFileList implements Serializable {
private static final long serialVersionUID = 1L;
private boolean downloadedFromInternet = false;
IndexItem basemap;
ArrayList<IndexItem> indexFiles = new ArrayList<IndexItem>();
private String mapversion;
private Comparator<IndexItem> comparator = new Comparator<IndexItem>(){
@Override
public int compare(IndexItem o1, IndexItem o2) {
String object1 = o1.getFileName();
String object2 = o2.getFileName();
if(object1.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
if(object2.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
return object1.compareTo(object2);
} else {
return -1;
}
} else if(object2.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
return 1;
}
return object1.compareTo(object2);
}
};
public void setDownloadedFromInternet(boolean downloadedFromInternet) {
this.downloadedFromInternet = downloadedFromInternet;
}
public boolean isDownloadedFromInternet() {
return downloadedFromInternet;
}
public void setMapVersion(String mapversion) {
this.mapversion = mapversion;
}
@SuppressLint("DefaultLocale")
public void add(IndexItem indexItem) {
indexFiles.add(indexItem);
if(indexItem.getFileName().toLowerCase().startsWith("world_basemap")) {
basemap = indexItem;
}
}
public void sort(){
Collections.sort(indexFiles, comparator);
}
public boolean isAcceptable() {
return (indexFiles != null && !indexFiles.isEmpty()) || (mapversion != null);
}
public List<IndexItem> getIndexFiles() {
return indexFiles;
}
public IndexItem getBasemap() {
return basemap;
}
public boolean isIncreasedMapVersion() {
try {
int mapVersionInList = Integer.parseInt(mapversion);
return IndexConstants.BINARY_MAP_VERSION < mapVersionInList;
} catch (NumberFormatException e) {
//ignore this...
}
return false;
}
}
public static IndexFileList getIndexesList(Context ctx) {
PackageManager pm = ctx.getPackageManager();
@ -68,7 +141,6 @@ public class DownloadOsmandIndexesHelper {
OsmandSettings settings) {
try {
String ext = DownloadActivityType.addVersionToExt(IndexConstants.TTSVOICE_INDEX_EXT_ZIP, IndexConstants.TTSVOICE_VERSION);
String extvoice = DownloadActivityType.addVersionToExt(IndexConstants.VOICE_INDEX_EXT_ZIP, IndexConstants.VOICE_VERSION);
File voicePath = settings.getContext().getAppPath(IndexConstants.VOICE_INDEX_DIR);
// list = amanager.list("voice");
String date = "";

View file

@ -0,0 +1,224 @@
package net.osmand.plus.download;
import android.annotation.SuppressLint;
import android.content.Context;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import net.osmand.OsmAndCollator;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
@SuppressLint("DefaultLocale")
public class DownloadResourceGroup {
private final DownloadResourceGroupType type;
private final DownloadResourceGroup parentGroup;
// ASSERT: individualResources are not empty if and only if groups are empty
private final List<IndexItem> individualResources;
private final List<DownloadResourceGroup> groups;
protected final String id;
protected WorldRegion region;
public enum DownloadResourceGroupType {
// headers
WORLD_MAPS(R.string.world_maps), REGION_MAPS(R.string.region_maps), VOICE_GROUP(R.string.voices), SUBREGIONS(
R.string.regions), VOICE_HEADER_REC(R.string.index_name_voice), VOICE_HEADER_TTS(
R.string.index_name_tts_voice),
// screen items
VOICE_REC(R.string.index_name_voice), VOICE_TTS(R.string.index_name_tts_voice), WORLD(-1), REGION(-1);
final int resId;
private DownloadResourceGroupType(int resId) {
this.resId = resId;
}
public boolean isScreen() {
return this == WORLD || this == REGION || this == VOICE_TTS || this == VOICE_REC;
}
public String getDefaultId() {
return name().toLowerCase();
}
public int getResourceId() {
return resId;
}
public boolean containsIndexItem() {
return isHeader() && this != SUBREGIONS && this != VOICE_GROUP;
}
public boolean isHeader() {
return this == VOICE_HEADER_REC || this == VOICE_HEADER_TTS || this == SUBREGIONS || this == WORLD_MAPS
|| this == REGION_MAPS || this == VOICE_GROUP;
}
}
public DownloadResourceGroup(DownloadResourceGroup parentGroup, DownloadResourceGroupType type) {
this(parentGroup, type, type.getDefaultId());
}
public DownloadResourceGroup(DownloadResourceGroup parentGroup, DownloadResourceGroupType type, String id) {
boolean flat = type.containsIndexItem();
if (flat) {
this.individualResources = new ArrayList<IndexItem>();
this.groups = null;
} else {
this.individualResources = null;
this.groups = new ArrayList<DownloadResourceGroup>();
}
this.id = id;
this.type = type;
this.parentGroup = parentGroup;
}
public void trimEmptyGroups() {
if(groups != null) {
for(DownloadResourceGroup gr : groups) {
gr.trimEmptyGroups();
}
Iterator<DownloadResourceGroup> gr = groups.iterator();
while(gr.hasNext()) {
DownloadResourceGroup group = gr.next();
if(group.isEmpty()) {
gr.remove();
}
}
}
}
public void addGroup(DownloadResourceGroup g) {
if(type.isScreen()) {
if(!g.type.isHeader()) {
throw new UnsupportedOperationException("Trying to add " + g.getUniqueId() + " to " + getUniqueId());
}
}
if(type.isHeader()) {
if(!g.type.isScreen()) {
throw new UnsupportedOperationException("Trying to add " + g.getUniqueId() + " to " + getUniqueId());
}
}
groups.add(g);
if (g.individualResources != null) {
final net.osmand.Collator collator = OsmAndCollator.primaryCollator();
final OsmandApplication app = getRoot().app;
final OsmandRegions osmandRegions = app.getRegions();
Collections.sort(g.individualResources, new Comparator<IndexItem>() {
@Override
public int compare(IndexItem lhs, IndexItem rhs) {
return collator.compare(lhs.getVisibleName(app.getApplicationContext(), osmandRegions),
rhs.getVisibleName(app.getApplicationContext(), osmandRegions));
}
});
}
}
public void addItem(IndexItem i) {
individualResources.add(i);
}
public boolean isEmpty() {
return isEmpty(individualResources) && isEmpty(groups);
}
private boolean isEmpty(List<?> l) {
return l == null || l.isEmpty();
}
public DownloadResourceGroup getParentGroup() {
return parentGroup;
}
public List<DownloadResourceGroup> getGroups() {
return groups;
}
public int size() {
return groups != null ? groups.size() : individualResources.size();
}
public DownloadResourceGroup getGroupByIndex(int ind) {
if(groups != null && ind < groups.size()) {
return groups.get(ind);
}
return null;
}
public IndexItem getItemByIndex(int ind) {
if(individualResources != null && ind < individualResources.size()) {
return individualResources.get(ind);
}
return null;
}
public DownloadResources getRoot() {
if (this instanceof DownloadResources) {
return (DownloadResources) this;
} else if (parentGroup != null) {
return parentGroup.getRoot();
}
return null;
}
public DownloadResourceGroupType getType() {
return type;
}
public DownloadResourceGroup getGroupById(String uid) {
String[] lst = uid.split("\\#");
return getGroupById(lst, 0);
}
public List<IndexItem> getIndividualResources() {
return individualResources;
}
public WorldRegion getRegion() {
return region;
}
private DownloadResourceGroup getGroupById(String[] lst, int subInd) {
if (lst.length > subInd && lst[subInd].equals(id)) {
if (lst.length == subInd + 1) {
return this;
} else if (groups != null) {
for (DownloadResourceGroup rg : groups) {
DownloadResourceGroup r = rg.getGroupById(lst, subInd + 1);
if (r != null) {
return r;
}
}
}
}
return null;
}
public String getName(Context ctx) {
if (region != null) {
return region.getName();
} else if (type != null && type.resId != -1) {
return ctx.getString(type.resId);
} else {
return id;
}
}
public String getUniqueId() {
if (parentGroup == null) {
return id;
}
return parentGroup.getUniqueId() + "#" + id;
}
}

View file

@ -0,0 +1,277 @@
package net.osmand.plus.download;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.osmand.IndexConstants;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.AssetIndexItem;
public class DownloadResources extends DownloadResourceGroup {
public boolean isDownloadedFromInternet = false;
public boolean mapVersionIsIncreased = false;
public OsmandApplication app;
private Map<String, String> indexFileNames = new LinkedHashMap<>();
private Map<String, String> indexActivatedFileNames = new LinkedHashMap<>();
private List<IndexItem> rawResources;
private List<IndexItem> itemsToUpdate = new ArrayList<>();
//public static final String WORLD_BASEMAP_KEY = "world_basemap.obf.zip";
public static final String WORLD_SEAMARKS_KEY = "world_seamarks_basemap";
public DownloadResources(OsmandApplication app) {
super(null, DownloadResourceGroupType.WORLD, "");
this.region = app.getWorldRegion();
this.app = app;
}
public List<IndexItem> getItemsToUpdate() {
return itemsToUpdate;
}
public void initAlreadyLoadedFiles() {
java.text.DateFormat dateFormat = app.getResourceManager().getDateFormat();
Map<String, String> indexActivatedFileNames = app.getResourceManager().getIndexFileNames();
listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT, indexActivatedFileNames);
Map<String, String> indexFileNames = app.getResourceManager().getIndexFileNames();
listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT, indexFileNames);
app.getAppCustomization().updatedLoadedFiles(indexFileNames, indexActivatedFileNames);
listWithAlternatives(dateFormat, app.getAppPath(IndexConstants.TILES_INDEX_DIR), IndexConstants.SQLITE_EXT,
indexFileNames);
app.getResourceManager().getBackupIndexes(indexFileNames);
this.indexFileNames = indexFileNames;
this.indexActivatedFileNames = indexActivatedFileNames;
prepareFilesToUpdate();
}
public boolean checkIfItemOutdated(IndexItem item, java.text.DateFormat format) {
boolean outdated = false;
String sfName = item.getTargetFileName();
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
item.setDownloaded(false);
item.setOutdated(false);
if(indexactivateddate == null && indexfilesdate == null) {
return outdated;
}
item.setDownloaded(true);
String date = item.getDate(format);
boolean parsed = false;
if(indexactivateddate != null) {
try {
item.setLocalTimestamp(format.parse(indexactivateddate).getTime());
parsed = true;
} catch (ParseException e) {
e.printStackTrace();
}
}
if (!parsed && indexfilesdate != null) {
try {
item.setLocalTimestamp(format.parse(indexfilesdate).getTime());
parsed = true;
} catch (ParseException e) {
e.printStackTrace();
}
}
if (date != null && !date.equals(indexactivateddate) && !date.equals(indexfilesdate)) {
if ((item.getType() == DownloadActivityType.NORMAL_FILE && !item.extra)
|| item.getType() == DownloadActivityType.ROADS_FILE
|| item.getType() == DownloadActivityType.WIKIPEDIA_FILE
|| item.getType() == DownloadActivityType.SRTM_COUNTRY_FILE) {
outdated = true;
} else {
long itemSize = item.getContentSize();
long oldItemSize = 0;
if (item.getType() == DownloadActivityType.VOICE_FILE) {
if (item instanceof AssetIndexItem) {
File file = new File(((AssetIndexItem) item).getDestFile());
oldItemSize = file.length();
} else {
File fl = new File(item.getType().getDownloadFolder(app, item), sfName + "/_config.p");
if (fl.exists()) {
oldItemSize = fl.length();
try {
InputStream is = app.getAssets().open("voice/" + sfName + "/config.p");
if (is != null) {
itemSize = is.available();
is.close();
}
} catch (IOException e) {
}
}
}
} else {
oldItemSize = app.getAppPath(item.getTargetFileName()).length();
}
if (itemSize != oldItemSize) {
outdated = true;
}
}
}
item.setOutdated(outdated);
return outdated;
}
protected void updateFilesToUpdate() {
List<IndexItem> stillUpdate = new ArrayList<IndexItem>();
for (IndexItem item : itemsToUpdate) {
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null && !date.equals(indexactivateddate) && !date.equals(indexfilesdate)
&& indexActivatedFileNames.containsKey(sfName)) {
stillUpdate.add(item);
}
}
itemsToUpdate = stillUpdate;
}
private Map<String, String> listWithAlternatives(final java.text.DateFormat dateFormat, File file,
final String ext, final Map<String, String> files) {
if (file.isDirectory()) {
file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(ext)) {
String date = dateFormat.format(findFileInDir(new File(dir, filename)).lastModified());
files.put(filename, date);
return true;
} else {
return false;
}
}
});
}
return files;
}
private File findFileInDir(File file) {
if (file.isDirectory()) {
File[] lf = file.listFiles();
if (lf != null) {
for (File f : lf) {
if (f.isFile()) {
return f;
}
}
}
}
return file;
}
private void prepareFilesToUpdate() {
List<IndexItem> filtered = rawResources;
if (filtered != null) {
itemsToUpdate.clear();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
for (IndexItem item : filtered) {
boolean outdated = checkIfItemOutdated(item, format);
// include only activated files here
if (outdated && indexActivatedFileNames.containsKey(item.getTargetFileName())) {
itemsToUpdate.add(item);
}
}
}
}
protected boolean prepareData(List<IndexItem> resources) {
this.rawResources = resources;
DownloadResourceGroup voiceGroup = new DownloadResourceGroup(this, DownloadResourceGroupType.VOICE_GROUP);
DownloadResourceGroup voiceScreenRec = new DownloadResourceGroup(voiceGroup, DownloadResourceGroupType.VOICE_REC);
DownloadResourceGroup voiceScreenTTS = new DownloadResourceGroup(voiceGroup, DownloadResourceGroupType.VOICE_TTS);
DownloadResourceGroup voiceRec = new DownloadResourceGroup(voiceGroup, DownloadResourceGroupType.VOICE_HEADER_REC);
DownloadResourceGroup voiceTTS = new DownloadResourceGroup(voiceGroup, DownloadResourceGroupType.VOICE_HEADER_TTS);
voiceScreenTTS.addGroup(voiceTTS);
voiceScreenRec.addGroup(voiceRec);
voiceGroup.addGroup(voiceScreenRec);
voiceGroup.addGroup(voiceScreenTTS);
DownloadResourceGroup worldMaps = new DownloadResourceGroup(this, DownloadResourceGroupType.WORLD_MAPS);
Map<WorldRegion, List<IndexItem> > groupByRegion = new LinkedHashMap<WorldRegion, List<IndexItem>>();
Map<String, WorldRegion> downloadIdForRegion = new LinkedHashMap<String, WorldRegion>();
for(WorldRegion wg : region.getFlattenedSubregions()) {
downloadIdForRegion.put(wg.getDownloadsId(), wg);
}
for (IndexItem ii : resources) {
if (ii.getType() == DownloadActivityType.VOICE_FILE) {
if (ii.getFileName().endsWith(IndexConstants.TTSVOICE_INDEX_EXT_ZIP)) {
voiceTTS.addItem(ii);
} else {
voiceRec.addItem(ii);
}
continue;
}
String basename = ii.getBasename().toLowerCase();
WorldRegion wg = downloadIdForRegion.get(basename);
if (wg != null) {
if (!groupByRegion.containsKey(wg)) {
groupByRegion.put(wg, new ArrayList<IndexItem>());
}
groupByRegion.get(wg).add(ii);
} else {
worldMaps.addItem(ii);
}
}
LinkedList<WorldRegion> queue = new LinkedList<WorldRegion>();
LinkedList<DownloadResourceGroup> parent = new LinkedList<DownloadResourceGroup>();
DownloadResourceGroup worldSubregions = new DownloadResourceGroup(this, DownloadResourceGroupType.SUBREGIONS);
addGroup(worldSubregions);
for(WorldRegion rg : region.getSubregions()) {
queue.add(rg);
parent.add(worldSubregions);
}
while(!queue.isEmpty()) {
WorldRegion reg = queue.pollFirst();
DownloadResourceGroup parentGroup = parent.pollFirst();
List<WorldRegion> subregions = reg.getSubregions();
DownloadResourceGroup mainGrp = new DownloadResourceGroup(parentGroup, DownloadResourceGroupType.REGION, reg.getRegionId());
mainGrp.region = reg;
parentGroup.addGroup(mainGrp);
DownloadResourceGroup subRegions = new DownloadResourceGroup(mainGrp, DownloadResourceGroupType.SUBREGIONS);
mainGrp.addGroup(subRegions);
List<IndexItem> list = groupByRegion.get(reg);
if(list != null) {
DownloadResourceGroup flatFiles = new DownloadResourceGroup(mainGrp, DownloadResourceGroupType.REGION_MAPS);
for(IndexItem ii : list) {
flatFiles.addItem(ii);
}
mainGrp.addGroup(flatFiles);
}
// add to processing queue
for(WorldRegion rg : subregions) {
queue.add(rg);
parent.add(subRegions);
}
}
// Possible improvements
// 1. if there is no subregions no need to create resource group REGIONS_MAPS - objection raise diversity and there is no value
// 2. if there is no subregions and there only 1 index item it could be merged to the level up - objection there is no such maps
// 3. if hillshade/srtm is disabled, all maps from inner level could be combined into 1
addGroup(worldMaps);
addGroup(voiceGroup);
trimEmptyGroups();
initAlreadyLoadedFiles();
return true;
}
}

View file

@ -3,7 +3,6 @@ package net.osmand.plus.download;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Iterator;

View file

@ -1,90 +0,0 @@
package net.osmand.plus.download;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.osmand.IndexConstants;
public class IndexFileList implements Serializable {
private static final long serialVersionUID = 1L;
private boolean downloadedFromInternet = false;
IndexItem basemap;
ArrayList<IndexItem> indexFiles = new ArrayList<IndexItem>();
private String mapversion;
private Comparator<IndexItem> comparator = new Comparator<IndexItem>(){
@Override
public int compare(IndexItem o1, IndexItem o2) {
String object1 = o1.getFileName();
String object2 = o2.getFileName();
if(object1.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
if(object2.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
return object1.compareTo(object2);
} else {
return -1;
}
} else if(object2.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
return 1;
}
return object1.compareTo(object2);
}
};
public void setDownloadedFromInternet(boolean downloadedFromInternet) {
this.downloadedFromInternet = downloadedFromInternet;
}
public boolean isDownloadedFromInternet() {
return downloadedFromInternet;
}
public void setMapVersion(String mapversion) {
this.mapversion = mapversion;
}
public void add(IndexItem indexItem) {
indexFiles.add(indexItem);
if(indexItem.getFileName().toLowerCase().startsWith("world_basemap")) {
basemap = indexItem;
}
}
public void sort(){
Collections.sort(indexFiles, comparator);
}
public boolean isAcceptable() {
return (indexFiles != null && !indexFiles.isEmpty()) || (mapversion != null);
}
public List<IndexItem> getIndexFiles() {
return indexFiles;
}
public IndexItem getBasemap() {
return basemap;
}
public boolean isIncreasedMapVersion() {
try {
int mapVersionInList = Integer.parseInt(mapversion);
return IndexConstants.BINARY_MAP_VERSION < mapVersionInList;
} catch (NumberFormatException e) {
//ignore this...
}
return false;
}
public IndexItem getIndexFilesByName(String key) {
for(IndexItem i : indexFiles) {
if(i.getFileName().equals(key)) {
return i;
}
}
return null;
}
}

View file

@ -2,8 +2,8 @@ package net.osmand.plus.download;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Map;
import net.osmand.IndexConstants;
import net.osmand.PlatformUtil;
@ -16,12 +16,11 @@ import org.apache.commons.logging.Log;
import android.content.Context;
import android.support.annotation.NonNull;
public class IndexItem implements Comparable<IndexItem>/*, Parcelable*/ {
public class IndexItem implements Comparable<IndexItem> {
private static final Log log = PlatformUtil.getLog(IndexItem.class);
String description;
String fileName;
String simplifiedFileName;
String size;
long timestamp;
long contentSize;
@ -29,11 +28,15 @@ public class IndexItem implements Comparable<IndexItem>/*, Parcelable*/ {
DownloadActivityType type;
boolean extra;
// Update information
boolean outdated;
boolean downloaded;
long localTimestamp;
public IndexItem(String fileName, String description, long timestamp, String size, long contentSize,
long containerSize, DownloadActivityType tp) {
this.fileName = fileName;
this.simplifiedFileName = fileName.toLowerCase().replace("_2.", ".").replace("hillshade_", "");
this.description = description;
this.timestamp = timestamp;
this.size = size;
@ -50,9 +53,6 @@ public class IndexItem implements Comparable<IndexItem>/*, Parcelable*/ {
return fileName;
}
public String getSimplifiedFileName() {
return simplifiedFileName;
}
public String getDescription() {
return description;
@ -74,6 +74,10 @@ public class IndexItem implements Comparable<IndexItem>/*, Parcelable*/ {
return ((double)contentSize) / (1 << 20);
}
public double getArchiveSizeMB() {
return ((double)containerSize) / (1 << 20);
}
public String getSizeDescription(Context ctx) {
return size + " MB";
}
@ -132,17 +136,53 @@ public class IndexItem implements Comparable<IndexItem>/*, Parcelable*/ {
@Override
public int compareTo(@NonNull IndexItem another) {
// if(another == null) {
// return -1;
// }
return getFileName().compareTo(another.getFileName());
}
public boolean isAlreadyDownloaded(Map<String, String> listAlreadyDownloaded) {
return listAlreadyDownloaded.containsKey(getTargetFileName());
public String getDaysBehind(OsmandApplication app) {
if (localTimestamp > 0) {
long days = Math.max(1, (getTimestamp() - localTimestamp) / (24 * 60 * 60 * 1000) + 1);
return days + " " + app.getString(R.string.days_behind);
}
return "";
}
public String getRemoteDate(DateFormat dateFormat) {
if(timestamp <= 0) {
return "";
}
return dateFormat.format(new Date(timestamp));
}
public String getLocalDate(DateFormat dateFormat) {
if(localTimestamp <= 0) {
return "";
}
return dateFormat.format(new Date(localTimestamp));
}
public boolean isOutdated() {
return outdated;
}
public void setOutdated(boolean outdated) {
this.outdated = outdated;
}
public void setDownloaded(boolean downloaded) {
this.downloaded = downloaded;
}
public void setLocalTimestamp(long localTimestamp) {
this.localTimestamp = localTimestamp;
}
public boolean isDownloaded() {
return downloaded;
}
public String getVisibleName(Context ctx, OsmandRegions osmandRegions) {
return type.getVisibleName(this, ctx, osmandRegions, true);
@ -162,61 +202,33 @@ public class IndexItem implements Comparable<IndexItem>/*, Parcelable*/ {
return format.format(new Date(timestamp));
}
public static class DownloadEntry {
public long dateModified;
public double sizeMB;
public File targetFile;
public boolean zipStream;
public boolean unzipFolder;
public File fileToDownload;
public String baseName;
public String urlToDownload;
public boolean isAsset;
public String assetName;
public DownloadActivityType type;
public DownloadEntry() {
}
public DownloadEntry(String assetName, String fileName, long dateModified) {
this.dateModified = dateModified;
targetFile = new File(fileName);
this.assetName = assetName;
isAsset = true;
}
}
// @Override
// public String toString() {
// return "IndexItem{" +
// "description='" + description + '\'' +
// ", fileName='" + fileName + '\'' +
// ", simplifiedFileName='" + simplifiedFileName + '\'' +
// ", size='" + size + '\'' +
// ", timestamp=" + timestamp +
// ", contentSize=" + contentSize +
// ", containerSize=" + containerSize +
// ", type=" + type.getTag() +
// ", extra=" + extra +
// '}';
// }
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(this.description);
// dest.writeString(this.fileName);
// dest.writeString(this.size);
// dest.writeLong(this.timestamp);
// dest.writeLong(this.contentSize);
// dest.writeLong(this.containerSize);
// dest.writeParcelable(this.type, flags);
// dest.writeByte(extra ? (byte) 1 : (byte) 0);
// dest.writeString(this.initializedName);
// dest.writeString(this.simplifiedFileName);
// }
//
// protected IndexItem(Parcel in) {
// this.description = in.readString();
// this.fileName = in.readString();
// this.size = in.readString();
// this.timestamp = in.readLong();
// this.contentSize = in.readLong();
// this.containerSize = in.readLong();
// this.type = in.readParcelable(DownloadActivityType.class.getClassLoader());
// this.extra = in.readByte() != 0;
// this.initializedName = in.readString();
// this.simplifiedFileName = in.readString();
// }
//
// public static final Parcelable.Creator<IndexItem> CREATOR = new Parcelable.Creator<IndexItem>() {
// public IndexItem createFromParcel(Parcel source) {
// return new IndexItem(source);
// }
//
// public IndexItem[] newArray(int size) {
// return new IndexItem[size];
// }
// };
}

View file

@ -1,130 +0,0 @@
package net.osmand.plus.download;
import android.support.annotation.NonNull;
import net.osmand.Collator;
import net.osmand.OsmAndCollator;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class IndexItemCategory implements Comparable<IndexItemCategory> {
public final String name;
public final List<IndexItem> items = new ArrayList<>();
private final int order;
public IndexItemCategory(String name, int order) {
this.name = name;
this.order = order;
}
@Override
public int compareTo(@NonNull IndexItemCategory another) {
return order < another.order ? -1 : 1;
}
public static List<IndexItemCategory> categorizeIndexItems(final OsmandApplication ctx,
Collection<IndexItem> indexItems) {
boolean skipWiki = Version.isFreeVersion(ctx);
final Map<String, IndexItemCategory> cats = new TreeMap<>();
for (IndexItem i : indexItems) {
int nameId = R.string.index_name_other;
int order = 0;
String lc = i.getFileName().toLowerCase();
if (lc.endsWith(".voice.zip")) {
nameId = R.string.index_name_voice;
order = 1;
} else if (lc.contains(".ttsvoice.zip")) {
nameId = R.string.index_name_tts_voice;
order = 2;
} else if (lc.contains("_wiki_")) {
if(skipWiki) {
continue;
}
nameId = R.string.index_name_wiki;
order = 10;
} else if (lc.startsWith("us") ||
(lc.contains("united states") && lc.startsWith("north-america")) ) {
nameId = R.string.index_name_us;
order = 31;
} else if (lc.startsWith("canada")) {
nameId = R.string.index_name_canada;
order = 32;
} else if (lc.contains("openmaps")) {
nameId = R.string.index_name_openmaps;
order = 90;
} else if (lc.contains("northamerica") || lc.contains("north-america")) {
nameId = R.string.index_name_north_america;
order = 30;
} else if (lc.contains("centralamerica") || lc.contains("central-america")
|| lc.contains("caribbean")) {
nameId = R.string.index_name_central_america;
order = 40;
} else if (lc.contains("southamerica") || lc.contains("south-america")) {
nameId = R.string.index_name_south_america;
order = 45;
} else if ( lc.contains("germany")) {
nameId = R.string.index_name_germany;
order = 16;
} else if (lc.startsWith("france_")) {
nameId = R.string.index_name_france;
order = 17;
} else if (lc.startsWith("italy_")) {
nameId = R.string.index_name_italy;
order = 18;
} else if (lc.startsWith("gb_") || lc.startsWith("british")) {
nameId = R.string.index_name_gb;
order = 19;
} else if ( lc.contains("netherlands")) {
nameId = R.string.index_name_netherlands;
order = 20;
} else if (lc.contains("russia")) {
nameId = R.string.index_name_russia;
order = 25;
} else if (lc.contains("europe")) {
nameId = R.string.index_name_europe;
order = 15;
} else if (lc.contains("africa") && !lc.contains("_wiki_")) {
nameId = R.string.index_name_africa;
order = 80;
} else if (lc.contains("_asia")|| lc.startsWith("asia")) {
nameId = R.string.index_name_asia;
order = 50;
} else if (lc.contains("oceania") || lc.contains("australia")) {
nameId = R.string.index_name_oceania;
order = 70;
} else if (lc.contains("tour")) {
nameId = R.string.index_tours;
}
String name = ctx.getString(nameId);
if (!cats.containsKey(name)) {
cats.put(name, new IndexItemCategory(name, order));
}
cats.get(name).items.add(i);
}
ArrayList<IndexItemCategory> r = new ArrayList<>(cats.values());
final Collator collator = OsmAndCollator.primaryCollator();
for(IndexItemCategory ct : r) {
final OsmandRegions osmandRegions = ctx.getResourceManager().getOsmandRegions();
Collections.sort(ct.items, new Comparator<IndexItem>() {
@Override
public int compare(IndexItem lhs, IndexItem rhs) {
return collator.compare(lhs.getVisibleName(ctx, osmandRegions),
rhs.getVisibleName(ctx, osmandRegions));
}
});
}
Collections.sort(r);
return r;
}
}

View file

@ -1,272 +0,0 @@
package net.osmand.plus.download;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import net.osmand.PlatformUtil;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmAndListFragment;
import net.osmand.plus.download.items.TwoLineWithImagesViewHolder;
import org.apache.commons.logging.Log;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class UpdatesIndexFragment extends OsmAndListFragment {
private static final Log LOG = PlatformUtil.getLog(UpdateIndexAdapter.class);
private static final int RELOAD_ID = 5;
private UpdateIndexAdapter listAdapter;
List<IndexItem> indexItems = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (BaseDownloadActivity.downloadListIndexThread != null) {
indexItems = new ArrayList<>(DownloadActivity.downloadListIndexThread.getItemsToUpdate());
}
createListView();
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.update_index_frament, container, false);
}
@Override
public ArrayAdapter<?> getAdapter() {
return listAdapter;
}
private void createListView() {
updateUpdateAllButton();
if (indexItems.size() == 0) {
if (DownloadActivity.downloadListIndexThread.isDownloadedFromInternet()) {
indexItems.add(new IndexItem(getString(R.string.everything_up_to_date), "", 0, "", 0, 0, null));
} else {
indexItems.add(new IndexItem(getString(R.string.no_index_file_to_download), "", 0, "", 0, 0, null));
}
}
final OsmandRegions osmandRegions =
getMyApplication().getResourceManager().getOsmandRegions();
listAdapter = new UpdateIndexAdapter(getMyActivity(), R.layout.download_index_list_item, indexItems);
listAdapter.sort(new Comparator<IndexItem>() {
@Override
public int compare(IndexItem indexItem, IndexItem indexItem2) {
return indexItem.getVisibleName(getMyApplication(), osmandRegions)
.compareTo(indexItem2.getVisibleName(getMyApplication(), osmandRegions));
}
});
setListAdapter(listAdapter);
}
private void updateUpdateAllButton() {
View view = getView();
if (getView() == null) {
return;
}
final TextView updateAllButton = (TextView) view.findViewById(R.id.updateAllButton);
if (indexItems.size() == 0 || indexItems.get(0).getType() == null) {
updateAllButton.setVisibility(View.GONE);
} else {
updateAllButton.setVisibility(View.VISIBLE);
long downloadsSize = 0;
for (IndexItem indexItem : indexItems) {
downloadsSize += indexItem.getSize();
}
String updateAllText = getActivity().getString(R.string.update_all, downloadsSize >> 20);
updateAllButton.setText(updateAllText);
updateAllButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getMyActivity().startDownload(indexItems.toArray(new IndexItem[indexItems.size()]));
}
});
}
}
@Override
public void onResume() {
super.onResume();
}
public void updateItemsList() {
if (listAdapter == null) {
return;
}
List<IndexItem> items = BaseDownloadActivity.downloadListIndexThread.getItemsToUpdate();
if(items != null) {
indexItems = new ArrayList<IndexItem>(items);
createListView();
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final IndexItem e = (IndexItem) getListAdapter().getItem(position);
getMyActivity().startDownload(e);
}
public DownloadActivity getMyActivity() {
return (DownloadActivity) getActivity();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
updateUpdateAllButton();
ActionBar actionBar = getMyActivity().getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
if (getMyApplication().getAppCustomization().showDownloadExtraActions()) {
MenuItem item = menu.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
item.setIcon(R.drawable.ic_action_refresh_dark);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
}
public OsmandApplication getMyApplication() {
return getMyActivity().getMyApplication();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == RELOAD_ID) {
// re-create the thread
DownloadActivity.downloadListIndexThread.runReloadIndexFiles();
return true;
}
return super.onOptionsItemSelected(item);
}
private class UpdateIndexAdapter extends ArrayAdapter<IndexItem> {
List<IndexItem> items;
public UpdateIndexAdapter(Context context, int resource, List<IndexItem> items) {
super(context, resource, items);
this.items = items;
}
public List<IndexItem> getIndexFiles() {
return items;
}
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(getMyActivity());
v = inflater.inflate(R.layout.two_line_with_images_list_item, null);
v.setTag(new UpdateViewHolder(v, getMyActivity()));
}
UpdateViewHolder holder = (UpdateViewHolder) v.getTag();
holder.bindUpdatesIndexItem(items.get(position));
return v;
}
public void setIndexFiles(List<IndexItem> filtered) {
clear();
for (IndexItem item : filtered) {
add(item);
}
final OsmandRegions osmandRegions =
getMyApplication().getResourceManager().getOsmandRegions();
sort(new Comparator<IndexItem>() {
@Override
public int compare(IndexItem indexItem, IndexItem indexItem2) {
return indexItem.getVisibleName(getMyApplication(), osmandRegions).compareTo(indexItem2.getVisibleName(getMyApplication(), osmandRegions));
}
});
}
}
private static class UpdateViewHolder extends TwoLineWithImagesViewHolder {
private final java.text.DateFormat format;
private UpdateViewHolder(View convertView,
final DownloadActivity context) {
super(convertView, context);
format = context.getMyApplication().getResourceManager().getDateFormat();
}
public void bindUpdatesIndexItem(IndexItem indexItem) {
if (indexItem.getFileName().equals(context.getString(R.string.everything_up_to_date)) ||
indexItem.getFileName().equals(context.getString(R.string.no_index_file_to_download))) {
nameTextView.setText(indexItem.getFileName());
descrTextView.setText("");
return;
}
OsmandRegions osmandRegions =
context.getMyApplication().getResourceManager().getOsmandRegions();
String eName = indexItem.getVisibleName(context.getMyApplication(), osmandRegions);
nameTextView.setText(eName.trim().replace('\n', ' ').replace("TTS", "")); //$NON-NLS-1$
String d = getMapDescription(indexItem);
descrTextView.setText(d);
String sfName = indexItem.getTargetFileName();
Map<String, String> indexActivatedFileNames = context.getMyApplication().getResourceManager().getIndexFileNames();
String dt = indexActivatedFileNames.get(sfName);
mapDateTextView.setText("");
if (dt != null) {
try {
Date tm = format.parse(dt);
long days = Math.max(1, (indexItem.getTimestamp() - tm.getTime()) / (24 * 60 * 60 * 1000) + 1);
mapDateTextView.setText(days + " " + context.getString(R.string.days_behind));
} catch (ParseException e1) {
e1.printStackTrace();
}
}
rightImageButton.setVisibility(View.VISIBLE);
rightImageButton.setImageDrawable(
context.getMyApplication().getIconsCache()
.getContentIcon(R.drawable.ic_action_import));
}
private String getMapDescription(IndexItem item) {
String typeName = getTypeName(item, item.getType().getStringResource());
String date = item.getDate(format);
String size = item.getSizeDescription(context);
return typeName + " " + date + " " + size;
}
private String getTypeName(IndexItem item, int resId) {
Activity activity = context;
if (resId == R.string.download_regular_maps) {
return activity.getString(R.string.shared_string_map);
} else if (resId == R.string.download_wikipedia_maps) {
return activity.getString(R.string.shared_string_wikipedia);
} else if (resId == R.string.voices) {
return item.getTargetFileName().contains("tts") ? activity.getString(R.string.ttsvoice) : activity
.getString(R.string.voice);
} else if (resId == R.string.download_roads_only_maps) {
return activity.getString(R.string.roads_only);
} else if (resId == R.string.download_srtm_maps) {
return activity.getString(R.string.download_srtm_maps);
} else if (resId == R.string.download_hillshade_maps) {
return activity.getString(R.string.download_hillshade_maps);
}
return "";
}
}
}

View file

@ -1,139 +0,0 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import net.osmand.plus.R;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class ActiveDownloadsDialogFragment extends DialogFragment {
private IndexItemAdapter adapter;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.downloads).setNegativeButton(R.string.shared_string_dismiss, null);
adapter = new IndexItemAdapter(getDownloadActivity());
builder.setAdapter(adapter, null);
getDownloadActivity().setActiveDownloads(this);
return builder.create();
}
public void refresh() {
adapter.updateData();
}
public void onDetach() {
super.onDetach();
getDownloadActivity().setActiveDownloads(null);
};
DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public static class IndexItemAdapter extends ArrayAdapter<IndexItem> {
private final Drawable deleteDrawable;
private final DownloadActivity context;
private boolean isFinished;
public IndexItemAdapter(DownloadActivity context) {
super(context, R.layout.two_line_with_images_list_item, new ArrayList<IndexItem>());
this.context = context;
deleteDrawable = context.getMyApplication().getIconsCache()
.getPaintedContentIcon(R.drawable.ic_action_remove_dark,
context.getResources().getColor(R.color.dash_search_icon_dark));
updateData();
}
public void updateData() {
clear();
addAll(context.getDownloadThread().getCurrentDownloadingItems());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.two_line_with_images_list_item, parent, false);
DownloadEntryViewHolder viewHolder =
new DownloadEntryViewHolder(convertView, context, deleteDrawable, this);
convertView.setTag(viewHolder);
}
DownloadEntryViewHolder viewHolder = (DownloadEntryViewHolder) convertView.getTag();
IndexItem item = getItem(position);
IndexItem cdi = context.getDownloadThread().getCurrentDownloadingItem();
viewHolder.bindDownloadEntry(getItem(position),
cdi == item ? context.getDownloadThread().getCurrentDownloadingItemProgress() : -1,
context.getDownloadThread().isDownloading(item));
return convertView;
}
}
private static class DownloadEntryViewHolder extends TwoLineWithImagesViewHolder {
private final Drawable deleteDrawable;
private final IndexItemAdapter adapter;
private DownloadEntryViewHolder(View convertView, final DownloadActivity context,
Drawable deleteDrawable, IndexItemAdapter adapter) {
super(convertView, context);
this.deleteDrawable = deleteDrawable;
this.adapter = adapter;
progressBar.setVisibility(View.VISIBLE);
rightImageButton.setImageDrawable(deleteDrawable);
}
public void bindDownloadEntry(final IndexItem item, final int progress,
boolean isDownloaded) {
nameTextView.setText(item.getVisibleName(context,
context.getMyApplication().getRegions()));
rightImageButton.setVisibility(View.VISIBLE);
int localProgress = progress;
boolean isIndeterminate = true;
if (progress != -1) {
isIndeterminate = false;
double downloaded = item.getContentSizeMB() * progress / 100;
descrTextView.setText(context.getString(R.string.value_downloaded_from_max, downloaded,
item.getContentSizeMB()));
} else if (isDownloaded) {
isIndeterminate = false;
localProgress = progressBar.getMax();
descrTextView.setText(context.getString(R.string.file_size_in_mb,
item.getContentSizeMB()));
rightImageButton.setVisibility(View.GONE);
} else {
descrTextView.setText(context.getString(R.string.file_size_in_mb,
item.getContentSizeMB()));
}
rightImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.getDownloadThread().cancelDownload(item);
adapter.updateData();
}
});
progressBar.setIndeterminate(isIndeterminate);
progressBar.setProgress(localProgress);
}
}
}

View file

@ -1,10 +0,0 @@
package net.osmand.plus.download.items;
/**
* Used to have smooth transition between dialogs
*/
public interface DialogDismissListener {
void onDialogDismissed();
}

View file

@ -1,257 +0,0 @@
package net.osmand.plus.download.items;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.TypedValue;
import android.view.View;
import android.widget.Toast;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.openseamapsplugin.NauticalMapsPlugin;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import java.text.DateFormat;
import java.util.Map;
public class ItemViewHolder extends TwoLineWithImagesViewHolder {
private final java.text.DateFormat dateFormat;
private boolean srtmDisabled;
private boolean nauticalPluginDisabled;
private boolean freeVersion;
private int textColorPrimary;
private int textColorSecondary;
private RightButtonAction rightButtonAction;
private enum RightButtonAction {
UNKNOWN,
ASK_FOR_SEAMARKS_PLUGIN,
ASK_FOR_SRTM_PLUGIN_PURCHASE,
ASK_FOR_SRTM_PLUGIN_ENABLE,
ASK_FOR_FULL_VERSION_PURCHASE
}
public ItemViewHolder(View convertView,
DownloadActivity context,
DateFormat dateFormat) {
super(convertView, context);
this.dateFormat = dateFormat;
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
textColorPrimary = typedValue.data;
theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
textColorSecondary = typedValue.data;
}
public void initAppStatusVariables() {
srtmDisabled = OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) == null;
nauticalPluginDisabled = OsmandPlugin.getEnabledPlugin(NauticalMapsPlugin.class) == null;
freeVersion = Version.isFreeVersion(context.getMyApplication());
}
public void bindIndexItem(final IndexItem indexItem,
boolean showTypeInTitle, boolean showTypeInDesc, int progress) {
initAppStatusVariables();
boolean disabled = false;
rightButtonAction = RightButtonAction.UNKNOWN;
rightImageButton.setClickable(false);
if (progress != -1) {
rightImageButton.setClickable(true);
rightImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.makeSureUserCancelDownload(indexItem);
}
});
} else if (indexItem.getType() == DownloadActivityType.VOICE_FILE) {
nameTextView.setText(indexItem.getVisibleName(context,
context.getMyApplication().getRegions(), false));
} else {
if (indexItem.getSimplifiedFileName().equals(ItemsListBuilder.WORLD_SEAMARKS_KEY)
&& nauticalPluginDisabled) {
rightButtonAction = RightButtonAction.ASK_FOR_SEAMARKS_PLUGIN;
disabled = true;
}
if ((indexItem.getType() == DownloadActivityType.SRTM_COUNTRY_FILE ||
indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) && srtmDisabled) {
OsmandPlugin srtmPlugin = OsmandPlugin.getPlugin(SRTMPlugin.class);
if (srtmPlugin == null || srtmPlugin.needsInstallation()) {
rightButtonAction = RightButtonAction.ASK_FOR_SRTM_PLUGIN_PURCHASE;
} else if (!srtmPlugin.isActive()) {
rightButtonAction = RightButtonAction.ASK_FOR_SRTM_PLUGIN_ENABLE;
}
disabled = true;
} else if (indexItem.getType() == DownloadActivityType.WIKIPEDIA_FILE && freeVersion) {
rightButtonAction = RightButtonAction.ASK_FOR_FULL_VERSION_PURCHASE;
disabled = true;
}
if (showTypeInTitle) {
nameTextView.setText(indexItem.getType().getString(context));
} else {
nameTextView.setText(indexItem.getVisibleName(context, context.getMyApplication().getRegions(), false));
}
}
if (progress == -1) {
descrTextView.setVisibility(View.VISIBLE);
if (!showTypeInTitle && (indexItem.getType() == DownloadActivityType.SRTM_COUNTRY_FILE ||
indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) && srtmDisabled) {
descrTextView.setText(indexItem.getType().getString(context));
} else if (showTypeInDesc) {
descrTextView.setText(indexItem.getType().getString(context) + "" + indexItem.getSizeDescription(context));
} else {
descrTextView.setText(indexItem.getSizeDescription(context));
}
rightImageButton.setVisibility(View.VISIBLE);
rightImageButton.setImageDrawable(getContentIcon(context, R.drawable.ic_action_import));
progressBar.setVisibility(View.GONE);
Map<String,String> indexFileNames = context.getIndexFileNames();
if (indexFileNames != null && indexItem.isAlreadyDownloaded(indexFileNames)) {
boolean outdated = false;
String date;
if (indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) {
date = indexItem.getDate(dateFormat);
} else {
String sfName = indexItem.getTargetFileName();
Map<String,String> indexActivatedFileNames = context.getIndexActivatedFileNames();
final boolean updatableResource = indexActivatedFileNames.containsKey(sfName);
date = updatableResource ? indexActivatedFileNames.get(sfName) : indexFileNames.get(sfName);
outdated = DownloadActivity.downloadListIndexThread.checkIfItemOutdated(indexItem);
}
String updateDescr = context.getResources().getString(R.string.local_index_installed) + ": "
+ date;
mapDateTextView.setText(updateDescr);
int colorId = outdated ? R.color.color_distance : R.color.color_ok;
final int color = context.getResources().getColor(colorId);
mapDateTextView.setTextColor(color);
leftImageView.setImageDrawable(getContentIcon(context,
indexItem.getType().getIconResource(), color));
nameTextView.setTextColor(textColorPrimary);
} else if (disabled) {
leftImageView.setImageDrawable(getContentIcon(context,
indexItem.getType().getIconResource(), textColorSecondary));
nameTextView.setTextColor(textColorSecondary);
} else {
leftImageView.setImageDrawable(getContentIcon(context,
indexItem.getType().getIconResource()));
nameTextView.setTextColor(textColorPrimary);
}
} else {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(progress);
rightImageButton.setImageDrawable(
getContentIcon(context, R.drawable.ic_action_remove_dark));
}
if (rightButtonAction != RightButtonAction.UNKNOWN) {
rightButton.setText(R.string.get_plugin);
rightButton.setVisibility(View.VISIBLE);
rightImageButton.setVisibility(View.GONE);
final RightButtonAction action = rightButtonAction;
rightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (action) {
case ASK_FOR_FULL_VERSION_PURCHASE:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(Version.marketPrefix(context.getMyApplication())
+ "net.osmand.plus"));
context.startActivity(intent);
break;
case ASK_FOR_SEAMARKS_PLUGIN:
context.startActivity(new Intent(context,
context.getMyApplication().getAppCustomization().getPluginsActivity()));
AccessibleToast.makeText(context.getApplicationContext(),
context.getString(R.string.activate_seamarks_plugin), Toast.LENGTH_SHORT).show();
break;
case ASK_FOR_SRTM_PLUGIN_PURCHASE:
OsmandPlugin plugin = OsmandPlugin.getPlugin(SRTMPlugin.class);
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(plugin.getInstallURL())));
break;
case ASK_FOR_SRTM_PLUGIN_ENABLE:
context.startActivity(new Intent(context,
context.getMyApplication().getAppCustomization().getPluginsActivity()));
AccessibleToast.makeText(context,
context.getString(R.string.activate_srtm_plugin), Toast.LENGTH_SHORT).show();
break;
case UNKNOWN:
break;
}
}
});
} else {
rightButton.setVisibility(View.GONE);
rightImageButton.setVisibility(View.VISIBLE);
}
}
public void bindIndexItem(final IndexItem indexItem,
boolean showTypeInTitle, boolean showTypeInDesc) {
bindIndexItem(indexItem, showTypeInTitle, showTypeInDesc, -1);
}
public void bindRegion(WorldRegion region) {
nameTextView.setText(region.getName());
nameTextView.setTextColor(textColorPrimary);
if (region.getResourceTypes().size() > 0) {
StringBuilder stringBuilder = new StringBuilder();
for (DownloadActivityType activityType : region.getResourceTypes()) {
if (stringBuilder.length() > 0) {
stringBuilder.append(", ");
}
stringBuilder.append(activityType.getString(context));
}
}
descrTextView.setVisibility(View.GONE);
mapDateTextView.setVisibility(View.GONE);
Drawable leftImageDrawable = null;
switch (region.getMapState()) {
case NOT_DOWNLOADED:
leftImageDrawable = getContentIcon(context, R.drawable.ic_map);
break;
case DOWNLOADED:
leftImageDrawable = getContentIcon(context, R.drawable.ic_map,
context.getResources().getColor(R.color.color_ok));
break;
case OUTDATED:
leftImageDrawable = getContentIcon(context, R.drawable.ic_map,
context.getResources().getColor(R.color.color_distance));
break;
}
leftImageView.setImageDrawable(leftImageDrawable);
rightButton.setVisibility(View.GONE);
rightImageButton.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
private Drawable getContentIcon(DownloadActivity context, int resourceId) {
return context.getMyApplication().getIconsCache().getContentIcon(resourceId);
}
private Drawable getContentIcon(DownloadActivity context, int resourceId, int color) {
return context.getMyApplication().getIconsCache().getPaintedContentIcon(resourceId, color);
}
public boolean isItemAvailable() {
return rightButtonAction == RightButtonAction.UNKNOWN;
}
}

View file

@ -1,286 +0,0 @@
package net.osmand.plus.download.items;
import android.content.Context;
import net.osmand.PlatformUtil;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import net.osmand.util.Algorithms;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ItemsListBuilder {
//public static final String WORLD_BASEMAP_KEY = "world_basemap.obf.zip";
public static final String WORLD_SEAMARKS_KEY = "world_seamarks_basemap.obf.zip";
private Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions;
private List<IndexItem> voiceRecItems;
private List<IndexItem> voiceTTSItems;
public static class ResourceItem {
private String resourceId;
private String title;
private IndexItem indexItem;
private WorldRegion worldRegion;
public IndexItem getIndexItem() {
return indexItem;
}
public WorldRegion getWorldRegion() {
return worldRegion;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public ResourceItem(IndexItem indexItem, WorldRegion worldRegion) {
this.indexItem = indexItem;
this.worldRegion = worldRegion;
}
}
class ResourceItemComparator implements Comparator<Object> {
@Override
public int compare(Object obj1, Object obj2) {
String str1;
String str2;
if (obj1 instanceof WorldRegion) {
str1 = ((WorldRegion) obj1).getName();
} else {
ResourceItem item = (ResourceItem) obj1;
str1 = item.title + item.getIndexItem().getType().getOrderIndex();
}
if (obj2 instanceof WorldRegion) {
str2 = ((WorldRegion) obj2).getName();
} else {
ResourceItem item = (ResourceItem) obj2;
str2 = item.title + item.getIndexItem().getType().getOrderIndex();
}
return str1.compareTo(str2);
}
}
public enum VoicePromptsType {
NONE,
RECORDED,
TTS
}
private static final org.apache.commons.logging.Log LOG = PlatformUtil.getLog(ItemsListBuilder.class);
private List<ResourceItem> regionMapItems;
private List<Object> allResourceItems;
private List<WorldRegion> allSubregionItems;
private OsmandApplication app;
private WorldRegion region;
private boolean srtmDisabled;
private boolean hasSrtm;
private boolean hasHillshade;
public List<ResourceItem> getRegionMapItems() {
return regionMapItems;
}
public List<Object> getAllResourceItems() {
return allResourceItems;
}
public List<WorldRegion> getRegionsFromAllItems() {
List<WorldRegion> list = new LinkedList<>();
for (Object obj : allResourceItems) {
if (obj instanceof WorldRegion) {
list.add((WorldRegion) obj);
}
}
return list;
}
public static String getVoicePromtName(Context ctx, VoicePromptsType type) {
switch (type) {
case RECORDED:
return ctx.getResources().getString(R.string.index_name_voice);
case TTS:
return ctx.getResources().getString(R.string.index_name_tts_voice);
default:
return "";
}
}
public List<IndexItem> getVoicePromptsItems(VoicePromptsType type) {
switch (type) {
case RECORDED:
return voiceRecItems;
case TTS:
return voiceTTSItems;
default:
return new LinkedList<>();
}
}
public boolean isVoicePromptsItemsEmpty(VoicePromptsType type) {
switch (type) {
case RECORDED:
return voiceRecItems.isEmpty();
case TTS:
return voiceTTSItems.isEmpty();
default:
return true;
}
}
// FIXME
public ItemsListBuilder(OsmandApplication app, String regionId, Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions,
List<IndexItem> voiceRecItems, List<IndexItem> voiceTTSItems) {
this.app = app;
this.resourcesByRegions = resourcesByRegions;
this.voiceRecItems = voiceRecItems;
this.voiceTTSItems = voiceTTSItems;
regionMapItems = new LinkedList<>();
allResourceItems = new LinkedList<>();
allSubregionItems = new LinkedList<>();
region = app.getWorldRegion().getRegionById(regionId);
}
public ItemsListBuilder build() {
if (obtainDataAndItems()) {
return this;
} else {
return null;
}
}
private boolean obtainDataAndItems() {
if (resourcesByRegions.isEmpty() || region == null) {
return false;
}
collectSubregionsDataAndItems();
collectResourcesDataAndItems();
return true;
}
private void collectSubregionsDataAndItems() {
srtmDisabled = OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) == null;
hasSrtm = false;
hasHillshade = false;
// Collect all regions (and their parents) that have at least one
// resource available in repository or locally.
allResourceItems.clear();
allSubregionItems.clear();
regionMapItems.clear();
for (WorldRegion subregion : region.getFlattenedSubregions()) {
if (subregion.getSuperregion() == region) {
if (subregion.getFlattenedSubregions().size() > 0) {
allSubregionItems.add(subregion);
} else {
collectSubregionItems(subregion);
}
}
}
}
private void collectSubregionItems(WorldRegion region) {
Map<String, IndexItem> regionResources = resourcesByRegions.get(region);
if (regionResources == null) {
return;
}
List<ResourceItem> regionMapArray = new LinkedList<>();
List<Object> allResourcesArray = new LinkedList<>();
Context context = app.getApplicationContext();
OsmandRegions osmandRegions = app.getRegions();
for (IndexItem indexItem : regionResources.values()) {
String name = indexItem.getVisibleName(context, osmandRegions, false);
if (Algorithms.isEmpty(name)) {
continue;
}
ResourceItem resItem = new ResourceItem(indexItem, region);
resItem.setResourceId(indexItem.getSimplifiedFileName());
resItem.setTitle(name);
if (region != this.region && srtmDisabled) {
if (indexItem.getType() == DownloadActivityType.SRTM_COUNTRY_FILE) {
if (hasSrtm) {
continue;
} else {
hasSrtm = true;
}
} else if (indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) {
if (hasHillshade) {
continue;
} else {
hasHillshade = true;
}
}
}
if (region == this.region) {
regionMapArray.add(resItem);
} else {
allResourcesArray.add(resItem);
}
}
regionMapItems.addAll(regionMapArray);
if (allResourcesArray.size() > 1) {
allSubregionItems.add(region);
} else {
allResourceItems.addAll(allResourcesArray);
}
}
private void collectResourcesDataAndItems() {
collectSubregionItems(region);
allResourceItems.addAll(allSubregionItems);
Collections.sort(allResourceItems, new ResourceItemComparator());
Collections.sort(regionMapItems, new ResourceItemComparator());
}
}

View file

@ -1,117 +0,0 @@
package net.osmand.plus.download.items;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.DownloadActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class RegionDialogFragment extends DialogFragment {
public static final String TAG = "RegionDialogFragment";
private static final String REGION_ID_DLG_KEY = "world_region_dialog_key";
private String regionId;
private DialogDismissListener dialogDismissListener;
private DialogDismissListener listener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean isLightTheme = getMyApplication()
.getSettings().OSMAND_THEME.get() == OsmandSettings.OSMAND_LIGHT_THEME;
int themeId = isLightTheme ? R.style.OsmandLightTheme : R.style.OsmandDarkTheme;
setStyle(STYLE_NO_FRAME, themeId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.maps_in_category_fragment, container, false);
if (savedInstanceState != null) {
regionId = savedInstanceState.getString(REGION_ID_DLG_KEY);
}
if (regionId == null) {
regionId = getArguments().getString(REGION_ID_DLG_KEY);
}
if (regionId == null)
regionId = "";
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(getMyApplication().getIconsCache().getIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
if (regionId.length() > 0) {
Fragment fragment = getChildFragmentManager().findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
getChildFragmentManager().beginTransaction().add(R.id.fragmentContainer,
RegionItemsFragment.createInstance(regionId)).commit();
}
WorldRegion region = getMyApplication().getWorldRegion().getRegionById(regionId);
if (region != null) {
toolbar.setTitle(region.getName());
}
}
getDownloadActivity().registerFreeVersionBanner(view);
listener = new DialogDismissListener() {
@Override
public void onDialogDismissed() {
if (getDownloadActivity() != null)
getDownloadActivity().registerFreeVersionBanner(view);
}
};
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(REGION_ID_DLG_KEY, regionId);
super.onSaveInstanceState(outState);
}
private OsmandApplication getMyApplication() {
return (OsmandApplication) getActivity().getApplication();
}
private DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public void onRegionSelected(String regionId) {
final RegionDialogFragment regionDialogFragment = createInstance(regionId);
regionDialogFragment.setOnDismissListener(listener);
getDownloadActivity().showDialog(getActivity(), regionDialogFragment);
}
public static RegionDialogFragment createInstance(String regionId) {
Bundle bundle = new Bundle();
bundle.putString(REGION_ID_DLG_KEY, regionId);
RegionDialogFragment fragment = new RegionDialogFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (dialogDismissListener != null)
dialogDismissListener.onDialogDismissed();
}
public void setOnDismissListener(DialogDismissListener listener) {
this.dialogDismissListener = listener;
}
}

View file

@ -1,324 +0,0 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadEntry;
import net.osmand.plus.download.IndexItem;
import org.apache.commons.logging.Log;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class RegionItemsFragment extends OsmandExpandableListFragment {
public static final String TAG = "RegionItemsFragment";
private RegionsItemsAdapter listAdapter;
private static final String REGION_ID_KEY = "world_region_id_key";
private String regionId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_items_fragment, container, false);
if (savedInstanceState != null) {
regionId = savedInstanceState.getString(REGION_ID_KEY);
}
if (regionId == null) {
regionId = getArguments().getString(REGION_ID_KEY);
}
if (regionId == null)
regionId = "";
ExpandableListView listView = (ExpandableListView) view.findViewById(android.R.id.list);
listAdapter = new RegionsItemsAdapter();
listView.setAdapter(listAdapter);
setListView(listView);
if (regionId.length() > 0) {
ItemsListBuilder builder = getDownloadActivity().getItemsBuilder(regionId, false);
if (builder != null) {
fillRegionItemsAdapter(builder);
listAdapter.notifyDataSetChanged();
expandAllGroups();
}
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(REGION_ID_KEY, regionId);
super.onSaveInstanceState(outState);
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
Object obj = listAdapter.getChild(groupPosition, childPosition);
if (obj instanceof WorldRegion) {
WorldRegion region = (WorldRegion) obj;
((RegionDialogFragment) getParentFragment())
.onRegionSelected(region.getRegionId());
return true;
} else if (obj instanceof ItemsListBuilder.ResourceItem) {
if (((ItemViewHolder) v.getTag()).isItemAvailable()) {
IndexItem indexItem = ((ItemsListBuilder.ResourceItem) obj).getIndexItem();
if (indexItem.getType() == DownloadActivityType.ROADS_FILE) {
IndexItem regularMap =
((ItemsListBuilder.ResourceItem) listAdapter.getChild(0, 0))
.getIndexItem();
if (regularMap.getType() == DownloadActivityType.NORMAL_FILE
&& regularMap.isAlreadyDownloaded(getMyActivity().getIndexFileNames())) {
ConfirmDownloadUnneededMapDialogFragment.createInstance(indexItem)
.show(getChildFragmentManager(), "dialog");
return true;
}
}
getMyActivity().startDownload(indexItem);
return true;
}
}
return false;
}
private void expandAllGroups() {
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
getExpandableListView().expandGroup(i);
}
}
public OsmandApplication getMyApplication() {
return (OsmandApplication) getActivity().getApplication();
}
public DownloadActivity getMyActivity() {
return (DownloadActivity) getActivity();
}
private void fillRegionItemsAdapter(ItemsListBuilder builder) {
if (listAdapter != null) {
listAdapter.clear();
if (builder.getRegionMapItems().size() > 0) {
String sectionTitle = getResources().getString(R.string.region_maps);
listAdapter.add(sectionTitle, builder.getRegionMapItems());
}
if (builder.getAllResourceItems().size() > 0) {
String sectionTitle;
if (builder.getRegionMapItems().size() > 0) {
sectionTitle = getResources().getString(R.string.additional_maps);
} else {
sectionTitle = getResources().getString(R.string.regions);
}
listAdapter.add(sectionTitle, builder.getAllResourceItems());
}
}
}
private DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public static RegionItemsFragment createInstance(String regionId) {
Bundle bundle = new Bundle();
bundle.putString(REGION_ID_KEY, regionId);
RegionItemsFragment fragment = new RegionItemsFragment();
fragment.setArguments(bundle);
return fragment;
}
private class RegionsItemsAdapter extends OsmandBaseExpandableListAdapter {
private Map<String, List<Object>> data = new LinkedHashMap<>();
private List<String> sections = new LinkedList<>();
private int groupInProgressPosition = -1;
private int childInProgressPosition = -1;
private int progress = -1;
private boolean isFinished;
public RegionsItemsAdapter() {
}
public void clear() {
data.clear();
sections.clear();
notifyDataSetChanged();
}
public void add(String section, List<?> list) {
if (!sections.contains(section)) {
sections.add(section);
}
if (!data.containsKey(section)) {
data.put(section, new ArrayList<>());
}
data.get(section).addAll(list);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
String section = sections.get(groupPosition);
return data.get(section).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition * 10000 + childPosition;
}
@Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ItemViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.two_line_with_images_list_item, parent, false);
viewHolder = new ItemViewHolder(convertView, getMyActivity(),
getMyApplication().getResourceManager().getDateFormat());
convertView.setTag(viewHolder);
} else {
viewHolder = (ItemViewHolder) convertView.getTag();
}
final Object child = getChild(groupPosition, childPosition);
if (child instanceof WorldRegion) {
viewHolder.bindRegion((WorldRegion) child);
} else if (child instanceof ItemsListBuilder.ResourceItem) {
final int localProgress = groupPosition == groupInProgressPosition
&& childPosition == childInProgressPosition ? progress : -1;
viewHolder.bindIndexItem(((ItemsListBuilder.ResourceItem) child).getIndexItem(),
false, true, localProgress);
} else {
throw new IllegalArgumentException("Item must be of type WorldRegion or " +
"ResourceItem but is of type:" + child.getClass());
}
return convertView;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
View v = convertView;
String section = getGroup(groupPosition);
if (v == null) {
v = LayoutInflater.from(getDownloadActivity())
.inflate(R.layout.download_item_list_section, parent, false);
}
TextView nameView = ((TextView) v.findViewById(R.id.section_name));
nameView.setText(section);
v.setOnClickListener(null);
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getActivity().getTheme();
theme.resolveAttribute(R.attr.ctx_menu_info_view_bg, typedValue, true);
v.setBackgroundColor(typedValue.data);
return v;
}
@Override
public int getChildrenCount(int groupPosition) {
String section = sections.get(groupPosition);
return data.get(section).size();
}
@Override
public String getGroup(int groupPosition) {
return sections.get(groupPosition);
}
@Override
public int getGroupCount() {
return sections.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
public static class ConfirmDownloadUnneededMapDialogFragment extends DialogFragment {
private static final String INDEX_ITEM = "index_item";
private static IndexItem item = null;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final IndexItem indexItem = item;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.are_you_sure);
builder.setMessage(R.string.confirm_download_roadmaps);
builder.setNegativeButton(R.string.shared_string_cancel, null)
.setPositiveButton(R.string.shared_string_download,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(indexItem != null) {
((DownloadActivity) getActivity()).startDownload(indexItem);
}
}
});
return builder.create();
}
public static ConfirmDownloadUnneededMapDialogFragment createInstance(@NonNull IndexItem indexItem) {
ConfirmDownloadUnneededMapDialogFragment fragment =
new ConfirmDownloadUnneededMapDialogFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
}
}

View file

@ -1,33 +0,0 @@
package net.osmand.plus.download.items;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
*/
public class TwoLineWithImagesViewHolder {
protected final TextView nameTextView;
protected final TextView descrTextView;
protected final ImageView leftImageView;
protected final ImageView rightImageButton;
protected final Button rightButton;
protected final ProgressBar progressBar;
protected final TextView mapDateTextView;
protected final DownloadActivity context;
public TwoLineWithImagesViewHolder(View view, DownloadActivity context) {
this.context = context;
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mapDateTextView = (TextView) view.findViewById(R.id.mapDateTextView);
rightButton = (Button) view.findViewById(R.id.rightButton);
leftImageView = (ImageView) view.findViewById(R.id.leftImageView);
descrTextView = (TextView) view.findViewById(R.id.description);
rightImageButton = (ImageView) view.findViewById(R.id.rightImageButton);
nameTextView = (TextView) view.findViewById(R.id.name);
}
}

View file

@ -1,101 +0,0 @@
package net.osmand.plus.download.items;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.items.ItemsListBuilder.VoicePromptsType;
import org.apache.commons.logging.Log;
public class VoiceDialogFragment extends DialogFragment {
private static final Log LOG = PlatformUtil.getLog(VoiceDialogFragment.class);
public static final String TAG = "VoiceDialogFragment";
private static final String VOICE_PROMPT_TYPE_DLG_KEY = "voice_prompt_type_dlg_key";
private VoicePromptsType voicePromptsType = VoicePromptsType.NONE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean isLightTheme = ((OsmandApplication) getActivity().getApplication())
.getSettings().OSMAND_THEME.get() == OsmandSettings.OSMAND_LIGHT_THEME;
int themeId = isLightTheme ? R.style.OsmandLightTheme : R.style.OsmandDarkTheme;
setStyle(STYLE_NO_FRAME, themeId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.maps_in_category_fragment, container, false);
String value = null;
try {
if (savedInstanceState != null) {
value = savedInstanceState.getString(VOICE_PROMPT_TYPE_DLG_KEY);
if (value != null) {
voicePromptsType = VoicePromptsType.valueOf(value);
}
}
if (voicePromptsType == VoicePromptsType.NONE) {
value = getArguments().getString(VOICE_PROMPT_TYPE_DLG_KEY);
if (value != null) {
voicePromptsType = VoicePromptsType.valueOf(value);
}
}
} catch (IllegalArgumentException e) {
LOG.warn("VOICE_PROMPT_TYPE_DLG_KEY=" + value);
}
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(getMyApplication().getIconsCache().getIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
if (voicePromptsType != VoicePromptsType.NONE) {
Fragment fragment = getChildFragmentManager().findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
getChildFragmentManager().beginTransaction().add(R.id.fragmentContainer,
VoiceItemsFragment.createInstance(voicePromptsType)).commit();
}
toolbar.setTitle(ItemsListBuilder.getVoicePromtName(getActivity(), voicePromptsType));
}
((DownloadActivity)getActivity()).registerFreeVersionBanner(view);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(VOICE_PROMPT_TYPE_DLG_KEY, voicePromptsType.name());
super.onSaveInstanceState(outState);
}
private OsmandApplication getMyApplication() {
return (OsmandApplication) getActivity().getApplication();
}
public static VoiceDialogFragment createInstance(VoicePromptsType voicePromptsType) {
Bundle bundle = new Bundle();
bundle.putString(VOICE_PROMPT_TYPE_DLG_KEY, voicePromptsType.name());
VoiceDialogFragment fragment = new VoiceDialogFragment();
fragment.setArguments(bundle);
return fragment;
}
}

View file

@ -1,254 +0,0 @@
package net.osmand.plus.download.items;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.download.items.ItemsListBuilder.VoicePromptsType;
import org.apache.commons.logging.Log;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class VoiceItemsFragment extends OsmandExpandableListFragment {
public static final String TAG = "VoiceItemsFragment";
private static final Log LOG = PlatformUtil.getLog(VoiceItemsFragment.class);
private static final String VOICE_PROMPT_TYPE_KEY = "voice_prompt_type_key";
private VoicePromptsType voicePromptsType = VoicePromptsType.NONE;
private VoiceItemsAdapter listAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_items_fragment, container, false);
String value = null;
try {
if (savedInstanceState != null) {
value = savedInstanceState.getString(VOICE_PROMPT_TYPE_KEY);
if (value != null) {
voicePromptsType = VoicePromptsType.valueOf(value);
}
}
if (voicePromptsType == VoicePromptsType.NONE) {
value = getArguments().getString(VOICE_PROMPT_TYPE_KEY);
if (value != null) {
voicePromptsType = VoicePromptsType.valueOf(value);
}
}
} catch (IllegalArgumentException e) {
LOG.warn("VOICE_PROMPT_TYPE_KEY=" + value);
}
ExpandableListView listView = (ExpandableListView) view.findViewById(android.R.id.list);
listAdapter = new VoiceItemsAdapter(getActivity());
listView.setAdapter(listAdapter);
setListView(listView);
if (voicePromptsType != VoicePromptsType.NONE) {
ItemsListBuilder builder = getDownloadActivity().getVoicePromptsBuilder();
if (builder != null) {
fillVoiceItemsAdapter(builder);
listAdapter.notifyDataSetChanged();
expandAllGroups();
}
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(VOICE_PROMPT_TYPE_KEY, voicePromptsType.name());
super.onSaveInstanceState(outState);
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Object obj = listAdapter.getChild(groupPosition, childPosition);
if (((ItemViewHolder) v.getTag()).isItemAvailable()) {
IndexItem indexItem = (IndexItem) obj;
((BaseDownloadActivity) getActivity())
.startDownload(indexItem);
return true;
} else {
return false;
}
}
private void expandAllGroups() {
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
getExpandableListView().expandGroup(i);
}
}
public OsmandApplication getMyApplication() {
return (OsmandApplication) getActivity().getApplication();
}
public DownloadActivity getMyActivity() {
return (DownloadActivity) getActivity();
}
private void fillVoiceItemsAdapter(ItemsListBuilder builder) {
if (listAdapter != null) {
listAdapter.clear();
if (builder.getVoicePromptsItems(voicePromptsType).size() > 0) {
String sectionTitle = getResources().getString(R.string.voices);
listAdapter.add(sectionTitle, builder.getVoicePromptsItems(voicePromptsType));
}
}
}
private DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public static VoiceItemsFragment createInstance(VoicePromptsType voicePromptsType) {
Bundle bundle = new Bundle();
bundle.putString(VOICE_PROMPT_TYPE_KEY, voicePromptsType.name());
VoiceItemsFragment fragment = new VoiceItemsFragment();
fragment.setArguments(bundle);
return fragment;
}
private class VoiceItemsAdapter extends OsmandBaseExpandableListAdapter {
private Map<String, List<Object>> data = new LinkedHashMap<>();
private List<String> sections = new LinkedList<>();
public VoiceItemsAdapter(Context ctx) {
TypedArray ta = ctx.getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary});
ta.recycle();
}
public void clear() {
data.clear();
sections.clear();
notifyDataSetChanged();
}
public void add(String section, List<?> list) {
if (!sections.contains(section)) {
sections.add(section);
}
if (!data.containsKey(section)) {
data.put(section, new ArrayList<>());
}
data.get(section).addAll(list);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
String section = sections.get(groupPosition);
return data.get(section).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition * 10000 + childPosition;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final Object child = getChild(groupPosition, childPosition);
ItemViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.two_line_with_images_list_item, parent, false);
viewHolder = new ItemViewHolder(convertView,
getMyActivity(),
getMyApplication().getResourceManager().getDateFormat());
convertView.setTag(viewHolder);
} else {
viewHolder = (ItemViewHolder) convertView.getTag();
}
IndexItem item = (IndexItem) child;
viewHolder.bindIndexItem(item, true, false);
return convertView;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
String section = getGroup(groupPosition);
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getDownloadActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.download_item_list_section, parent, false);
}
TextView nameView = ((TextView) v.findViewById(R.id.section_name));
nameView.setText(section);
v.setOnClickListener(null);
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getActivity().getTheme();
theme.resolveAttribute(R.attr.ctx_menu_info_view_bg, typedValue, true);
v.setBackgroundColor(typedValue.data);
return v;
}
@Override
public int getChildrenCount(int groupPosition) {
String section = sections.get(groupPosition);
return data.get(section).size();
}
@Override
public String getGroup(int groupPosition) {
return sections.get(groupPosition);
}
@Override
public int getGroupCount() {
return sections.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}

View file

@ -1,357 +0,0 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.download.items.ItemsListBuilder.VoicePromptsType;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class WorldItemsFragment extends OsmandExpandableListFragment {
public static final String TAG = "WorldItemsFragment";
public static final int RELOAD_ID = 0;
public static final int SEARCH_ID = 1;
private WorldItemsAdapter listAdapter;
protected int worldRegionsIndex = -1;
protected int worldMapsIndex = -1;
protected int voicePromptsIndex = -1;
protected int voicePromptsItemsRecordedSubIndex = -1;
protected int voicePromptsItemsTTSSubIndex = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_index_fragment, container, false);
ExpandableListView listView = (ExpandableListView) view.findViewById(android.R.id.list);
listAdapter = new WorldItemsAdapter(getActivity());
listView.setAdapter(listAdapter);
expandAllGroups();
setListView(listView);
View usedSpaceCard = inflater.inflate(R.layout.used_space_card, listView, false);
getMyActivity().updateDescriptionTextWithSize(usedSpaceCard);
listView.addHeaderView(usedSpaceCard);
onCategorizationFinished();
return view;
}
@Override
public void onResume() {
super.onResume();
if (!listAdapter.isEmpty()) {
expandAllGroups();
}
}
private void expandAllGroups() {
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
getExpandableListView().expandGroup(i);
}
}
public OsmandApplication getMyApplication() {
return (OsmandApplication) getActivity().getApplication();
}
public DownloadActivity getMyActivity() {
return (DownloadActivity) getActivity();
}
private void fillWorldItemsAdapter(ItemsListBuilder builder) {
if (listAdapter != null) {
listAdapter.clear();
if (builder.getRegionMapItems().size() > 0) {
int unusedIndex = 0;
worldRegionsIndex = unusedIndex++;
listAdapter.add(getResources().getString(R.string.world_regions), builder.getRegionsFromAllItems());
worldMapsIndex = unusedIndex++;
listAdapter.add(getResources().getString(R.string.world_maps), builder.getRegionMapItems());
int unusedSubIndex = 0;
List<String> voicePromptsItems = new LinkedList<>();
if (!builder.isVoicePromptsItemsEmpty(VoicePromptsType.RECORDED)) {
voicePromptsItems.add(ItemsListBuilder.getVoicePromtName(getActivity(), VoicePromptsType.RECORDED));
voicePromptsItemsRecordedSubIndex = unusedSubIndex++;
}
if (!builder.isVoicePromptsItemsEmpty(VoicePromptsType.TTS)) {
voicePromptsItems.add(ItemsListBuilder.getVoicePromtName(getActivity(), VoicePromptsType.TTS));
voicePromptsItemsTTSSubIndex = unusedSubIndex;
}
if (!voicePromptsItems.isEmpty()) {
voicePromptsIndex = unusedIndex;
listAdapter.add(getResources().getString(R.string.voices), voicePromptsItems);
}
}
}
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
if (groupPosition == worldRegionsIndex) {
WorldRegion region = (WorldRegion)listAdapter.getChild(groupPosition, childPosition);
final RegionDialogFragment regionDialogFragment = RegionDialogFragment.createInstance(region.getRegionId());
regionDialogFragment.setOnDismissListener(getDownloadActivity());
getDownloadActivity().showDialog(getActivity(), regionDialogFragment);
return true;
} else if (groupPosition == voicePromptsIndex) {
if (childPosition == voicePromptsItemsRecordedSubIndex) {
getDownloadActivity().showDialog(getActivity(),
VoiceDialogFragment.createInstance(VoicePromptsType.RECORDED));
} else {
getDownloadActivity().showDialog(getActivity(),
VoiceDialogFragment.createInstance(VoicePromptsType.TTS));
}
}else if (groupPosition == worldMapsIndex) {
if(((ItemViewHolder) v.getTag()).isItemAvailable()) {
IndexItem indexItem = ((ItemsListBuilder.ResourceItem)
listAdapter.getChild(groupPosition, childPosition)).getIndexItem();
((BaseDownloadActivity) getActivity())
.startDownload(indexItem);
return true;
}
}
return false;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem itemReload = menu.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
itemReload.setIcon(R.drawable.ic_action_refresh_dark);
MenuItemCompat.setShowAsAction(itemReload, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
MenuItem itemSearch = menu.add(0, SEARCH_ID, 1, R.string.shared_string_search);
itemSearch.setIcon(R.drawable.ic_action_search_dark);
MenuItemCompat.setShowAsAction(itemSearch, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case RELOAD_ID:
// re-create the thread
DownloadActivity.downloadListIndexThread.runReloadIndexFiles();
return true;
case SEARCH_ID:
getDownloadActivity().showDialog(getActivity(), SearchDialogFragment.createInstance(""));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public void onCategorizationFinished() {
ItemsListBuilder builder = getDownloadActivity().getItemsBuilder();
if (builder != null) {
fillWorldItemsAdapter(builder);
listAdapter.notifyDataSetChanged();
expandAllGroups();
}
}
private class WorldItemsAdapter extends OsmandBaseExpandableListAdapter {
private Map<String, List<Object>> data = new LinkedHashMap<>();
private List<String> sections = new LinkedList<>();
private class SimpleViewHolder {
TextView textView;
}
public WorldItemsAdapter(Context ctx) {
TypedArray ta = ctx.getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary});
ta.recycle();
}
public void clear() {
data.clear();
sections.clear();
notifyDataSetChanged();
}
public void add(String section, List<?> list) {
if (!sections.contains(section)) {
sections.add(section);
}
if (!data.containsKey(section)) {
data.put(section, new ArrayList<>());
}
data.get(section).addAll(list);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
String section = sections.get(groupPosition);
return data.get(section).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition * 10000 + childPosition;
}
@Override
public int getChildType(int groupPosition, int childPosition) {
if (groupPosition == worldRegionsIndex || groupPosition == voicePromptsIndex) {
return 0;
} else {
return 1;
}
}
@Override
public int getChildTypeCount() {
return 2;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final Object child = getChild(groupPosition, childPosition);
if (groupPosition == worldRegionsIndex) {
WorldRegion item = (WorldRegion)child;
SimpleViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.simple_list_menu_item, parent, false);
viewHolder = new SimpleViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(viewHolder);
} else {
viewHolder = (SimpleViewHolder) convertView.getTag();
}
Drawable iconLeft = getMyApplication().getIconsCache()
.getContentIcon(R.drawable.ic_world_globe_dark);
viewHolder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft, null, null, null);
viewHolder.textView.setText(item.getName());
} else if (groupPosition == worldMapsIndex) {
ItemsListBuilder.ResourceItem item = (ItemsListBuilder.ResourceItem) child;
ItemViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.two_line_with_images_list_item, parent, false);
viewHolder = new ItemViewHolder(convertView,
getMyActivity(),
getMyApplication().getResourceManager().getDateFormat());
convertView.setTag(viewHolder);
} else {
viewHolder = (ItemViewHolder) convertView.getTag();
}
viewHolder.bindIndexItem(item.getIndexItem(), false, false);
} else if (groupPosition == voicePromptsIndex) {
String item = (String)child;
SimpleViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.simple_list_menu_item, parent, false);
viewHolder = new SimpleViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(viewHolder);
} else {
viewHolder = (SimpleViewHolder) convertView.getTag();
}
Drawable iconLeft = getMyApplication().getIconsCache()
.getContentIcon(R.drawable.ic_action_volume_up);
viewHolder.textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft, null, null, null);
viewHolder.textView.setText(item);
}
return convertView;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, final View convertView,
final ViewGroup parent) {
View v = convertView;
String section = getGroup(groupPosition);
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getDownloadActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.download_item_list_section, parent, false);
}
TextView nameView = ((TextView) v.findViewById(R.id.section_name));
nameView.setText(section);
v.setOnClickListener(null);
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getActivity().getTheme();
theme.resolveAttribute(R.attr.ctx_menu_info_view_bg, typedValue, true);
v.setBackgroundColor(typedValue.data);
return v;
}
@Override
public int getChildrenCount(int groupPosition) {
String section = sections.get(groupPosition);
return data.get(section).size();
}
@Override
public String getGroup(int groupPosition) {
return sections.get(groupPosition);
}
@Override
public int getGroupCount() {
return sections.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}

View file

@ -0,0 +1,94 @@
package net.osmand.plus.download.ui;
import java.util.ArrayList;
import java.util.List;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import net.osmand.plus.download.IndexItem;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class ActiveDownloadsDialogFragment extends DialogFragment implements DownloadEvents {
private IndexItemAdapter adapter;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.downloads).setNegativeButton(R.string.shared_string_dismiss, null);
adapter = new IndexItemAdapter(this, getDownloadActivity());
builder.setAdapter(adapter, null);
return builder.create();
}
public void newDownloadIndexes() {
adapter.refreshAllData();
};
@Override
public void downloadHasFinished() {
adapter.refreshAllData();
}
public void downloadInProgress() {
adapter.notifyDataSetChanged();
};
DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public static class IndexItemAdapter extends ArrayAdapter<IndexItem> {
private final DownloadActivity context;
private DialogFragment dlgFragment;
public IndexItemAdapter(DialogFragment dlgFragment, DownloadActivity context) {
super(context, R.layout.two_line_with_images_list_item, new ArrayList<IndexItem>());
this.dlgFragment = dlgFragment;
this.context = context;
refreshAllData();
}
public void refreshAllData() {
clear();
List<IndexItem> items = context.getDownloadThread().getCurrentDownloadingItems();
if(items.isEmpty()) {
dlgFragment.dismissAllowingStateLoss();
}
addAll(context.getDownloadThread().getCurrentDownloadingItems());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.two_line_with_images_list_item, parent, false);
ItemViewHolder viewHolder =
new ItemViewHolder(convertView, context);
viewHolder.setSilentCancelDownload(true);
viewHolder.setShowTypeInDesc(true);
viewHolder.setShowProgressInDescr(true);
convertView.setTag(viewHolder);
}
ItemViewHolder viewHolder = (ItemViewHolder) convertView.getTag();
IndexItem item = getItem(position);
viewHolder.bindIndexItem(item);
return convertView;
}
}
}

View file

@ -0,0 +1,468 @@
package net.osmand.plus.download.ui;
import java.util.ArrayList;
import java.util.List;
import net.osmand.plus.IconsCache;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivity.BannerAndDownloadFreeVersion;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import net.osmand.plus.download.DownloadResourceGroup;
import net.osmand.plus.download.DownloadResourceGroup.DownloadResourceGroupType;
import net.osmand.plus.download.DownloadResources;
import net.osmand.plus.download.IndexItem;
import net.osmand.util.Algorithms;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;
public class DownloadResourceGroupFragment extends DialogFragment implements DownloadEvents, OnChildClickListener {
public static final int RELOAD_ID = 0;
public static final int SEARCH_ID = 1;
public static final String TAG = "RegionDialogFragment";
private static final String REGION_ID_DLG_KEY = "world_region_dialog_key";
private String groupId;
private View view;
private BannerAndDownloadFreeVersion banner;
protected ExpandableListView listView;
protected DownloadResourceGroupAdapter listAdapter;
private DownloadResourceGroup group;
private DownloadActivity activity;
private Toolbar toolbar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean isLightTheme = getMyApplication().getSettings().OSMAND_THEME.get() == OsmandSettings.OSMAND_LIGHT_THEME;
int themeId = isLightTheme ? R.style.OsmandLightTheme : R.style.OsmandDarkTheme;
setStyle(STYLE_NO_FRAME, themeId);
setHasOptionsMenu(true);
}
public boolean openAsDialog() {
return !Algorithms.isEmpty(groupId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.maps_in_category_fragment, container, false);
if (savedInstanceState != null) {
groupId = savedInstanceState.getString(REGION_ID_DLG_KEY);
}
if (groupId == null && getArguments() != null) {
groupId = getArguments().getString(REGION_ID_DLG_KEY);
}
if (groupId == null) {
groupId = "";
}
activity = (DownloadActivity) getActivity();
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(getMyApplication().getIconsCache().getIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
if (!openAsDialog()) {
toolbar.setVisibility(View.GONE);
}
setHasOptionsMenu(true);
if(openAsDialog()) {
banner = new BannerAndDownloadFreeVersion(view, (DownloadActivity) getActivity());
} else {
banner = null;
view.findViewById(R.id.freeVersionBanner).setVisibility(View.GONE);
}
listView = (ExpandableListView) view.findViewById(android.R.id.list);
listView.setOnChildClickListener(this);
listAdapter = new DownloadResourceGroupAdapter(activity);
listView.setAdapter(listAdapter);
reloadData();
return view;
}
private void reloadData() {
DownloadResources indexes = activity.getDownloadThread().getIndexes();
group = indexes.getGroupById(groupId);
if (group != null) {
listAdapter.update(group);
toolbar.setTitle(group.getName(activity));
}
expandAllGroups();
}
private void expandAllGroups() {
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
listView.expandGroup(i);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setShowsDialog(openAsDialog());
listView.setBackgroundColor(getResources().getColor(
getMyApplication().getSettings().isLightContent() ? R.color.bg_color_light : R.color.bg_color_dark));
}
@Override
public void newDownloadIndexes() {
if(banner != null) {
banner.updateBannerInProgress();
}
reloadData();
}
@Override
public void downloadHasFinished() {
if(banner != null) {
banner.updateBannerInProgress();
}
listAdapter.notifyDataSetChanged();
}
@Override
public void downloadInProgress() {
if(banner != null) {
banner.updateBannerInProgress();
}
listAdapter.notifyDataSetChanged();
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Object child = listAdapter.getChild(groupPosition, childPosition);
if (child instanceof DownloadResourceGroup) {
String uniqueId = ((DownloadResourceGroup) child).getUniqueId();
final DownloadResourceGroupFragment regionDialogFragment = DownloadResourceGroupFragment
.createInstance(uniqueId);
((DownloadActivity) getActivity()).showDialog(getActivity(), regionDialogFragment);
return true;
} else if (child instanceof IndexItem) {
IndexItem indexItem = (IndexItem) child;
DownloadResourceGroup groupObj = listAdapter.getGroupObj(groupPosition);
boolean handled = false;
if (indexItem.getType() == DownloadActivityType.ROADS_FILE && groupObj != null
&& !activity.getDownloadThread().isDownloading(indexItem)) {
for (IndexItem ii : groupObj.getIndividualResources()) {
if (ii.getType() == DownloadActivityType.NORMAL_FILE) {
if (ii.isDownloaded()) {
handled = true;
ConfirmDownloadUnneededMapDialogFragment.createInstance(indexItem).show(
getChildFragmentManager(), "dialog");
}
break;
}
}
}
if (!handled) {
ItemViewHolder vh = (ItemViewHolder) v.getTag();
OnClickListener ls = vh.getRightButtonAction(indexItem, vh.getClickAction(indexItem));
ls.onClick(v);
}
return true;
}
return false;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(REGION_ID_DLG_KEY, groupId);
super.onSaveInstanceState(outState);
}
private OsmandApplication getMyApplication() {
return (OsmandApplication) getActivity().getApplication();
}
private DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (!openAsDialog()) {
MenuItem itemReload = menu.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
itemReload.setIcon(R.drawable.ic_action_refresh_dark);
MenuItemCompat.setShowAsAction(itemReload, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
MenuItem itemSearch = menu.add(0, SEARCH_ID, 1, R.string.shared_string_search);
itemSearch.setIcon(R.drawable.ic_action_search_dark);
MenuItemCompat.setShowAsAction(itemSearch, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case RELOAD_ID:
// re-create the thread
getDownloadActivity().getDownloadThread().runReloadIndexFiles();
return true;
case SEARCH_ID:
getDownloadActivity().showDialog(getActivity(), SearchDialogFragment.createInstance(""));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static DownloadResourceGroupFragment createInstance(String regionId) {
Bundle bundle = new Bundle();
bundle.putString(REGION_ID_DLG_KEY, regionId);
DownloadResourceGroupFragment fragment = new DownloadResourceGroupFragment();
fragment.setArguments(bundle);
return fragment;
}
public static class ConfirmDownloadUnneededMapDialogFragment extends DialogFragment {
private static IndexItem item = null;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final IndexItem indexItem = item;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.are_you_sure);
builder.setMessage(R.string.confirm_download_roadmaps);
builder.setNegativeButton(R.string.shared_string_cancel, null).setPositiveButton(
R.string.shared_string_download, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (indexItem != null) {
((DownloadActivity) getActivity()).startDownload(indexItem);
}
}
});
return builder.create();
}
public static ConfirmDownloadUnneededMapDialogFragment createInstance(@NonNull IndexItem indexItem) {
ConfirmDownloadUnneededMapDialogFragment fragment = new ConfirmDownloadUnneededMapDialogFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
}
private static class DownloadGroupViewHolder {
TextView textView;
private DownloadActivity ctx;
public DownloadGroupViewHolder(DownloadActivity ctx, View v) {
this.ctx = ctx;
textView = (TextView) v.findViewById(R.id.title);
}
private Drawable getIconForGroup(DownloadResourceGroup group) {
Drawable iconLeft;
if (group.getType() == DownloadResourceGroupType.VOICE_REC
|| group.getType() == DownloadResourceGroupType.VOICE_TTS) {
iconLeft = ctx.getMyApplication().getIconsCache().getContentIcon(R.drawable.ic_action_volume_up);
} else {
IconsCache cache = ctx.getMyApplication().getIconsCache();
if (group.getParentGroup() == null
|| group.getParentGroup().getType() == DownloadResourceGroupType.WORLD) {
iconLeft = cache.getContentIcon(R.drawable.ic_world_globe_dark);
} else {
DownloadResourceGroup ggr = group
.getGroupById(DownloadResourceGroupType.REGION_MAPS.getDefaultId());
iconLeft = cache.getContentIcon(R.drawable.ic_map);
if (ggr != null && ggr.getIndividualResources() != null) {
IndexItem item = null;
for (IndexItem ii : ggr.getIndividualResources()) {
if (ii.getType() == DownloadActivityType.NORMAL_FILE
|| ii.getType() == DownloadActivityType.ROADS_FILE) {
if (ii.isDownloaded() || ii.isOutdated()) {
item = ii;
break;
}
}
}
if (item != null) {
if (item.isOutdated()) {
iconLeft = cache.getIcon(R.drawable.ic_map,
ctx.getResources().getColor(R.color.color_distance));
} else {
iconLeft = cache.getIcon(R.drawable.ic_map,
ctx.getResources().getColor(R.color.color_ok));
}
}
}
}
}
return iconLeft;
}
public void bindItem(DownloadResourceGroup group) {
Drawable iconLeft = getIconForGroup(group);
textView.setCompoundDrawablesWithIntrinsicBounds(iconLeft, null, null, null);
String name = group.getName(ctx);
textView.setText(name);
}
}
public static class DownloadResourceGroupAdapter extends OsmandBaseExpandableListAdapter {
private List<DownloadResourceGroup> data = new ArrayList<DownloadResourceGroup>();
private DownloadActivity ctx;
public DownloadResourceGroupAdapter(DownloadActivity ctx) {
this.ctx = ctx;
TypedArray ta = ctx.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
ta.recycle();
}
public void clear() {
data.clear();
notifyDataSetChanged();
}
public void update(DownloadResourceGroup mainGroup) {
data = mainGroup.getGroups();
notifyDataSetChanged();
}
@Override
public Object getChild(int groupPosition, int childPosition) {
DownloadResourceGroup drg = data.get(groupPosition);
if (drg.getType().containsIndexItem()) {
return drg.getItemByIndex(childPosition);
}
return drg.getGroupByIndex(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition * 10000 + childPosition;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
final Object child = getChild(groupPosition, childPosition);
if (child instanceof IndexItem) {
IndexItem item = (IndexItem) child;
ItemViewHolder viewHolder;
if (convertView != null && convertView.getTag() instanceof ItemViewHolder) {
viewHolder = (ItemViewHolder) convertView.getTag();
} else {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.two_line_with_images_list_item, parent, false);
viewHolder = new ItemViewHolder(convertView, ctx);
viewHolder.setShowRemoteDate(true);
viewHolder.setShowTypeInDesc(true);
convertView.setTag(viewHolder);
}
viewHolder.bindIndexItem(item);
} else {
DownloadResourceGroup group = (DownloadResourceGroup) child;
DownloadGroupViewHolder viewHolder;
if (convertView != null && convertView.getTag() instanceof DownloadGroupViewHolder) {
viewHolder = (DownloadGroupViewHolder) convertView.getTag();
} else {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_list_menu_item,
parent, false);
viewHolder = new DownloadGroupViewHolder(ctx, convertView);
convertView.setTag(viewHolder);
}
viewHolder.bindItem(group);
}
return convertView;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, final View convertView, final ViewGroup parent) {
View v = convertView;
String section = getGroup(groupPosition);
if (v == null) {
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.download_item_list_section, parent, false);
}
TextView nameView = ((TextView) v.findViewById(R.id.section_name));
nameView.setText(section);
v.setOnClickListener(null);
TypedValue typedValue = new TypedValue();
Resources.Theme theme = ctx.getTheme();
theme.resolveAttribute(R.attr.ctx_menu_info_view_bg, typedValue, true);
v.setBackgroundColor(typedValue.data);
return v;
}
@Override
public int getChildrenCount(int groupPosition) {
return data.get(groupPosition).size();
}
public DownloadResourceGroup getGroupObj(int groupPosition) {
return data.get(groupPosition);
}
@Override
public String getGroup(int groupPosition) {
DownloadResourceGroup drg = data.get(groupPosition);
int rid = drg.getType().getResourceId();
if (rid != -1) {
return ctx.getString(rid);
}
return "";
}
@Override
public int getGroupCount() {
return data.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}

View file

@ -0,0 +1,297 @@
package net.osmand.plus.download.ui;
import java.text.DateFormat;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadResources;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.openseamapsplugin.NauticalMapsPlugin;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class ItemViewHolder {
protected final TextView nameTextView;
protected final TextView descrTextView;
protected final ImageView leftImageView;
protected final ImageView rightImageButton;
protected final Button rightButton;
protected final ProgressBar progressBar;
private boolean srtmDisabled;
private boolean srtmNeedsInstallation;
private boolean nauticalPluginDisabled;
private boolean freeVersion;
protected final DownloadActivity context;
private int textColorPrimary;
private int textColorSecondary;
boolean showTypeInDesc;
boolean showRemoteDate;
boolean silentCancelDownload;
boolean showProgressInDesc;
private DateFormat dateFormat;
private enum RightButtonAction {
DOWNLOAD,
ASK_FOR_SEAMARKS_PLUGIN,
ASK_FOR_SRTM_PLUGIN_PURCHASE,
ASK_FOR_SRTM_PLUGIN_ENABLE,
ASK_FOR_FULL_VERSION_PURCHASE
}
public ItemViewHolder(View view, DownloadActivity context) {
this.context = context;
dateFormat = android.text.format.DateFormat.getMediumDateFormat(context);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
rightButton = (Button) view.findViewById(R.id.rightButton);
leftImageView = (ImageView) view.findViewById(R.id.leftImageView);
descrTextView = (TextView) view.findViewById(R.id.description);
rightImageButton = (ImageView) view.findViewById(R.id.rightImageButton);
nameTextView = (TextView) view.findViewById(R.id.name);
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
textColorPrimary = typedValue.data;
theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
textColorSecondary = typedValue.data;
}
public void setShowRemoteDate(boolean showRemoteDate) {
this.showRemoteDate = showRemoteDate;
}
public void setShowProgressInDescr(boolean b) {
showProgressInDesc = b;
}
public void setSilentCancelDownload(boolean silentCancelDownload) {
this.silentCancelDownload = silentCancelDownload;
}
public void setShowTypeInDesc(boolean showTypeInDesc) {
this.showTypeInDesc = showTypeInDesc;
}
// FIXME don't initialize on every row
private void initAppStatusVariables() {
srtmDisabled = OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) == null;
nauticalPluginDisabled = OsmandPlugin.getEnabledPlugin(NauticalMapsPlugin.class) == null;
freeVersion = Version.isFreeVersion(context.getMyApplication());
OsmandPlugin srtmPlugin = OsmandPlugin.getPlugin(SRTMPlugin.class);
srtmNeedsInstallation = srtmPlugin == null || srtmPlugin.needsInstallation();
}
public void bindIndexItem(final IndexItem indexItem) {
initAppStatusVariables();
boolean isDownloading = context.getDownloadThread().isDownloading(indexItem);
int progress = -1;
if (context.getDownloadThread().getCurrentDownloadingItem() == indexItem) {
progress = context.getDownloadThread().getCurrentDownloadingItemProgress();
}
boolean disabled = checkDisabledAndClickAction(indexItem);
/// name and left item
nameTextView.setText(indexItem.getVisibleName(context, context.getMyApplication().getRegions(), false));
if(!disabled) {
nameTextView.setTextColor(textColorPrimary);
} else {
nameTextView.setTextColor(textColorSecondary);
}
int color = textColorSecondary;
if(indexItem.isDownloaded() && !isDownloading) {
int colorId = indexItem.isOutdated() ? R.color.color_distance : R.color.color_ok;
color = context.getResources().getColor(colorId);
}
if (indexItem.isDownloaded()) {
leftImageView.setImageDrawable(getContentIcon(context,
indexItem.getType().getIconResource(), color));
} else if (disabled) {
leftImageView.setImageDrawable(getContentIcon(context,
indexItem.getType().getIconResource(), textColorSecondary));
} else {
leftImageView.setImageDrawable(getContentIcon(context,
indexItem.getType().getIconResource()));
}
descrTextView.setTextColor(textColorSecondary);
if (!isDownloading) {
progressBar.setVisibility(View.GONE);
descrTextView.setVisibility(View.VISIBLE);
if ((indexItem.getType() == DownloadActivityType.SRTM_COUNTRY_FILE ||
indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) && srtmDisabled) {
descrTextView.setText(indexItem.getType().getString(context));
} else if (showTypeInDesc) {
descrTextView.setText(indexItem.getType().getString(context) +
"" + indexItem.getSizeDescription(context) +
"" + (showRemoteDate ? indexItem.getRemoteDate(dateFormat) : indexItem.getLocalDate(dateFormat)));
} else {
descrTextView.setText(indexItem.getSizeDescription(context) + "" +
(showRemoteDate ? indexItem.getRemoteDate(dateFormat) : indexItem.getLocalDate(dateFormat)));
}
rightImageButton.setImageDrawable(getContentIcon(context, R.drawable.ic_action_import));
rightImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.startDownload(indexItem);
}
});
} else {
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(progress == -1);
progressBar.setProgress(progress);
if (showProgressInDesc) {
double mb = indexItem.getArchiveSizeMB();
String v ;
if (progress != -1) {
v = context.getString(R.string.value_downloaded_from_max, mb * progress / 100, mb);
} else {
v = context.getString(R.string.file_size_in_mb, mb);
}
if(showTypeInDesc && indexItem.getType() == DownloadActivityType.ROADS_FILE) {
descrTextView.setText(indexItem.getType().getString(context) + "" + v);
} else {
descrTextView.setText(v);
}
descrTextView.setVisibility(View.VISIBLE);
} else {
descrTextView.setVisibility(View.GONE);
}
rightImageButton.setImageDrawable(getContentIcon(context, R.drawable.ic_action_remove_dark));
rightImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(silentCancelDownload) {
context.getDownloadThread().cancelDownload(indexItem);
} else {
context.makeSureUserCancelDownload(indexItem);
}
}
});
}
}
private boolean checkDisabledAndClickAction(final IndexItem indexItem) {
RightButtonAction clickAction = getClickAction(indexItem);
boolean disabled = clickAction != RightButtonAction.DOWNLOAD;
if (clickAction != RightButtonAction.DOWNLOAD) {
rightButton.setText(R.string.get_plugin);
rightButton.setVisibility(View.VISIBLE);
rightImageButton.setVisibility(View.GONE);
rightButton.setOnClickListener(getRightButtonAction(indexItem, clickAction));
} else {
rightButton.setVisibility(View.GONE);
rightImageButton.setVisibility(View.VISIBLE);
}
return disabled;
}
@SuppressLint("DefaultLocale")
public RightButtonAction getClickAction(final IndexItem indexItem) {
RightButtonAction clickAction = RightButtonAction.DOWNLOAD;
if (indexItem.getBasename().toLowerCase().equals(DownloadResources.WORLD_SEAMARKS_KEY)
&& nauticalPluginDisabled) {
clickAction = RightButtonAction.ASK_FOR_SEAMARKS_PLUGIN;
} else if ((indexItem.getType() == DownloadActivityType.SRTM_COUNTRY_FILE ||
indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) && srtmDisabled) {
if (srtmNeedsInstallation) {
clickAction = RightButtonAction.ASK_FOR_SRTM_PLUGIN_PURCHASE;
} else {
clickAction = RightButtonAction.ASK_FOR_SRTM_PLUGIN_ENABLE;
}
} else if (indexItem.getType() == DownloadActivityType.WIKIPEDIA_FILE && freeVersion) {
clickAction = RightButtonAction.ASK_FOR_FULL_VERSION_PURCHASE;
}
return clickAction;
}
public OnClickListener getRightButtonAction(final IndexItem item, final RightButtonAction clickAction) {
if (clickAction != RightButtonAction.DOWNLOAD) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (clickAction) {
case ASK_FOR_FULL_VERSION_PURCHASE:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Version.marketPrefix(context
.getMyApplication()) + "net.osmand.plus"));
context.startActivity(intent);
break;
case ASK_FOR_SEAMARKS_PLUGIN:
context.startActivity(new Intent(context, context.getMyApplication().getAppCustomization()
.getPluginsActivity()));
AccessibleToast.makeText(context.getApplicationContext(),
context.getString(R.string.activate_seamarks_plugin), Toast.LENGTH_SHORT).show();
break;
case ASK_FOR_SRTM_PLUGIN_PURCHASE:
OsmandPlugin plugin = OsmandPlugin.getPlugin(SRTMPlugin.class);
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(plugin.getInstallURL())));
break;
case ASK_FOR_SRTM_PLUGIN_ENABLE:
context.startActivity(new Intent(context, context.getMyApplication().getAppCustomization()
.getPluginsActivity()));
AccessibleToast.makeText(context, context.getString(R.string.activate_srtm_plugin),
Toast.LENGTH_SHORT).show();
break;
case DOWNLOAD:
break;
}
}
};
} else {
final boolean isDownloading = context.getDownloadThread().isDownloading(item);
return new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isDownloading) {
if(silentCancelDownload) {
context.getDownloadThread().cancelDownload(item);
} else {
context.makeSureUserCancelDownload(item);
}
} else {
context.startDownload(item);
}
}
};
}
}
private Drawable getContentIcon(DownloadActivity context, int resourceId) {
return context.getMyApplication().getIconsCache().getContentIcon(resourceId);
}
private Drawable getContentIcon(DownloadActivity context, int resourceId, int color) {
return context.getMyApplication().getIconsCache().getPaintedContentIcon(resourceId, color);
}
}

View file

@ -1,4 +1,4 @@
package net.osmand.plus.download;
package net.osmand.plus.download.ui;
import android.app.Activity;
import android.app.AlertDialog;
@ -33,7 +33,6 @@ import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.osmand.IProgress;
import net.osmand.IndexConstants;
import net.osmand.access.AccessibleToast;
@ -49,6 +48,10 @@ import net.osmand.plus.activities.LocalIndexInfo;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.dialogs.DirectionsDialogs;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.helpers.FileNameTranslationHelper;
import net.osmand.plus.resources.IncrementalChangesManager;
import net.osmand.plus.resources.IncrementalChangesManager.IncrementalUpdate;
@ -69,7 +72,7 @@ import java.util.Map;
import java.util.Set;
public class LocalIndexesFragment extends OsmandExpandableListFragment {
public class LocalIndexesFragment extends OsmandExpandableListFragment implements DownloadEvents {
private LoadLocalIndexTask asyncLoader;
private LocalIndexesAdapter listAdapter;
@ -161,6 +164,8 @@ public class LocalIndexesFragment extends OsmandExpandableListFragment {
}
private void showContextMenu(final LocalIndexInfo info) {
Builder builder = new AlertDialog.Builder(getActivity());
final ContextMenuAdapter adapter = new ContextMenuAdapter(getActivity());
@ -448,6 +453,20 @@ public class LocalIndexesFragment extends OsmandExpandableListFragment {
}
}
@Override
public void newDownloadIndexes() {
}
@Override
public void downloadHasFinished() {
((DownloadActivity) getActivity()).updateDescriptionTextWithSize(getView());
reloadData();
}
@Override
public void downloadInProgress() {
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

View file

@ -1,4 +1,4 @@
package net.osmand.plus.download.items;
package net.osmand.plus.download.ui;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
@ -10,18 +10,27 @@ import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SearchView;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
// FIXME
public class SearchDialogFragment extends DialogFragment {
public static DialogFragment createInstance(String tg) {
return new SearchDialogFragment();
}
/*extends DialogFragment implements DownloadEvents {
public static final String TAG = "SearchDialogFragment";
private static final String SEARCH_TEXT_DLG_KEY = "search_text_dlg_key";
private String searchText;
SearchView search;
private SearchView search;
@Override
public void onCreate(Bundle savedInstanceState) {
@ -125,7 +134,7 @@ public class SearchDialogFragment extends DialogFragment {
return (DownloadActivity) getActivity();
}
public void onCategorizationFinished() {
public void newDownloadIndexes() {
Fragment f = getChildFragmentManager().findFragmentByTag(SearchItemsFragment.TAG);
if (f != null) {
((SearchItemsFragment) f).onCategorizationFinished();
@ -139,4 +148,5 @@ public class SearchDialogFragment extends DialogFragment {
fragment.setArguments(bundle);
return fragment;
}
*/
}

View file

@ -1,4 +1,4 @@
package net.osmand.plus.download.items;
package net.osmand.plus.download.ui;
import java.util.ArrayList;
import java.util.Collections;
@ -14,6 +14,7 @@ import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import net.osmand.plus.download.IndexItem;
import android.content.Context;
import android.content.res.TypedArray;
@ -28,7 +29,8 @@ import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
public class SearchItemsFragment extends Fragment {
//FIXME merge into search dialog fragment
public class SearchItemsFragment { /*extends Fragment implements DownloadEvents {
public static final String TAG = "SearchItemsFragment";
private SearchItemsAdapter listAdapter;
@ -331,4 +333,5 @@ public class SearchItemsFragment extends Fragment {
}
}
}
*/
}

View file

@ -0,0 +1,188 @@
package net.osmand.plus.download.ui;
import java.util.Comparator;
import java.util.List;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmAndListFragment;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents;
import net.osmand.plus.download.DownloadResources;
import net.osmand.plus.download.IndexItem;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class UpdatesIndexFragment extends OsmAndListFragment implements DownloadEvents {
private static final int RELOAD_ID = 5;
private UpdateIndexAdapter listAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
invalidateListView();
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.update_index_frament, container, false);
}
@Override
public ArrayAdapter<?> getAdapter() {
return listAdapter;
}
@Override
public void downloadHasFinished() {
invalidateListView();
updateUpdateAllButton();
}
@Override
public void downloadInProgress() {
listAdapter.notifyDataSetChanged();
}
@Override
public void newDownloadIndexes() {
invalidateListView();
updateUpdateAllButton();
}
public void invalidateListView() {
DownloadResources indexes = getMyActivity().getDownloadThread().getIndexes();
List<IndexItem> indexItems = indexes.getItemsToUpdate();
if (indexItems.size() == 0) {
if (indexes.isDownloadedFromInternet) {
indexItems.add(new IndexItem(getString(R.string.everything_up_to_date), "", 0, "", 0, 0, null));
} else {
indexItems.add(new IndexItem(getString(R.string.no_index_file_to_download), "", 0, "", 0, 0, null));
}
}
final OsmandRegions osmandRegions =
getMyApplication().getResourceManager().getOsmandRegions();
listAdapter = new UpdateIndexAdapter(getMyActivity(), R.layout.download_index_list_item, indexItems);
listAdapter.sort(new Comparator<IndexItem>() {
@Override
public int compare(IndexItem indexItem, IndexItem indexItem2) {
return indexItem.getVisibleName(getMyApplication(), osmandRegions)
.compareTo(indexItem2.getVisibleName(getMyApplication(), osmandRegions));
}
});
setListAdapter(listAdapter);
}
private void updateUpdateAllButton() {
View view = getView();
if (view == null) {
return;
}
DownloadResources indexes = getMyActivity().getDownloadThread().getIndexes();
final List<IndexItem> indexItems = indexes.getItemsToUpdate();
final TextView updateAllButton = (TextView) view.findViewById(R.id.updateAllButton);
if (indexItems.size() == 0 || indexItems.get(0).getType() == null) {
updateAllButton.setVisibility(View.GONE);
} else {
updateAllButton.setVisibility(View.VISIBLE);
long downloadsSize = 0;
for (IndexItem indexItem : indexItems) {
downloadsSize += indexItem.getSize();
}
String updateAllText = getActivity().getString(R.string.update_all, downloadsSize >> 20);
updateAllButton.setText(updateAllText);
updateAllButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getMyActivity().startDownload(indexItems.toArray(new IndexItem[indexItems.size()]));
}
});
}
}
@Override
public void onResume() {
super.onResume();
updateUpdateAllButton();
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final IndexItem e = (IndexItem) getListAdapter().getItem(position);
ItemViewHolder vh = (ItemViewHolder) v.getTag();
OnClickListener ls = vh.getRightButtonAction(e, vh.getClickAction(e));
ls.onClick(v);
}
public DownloadActivity getMyActivity() {
return (DownloadActivity) getActivity();
}
@SuppressWarnings("deprecation")
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
ActionBar actionBar = getMyActivity().getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
if (getMyApplication().getAppCustomization().showDownloadExtraActions()) {
MenuItem item = menu.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
item.setIcon(R.drawable.ic_action_refresh_dark);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
}
public OsmandApplication getMyApplication() {
return getMyActivity().getMyApplication();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == RELOAD_ID) {
// re-create the thread
getMyActivity().getDownloadThread().runReloadIndexFiles();
return true;
}
return super.onOptionsItemSelected(item);
}
private class UpdateIndexAdapter extends ArrayAdapter<IndexItem> {
List<IndexItem> items;
public UpdateIndexAdapter(Context context, int resource, List<IndexItem> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(getMyActivity());
v = inflater.inflate(R.layout.two_line_with_images_list_item, parent, false);
v.setTag(new ItemViewHolder(v, getMyActivity()));
}
ItemViewHolder holder = (ItemViewHolder) v.getTag();
holder.setShowRemoteDate(true);
holder.setShowTypeInDesc(true);
holder.bindIndexItem(items.get(position));
return v;
}
}
}

View file

@ -32,7 +32,6 @@ import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.osmand.IndexConstants;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.ContextMenuAdapter;
@ -56,7 +55,7 @@ import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.activities.SavingTrackHelper;
import net.osmand.plus.activities.TrackActivity;
import net.osmand.plus.dialogs.DirectionsDialogs;
import net.osmand.plus.download.LocalIndexesFragment;
import net.osmand.plus.download.ui.LocalIndexesFragment;
import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.monitoring.OsmandMonitoringPlugin;
import net.osmand.plus.osmedit.OsmEditingPlugin;