aboutsummaryrefslogtreecommitdiffstats
path: root/OsmAnd/src/net/osmand/plus/settings/DataStorageFragment.java
blob: 31831e37943a653ab8de89b138742613fa7b98c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package net.osmand.plus.settings;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceScreen;
import android.support.v7.preference.PreferenceViewHolder;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import net.osmand.AndroidUtils;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.ProgressImplementation;
import net.osmand.plus.R;
import net.osmand.plus.UiUtilities;
import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.OsmandActionBarActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.settings.bottomsheets.ChangeDataStorageBottomSheet;
import net.osmand.plus.settings.bottomsheets.SelectFolderBottomSheet;
import net.osmand.util.Algorithms;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;

import static net.osmand.plus.settings.DataStorageHelper.INTERNAL_STORAGE;
import static net.osmand.plus.settings.DataStorageHelper.MANUALLY_SPECIFIED;
import static net.osmand.plus.settings.DataStorageHelper.OTHER_MEMORY;
import static net.osmand.plus.settings.DataStorageHelper.TILES_MEMORY;
import static net.osmand.plus.settings.bottomsheets.ChangeDataStorageBottomSheet.CHOSEN_DIRECTORY;
import static net.osmand.plus.settings.bottomsheets.ChangeDataStorageBottomSheet.MOVE_DATA;
import static net.osmand.plus.settings.bottomsheets.SelectFolderBottomSheet.PATH_CHANGED;
import static net.osmand.plus.settings.bottomsheets.SelectFolderBottomSheet.NEW_PATH;

public class DataStorageFragment extends BaseSettingsFragment implements DataStorageHelper.UpdateMemoryInfoUIAdapter {
	public final static int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 500;
	
	private final static String CHANGE_DIRECTORY_BUTTON = "change_directory";
	private final static String OSMAND_USAGE = "osmand_usage";
	private final static String CALCULATE_TILES_BTN_PRESSED = "calculate_tiles_btn_pressed";
	private final static String ITEMS_HOLDER = "items_holder";

	private ArrayList<DataStorageMenuItem> menuItems;
	private ArrayList<DataStorageMemoryItem> memoryItems;
	private ArrayList<CheckBoxPreference> dataStorageRadioButtonsGroup;
	private Preference changeButton;
	private DataStorageMenuItem currentDataStorage;
	private String tmpManuallySpecifiedPath;
	private DataStorageHelper itemsHolder;
	private boolean calculateTilesBtnPressed;
	
	private DataStorageHelper.RefreshMemoryUsedInfo calculateMemoryTask;
	private DataStorageHelper.RefreshMemoryUsedInfo calculateTilesMemoryTask;

	private OsmandApplication app;
	private OsmandActionBarActivity activity;
	private OsmandSettings settings;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		app = getMyApplication();
		activity = getMyActivity();
		settings = app.getSettings();
		if (savedInstanceState != null) {
			calculateTilesBtnPressed = savedInstanceState.getBoolean(CALCULATE_TILES_BTN_PRESSED);
			itemsHolder = savedInstanceState.getParcelable(ITEMS_HOLDER);
		}
		if (itemsHolder == null) {
			refreshDataInfo();
		}
		super.onCreate(savedInstanceState);
	}
	
	@Override
	protected void setupPreferences() {
		
		PreferenceScreen screen = getPreferenceScreen();

		if (screen == null || itemsHolder == null) {
			return;
		}

		menuItems = itemsHolder.getStorageItems();
		memoryItems = itemsHolder.getMemoryInfoItems();
		dataStorageRadioButtonsGroup = new ArrayList<>();

		for (DataStorageMenuItem item : menuItems) {
			CheckBoxPreference preference = new CheckBoxPreference(activity);
			preference.setKey(item.getKey());
			preference.setTitle(item.getTitle());
			preference.setLayoutResource(R.layout.data_storage_list_item);
			screen.addPreference(preference);
			dataStorageRadioButtonsGroup.add(preference);
		}

		currentDataStorage = itemsHolder.getCurrentStorage();

		changeButton = new Preference(app);
		changeButton.setKey(CHANGE_DIRECTORY_BUTTON);
		changeButton.setLayoutResource(R.layout.bottom_sheet_item_btn_with_icon_and_text);
		screen.addPreference(changeButton);

		updateView(currentDataStorage.getKey());
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {
		if (CHANGE_DIRECTORY_BUTTON.equals(preference.getKey())) {
			showFolderSelectionDialog();
			return false;
		}
		return super.onPreferenceClick(preference);
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		super.onPreferenceChange(preference, newValue);

		if (newValue instanceof Bundle) {
			//results from BottomSheets
			Bundle resultData = (Bundle) newValue;
			if (resultData.containsKey(ChangeDataStorageBottomSheet.TAG)) {
				boolean moveMaps = resultData.getBoolean(MOVE_DATA);
				DataStorageMenuItem newDataStorage = resultData.getParcelable(CHOSEN_DIRECTORY);
				if (newDataStorage != null) {
					if (tmpManuallySpecifiedPath != null) {
						String directory = tmpManuallySpecifiedPath;
						tmpManuallySpecifiedPath = null;
						newDataStorage.setDirectory(directory);
					}
					if (moveMaps) {
						moveData(currentDataStorage, newDataStorage);
					} else {
						confirm(app, activity, newDataStorage, false);
					}
				}
			} else if (resultData.containsKey(SelectFolderBottomSheet.TAG)) {
				boolean pathChanged = resultData.getBoolean(PATH_CHANGED);
				if (pathChanged) {
					tmpManuallySpecifiedPath = resultData.getString(NEW_PATH);
					if (tmpManuallySpecifiedPath != null) {
						DataStorageMenuItem manuallySpecified = null;
						try {
							manuallySpecified = (DataStorageMenuItem) itemsHolder.getManuallySpecified().clone();
							manuallySpecified.setDirectory(tmpManuallySpecifiedPath);
						} catch (CloneNotSupportedException e) {
							return false;
						}
						ChangeDataStorageBottomSheet.showInstance(getFragmentManager(), MANUALLY_SPECIFIED,
								currentDataStorage, manuallySpecified, this, false);
					}
				}
			}
		} else {
			//show necessary dialog
			String key = preference.getKey();
			if (key != null) {
				DataStorageMenuItem newDataStorage = itemsHolder.getStorage(key);
				if (newDataStorage != null) {
					if (!currentDataStorage.getKey().equals(newDataStorage.getKey())) {
						if (newDataStorage.getType() == OsmandSettings.EXTERNAL_STORAGE_TYPE_DEFAULT
								&& !DownloadActivity.hasPermissionToWriteExternalStorage(activity)) {
							ActivityCompat.requestPermissions(activity,
									new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
									DataStorageFragment.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
						} else if (key.equals(MANUALLY_SPECIFIED)) {
							showFolderSelectionDialog();
						} else {
							ChangeDataStorageBottomSheet.showInstance(getFragmentManager(), key,
									currentDataStorage, newDataStorage, DataStorageFragment.this, false);
						}
					}
				}
			}
		}
		return false;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(CALCULATE_TILES_BTN_PRESSED, calculateTilesBtnPressed);
		outState.putParcelable(ITEMS_HOLDER, itemsHolder);
	}

	@Override
	protected void onBindPreferenceViewHolder(Preference preference, PreferenceViewHolder holder) {
		super.onBindPreferenceViewHolder(preference, holder);
		String key = preference.getKey();
		if (key == null) {
			return;
		}
		int activeColorResId = isNightMode() ? R.color.active_color_primary_dark : R.color.active_color_primary_light;
		int activeColor = ContextCompat.getColor(app, activeColorResId);
		int primaryTextColorResId = isNightMode() ? R.color.text_color_primary_dark : R.color.text_color_primary_light;
		int primaryTextColor = ContextCompat.getColor(app, primaryTextColorResId);

		String[] memoryUnitsFormats = new String[] {
				getString(R.string.shared_string_memory_kb_desc),
				getString(R.string.shared_string_memory_mb_desc),
				getString(R.string.shared_string_memory_gb_desc),
				getString(R.string.shared_string_memory_tb_desc)
		};
		
		final View itemView = holder.itemView;
		if (preference instanceof CheckBoxPreference) {
			DataStorageMenuItem item = itemsHolder.getStorage(key);
			if (item != null) {
				TextView tvTitle = itemView.findViewById(android.R.id.title);
				TextView tvSummary = itemView.findViewById(R.id.summary);
				TextView tvAdditionalDescription = itemView.findViewById(R.id.additionalDescription);
				ImageView ivIcon = itemView.findViewById(R.id.icon);
				View divider = itemView.findViewById(R.id.divider);
				View secondPart = itemView.findViewById(R.id.secondPart);

				tvTitle.setText(item.getTitle());
				String currentKey = item.getKey();
				boolean isCurrent = currentDataStorage.getKey().equals(currentKey);

				int defaultIconColor = isNightMode() ? R.color.icon_color_default_dark : R.color.icon_color_default_light;
				int chosenIconColor = isNightMode() ? R.color.icon_color_osmand_dark : R.color.icon_color_osmand_light;
				Drawable icon = app.getUIUtilities().getIcon(item.getIconResId(), 
						isCurrent ? chosenIconColor : defaultIconColor);
				ivIcon.setImageDrawable(icon);

				if (currentKey.equals(MANUALLY_SPECIFIED)) {
					tvSummary.setText(item.getDirectory());
					secondPart.setVisibility(View.GONE);
					tvAdditionalDescription.setVisibility(View.GONE);
					divider.setVisibility(View.GONE);
				} else {
					tvAdditionalDescription.setVisibility(View.VISIBLE);
					divider.setVisibility(View.VISIBLE);
					secondPart.setVisibility(View.VISIBLE);
					String space = getSpaceDescription(item.getDirectory());
					if (!space.equals("")) {
						space = space.replaceAll(" • ", "  •  ");
						tvSummary.setText(space);
						tvSummary.setVisibility(View.VISIBLE);
					} else {
						tvSummary.setVisibility(View.GONE);
					}
					if (currentKey.equals(INTERNAL_STORAGE)) {
						tvAdditionalDescription.setText(item.getDescription());
					} else {
						tvAdditionalDescription.setText(item.getDirectory());
					}
				}
			}
		} else if (key.equals(CHANGE_DIRECTORY_BUTTON)) {
			ImageView icon = itemView.findViewById(R.id.button_icon);
			TextView title = itemView.findViewById(R.id.button_text);
			Drawable drawable = UiUtilities.getColoredSelectableDrawable(app, activeColor, 0.3f);
			AndroidUtils.setBackground(itemView, drawable);
			icon.setVisibility(View.INVISIBLE);
			title.setText(R.string.shared_string_change);
		} else if(key.equals(OSMAND_USAGE)) {
			long totalUsageBytes = itemsHolder.getTotalUsedBytes();
			TextView tvSummary = itemView.findViewById(R.id.summary);
			tvSummary.setText(DataStorageHelper.getFormattedMemoryInfo(totalUsageBytes, memoryUnitsFormats));
		} else {
			for (DataStorageMemoryItem mi : memoryItems) {
				if (key.equals(mi.getKey())) {
					TextView tvMemory = itemView.findViewById(R.id.memory);
					String summary = "";
					int color = 0;
					if (mi.getKey().equals(TILES_MEMORY) && !calculateTilesBtnPressed) {
						summary = getString(R.string.shared_string_calculate);
						color = activeColor;
						tvMemory.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								calculateTilesBtnPressed = true;
								calculateTilesMemoryTask = itemsHolder.calculateTilesMemoryUsed(DataStorageFragment.this);
								updateAllSettings();
							}
						});
					} else {
						tvMemory.setOnClickListener(null);
						color = primaryTextColor;
						summary = DataStorageHelper.getFormattedMemoryInfo(mi.getUsedMemoryBytes(), memoryUnitsFormats);
					}
					View divider = itemView.findViewById(R.id.divider);
					if (mi.getKey().equals(OTHER_MEMORY)) {
						divider.setVisibility(View.VISIBLE);
					} else {
						divider.setVisibility(View.GONE);
					}
					tvMemory.setTextColor(color);
					tvMemory.setText(summary);
				}
			}
		}
	}

	@Override
	public void onDestroy() {
		if (!activity.isChangingConfigurations()) {
			if (calculateMemoryTask != null) {
				calculateMemoryTask.cancel(true);
			}
			if (calculateTilesMemoryTask != null) {
				calculateTilesMemoryTask.cancel(true);
			}
		}
		super.onDestroy();
	}

	private void updateView(String key) {
		//selection set up
		for (CheckBoxPreference preference : dataStorageRadioButtonsGroup) {
			String preferenceKey = preference.getKey();
			boolean checked = preferenceKey != null && preferenceKey.equals(key);
			preference.setChecked(checked);
		}
		boolean visible = key.equals(MANUALLY_SPECIFIED);
		changeButton.setVisible(visible);
	}

	private void showFolderSelectionDialog() {
		DataStorageMenuItem manuallySpecified = itemsHolder.getManuallySpecified();
		if (manuallySpecified != null) {
			SelectFolderBottomSheet.showInstance(getFragmentManager(), manuallySpecified.getKey(),
					manuallySpecified.getDirectory(), DataStorageFragment.this,
					getString(R.string.storage_directory_manual), getString(R.string.paste_Osmand_data_folder_path),
					getString(R.string.shared_string_select_folder), false);
		}
	}

	private void moveData(final DataStorageMenuItem currentStorage, final DataStorageMenuItem newStorage) {
		File fromDirectory = new File(currentStorage.getDirectory());
		File toDirectory = new File(newStorage.getDirectory());
		@SuppressLint("StaticFieldLeak")
		MoveFilesToDifferentDirectory task = new MoveFilesToDifferentDirectory(activity, fromDirectory, toDirectory) {

			private MessageFormat formatMb = new MessageFormat("{0, number,##.#} MB", Locale.US);

			@NonNull
			private String getFormattedSize(long sizeBytes) {
				int size = (int) ((sizeBytes + 512) >> 10);
				if (size >= 0) {
					if (size > 100) {
						return formatMb.format(new Object[]{(float) size / (1 << 10)});
					} else {
						return size + " kB";
					}
				}
				return "";
			}

			private void showResultsDialog() {
				StringBuilder sb = new StringBuilder();
				Context ctx = activity.get();
				if (ctx == null) {
					return;
				}
				int moved = getMovedCount();
				int copied = getCopiedCount();
				int failed = getFailedCount();
				sb.append(ctx.getString(R.string.files_moved, moved, getFormattedSize(getMovedSize()))).append("\n");
				if (copied > 0) {
					sb.append(ctx.getString(R.string.files_copied, copied, getFormattedSize(getCopiedSize()))).append("\n");
				}
				if (failed > 0) {
					sb.append(ctx.getString(R.string.files_failed, failed, getFormattedSize(getFailedSize()))).append("\n");
				}
				if (copied > 0 || failed > 0) {
					int count = copied + failed;
					sb.append(ctx.getString(R.string.files_present, count, getFormattedSize(getCopiedSize() + getFailedSize()), newStorage.getDirectory()));
				}
				AlertDialog.Builder bld = new AlertDialog.Builder(ctx);
				bld.setMessage(sb.toString());
				bld.setPositiveButton(R.string.shared_string_restart, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						confirm(app, activity.get(), newStorage, true);
					}
				});
				bld.show();
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				OsmandActionBarActivity a = this.activity.get();
				if (a == null) {
					return;
				}
				OsmandApplication app = a.getMyApplication();
				if (result) {
					app.getResourceManager().resetStoreDirectory();
					// immediately proceed with change (to not loose where maps are currently located)
					if (getCopiedCount() > 0 || getFailedCount() > 0) {
						showResultsDialog();
					} else {
						confirm(app, a, newStorage, false);
					}
				} else {
					showResultsDialog();
					Toast.makeText(a, R.string.copying_osmand_file_failed,
							Toast.LENGTH_SHORT).show();
				}

			}
		};
		task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void confirm(OsmandApplication app, OsmandActionBarActivity activity, DataStorageMenuItem newStorageDirectory, boolean silentRestart) {
		String newDirectory = newStorageDirectory.getDirectory();
		int type = newStorageDirectory.getType();
		File newDirectoryFile = new File(newDirectory);
		boolean wr = OsmandSettings.isWritable(newDirectoryFile);
		if (wr) {
			app.setExternalStorageDirectory(type, newDirectory);
			reloadData();
			if (silentRestart) {
				MapActivity.doRestart(activity);
			} else {
				app.restartApp(activity);
			}
		} else {
			Toast.makeText(activity, R.string.specified_directiory_not_writeable,
					Toast.LENGTH_LONG).show();
		}
		refreshDataInfo();
		updateAllSettings();
	}
	
	private void refreshDataInfo() {
		calculateTilesBtnPressed = false;
		itemsHolder = DataStorageHelper.refreshInfo(app);
		calculateMemoryTask = itemsHolder.calculateMemoryUsedInfo(this);
	}

	private String getSpaceDescription(String path) {
		File dir = new File(path);
		File dirParent = dir.getParentFile();
		while (!dir.exists() && dirParent != null) {
			dir = dir.getParentFile();
			dirParent = dir.getParentFile();
		}
		if (dir.exists()) {
			DecimalFormat formatter = new DecimalFormat("#.##");
			float freeSpace = AndroidUtils.getFreeSpaceGb(dir);
			float totalSpace = AndroidUtils.getTotalSpaceGb(dir);
			if (freeSpace < 0 || totalSpace < 0) {
				return "";
			}
			return String.format(getString(R.string.data_storage_space_description),
					formatter.format(freeSpace),
					formatter.format(totalSpace));
		}
		return "";
	}

	protected void reloadData() {
		new ReloadData(activity, getMyApplication()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
	}

	@Override
	public void onMemoryInfoUpdate() {
		updateAllSettings();
		app.getSettings().OSMAND_USAGE_SPACE.set(itemsHolder.getTotalUsedBytes());
	}
	
	public static class MoveFilesToDifferentDirectory extends AsyncTask<Void, Void, Boolean> {

		protected WeakReference<OsmandActionBarActivity> activity;
		private WeakReference<Context> context;
		private File from;
		private File to;
		protected ProgressImplementation progress;
		private Runnable runOnSuccess;
		private int movedCount;
		private long movedSize;
		private int copiedCount;
		private long copiedSize;
		private int failedCount;
		private long failedSize;

		public MoveFilesToDifferentDirectory(OsmandActionBarActivity activity, File from, File to) {
			this.activity = new WeakReference<>(activity);
			this.context = new WeakReference<>((Context) activity);
			this.from = from;
			this.to = to;
		}

		public void setRunOnSuccess(Runnable runOnSuccess) {
			this.runOnSuccess = runOnSuccess;
		}

		public int getMovedCount() {
			return movedCount;
		}

		public int getCopiedCount() {
			return copiedCount;
		}

		public int getFailedCount() {
			return failedCount;
		}

		public long getMovedSize() {
			return movedSize;
		}

		public long getCopiedSize() {
			return copiedSize;
		}

		public long getFailedSize() {
			return failedSize;
		}

		@Override
		protected void onPreExecute() {
			Context ctx = context.get();
			if (context == null) {
				return;
			}
			movedCount = 0;
			copiedCount = 0;
			failedCount = 0;
			progress = ProgressImplementation.createProgressDialog(
					ctx, ctx.getString(R.string.copying_osmand_files),
					ctx.getString(R.string.copying_osmand_files_descr, to.getPath()),
					ProgressDialog.STYLE_HORIZONTAL);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			Context ctx = context.get();
			if (ctx == null) {
				return;
			}
			if (result != null) {
				if (result.booleanValue() && runOnSuccess != null) {
					runOnSuccess.run();
				} else if (!result.booleanValue()) {
					Toast.makeText(ctx, R.string.shared_string_io_error, Toast.LENGTH_LONG).show();
				}
			}
			try {
				if (progress.getDialog().isShowing()) {
					progress.getDialog().dismiss();
				}
			} catch (Exception e) {
				//ignored
			}
		}

		private void movingFiles(File f, File t, int depth) throws IOException {
			Context ctx = context.get();
			if (ctx == null) {
				return;
			}
			if (depth <= 2) {
				progress.startTask(ctx.getString(R.string.copying_osmand_one_file_descr, t.getName()), -1);
			}
			if (f.isDirectory()) {
				t.mkdirs();
				File[] lf = f.listFiles();
				if (lf != null) {
					for (int i = 0; i < lf.length; i++) {
						if (lf[i] != null) {
							movingFiles(lf[i], new File(t, lf[i].getName()), depth + 1);
						}
					}
				}
				f.delete();
			} else if (f.isFile()) {
				if (t.exists()) {
					Algorithms.removeAllFiles(t);
				}
				boolean rnm = false;
				long fileSize = f.length();
				try {
					rnm = f.renameTo(t);
					movedCount++;
					movedSize += fileSize;
				} catch (RuntimeException e) {
				}
				if (!rnm) {
					FileInputStream fin = new FileInputStream(f);
					FileOutputStream fout = new FileOutputStream(t);
					try {
						progress.startTask(ctx.getString(R.string.copying_osmand_one_file_descr, t.getName()), (int) (f.length() / 1024));
						Algorithms.streamCopy(fin, fout, progress, 1024);
						copiedCount++;
						copiedSize += fileSize;
					} catch (IOException e) {
						failedCount++;
						failedSize += fileSize;
					} finally {
						fin.close();
						fout.close();
					}
					f.delete();
				}
			}
			if (depth <= 2) {
				progress.finishTask();
			}
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			to.mkdirs();
			try {
				movingFiles(from, to, 0);
			} catch (IOException e) {
				return false;
			}
			return true;
		}

	}

	public static class ReloadData extends AsyncTask<Void, Void, Boolean> {
		private WeakReference<Context> ctx;
		protected ProgressImplementation progress;
		private OsmandApplication app;

		public ReloadData(Context ctx, OsmandApplication app) {
			this.ctx = new WeakReference<>(ctx);
			this.app = app;
		}

		@Override
		protected void onPreExecute() {
			Context c = ctx.get();
			if (c == null) {
				return;
			}
			progress = ProgressImplementation.createProgressDialog(c, c.getString(R.string.loading_data),
					c.getString(R.string.loading_data), ProgressDialog.STYLE_HORIZONTAL);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			try {
				if (progress.getDialog().isShowing()) {
					progress.getDialog().dismiss();
				}
			} catch (Exception e) {
				//ignored
			}
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			app.getResourceManager().reloadIndexes(progress, new ArrayList<String>());
			return true;
		}
	}
}