#3832 Remove unused code via Declaraction Redundancy>Unused Declaration Inspection - delete unused files - remove empty declarations and implementations

This commit is contained in:
Sean Mac Gillicuddy 2020-06-22 10:20:39 +01:00
parent 454d7adaa8
commit 3166d6ea85
99 changed files with 202 additions and 1949 deletions

View file

@ -44,5 +44,17 @@
<inspection_tool class="UnnecessarySuperConstructor" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="UnnecessarySuperConstructor" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="UnnecessaryThis" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="UnnecessaryThis" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="UnnecessaryToStringCall" enabled="true" level="WARNING" enabled_by_default="true" /> <inspection_tool class="UnnecessaryToStringCall" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="unused" enabled="true" level="WARNING" enabled_by_default="true" test_entries="false">
<option name="LOCAL_VARIABLE" value="true" />
<option name="FIELD" value="true" />
<option name="METHOD" value="true" />
<option name="CLASS" value="true" />
<option name="PARAMETER" value="true" />
<option name="REPORT_PARAMETER_FOR_PUBLIC_METHODS" value="true" />
<option name="ADD_MAINS_TO_ENTRIES" value="true" />
<option name="ADD_APPLET_TO_ENTRIES" value="true" />
<option name="ADD_SERVLET_TO_ENTRIES" value="true" />
<option name="ADD_NONJAVA_TO_ENTRIES" value="true" />
</inspection_tool>
</profile> </profile>
</component> </component>

View file

@ -97,12 +97,6 @@ public class CommonsApplication extends MultiDexApplication {
public static final String FEEDBACK_EMAIL_TEMPLATE_HEADER = "-- Technical information --"; public static final String FEEDBACK_EMAIL_TEMPLATE_HEADER = "-- Technical information --";
/**
* Constants End
*/
private RefWatcher refWatcher;
private static CommonsApplication INSTANCE; private static CommonsApplication INSTANCE;
public static CommonsApplication getInstance() { public static CommonsApplication getInstance() {
return INSTANCE; return INSTANCE;
@ -191,10 +185,6 @@ public class CommonsApplication extends MultiDexApplication {
Timber.plant(new Timber.DebugTree()); Timber.plant(new Timber.DebugTree());
} }
public static boolean isRoboUnitTest() {
return "robolectric".equals(Build.FINGERPRINT);
}
private ThreadPoolService getFileLoggingThreadPool() { private ThreadPoolService getFileLoggingThreadPool() {
return new ThreadPoolService.Builder("file-logging-thread") return new ThreadPoolService.Builder("file-logging-thread")
.setPriority(Process.THREAD_PRIORITY_LOWEST) .setPriority(Process.THREAD_PRIORITY_LOWEST)
@ -230,17 +220,6 @@ public class CommonsApplication extends MultiDexApplication {
return LeakCanary.install(this); return LeakCanary.install(this);
} }
/**
* Provides a way to get member refWatcher
*
* @param context Application context
* @return application member refWatcher
*/
public static RefWatcher getRefWatcher(Context context) {
CommonsApplication application = (CommonsApplication) context.getApplicationContext();
return application.refWatcher;
}
/** /**
* clears data of current application * clears data of current application
* @param context Application context * @param context Application context

View file

@ -1,79 +0,0 @@
package fr.free.nrw.commons;
import androidx.annotation.Nullable;
/**
* represents Licence object
*/
public class License {
private String key;
private String template;
private String url;
private String name;
/**
* Constructs a new instance of License.
*
* @param key license key
* @param template license template
* @param url license URL
* @param name licence name
*
* @throws RuntimeException if License.key or Licence.template is null
*/
public License(String key, String template, String url, String name) {
if (key == null) {
throw new RuntimeException("License.key must not be null");
}
if (template == null) {
throw new RuntimeException("License.template must not be null");
}
this.key = key;
this.template = template;
this.url = url;
this.name = name;
}
/**
* Gets the license key.
* @return license key as a String.
*/
public String getKey() {
return key;
}
/**
* Gets the license template.
* @return license template as a String.
*/
public String getTemplate() {
return template;
}
/**
* Gets the license name. If name is null, return license key.
* @return license name as string. if name null, license key as String
*/
public String getName() {
if (name == null) {
// hack
return getKey();
} else {
return name;
}
}
/**
* Gets the license URL
*
* @param language license language
* @return URL
*/
public @Nullable String getUrl(String language) {
if (url == null) {
return null;
} else {
return url.replace("$lang", language);
}
}
}

View file

@ -4,5 +4,5 @@ package fr.free.nrw.commons;
* Base interface for all the views * Base interface for all the views
*/ */
public interface MvpView { public interface MvpView {
void showMessage(String message);
} }

View file

@ -1,7 +0,0 @@
package fr.free.nrw.commons;
import android.content.Context;
public interface ViewHolder<T> {
void bindModel(Context context, T model);
}

View file

@ -1,9 +1,7 @@
package fr.free.nrw.commons.actions; package fr.free.nrw.commons.actions;
import org.wikipedia.csrf.CsrfTokenClient;
import org.wikipedia.dataclient.Service;
import io.reactivex.Observable; import io.reactivex.Observable;
import org.wikipedia.csrf.CsrfTokenClient;
/** /**
* This class acts as a Client to facilitate wiki page editing * This class acts as a Client to facilitate wiki page editing
@ -16,14 +14,11 @@ public class PageEditClient {
private final CsrfTokenClient csrfTokenClient; private final CsrfTokenClient csrfTokenClient;
private final PageEditInterface pageEditInterface; private final PageEditInterface pageEditInterface;
private final Service service;
public PageEditClient(CsrfTokenClient csrfTokenClient, public PageEditClient(CsrfTokenClient csrfTokenClient,
PageEditInterface pageEditInterface, PageEditInterface pageEditInterface) {
Service service) {
this.csrfTokenClient = csrfTokenClient; this.csrfTokenClient = csrfTokenClient;
this.pageEditInterface = pageEditInterface; this.pageEditInterface = pageEditInterface;
this.service = service;
} }
/** /**

View file

@ -1,5 +1,10 @@
package fr.free.nrw.commons.auth; package fr.free.nrw.commons.auth;
import static android.view.KeyEvent.KEYCODE_ENTER;
import static android.view.View.VISIBLE;
import static android.view.inputmethod.EditorInfo.IME_ACTION_DONE;
import static fr.free.nrw.commons.di.NetworkingModule.NAMED_COMMONS_WIKI_SITE;
import android.accounts.AccountAuthenticatorActivity; import android.accounts.AccountAuthenticatorActivity;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context; import android.content.Context;
@ -17,7 +22,6 @@ import android.view.inputmethod.InputMethodManager;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.ColorRes; import androidx.annotation.ColorRes;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
@ -26,25 +30,12 @@ import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.NavUtils; import androidx.core.app.NavUtils;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import com.google.android.material.textfield.TextInputLayout;
import org.wikipedia.AppAdapter;
import org.wikipedia.dataclient.ServiceFactory;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import org.wikipedia.login.LoginClient;
import org.wikipedia.login.LoginClient.LoginCallback;
import org.wikipedia.login.LoginResult;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import butterknife.OnEditorAction; import butterknife.OnEditorAction;
import butterknife.OnFocusChange; import butterknife.OnFocusChange;
import com.google.android.material.textfield.TextInputLayout;
import fr.free.nrw.commons.BuildConfig; import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.Utils;
@ -58,16 +49,20 @@ import fr.free.nrw.commons.utils.ConfigUtils;
import fr.free.nrw.commons.utils.SystemThemeUtils; import fr.free.nrw.commons.utils.SystemThemeUtils;
import fr.free.nrw.commons.utils.ViewUtil; import fr.free.nrw.commons.utils.ViewUtil;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import javax.inject.Inject;
import javax.inject.Named;
import org.wikipedia.AppAdapter;
import org.wikipedia.dataclient.ServiceFactory;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import org.wikipedia.login.LoginClient;
import org.wikipedia.login.LoginClient.LoginCallback;
import org.wikipedia.login.LoginResult;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
import timber.log.Timber; import timber.log.Timber;
import static android.view.KeyEvent.KEYCODE_ENTER;
import static android.view.View.VISIBLE;
import static android.view.inputmethod.EditorInfo.IME_ACTION_DONE;
import static fr.free.nrw.commons.di.NetworkingModule.NAMED_COMMONS_WIKI_SITE;
public class LoginActivity extends AccountAuthenticatorActivity { public class LoginActivity extends AccountAuthenticatorActivity {
@Inject @Inject
@ -246,7 +241,6 @@ public class LoginActivity extends AccountAuthenticatorActivity {
public void performLogin() { public void performLogin() {
Timber.d("Login to start!"); Timber.d("Login to start!");
final String username = usernameEdit.getText().toString(); final String username = usernameEdit.getText().toString();
final String rawUsername = usernameEdit.getText().toString().trim();
final String password = passwordEdit.getText().toString(); final String password = passwordEdit.getText().toString();
String twoFactorCode = twoFactorEdit.getText().toString(); String twoFactorCode = twoFactorEdit.getText().toString();

View file

@ -6,7 +6,6 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
@ -29,7 +28,6 @@ public class BookmarkLocationsFragment extends DaggerFragment {
@BindView(R.id.statusMessage) TextView statusTextView; @BindView(R.id.statusMessage) TextView statusTextView;
@BindView(R.id.loadingImagesProgressBar) ProgressBar progressBar; @BindView(R.id.loadingImagesProgressBar) ProgressBar progressBar;
@BindView(R.id.listView) RecyclerView recyclerView; @BindView(R.id.listView) RecyclerView recyclerView;
@BindView(R.id.parentLayout) RelativeLayout parentLayout;
@Inject BookmarkLocationsController controller; @Inject BookmarkLocationsController controller;
@Inject ContributionController contributionController; @Inject ContributionController contributionController;

View file

@ -54,10 +54,4 @@ public class BookmarkPicturesController {
return bookmarks.size() != currentBookmarks.size(); return bookmarks.size() != currentBookmarks.size();
} }
/**
* Cancels the requests to the API and the DB
*/
void stop() {
//noop
}
} }

View file

@ -71,11 +71,6 @@ public class BookmarkPicturesFragment extends DaggerFragment {
initList(); initList();
} }
@Override
public void onStop() {
super.onStop();
controller.stop();
}
@Override @Override
public void onDestroy() { public void onDestroy() {

View file

@ -13,9 +13,6 @@ public class Category {
private Date lastUsed; private Date lastUsed;
private int timesUsed; private int timesUsed;
public Category() {
}
public Category(Uri contentUri, String name, Date lastUsed, int timesUsed) { public Category(Uri contentUri, String name, Date lastUsed, int timesUsed) {
this.contentUri = contentUri; this.contentUri = contentUri;
this.name = name; this.name = name;
@ -32,15 +29,6 @@ public class Category {
return name; return name;
} }
/**
* Modifies name
*
* @param name Category name
*/
public void setName(String name) {
this.name = name;
}
/** /**
* Gets last used date * Gets last used date
* *

View file

@ -1,5 +0,0 @@
package fr.free.nrw.commons.category;
public interface CategoryClickedListener {
void categoryClicked(CategoryItem item);
}

View file

@ -1,7 +0,0 @@
package fr.free.nrw.commons.category;
import java.util.List;
public interface OnCategoriesSaveHandler {
void onCategoriesSave(List<String> categories);
}

View file

@ -1,13 +1,9 @@
package fr.free.nrw.commons.concurrency; package fr.free.nrw.commons.concurrency;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/** /**
* This class is a thread pool which provides some additional features: * This class is a thread pool which provides some additional features:
@ -36,31 +32,6 @@ public class ThreadPoolService implements Executor {
}, b.exceptionHandler); }, b.exceptionHandler);
} }
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long time, TimeUnit timeUnit) {
return backgroundPool.schedule(callable, time, timeUnit);
}
public ScheduledFuture<?> schedule(Runnable runnable) {
return schedule(runnable, 0, TimeUnit.SECONDS);
}
public ScheduledFuture<?> schedule(Runnable runnable, long time, TimeUnit timeUnit) {
return backgroundPool.schedule(runnable, time, timeUnit);
}
public ScheduledFuture<?> scheduleAtFixedRate(final Runnable task, long initialDelay,
long period, final TimeUnit timeUnit) {
return backgroundPool.scheduleAtFixedRate(task, initialDelay, period, timeUnit);
}
public ScheduledThreadPoolExecutor executor() {
return backgroundPool;
}
public void shutdown(){
backgroundPool.shutdown();
}
@Override @Override
public void execute(Runnable command) { public void execute(Runnable command) {
backgroundPool.execute(command); backgroundPool.execute(command);

View file

@ -76,7 +76,6 @@ class ContributionBoundaryCallback @Inject constructor(
repository.save(contributions) repository.save(contributions)
.subscribeOn(ioThreadScheduler) .subscribeOn(ioThreadScheduler)
.subscribe { longs: List<Long?>? -> .subscribe { longs: List<Long?>? ->
repository["last_fetch_timestamp"] = System.currentTimeMillis()
} }
) )
} }

View file

@ -96,12 +96,12 @@ public class ContributionController {
public void handleActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { public void handleActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
FilePicker.handleActivityResult(requestCode, resultCode, data, activity, new DefaultCallback() { FilePicker.handleActivityResult(requestCode, resultCode, data, activity, new DefaultCallback() {
@Override @Override
public void onImagePickerError(Exception e, FilePicker.ImageSource source, int type) { public void onImagePickerError() {
ViewUtil.showShortToast(activity, R.string.error_occurred_in_picking_images); ViewUtil.showShortToast(activity, R.string.error_occurred_in_picking_images);
} }
@Override @Override
public void onImagesPicked(@NonNull List<UploadableFile> imagesFiles, FilePicker.ImageSource source, int type) { public void onImagesPicked(@NonNull List<UploadableFile> imagesFiles) {
Intent intent = handleImagesPicked(activity, imagesFiles); Intent intent = handleImagesPicked(activity, imagesFiles);
activity.startActivity(intent); activity.startActivity(intent);
} }

View file

@ -8,8 +8,6 @@ import fr.free.nrw.commons.BasePresenter;
public class ContributionsContract { public class ContributionsContract {
public interface View { public interface View {
void showMessage(String localizedMessage);
} }
public interface UserActionListener extends BasePresenter<ContributionsContract.View> { public interface UserActionListener extends BasePresenter<ContributionsContract.View> {

View file

@ -15,7 +15,6 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
@ -41,7 +40,6 @@ import fr.free.nrw.commons.mwapi.OkHttpJsonApiClient;
import fr.free.nrw.commons.nearby.NearbyController; import fr.free.nrw.commons.nearby.NearbyController;
import fr.free.nrw.commons.nearby.NearbyNotificationCardView; import fr.free.nrw.commons.nearby.NearbyNotificationCardView;
import fr.free.nrw.commons.nearby.Place; import fr.free.nrw.commons.nearby.Place;
import fr.free.nrw.commons.settings.Prefs;
import fr.free.nrw.commons.upload.UploadService; import fr.free.nrw.commons.upload.UploadService;
import fr.free.nrw.commons.utils.ConfigUtils; import fr.free.nrw.commons.utils.ConfigUtils;
import fr.free.nrw.commons.utils.DialogUtil; import fr.free.nrw.commons.utils.DialogUtil;
@ -109,7 +107,6 @@ public class ContributionsFragment
} }
}; };
private boolean shouldShowMediaDetailsFragment; private boolean shouldShowMediaDetailsFragment;
private boolean isAuthCookieAcquired;
@Override @Override
public void onCreate(@Nullable Bundle savedInstanceState) { public void onCreate(@Nullable Bundle savedInstanceState) {
@ -197,12 +194,6 @@ public class ContributionsFragment
} }
private void setupViewForMediaDetails() {
campaignView.setVisibility(View.GONE);
nearbyNotificationCardView.setVisibility(View.GONE);
((MainActivity)getActivity()).hideTabs();
}
@Override @Override
public void onBackStackChanged() { public void onBackStackChanged() {
((MainActivity)getActivity()).initBackButton(); ((MainActivity)getActivity()).initBackButton();
@ -213,7 +204,6 @@ public class ContributionsFragment
*/ */
void onAuthCookieAcquired() { void onAuthCookieAcquired() {
// Since we call onAuthCookieAcquired method from onAttach, isAdded is still false. So don't use it // Since we call onAuthCookieAcquired method from onAttach, isAdded is still false. So don't use it
isAuthCookieAcquired=true;
if (getActivity() != null) { // If fragment is attached to parent activity if (getActivity() != null) { // If fragment is attached to parent activity
getActivity().bindService(getUploadServiceIntent(), uploadServiceConnection, Context.BIND_AUTO_CREATE); getActivity().bindService(getUploadServiceIntent(), uploadServiceConnection, Context.BIND_AUTO_CREATE);
isUploadServiceConnected = true; isUploadServiceConnected = true;
@ -315,7 +305,6 @@ public class ContributionsFragment
} else if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION) } else if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)
&& store.getBoolean("displayLocationPermissionForCardView", true) && store.getBoolean("displayLocationPermissionForCardView", true)
&& (((MainActivity) getActivity()).viewPager.getCurrentItem() == CONTRIBUTIONS_TAB_POSITION)) { && (((MainActivity) getActivity()).viewPager.getCurrentItem() == CONTRIBUTIONS_TAB_POSITION)) {
nearbyNotificationCardView.permissionType = NearbyNotificationCardView.PermissionType.ENABLE_LOCATION_PERMISSION;
showNearbyCardPermissionRationale(); showNearbyCardPermissionRationale();
} }
} }
@ -330,7 +319,6 @@ public class ContributionsFragment
} }
private void onLocationPermissionGranted() { private void onLocationPermissionGranted() {
nearbyNotificationCardView.permissionType = NearbyNotificationCardView.PermissionType.NO_PERMISSION_NEEDED;
locationManager.registerLocationManager(); locationManager.registerLocationManager();
} }
@ -432,10 +420,6 @@ public class ContributionsFragment
} }
} }
@Override public void showMessage(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
@Override public void showCampaigns(Campaign campaign) { @Override public void showCampaigns(Campaign campaign) {
if (campaign != null) { if (campaign != null) {
campaignView.setCampaign(campaign); campaignView.setCampaign(campaign);

View file

@ -1,7 +1,6 @@
package fr.free.nrw.commons.contributions; package fr.free.nrw.commons.contributions;
import fr.free.nrw.commons.BasePresenter; import fr.free.nrw.commons.BasePresenter;
import java.util.List;
/** /**
* The contract for Contributions list View & Presenter * The contract for Contributions list View & Presenter
@ -10,11 +9,6 @@ public class ContributionsListContract {
public interface View { public interface View {
void showWelcomeTip(boolean numberOfUploads);
void showProgress(boolean shouldShow);
void showNoContributionsUI(boolean shouldShow);
} }
public interface UserActionListener extends BasePresenter<View> { public interface UserActionListener extends BasePresenter<View> {

View file

@ -1,7 +1,5 @@
package fr.free.nrw.commons.contributions; package fr.free.nrw.commons.contributions;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static fr.free.nrw.commons.di.NetworkingModule.NAMED_LANGUAGE_WIKI_PEDIA_WIKI_SITE; import static fr.free.nrw.commons.di.NetworkingModule.NAMED_LANGUAGE_WIKI_PEDIA_WIKI_SITE;
import android.content.Context; import android.content.Context;
@ -15,8 +13,6 @@ import android.view.ViewGroup;
import android.view.animation.Animation; import android.view.animation.Animation;
import android.view.animation.AnimationUtils; import android.view.animation.AnimationUtils;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentManager;
@ -47,16 +43,12 @@ public class ContributionsListFragment extends CommonsDaggerSupportFragment impl
@BindView(R.id.contributionsList) @BindView(R.id.contributionsList)
RecyclerView rvContributionsList; RecyclerView rvContributionsList;
@BindView(R.id.loadingContributionsProgressBar)
ProgressBar progressBar;
@BindView(R.id.fab_plus) @BindView(R.id.fab_plus)
FloatingActionButton fabPlus; FloatingActionButton fabPlus;
@BindView(R.id.fab_camera) @BindView(R.id.fab_camera)
FloatingActionButton fabCamera; FloatingActionButton fabCamera;
@BindView(R.id.fab_gallery) @BindView(R.id.fab_gallery)
FloatingActionButton fabGallery; FloatingActionButton fabGallery;
@BindView(R.id.noContributionsYet)
TextView noContributionsYet;
@BindView(R.id.fab_layout) @BindView(R.id.fab_layout)
LinearLayout fab_layout; LinearLayout fab_layout;
@ -187,26 +179,6 @@ public class ContributionsListFragment extends CommonsDaggerSupportFragment impl
} }
} }
/**
* Shows welcome message if user has no contributions yet i.e. new user.
*/
public void showWelcomeTip(final boolean shouldShow) {
noContributionsYet.setVisibility(shouldShow ? VISIBLE : GONE);
}
/**
* Responsible to set progress bar invisible and visible
*
* @param shouldShow True when contributions list should be hidden.
*/
public void showProgress(final boolean shouldShow) {
progressBar.setVisibility(shouldShow ? VISIBLE : GONE);
}
public void showNoContributionsUI(final boolean shouldShow) {
noContributionsYet.setVisibility(shouldShow ? VISIBLE : GONE);
}
@Override @Override
public void onSaveInstanceState(@NonNull Bundle outState) { public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);

View file

@ -2,14 +2,10 @@ package fr.free.nrw.commons.contributions;
import androidx.paging.DataSource.Factory; import androidx.paging.DataSource.Factory;
import io.reactivex.Completable; import io.reactivex.Completable;
import io.reactivex.Single;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named;
import fr.free.nrw.commons.kvstore.JsonKvStore;
import io.reactivex.Single;
/** /**
* The LocalDataSource class for Contributions * The LocalDataSource class for Contributions
@ -17,30 +13,12 @@ import io.reactivex.Single;
class ContributionsLocalDataSource { class ContributionsLocalDataSource {
private final ContributionDao contributionDao; private final ContributionDao contributionDao;
private final JsonKvStore defaultKVStore;
@Inject @Inject
public ContributionsLocalDataSource( public ContributionsLocalDataSource(ContributionDao contributionDao) {
@Named("default_preferences") JsonKvStore defaultKVStore,
ContributionDao contributionDao) {
this.defaultKVStore = defaultKVStore;
this.contributionDao = contributionDao; this.contributionDao = contributionDao;
} }
/**
* Fetch default number of contributions to be show, based on user preferences
*/
public String getString(String key) {
return defaultKVStore.getString(key);
}
/**
* Fetch default number of contributions to be show, based on user preferences
*/
public long getLong(String key) {
return defaultKVStore.getLong(key);
}
/** /**
* Get contribution object from cursor * Get contribution object from cursor
* @param uri * @param uri
@ -79,11 +57,5 @@ class ContributionsLocalDataSource {
return contributionDao.save(contributionList); return contributionDao.save(contributionList);
} }
public void set(String key, long value) {
defaultKVStore.putLong(key,value);
}
public Completable updateContribution(Contribution contribution) {
return contributionDao.update(contribution);
}
} }

View file

@ -14,30 +14,26 @@ import javax.inject.Named;
public class ContributionsPresenter implements UserActionListener { public class ContributionsPresenter implements UserActionListener {
private final ContributionsRepository repository; private final ContributionsRepository repository;
private final Scheduler mainThreadScheduler;
private final Scheduler ioThreadScheduler; private final Scheduler ioThreadScheduler;
private CompositeDisposable compositeDisposable; private CompositeDisposable compositeDisposable;
private ContributionsContract.View view;
@Inject @Inject
MediaDataExtractor mediaDataExtractor; MediaDataExtractor mediaDataExtractor;
@Inject @Inject
ContributionsPresenter(ContributionsRepository repository, @Named(CommonsApplicationModule.MAIN_THREAD) Scheduler mainThreadScheduler,@Named(CommonsApplicationModule.IO_THREAD) Scheduler ioThreadScheduler) { ContributionsPresenter(ContributionsRepository repository,
@Named(CommonsApplicationModule.IO_THREAD) Scheduler ioThreadScheduler) {
this.repository = repository; this.repository = repository;
this.mainThreadScheduler=mainThreadScheduler;
this.ioThreadScheduler=ioThreadScheduler; this.ioThreadScheduler=ioThreadScheduler;
} }
@Override @Override
public void onAttachView(ContributionsContract.View view) { public void onAttachView(ContributionsContract.View view) {
this.view = view;
compositeDisposable=new CompositeDisposable(); compositeDisposable=new CompositeDisposable();
} }
@Override @Override
public void onDetachView() { public void onDetachView() {
this.view = null;
compositeDisposable.clear(); compositeDisposable.clear();
} }

View file

@ -20,13 +20,6 @@ public class ContributionsRepository {
this.localDataSource = localDataSource; this.localDataSource = localDataSource;
} }
/**
* Fetch default number of contributions to be show, based on user preferences
*/
public String getString(String key) {
return localDataSource.getString(key);
}
/** /**
* Deletes a failed upload from DB * Deletes a failed upload from DB
* @param contribution * @param contribution
@ -53,11 +46,4 @@ public class ContributionsRepository {
return localDataSource.saveContributions(contributions); return localDataSource.saveContributions(contributions);
} }
public void set(String key, long value) {
localDataSource.set(key,value);
}
public Completable updateContribution(Contribution contribution) {
return localDataSource.updateContribution(contribution);
}
} }

View file

@ -63,7 +63,6 @@ public class MainActivity extends NavigationBaseActivity implements FragmentMana
public static final int NEARBY_TAB_POSITION = 1; public static final int NEARBY_TAB_POSITION = 1;
public boolean isContributionsFragmentVisible = true; // False means nearby fragment is visible public boolean isContributionsFragmentVisible = true; // False means nearby fragment is visible
public boolean onOrientationChanged;
private Menu menu; private Menu menu;
private MenuItem notificationsMenuItem; private MenuItem notificationsMenuItem;
@ -80,15 +79,11 @@ public class MainActivity extends NavigationBaseActivity implements FragmentMana
initMain(); initMain();
if (savedInstanceState != null ) {
onOrientationChanged = true; // Will be used in nearby fragment to determine significant update of map
//If nearby map was visible, call on Tab Selected to call all nearby operations //If nearby map was visible, call on Tab Selected to call all nearby operations
/*if (savedInstanceState.getInt("viewPagerCurrentItem") == 1) { /*if (savedInstanceState.getInt("viewPagerCurrentItem") == 1) {
((NearbyFragment)contributionsActivityPagerAdapter.getItem(1)).onTabSelected(onOrientationChanged); ((NearbyFragment)contributionsActivityPagerAdapter.getItem(1)).onTabSelected(onOrientationChanged);
}*/ }*/
} }
}
@Override @Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) { protected void onPostCreate(@Nullable Bundle savedInstanceState) {

View file

@ -37,17 +37,14 @@ public class DeleteHelper {
private final NotificationHelper notificationHelper; private final NotificationHelper notificationHelper;
private final PageEditClient pageEditClient; private final PageEditClient pageEditClient;
private final ViewUtilWrapper viewUtil; private final ViewUtilWrapper viewUtil;
private final String username;
@Inject @Inject
public DeleteHelper(NotificationHelper notificationHelper, public DeleteHelper(NotificationHelper notificationHelper,
@Named("commons-page-edit") PageEditClient pageEditClient, @Named("commons-page-edit") PageEditClient pageEditClient,
ViewUtilWrapper viewUtil, ViewUtilWrapper viewUtil) {
@Named("username") String username) {
this.notificationHelper = notificationHelper; this.notificationHelper = notificationHelper;
this.pageEditClient = pageEditClient; this.pageEditClient = pageEditClient;
this.viewUtil = viewUtil; this.viewUtil = viewUtil;
this.username = username;
} }
/** /**
@ -198,13 +195,11 @@ public class DeleteHelper {
.subscribe(aBoolean -> { .subscribe(aBoolean -> {
if (aBoolean) { if (aBoolean) {
reviewCallback.onSuccess(); reviewCallback.onSuccess();
} else {
reviewCallback.onFailure();
} }
}); });
}); });
alert.setNegativeButton(context.getString(R.string.cancel), (dialog, which) -> reviewCallback.onFailure()); alert.setNegativeButton(context.getString(R.string.cancel), (dialog, which) -> {});
AlertDialog d = alert.create(); AlertDialog d = alert.create();
d.show(); d.show();
} }

View file

@ -204,10 +204,10 @@ public class NetworkingModule {
@Named("commons-page-edit") @Named("commons-page-edit")
@Provides @Provides
@Singleton @Singleton
public PageEditClient provideCommonsPageEditClient(@Named(NAMED_COMMONS_CSRF) CsrfTokenClient csrfTokenClient, public PageEditClient provideCommonsPageEditClient(
@Named("commons-page-edit-service") PageEditInterface pageEditInterface, @Named(NAMED_COMMONS_CSRF) CsrfTokenClient csrfTokenClient,
@Named("commons-service") Service service) { @Named("commons-page-edit-service") PageEditInterface pageEditInterface) {
return new PageEditClient(csrfTokenClient, pageEditInterface, service); return new PageEditClient(csrfTokenClient, pageEditInterface);
} }
@Provides @Provides

View file

@ -7,10 +7,7 @@ package fr.free.nrw.commons.filepicker;
public abstract class DefaultCallback implements FilePicker.Callbacks { public abstract class DefaultCallback implements FilePicker.Callbacks {
@Override @Override
public void onImagePickerError(Exception e, FilePicker.ImageSource source, int type) { public void onImagePickerError() {
} }
@Override
public void onCanceled(FilePicker.ImageSource source, int type) {
}
} }

View file

@ -1,5 +1,7 @@
package fr.free.nrw.commons.filepicker; package fr.free.nrw.commons.filepicker;
import static fr.free.nrw.commons.filepicker.PickedFiles.singleFileList;
import android.app.Activity; import android.app.Activity;
import android.content.ClipData; import android.content.ClipData;
import android.content.Context; import android.content.Context;
@ -8,21 +10,17 @@ import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;
import android.net.Uri; import android.net.Uri;
import androidx.preference.PreferenceManager;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.text.TextUtils; import android.text.TextUtils;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.preference.PreferenceManager;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static fr.free.nrw.commons.filepicker.PickedFiles.singleFileList;
public class FilePicker implements Constants { public class FilePicker implements Constants {
private static final String KEY_PHOTO_URI = "photo_uri"; private static final String KEY_PHOTO_URI = "photo_uri";
@ -83,10 +81,6 @@ public class FilePicker implements Constants {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(KEY_TYPE, type).apply(); PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(KEY_TYPE, type).apply();
} }
private static int restoreType(@NonNull Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(KEY_TYPE, 0);
}
/** /**
* Opens default galery or a available galleries picker if there is no default * Opens default galery or a available galleries picker if there is no default
* *
@ -150,14 +144,6 @@ public class FilePicker implements Constants {
} else { } else {
onPictureReturnedFromDocuments(data, activity, callbacks); onPictureReturnedFromDocuments(data, activity, callbacks);
} }
} else {
if (requestCode == RequestCodes.PICK_PICTURE_FROM_DOCUMENTS) {
callbacks.onCanceled(FilePicker.ImageSource.DOCUMENTS, restoreType(activity));
} else if (requestCode == RequestCodes.PICK_PICTURE_FROM_GALLERY) {
callbacks.onCanceled(FilePicker.ImageSource.GALLERY, restoreType(activity));
} else {
callbacks.onCanceled(FilePicker.ImageSource.CAMERA_IMAGE, restoreType(activity));
}
} }
} }
} }
@ -186,24 +172,24 @@ public class FilePicker implements Constants {
try { try {
Uri photoPath = data.getData(); Uri photoPath = data.getData();
UploadableFile photoFile = PickedFiles.pickedExistingPicture(activity, photoPath); UploadableFile photoFile = PickedFiles.pickedExistingPicture(activity, photoPath);
callbacks.onImagesPicked(singleFileList(photoFile), FilePicker.ImageSource.DOCUMENTS, restoreType(activity)); callbacks.onImagesPicked(singleFileList(photoFile));
if (configuration(activity).shouldCopyPickedImagesToPublicGalleryAppFolder()) { if (configuration(activity).shouldCopyPickedImagesToPublicGalleryAppFolder()) {
PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile)); PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile));
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
callbacks.onImagePickerError(e, FilePicker.ImageSource.DOCUMENTS, restoreType(activity)); callbacks.onImagePickerError();
} }
} }
private static void onPictureReturnedFromGallery(Intent data, Activity activity, @NonNull FilePicker.Callbacks callbacks) { private static void onPictureReturnedFromGallery(Intent data, Activity activity, @NonNull FilePicker.Callbacks callbacks) {
try { try {
List<UploadableFile> files = getFilesFromGalleryPictures(data, activity); List<UploadableFile> files = getFilesFromGalleryPictures(data, activity);
callbacks.onImagesPicked(files, FilePicker.ImageSource.GALLERY, restoreType(activity)); callbacks.onImagesPicked(files);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
callbacks.onImagePickerError(e, FilePicker.ImageSource.GALLERY, restoreType(activity)); callbacks.onImagePickerError();
} }
} }
@ -241,14 +227,13 @@ public class FilePicker implements Constants {
files.add(photoFile); files.add(photoFile);
if (photoFile == null) { if (photoFile == null) {
Exception e = new IllegalStateException("Unable to get the picture returned from camera"); callbacks.onImagePickerError();
callbacks.onImagePickerError(e, FilePicker.ImageSource.CAMERA_IMAGE, restoreType(activity));
} else { } else {
if (configuration(activity).shouldCopyTakenPhotosToPublicGalleryAppFolder()) { if (configuration(activity).shouldCopyTakenPhotosToPublicGalleryAppFolder()) {
PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile)); PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile));
} }
callbacks.onImagesPicked(files, FilePicker.ImageSource.CAMERA_IMAGE, restoreType(activity)); callbacks.onImagesPicked(files);
} }
PreferenceManager.getDefaultSharedPreferences(activity) PreferenceManager.getDefaultSharedPreferences(activity)
@ -258,7 +243,7 @@ public class FilePicker implements Constants {
.apply(); .apply();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
callbacks.onImagePickerError(e, FilePicker.ImageSource.CAMERA_IMAGE, restoreType(activity)); callbacks.onImagePickerError();
} }
} }
@ -274,14 +259,13 @@ public class FilePicker implements Constants {
files.add(photoFile); files.add(photoFile);
if (photoFile == null) { if (photoFile == null) {
Exception e = new IllegalStateException("Unable to get the video returned from camera"); callbacks.onImagePickerError();
callbacks.onImagePickerError(e, FilePicker.ImageSource.CAMERA_VIDEO, restoreType(activity));
} else { } else {
if (configuration(activity).shouldCopyTakenPhotosToPublicGalleryAppFolder()) { if (configuration(activity).shouldCopyTakenPhotosToPublicGalleryAppFolder()) {
PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile)); PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile));
} }
callbacks.onImagesPicked(files, FilePicker.ImageSource.CAMERA_VIDEO, restoreType(activity)); callbacks.onImagesPicked(files);
} }
PreferenceManager.getDefaultSharedPreferences(activity) PreferenceManager.getDefaultSharedPreferences(activity)
@ -291,7 +275,7 @@ public class FilePicker implements Constants {
.apply(); .apply();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
callbacks.onImagePickerError(e, FilePicker.ImageSource.CAMERA_VIDEO, restoreType(activity)); callbacks.onImagePickerError();
} }
} }
@ -300,15 +284,10 @@ public class FilePicker implements Constants {
} }
public enum ImageSource {
GALLERY, DOCUMENTS, CAMERA_IMAGE, CAMERA_VIDEO
}
public interface Callbacks { public interface Callbacks {
void onImagePickerError(Exception e, FilePicker.ImageSource source, int type); void onImagePickerError();
void onImagesPicked(@NonNull List<UploadableFile> imageFiles, FilePicker.ImageSource source, int type); void onImagesPicked(@NonNull List<UploadableFile> imageFiles);
void onCanceled(FilePicker.ImageSource source, int type);
} }
} }

View file

@ -47,10 +47,6 @@ public class UploadableFile implements Parcelable {
file = (File) in.readSerializable(); file = (File) in.readSerializable();
} }
public Uri getContentUri() {
return contentUri;
}
public File getFile() { public File getFile() {
return file; return file;
} }

View file

@ -2,16 +2,9 @@ package fr.free.nrw.commons.kvstore;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import androidx.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import timber.log.Timber;
public class BasicKvStore implements KeyValueStore { public class BasicKvStore implements KeyValueStore {
private static final String KEY_VERSION = "__version__"; private static final String KEY_VERSION = "__version__";
/* /*
@ -25,53 +18,6 @@ public class BasicKvStore implements KeyValueStore {
_store = context.getSharedPreferences(storeName, Context.MODE_PRIVATE); _store = context.getSharedPreferences(storeName, Context.MODE_PRIVATE);
} }
/**
* If you don't want onVersionUpdate to be called on a fresh creation, the first version supplied for the kvstore should be set to 0.
*/
public BasicKvStore(Context context, String storeName, int version) {
this(context,storeName,version,false);
}
public BasicKvStore(Context context, String storeName, int version, boolean clearAllOnUpgrade) {
_store = context.getSharedPreferences(storeName, Context.MODE_PRIVATE);
int oldVersion = getInt(KEY_VERSION);
if (version > oldVersion) {
Timber.i("version updated from %s to %s, with clearFlag %b", oldVersion, version, clearAllOnUpgrade);
onVersionUpdate(oldVersion, version, clearAllOnUpgrade);
}
if (version < oldVersion) {
throw new IllegalArgumentException(
"kvstore downgrade not allowed, old version:" + oldVersion + ", new version: " +
version);
}
//Keep this statement at the end so that clearing of store does not cause version also to get removed.
putIntInternal(KEY_VERSION, version);
}
public void onVersionUpdate(int oldVersion, int version, boolean clearAllFlag) {
if(clearAllFlag) {
clearAll();
}
}
public Set<String> getKeySet() {
Map<String, ?> allContents = new HashMap<>(_store.getAll());
allContents.remove(KEY_VERSION);
return allContents.keySet();
}
@Nullable
public Map<String, ?> getAll() {
Map<String, ?> allContents = _store.getAll();
if (allContents == null || allContents.size() == 0) {
return null;
}
allContents.remove(KEY_VERSION);
return new HashMap<>(allContents);
}
@Override @Override
public String getString(String key) { public String getString(String key) {
return getString(key, null); return getString(key, null);
@ -82,11 +28,6 @@ public class BasicKvStore implements KeyValueStore {
return getBoolean(key, false); return getBoolean(key, false);
} }
@Override
public long getLong(String key) {
return getLong(key, 0);
}
@Override @Override
public int getInt(String key) { public int getInt(String key) {
return getInt(key, 0); return getInt(key, 0);
@ -102,24 +43,11 @@ public class BasicKvStore implements KeyValueStore {
return _store.getBoolean(key, defaultValue); return _store.getBoolean(key, defaultValue);
} }
@Override
public long getLong(String key, long defaultValue) {
return _store.getLong(key, defaultValue);
}
@Override @Override
public int getInt(String key, int defaultValue) { public int getInt(String key, int defaultValue) {
return _store.getInt(key, defaultValue); return _store.getInt(key, defaultValue);
} }
public void putAllStrings(Map<String, String> keyValuePairs) {
SharedPreferences.Editor editor = _store.edit();
for (Map.Entry<String, String> keyValuePair : keyValuePairs.entrySet()) {
putString(editor, keyValuePair.getKey(), keyValuePair.getValue(), false);
}
editor.apply();
}
@Override @Override
public void putString(String key, String value) { public void putString(String key, String value) {
SharedPreferences.Editor editor = _store.edit(); SharedPreferences.Editor editor = _store.edit();
@ -143,14 +71,6 @@ public class BasicKvStore implements KeyValueStore {
editor.apply(); editor.apply();
} }
@Override
public void putLong(String key, long value) {
assertKeyNotReserved(key);
SharedPreferences.Editor editor = _store.edit();
editor.putLong(key, value);
editor.apply();
}
@Override @Override
public void putInt(String key, int value) { public void putInt(String key, int value) {
assertKeyNotReserved(key); assertKeyNotReserved(key);
@ -178,13 +98,6 @@ public class BasicKvStore implements KeyValueStore {
putIntInternal(KEY_VERSION, version); putIntInternal(KEY_VERSION, version);
} }
@Override
public void clearAllWithVersion() {
SharedPreferences.Editor editor = _store.edit();
editor.clear();
editor.apply();
}
private void putIntInternal(String key, int value) { private void putIntInternal(String key, int value) {
SharedPreferences.Editor editor = _store.edit(); SharedPreferences.Editor editor = _store.edit();
editor.putInt(key, value); editor.putInt(key, value);
@ -197,14 +110,6 @@ public class BasicKvStore implements KeyValueStore {
} }
} }
public void registerChangeListener(SharedPreferences.OnSharedPreferenceChangeListener l) {
_store.registerOnSharedPreferenceChangeListener(l);
}
public void unregisterChangeListener(SharedPreferences.OnSharedPreferenceChangeListener l) {
_store.unregisterOnSharedPreferenceChangeListener(l);
}
public Set<String> getStringSet(String key){ public Set<String> getStringSet(String key){
return _store.getStringSet(key, new HashSet<>()); return _store.getStringSet(key, new HashSet<>());
} }

View file

@ -1,16 +1,10 @@
package fr.free.nrw.commons.kvstore; package fr.free.nrw.commons.kvstore;
import android.content.Context; import android.content.Context;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class JsonKvStore extends BasicKvStore { public class JsonKvStore extends BasicKvStore {
private final Gson gson; private final Gson gson;
@ -19,33 +13,11 @@ public class JsonKvStore extends BasicKvStore {
this.gson = gson; this.gson = gson;
} }
public JsonKvStore(Context context, String storeName, int version, Gson gson) {
super(context, storeName, version);
this.gson = gson;
}
public JsonKvStore(Context context, String storeName, int version, boolean clearAllOnUpgrade, Gson gson) {
super(context, storeName, version, clearAllOnUpgrade);
this.gson = gson;
}
public <T> void putAllJsons(Map<String, T> jsonMap) {
Map<String, String> stringsMap = new HashMap<>(jsonMap.size());
for (Map.Entry<String, T> keyValuePair : jsonMap.entrySet()) {
String jsonString = gson.toJson(keyValuePair.getValue());
stringsMap.put(keyValuePair.getKey(), jsonString);
}
putAllStrings(stringsMap);
}
public <T> void putJson(String key, T object) { public <T> void putJson(String key, T object) {
putString(key, gson.toJson(object)); putString(key, gson.toJson(object));
} }
public <T> void putJsonWithTypeInfo(String key, T object, Type type) {
putString(key, gson.toJson(object, type));
}
@Nullable @Nullable
public <T> T getJson(String key, Class<T> clazz) { public <T> T getJson(String key, Class<T> clazz) {
String jsonString = getString(key); String jsonString = getString(key);
@ -56,13 +28,4 @@ public class JsonKvStore extends BasicKvStore {
} }
} }
@Nullable
public <T> T getJson(String key, Type type) {
String jsonString = getString(key);
try {
return gson.fromJson(jsonString, type);
} catch (JsonSyntaxException e) {
return null;
}
}
} }

View file

@ -5,24 +5,18 @@ public interface KeyValueStore {
boolean getBoolean(String key); boolean getBoolean(String key);
long getLong(String key);
int getInt(String key); int getInt(String key);
String getString(String key, String defaultValue); String getString(String key, String defaultValue);
boolean getBoolean(String key, boolean defaultValue); boolean getBoolean(String key, boolean defaultValue);
long getLong(String key, long defaultValue);
int getInt(String key, int defaultValue); int getInt(String key, int defaultValue);
void putString(String key, String value); void putString(String key, String value);
void putBoolean(String key, boolean value); void putBoolean(String key, boolean value);
void putLong(String key, long value);
void putInt(String key, int value); void putInt(String key, int value);
boolean contains(String key); boolean contains(String key);
@ -31,5 +25,4 @@ public interface KeyValueStore {
void clearAll(); void clearAll();
void clearAllWithVersion();
} }

View file

@ -1,16 +1,12 @@
package fr.free.nrw.commons.location; package fr.free.nrw.commons.location;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.location.Location; import android.location.Location;
import android.location.LocationListener; import android.location.LocationListener;
import android.location.LocationManager; import android.location.LocationManager;
import android.os.Bundle; import android.os.Bundle;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import timber.log.Timber; import timber.log.Timber;
public class LocationServiceManager implements LocationListener { public class LocationServiceManager implements LocationListener {
@ -24,7 +20,6 @@ public class LocationServiceManager implements LocationListener {
//private Location lastLocationDuplicate; // Will be used for nearby card view on contributions activity //private Location lastLocationDuplicate; // Will be used for nearby card view on contributions activity
private final List<LocationUpdateListener> locationListeners = new CopyOnWriteArrayList<>(); private final List<LocationUpdateListener> locationListeners = new CopyOnWriteArrayList<>();
private boolean isLocationManagerRegistered = false; private boolean isLocationManagerRegistered = false;
private Set<Activity> locationExplanationDisplayed = new HashSet<>();
/** /**
* Constructs a new instance of LocationServiceManager. * Constructs a new instance of LocationServiceManager.
@ -143,7 +138,6 @@ public class LocationServiceManager implements LocationListener {
*/ */
public void unregisterLocationManager() { public void unregisterLocationManager() {
isLocationManagerRegistered = false; isLocationManagerRegistered = false;
locationExplanationDisplayed.clear();
try { try {
locationManager.removeUpdates(this); locationManager.removeUpdates(this);
} catch (SecurityException e) { } catch (SecurityException e) {
@ -224,9 +218,7 @@ public class LocationServiceManager implements LocationListener {
public enum LocationChangeType{ public enum LocationChangeType{
LOCATION_SIGNIFICANTLY_CHANGED, //Went out of borders of nearby markers LOCATION_SIGNIFICANTLY_CHANGED, //Went out of borders of nearby markers
LOCATION_SLIGHTLY_CHANGED, //User might be walking or driving LOCATION_SLIGHTLY_CHANGED, //User might be walking or driving
LOCATION_MEDIUM_CHANGED, //Between slight and significant changes, will be used for nearby card view updates.
LOCATION_NOT_CHANGED, LOCATION_NOT_CHANGED,
PERMISSION_JUST_GRANTED,
MAP_UPDATED, MAP_UPDATED,
SEARCH_CUSTOM_AREA SEARCH_CUSTOM_AREA
} }

View file

@ -21,7 +21,7 @@ import timber.log.Timber;
/** /**
* Extends Timber's debug tree to write logs to a file * Extends Timber's debug tree to write logs to a file
*/ */
public class FileLoggingTree extends Timber.DebugTree implements LogLevelSettableTree { public class FileLoggingTree extends Timber.DebugTree {
private final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); private final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private int logLevel; private int logLevel;
private final String logFileName; private final String logFileName;
@ -41,15 +41,6 @@ public class FileLoggingTree extends Timber.DebugTree implements LogLevelSettabl
this.executor = executor; this.executor = executor;
} }
/**
* Can be overridden to change file's log level
* @param logLevel
*/
@Override
public void setLogLevel(int logLevel) {
this.logLevel = logLevel;
}
/** /**
* Check and log any message * Check and log any message
* @param priority * @param priority

View file

@ -1,8 +0,0 @@
package fr.free.nrw.commons.logging;
/**
* Can be implemented to set the log level for file tree
*/
public interface LogLevelSettableTree {
void setLogLevel(int logLevel);
}

View file

@ -1,43 +0,0 @@
package fr.free.nrw.commons.media;
import com.google.gson.annotations.SerializedName;
/**
* Model class for parsing Captions when fetching captions using filename in MediaClient
*/
public class Caption {
/**
* users language in which caption is written
*/
@SerializedName("language")
private String language;
@SerializedName("value")
private String value;
/**
* No args constructor for use in serialization
*/
public Caption() {
}
/**
* @param value
* @param language
*/
public Caption(String language, String value) {
super();
this.language = language;
this.value = value;
}
@SerializedName("language")
public String getLanguage() {
return language;
}
@SerializedName("value")
public String getValue() {
return value;
}
}

View file

@ -1,76 +0,0 @@
package fr.free.nrw.commons.media;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
/**
* Represents the Wikibase item associated with a Wikimedia Commons file.
* For instance the Wikibase item M63996 represents the Commons file "Paul Cézanne - The Pigeon Tower at Bellevue - 1936.19 - Cleveland Museum of Art.jpg"
*/
public class CommonsWikibaseItem {
@SerializedName("type")
private String type;
@SerializedName("id")
private String id;
@SerializedName("labels")
private Map<String, Caption> labels;
@SerializedName("statements")
private Object statements = null;
/**
* No args constructor for use in serialization
*/
public CommonsWikibaseItem() {
}
/**
* @param id
* @param statements
* @param labels
* @param type
*/
public CommonsWikibaseItem(String type, String id, Map<String, Caption> labels, Object statements) {
super();
this.type = type;
this.id = id;
this.labels = labels;
this.statements = statements;
}
/**
* Ex: "mediainfo
*/
@SerializedName("type")
public String getType() {
return type;
}
/**
* @return Wikibase Id
*/
@SerializedName("id")
public String getId() {
return id;
}
/**
* @return value of captions
*/
@SerializedName("labels")
public Map<String, Caption> getLabels() {
return labels;
}
/**
* Contains the Depicts item
*/
@SerializedName("statements")
public Object getStatements() {
return statements;
}
}

View file

@ -1,6 +1,5 @@
package fr.free.nrw.commons.media; package fr.free.nrw.commons.media;
import io.reactivex.Observable;
import io.reactivex.Single; import io.reactivex.Single;
import org.wikipedia.wikidata.Entities; import org.wikipedia.wikidata.Entities;
import retrofit2.http.GET; import retrofit2.http.GET;
@ -11,14 +10,6 @@ import retrofit2.http.Query;
*/ */
public interface MediaDetailInterface { public interface MediaDetailInterface {
/**
* Fetches entity using file name
*
* @param filename name of the file to be used for fetching captions
*/
@GET("w/api.php?action=wbgetentities&props=labels&format=json&languagefallback=1&sites=commonswiki")
Observable<Entities> fetchEntitiesByFileName(@Query("languages") String language, @Query("titles") String filename);
/** /**
* Gets labels for Depictions using Entity Id from MediaWikiAPI * Gets labels for Depictions using Entity Id from MediaWikiAPI
* @param entityId EntityId (Ex: Q81566) of the depict entity * @param entityId EntityId (Ex: Q81566) of the depict entity
@ -27,11 +18,4 @@ public interface MediaDetailInterface {
@GET("/w/api.php?format=json&action=wbgetentities&props=labels&languagefallback=1") @GET("/w/api.php?format=json&action=wbgetentities&props=labels&languagefallback=1")
Single<Entities> getEntity(@Query("ids") String entityId); Single<Entities> getEntity(@Query("ids") String entityId);
/**
* Fetches caption using wikibaseIdentifier
*
* @param wikibaseIdentifier pageId for the media
*/
@GET("/w/api.php?action=wbgetentities&props=labels&format=json&languagefallback=1&sites=commonswiki")
Observable<Entities> getEntityForImage(@Query("languages") String language, @Query("ids") String wikibaseIdentifier);
} }

View file

@ -279,12 +279,6 @@ public class MediaDetailPagerFragment extends CommonsDaggerSupportFragment imple
public void onPageScrollStateChanged(int i) { public void onPageScrollStateChanged(int i) {
} }
public void onDataSetChanged() {
if (null != adapter) {
adapter.notifyDataSetChanged();
}
}
public interface MediaDetailProvider { public interface MediaDetailProvider {
Media getMediaAtPosition(int i); Media getMediaAtPosition(int i);

View file

@ -107,14 +107,6 @@ public interface MediaInterface {
@GET("w/api.php?format=json&action=parse&prop=text") @GET("w/api.php?format=json&action=parse&prop=text")
Single<MwParseResponse> getPageHtml(@Query("page") String title); Single<MwParseResponse> getPageHtml(@Query("page") String title);
/**
* Fetches caption using file name
*
* @param filename name of the file to be used for fetching captions
* */
@GET("w/api.php?action=wbgetentities&props=labels&format=json&languagefallback=1")
Single<MwQueryResponse> fetchCaptionByFilename(@Query("language") String language, @Query("titles") String filename);
/** /**
* Fetches list of images from a depiction entity * Fetches list of images from a depiction entity
* @param query depictionEntityId * @param query depictionEntityId

View file

@ -14,10 +14,6 @@ public class MwParseResponse extends MwResponse {
return parse; return parse;
} }
public boolean success() {
return parse != null;
}
@VisibleForTesting @VisibleForTesting
protected void setParse(@Nullable MwParseResult parse) { protected void setParse(@Nullable MwParseResult parse) {
this.parse = parse; this.parse = parse;

View file

@ -14,20 +14,19 @@ public class MultiPointerGestureDetector {
/** The listener for receiving notifications when gestures occur. */ /** The listener for receiving notifications when gestures occur. */
public interface Listener { public interface Listener {
/** A callback called right before the gesture is about to start. */ /** A callback called right before the gesture is about to start. */
public void onGestureBegin(MultiPointerGestureDetector detector); public void onGestureBegin();
/** A callback called each time the gesture gets updated. */ /** A callback called each time the gesture gets updated. */
public void onGestureUpdate(MultiPointerGestureDetector detector); public void onGestureUpdate();
/** A callback called right after the gesture has finished. */ /** A callback called right after the gesture has finished. */
public void onGestureEnd(MultiPointerGestureDetector detector); public void onGestureEnd();
} }
private static final int MAX_POINTERS = 2; private static final int MAX_POINTERS = 2;
private boolean mGestureInProgress; private boolean mGestureInProgress;
private int mPointerCount; private int mPointerCount;
private int mNewPointerCount;
private final int mId[] = new int[MAX_POINTERS]; private final int mId[] = new int[MAX_POINTERS];
private final float mStartX[] = new float[MAX_POINTERS]; private final float mStartX[] = new float[MAX_POINTERS];
private final float mStartY[] = new float[MAX_POINTERS]; private final float mStartY[] = new float[MAX_POINTERS];
@ -76,7 +75,7 @@ public class MultiPointerGestureDetector {
private void startGesture() { private void startGesture() {
if (!mGestureInProgress) { if (!mGestureInProgress) {
if (mListener != null) { if (mListener != null) {
mListener.onGestureBegin(this); mListener.onGestureBegin();
} }
mGestureInProgress = true; mGestureInProgress = true;
} }
@ -87,7 +86,7 @@ public class MultiPointerGestureDetector {
if (mGestureInProgress) { if (mGestureInProgress) {
mGestureInProgress = false; mGestureInProgress = false;
if (mListener != null) { if (mListener != null) {
mListener.onGestureEnd(this); mListener.onGestureEnd();
} }
} }
} }
@ -110,16 +109,6 @@ public class MultiPointerGestureDetector {
return (i < count) ? i : -1; return (i < count) ? i : -1;
} }
/** Gets the number of pressed pointers (fingers down). */
private static int getPressedPointerCount(MotionEvent event) {
int count = event.getPointerCount();
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
count--;
}
return count;
}
private void updatePointersOnTap(MotionEvent event) { private void updatePointersOnTap(MotionEvent event) {
mPointerCount = 0; mPointerCount = 0;
for (int i = 0; i < MAX_POINTERS; i++) { for (int i = 0; i < MAX_POINTERS; i++) {
@ -163,7 +152,7 @@ public class MultiPointerGestureDetector {
} }
// notify listener // notify listener
if (mGestureInProgress && mListener != null) { if (mGestureInProgress && mListener != null) {
mListener.onGestureUpdate(this); mListener.onGestureUpdate();
} }
break; break;
} }
@ -174,7 +163,6 @@ public class MultiPointerGestureDetector {
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_UP:
{ {
// restart gesture whenever the number of pointers changes // restart gesture whenever the number of pointers changes
mNewPointerCount = getPressedPointerCount(event);
stopGesture(); stopGesture();
updatePointersOnTap(event); updatePointersOnTap(event);
if (mPointerCount > 0 && shouldStartGesture()) { if (mPointerCount > 0 && shouldStartGesture()) {
@ -185,7 +173,6 @@ public class MultiPointerGestureDetector {
case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_CANCEL:
{ {
mNewPointerCount = 0;
stopGesture(); stopGesture();
reset(); reset();
break; break;
@ -207,16 +194,6 @@ public class MultiPointerGestureDetector {
startGesture(); startGesture();
} }
/** Gets whether there is a gesture in progress */
public boolean isGestureInProgress() {
return mGestureInProgress;
}
/** Gets the number of pointers after the current gesture */
public int getNewPointerCount() {
return mNewPointerCount;
}
/** Gets the number of pointers in the current gesture */ /** Gets the number of pointers in the current gesture */
public int getPointerCount() { public int getPointerCount() {
return mPointerCount; return mPointerCount;

View file

@ -20,7 +20,7 @@ public class TransformGestureDetector implements MultiPointerGestureDetector.Lis
public void onGestureUpdate(TransformGestureDetector detector); public void onGestureUpdate(TransformGestureDetector detector);
/** A callback called right after the gesture has finished. */ /** A callback called right after the gesture has finished. */
public void onGestureEnd(TransformGestureDetector detector); public void onGestureEnd();
} }
private final MultiPointerGestureDetector mDetector; private final MultiPointerGestureDetector mDetector;
@ -62,23 +62,23 @@ public class TransformGestureDetector implements MultiPointerGestureDetector.Lis
} }
@Override @Override
public void onGestureBegin(MultiPointerGestureDetector detector) { public void onGestureBegin() {
if (mListener != null) { if (mListener != null) {
mListener.onGestureBegin(this); mListener.onGestureBegin(this);
} }
} }
@Override @Override
public void onGestureUpdate(MultiPointerGestureDetector detector) { public void onGestureUpdate() {
if (mListener != null) { if (mListener != null) {
mListener.onGestureUpdate(this); mListener.onGestureUpdate(this);
} }
} }
@Override @Override
public void onGestureEnd(MultiPointerGestureDetector detector) { public void onGestureEnd() {
if (mListener != null) { if (mListener != null) {
mListener.onGestureEnd(this); mListener.onGestureEnd();
} }
} }
@ -95,21 +95,6 @@ public class TransformGestureDetector implements MultiPointerGestureDetector.Lis
mDetector.restartGesture(); mDetector.restartGesture();
} }
/** Gets whether there is a gesture in progress */
public boolean isGestureInProgress() {
return mDetector.isGestureInProgress();
}
/** Gets the number of pointers after the current gesture */
public int getNewPointerCount() {
return mDetector.getNewPointerCount();
}
/** Gets the number of pointers in the current gesture */
public int getPointerCount() {
return mDetector.getPointerCount();
}
/** Gets the X coordinate of the pivot point */ /** Gets the X coordinate of the pivot point */
public float getPivotX() { public float getPivotX() {
return calcAverage(mDetector.getStartX(), mDetector.getPointerCount()); return calcAverage(mDetector.getStartX(), mDetector.getPointerCount());

View file

@ -49,7 +49,6 @@ public abstract class AbstractAnimatedZoomableController extends DefaultZoomable
* @param imagePoint 2D point in image's relative coordinate system (i.e. 0 <= x, y <= 1) * @param imagePoint 2D point in image's relative coordinate system (i.e. 0 <= x, y <= 1)
* @param viewPoint 2D point in view's absolute coordinate system * @param viewPoint 2D point in view's absolute coordinate system
*/ */
@Override
public void zoomToPoint(float scale, PointF imagePoint, PointF viewPoint) { public void zoomToPoint(float scale, PointF imagePoint, PointF viewPoint) {
zoomToPoint(scale, imagePoint, viewPoint, LIMIT_ALL, 0, null); zoomToPoint(scale, imagePoint, viewPoint, LIMIT_ALL, 0, null);
} }

View file

@ -15,11 +15,6 @@ import java.lang.annotation.RetentionPolicy;
public class DefaultZoomableController public class DefaultZoomableController
implements ZoomableController, TransformGestureDetector.Listener { implements ZoomableController, TransformGestureDetector.Listener {
/** Interface for handling call backs when the image bounds are set. */
public interface ImageBoundsListener {
void onImageBoundsSet(RectF imageBounds);
}
@IntDef( @IntDef(
flag = true, flag = true,
value = {LIMIT_NONE, LIMIT_TRANSLATION_X, LIMIT_TRANSLATION_Y, LIMIT_SCALE, LIMIT_ALL}) value = {LIMIT_NONE, LIMIT_TRANSLATION_X, LIMIT_TRANSLATION_Y, LIMIT_SCALE, LIMIT_ALL})
@ -32,16 +27,10 @@ public class DefaultZoomableController
public static final int LIMIT_SCALE = 4; public static final int LIMIT_SCALE = 4;
public static final int LIMIT_ALL = LIMIT_TRANSLATION_X | LIMIT_TRANSLATION_Y | LIMIT_SCALE; public static final int LIMIT_ALL = LIMIT_TRANSLATION_X | LIMIT_TRANSLATION_Y | LIMIT_SCALE;
private static final float EPS = 1e-3f;
private static final Class<?> TAG = DefaultZoomableController.class; private static final Class<?> TAG = DefaultZoomableController.class;
private static final RectF IDENTITY_RECT = new RectF(0, 0, 1, 1);
private TransformGestureDetector mGestureDetector; private TransformGestureDetector mGestureDetector;
private @Nullable ImageBoundsListener mImageBoundsListener;
private @Nullable Listener mListener = null; private @Nullable Listener mListener = null;
private boolean mIsEnabled = false; private boolean mIsEnabled = false;
@ -65,11 +54,6 @@ public class DefaultZoomableController
private final Matrix mActiveTransformInverse = new Matrix(); private final Matrix mActiveTransformInverse = new Matrix();
private final float[] mTempValues = new float[9]; private final float[] mTempValues = new float[9];
private final RectF mTempRect = new RectF(); private final RectF mTempRect = new RectF();
private boolean mWasTransformCorrected;
public static DefaultZoomableController newInstance() {
return new DefaultZoomableController(TransformGestureDetector.newInstance());
}
public DefaultZoomableController(TransformGestureDetector gestureDetector) { public DefaultZoomableController(TransformGestureDetector gestureDetector) {
mGestureDetector = gestureDetector; mGestureDetector = gestureDetector;
@ -106,74 +90,16 @@ public class DefaultZoomableController
return mIsEnabled; return mIsEnabled;
} }
/** Sets whether the rotation gesture is enabled or not. */
public void setRotationEnabled(boolean enabled) {
mIsRotationEnabled = enabled;
}
/** Gets whether the rotation gesture is enabled or not. */
public boolean isRotationEnabled() {
return mIsRotationEnabled;
}
/** Sets whether the scale gesture is enabled or not. */
public void setScaleEnabled(boolean enabled) {
mIsScaleEnabled = enabled;
}
/** Gets whether the scale gesture is enabled or not. */
public boolean isScaleEnabled() {
return mIsScaleEnabled;
}
/** Sets whether the translation gesture is enabled or not. */
public void setTranslationEnabled(boolean enabled) {
mIsTranslationEnabled = enabled;
}
/** Gets whether the translations gesture is enabled or not. */
public boolean isTranslationEnabled() {
return mIsTranslationEnabled;
}
/**
* Sets the minimum scale factor allowed.
*
* <p>Hierarchy's scaling (if any) is not taken into account.
*/
public void setMinScaleFactor(float minScaleFactor) {
mMinScaleFactor = minScaleFactor;
}
/** Gets the minimum scale factor allowed. */ /** Gets the minimum scale factor allowed. */
public float getMinScaleFactor() { public float getMinScaleFactor() {
return mMinScaleFactor; return mMinScaleFactor;
} }
/**
* Sets the maximum scale factor allowed.
*
* <p>Hierarchy's scaling (if any) is not taken into account.
*/
public void setMaxScaleFactor(float maxScaleFactor) {
mMaxScaleFactor = maxScaleFactor;
}
/** Gets the maximum scale factor allowed. */ /** Gets the maximum scale factor allowed. */
public float getMaxScaleFactor() { public float getMaxScaleFactor() {
return mMaxScaleFactor; return mMaxScaleFactor;
} }
/** Sets whether gesture zooms are enabled or not. */
public void setGestureZoomEnabled(boolean isGestureZoomEnabled) {
mIsGestureZoomEnabled = isGestureZoomEnabled;
}
/** Gets whether gesture zooms are enabled or not. */
public boolean isGestureZoomEnabled() {
return mIsGestureZoomEnabled;
}
/** Gets the current scale factor. */ /** Gets the current scale factor. */
@Override @Override
public float getScaleFactor() { public float getScaleFactor() {
@ -186,21 +112,8 @@ public class DefaultZoomableController
if (!imageBounds.equals(mImageBounds)) { if (!imageBounds.equals(mImageBounds)) {
mImageBounds.set(imageBounds); mImageBounds.set(imageBounds);
onTransformChanged(); onTransformChanged();
if (mImageBoundsListener != null) {
mImageBoundsListener.onImageBoundsSet(mImageBounds);
} }
} }
}
/** Gets the non-transformed image bounds, in view-absolute coordinates. */
public RectF getImageBounds() {
return mImageBounds;
}
/** Gets the transformed image bounds, in view-absolute coordinates */
private RectF getTransformedImageBounds() {
return mTransformedImageBounds;
}
/** Sets the view bounds. */ /** Sets the view bounds. */
@Override @Override
@ -208,38 +121,12 @@ public class DefaultZoomableController
mViewBounds.set(viewBounds); mViewBounds.set(viewBounds);
} }
/** Gets the view bounds. */
public RectF getViewBounds() {
return mViewBounds;
}
/** Sets the image bounds listener. */
public void setImageBoundsListener(@Nullable ImageBoundsListener imageBoundsListener) {
mImageBoundsListener = imageBoundsListener;
}
/** Gets the image bounds listener. */
public @Nullable ImageBoundsListener getImageBoundsListener() {
return mImageBoundsListener;
}
/** Returns true if the zoomable transform is identity matrix. */ /** Returns true if the zoomable transform is identity matrix. */
@Override @Override
public boolean isIdentity() { public boolean isIdentity() {
return isMatrixIdentity(mActiveTransform, 1e-3f); return isMatrixIdentity(mActiveTransform, 1e-3f);
} }
/**
* Returns true if the transform was corrected during the last update.
*
* <p>We should rename this method to `wasTransformedWithoutCorrection` and just return the
* internal flag directly. However, this requires interface change and negation of meaning.
*/
@Override
public boolean wasTransformCorrected() {
return mWasTransformCorrected;
}
/** /**
* Gets the matrix that transforms image-absolute coordinates to view-absolute coordinates. The * Gets the matrix that transforms image-absolute coordinates to view-absolute coordinates. The
* zoomable transformation is taken into account. * zoomable transformation is taken into account.
@ -251,14 +138,6 @@ public class DefaultZoomableController
return mActiveTransform; return mActiveTransform;
} }
/**
* Gets the matrix that transforms image-relative coordinates to view-absolute coordinates. The
* zoomable transformation is taken into account.
*/
public void getImageRelativeToViewAbsoluteTransform(Matrix outMatrix) {
outMatrix.setRectToRect(IDENTITY_RECT, mTransformedImageBounds, Matrix.ScaleToFit.FILL);
}
/** /**
* Maps point from view-absolute to image-relative coordinates. This takes into account the * Maps point from view-absolute to image-relative coordinates. This takes into account the
* zoomable transformation. * zoomable transformation.
@ -273,19 +152,6 @@ public class DefaultZoomableController
return new PointF(points[0], points[1]); return new PointF(points[0], points[1]);
} }
/**
* Maps point from image-relative to view-absolute coordinates. This takes into account the
* zoomable transformation.
*/
public PointF mapImageToView(PointF imagePoint) {
float[] points = mTempValues;
points[0] = imagePoint.x;
points[1] = imagePoint.y;
mapRelativeToAbsolute(points, points, 1);
mActiveTransform.mapPoints(points, 0, points, 0, 1);
return new PointF(points[0], points[1]);
}
/** /**
* Maps array of 2D points from view-absolute to image-relative coordinates. This does NOT take * Maps array of 2D points from view-absolute to image-relative coordinates. This does NOT take
* into account the zoomable transformation. Points are represented by a float array of [x0, y0, * into account the zoomable transformation. Points are represented by a float array of [x0, y0,
@ -318,20 +184,6 @@ public class DefaultZoomableController
} }
} }
/**
* Zooms to the desired scale and positions the image so that the given image point corresponds to
* the given view point.
*
* @param scale desired scale, will be limited to {min, max} scale factor
* @param imagePoint 2D point in image's relative coordinate system (i.e. 0 <= x, y <= 1)
* @param viewPoint 2D point in view's absolute coordinate system
*/
public void zoomToPoint(float scale, PointF imagePoint, PointF viewPoint) {
FLog.v(TAG, "zoomToPoint");
calculateZoomToPointTransform(mActiveTransform, scale, imagePoint, viewPoint, LIMIT_ALL);
onTransformChanged();
}
/** /**
* Calculates the zoom transformation that would zoom to the desired scale and position the image * Calculates the zoom transformation that would zoom to the desired scale and position the image
* so that the given image point corresponds to the given view point. * so that the given image point corresponds to the given view point.
@ -391,12 +243,6 @@ public class DefaultZoomableController
public void onGestureBegin(TransformGestureDetector detector) { public void onGestureBegin(TransformGestureDetector detector) {
FLog.v(TAG, "onGestureBegin"); FLog.v(TAG, "onGestureBegin");
mPreviousTransform.set(mActiveTransform); mPreviousTransform.set(mActiveTransform);
onTransformBegin();
// We only received a touch down event so far, and so we don't know yet in which direction a
// future move event will follow. Therefore, if we can't scroll in all directions, we have to
// assume the worst case where the user tries to scroll out of edge, which would cause
// transformation to be corrected.
mWasTransformCorrected = !canScrollInAllDirection();
} }
@Override @Override
@ -408,11 +254,10 @@ public class DefaultZoomableController
mGestureDetector.restartGesture(); mGestureDetector.restartGesture();
} }
// A transformation happened, but was it without correction? // A transformation happened, but was it without correction?
mWasTransformCorrected = transformCorrected;
} }
@Override @Override
public void onGestureEnd(TransformGestureDetector detector) { public void onGestureEnd() {
FLog.v(TAG, "onGestureEnd"); FLog.v(TAG, "onGestureEnd");
onTransformEnd(); onTransformEnd();
} }
@ -445,12 +290,6 @@ public class DefaultZoomableController
return transformCorrected; return transformCorrected;
} }
private void onTransformBegin() {
if (mListener != null && isEnabled()) {
mListener.onTransformBegin(mActiveTransform);
}
}
private void onTransformChanged() { private void onTransformChanged() {
mActiveTransform.mapRect(mTransformedImageBounds, mImageBounds); mActiveTransform.mapRect(mTransformedImageBounds, mImageBounds);
if (mListener != null && isEnabled()) { if (mListener != null && isEnabled()) {
@ -458,12 +297,6 @@ public class DefaultZoomableController
} }
} }
private void onTransformEnd() {
if (mListener != null && isEnabled()) {
mListener.onTransformEnd(mActiveTransform);
}
}
/** /**
* Keeps the scaling factor within the specified limits. * Keeps the scaling factor within the specified limits.
* *
@ -602,14 +435,6 @@ public class DefaultZoomableController
return true; return true;
} }
/** Returns whether the scroll can happen in all directions. I.e. the image is not on any edge. */
private boolean canScrollInAllDirection() {
return mTransformedImageBounds.left < mViewBounds.left - EPS
&& mTransformedImageBounds.top < mViewBounds.top - EPS
&& mTransformedImageBounds.right > mViewBounds.right + EPS
&& mTransformedImageBounds.bottom > mViewBounds.bottom + EPS;
}
@Override @Override
public int computeHorizontalScrollRange() { public int computeHorizontalScrollRange() {
return (int) mTransformedImageBounds.width(); return (int) mTransformedImageBounds.width();
@ -640,7 +465,4 @@ public class DefaultZoomableController
return (int) mViewBounds.height(); return (int) mViewBounds.height();
} }
public Listener getListener() {
return mListener;
}
} }

View file

@ -1,148 +0,0 @@
package fr.free.nrw.commons.media.zoomControllers.zoomable;
import android.view.GestureDetector;
import android.view.MotionEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Gesture listener that allows multiple child listeners to be added and notified about gesture
* events.
*
* NOTE: The order of the listeners is important. Listeners can consume gesture events. For
* example, if one of the child listeners consumes {@link #onLongPress(MotionEvent)} (the listener
* returned true), subsequent listeners will not be notified about the event any more since it has
* been consumed.
*/
public class MultiGestureListener extends GestureDetector.SimpleOnGestureListener {
private final List<GestureDetector.SimpleOnGestureListener> mListeners = new ArrayList<>();
/**
* Adds a listener to the multi gesture listener.
*
* <p>NOTE: The order of the listeners is important since gesture events can be consumed.
*
* @param listener the listener to be added
*/
public synchronized void addListener(GestureDetector.SimpleOnGestureListener listener) {
mListeners.add(listener);
}
/**
* Removes the given listener so that it will not be notified about future events.
*
* <p>NOTE: The order of the listeners is important since gesture events can be consumed.
*
* @param listener the listener to remove
*/
public synchronized void removeListener(GestureDetector.SimpleOnGestureListener listener) {
mListeners.remove(listener);
}
@Override
public synchronized boolean onSingleTapUp(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onSingleTapUp(e)) {
return true;
}
}
return false;
}
@Override
public synchronized void onLongPress(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
mListeners.get(i).onLongPress(e);
}
}
@Override
public synchronized boolean onScroll(
MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onScroll(e1, e2, distanceX, distanceY)) {
return true;
}
}
return false;
}
@Override
public synchronized boolean onFling(
MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onFling(e1, e2, velocityX, velocityY)) {
return true;
}
}
return false;
}
@Override
public synchronized void onShowPress(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
mListeners.get(i).onShowPress(e);
}
}
@Override
public synchronized boolean onDown(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onDown(e)) {
return true;
}
}
return false;
}
@Override
public synchronized boolean onDoubleTap(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onDoubleTap(e)) {
return true;
}
}
return false;
}
@Override
public synchronized boolean onDoubleTapEvent(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onDoubleTapEvent(e)) {
return true;
}
}
return false;
}
@Override
public synchronized boolean onSingleTapConfirmed(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onSingleTapConfirmed(e)) {
return true;
}
}
return false;
}
@Override
public synchronized boolean onContextClick(MotionEvent e) {
final int size = mListeners.size();
for (int i = 0; i < size; i++) {
if (mListeners.get(i).onContextClick(e)) {
return true;
}
}
return false;
}
}

View file

@ -1,40 +0,0 @@
package fr.free.nrw.commons.media.zoomControllers.zoomable;
import android.graphics.Matrix;
import java.util.ArrayList;
import java.util.List;
public class MultiZoomableControllerListener implements ZoomableController.Listener {
private final List<ZoomableController.Listener> mListeners = new ArrayList<>();
@Override
public synchronized void onTransformBegin(Matrix transform) {
for (ZoomableController.Listener listener : mListeners) {
listener.onTransformBegin(transform);
}
}
@Override
public synchronized void onTransformChanged(Matrix transform) {
for (ZoomableController.Listener listener : mListeners) {
listener.onTransformChanged(transform);
}
}
@Override
public synchronized void onTransformEnd(Matrix transform) {
for (ZoomableController.Listener listener : mListeners) {
listener.onTransformEnd(transform);
}
}
public synchronized void addListener(ZoomableController.Listener listener) {
mListeners.add(listener);
}
public synchronized void removeListener(ZoomableController.Listener listener) {
mListeners.remove(listener);
}
}

View file

@ -13,13 +13,6 @@ public interface ZoomableController {
/** Listener interface. */ /** Listener interface. */
interface Listener { interface Listener {
/**
* Notifies the view that the transform began.
*
* @param transform the current transform matrix
*/
void onTransformBegin(Matrix transform);
/** /**
* Notifies the view that the transform changed. * Notifies the view that the transform changed.
* *
@ -27,12 +20,6 @@ public interface ZoomableController {
*/ */
void onTransformChanged(Matrix transform); void onTransformChanged(Matrix transform);
/**
* Notifies the view that the transform ended.
*
* @param transform the current transform matrix
*/
void onTransformEnd(Matrix transform);
} }
/** /**
@ -68,14 +55,6 @@ public interface ZoomableController {
/** Returns true if the zoomable transform is identity matrix, and the controller is idle. */ /** Returns true if the zoomable transform is identity matrix, and the controller is idle. */
boolean isIdentity(); boolean isIdentity();
/**
* Returns true if the transform was corrected during the last update.
*
* <p>This mainly happens when a gesture would cause the image to get out of limits and the
* transform gets corrected in order to prevent that.
*/
boolean wasTransformCorrected();
/** See {@link androidx.core.view.ScrollingView}. */ /** See {@link androidx.core.view.ScrollingView}. */
int computeHorizontalScrollRange(); int computeHorizontalScrollRange();

View file

@ -9,10 +9,8 @@ import android.graphics.drawable.Animatable;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.GestureDetector; import android.view.GestureDetector;
import android.view.MotionEvent; import android.view.MotionEvent;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.view.ScrollingView; import androidx.core.view.ScrollingView;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.logging.FLog; import com.facebook.common.logging.FLog;
import com.facebook.drawee.controller.AbstractDraweeController; import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.controller.BaseControllerListener;
@ -64,16 +62,12 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
private final ZoomableController.Listener mZoomableListener = private final ZoomableController.Listener mZoomableListener =
new ZoomableController.Listener() { new ZoomableController.Listener() {
@Override
public void onTransformBegin(Matrix transform) {}
@Override @Override
public void onTransformChanged(Matrix transform) { public void onTransformChanged(Matrix transform) {
ZoomableDraweeView.this.onTransformChanged(transform); ZoomableDraweeView.this.onTransformChanged(transform);
} }
@Override
public void onTransformEnd(Matrix transform) {}
}; };
private final GestureListenerWrapper mTapListenerWrapper = new GestureListenerWrapper(); private final GestureListenerWrapper mTapListenerWrapper = new GestureListenerWrapper();
@ -118,10 +112,6 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper); mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper);
} }
public void setIsDialtoneEnabled(boolean isDialtoneEnabled) {
mIsDialtoneEnabled = isDialtoneEnabled;
}
/** /**
* Gets the original image bounds, in view-absolute coordinates. * Gets the original image bounds, in view-absolute coordinates.
* *
@ -153,14 +143,6 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
outBounds.set(0, 0, getWidth(), getHeight()); outBounds.set(0, 0, getWidth(), getHeight());
} }
/** Sets a custom zoomable controller, instead of using the default one. */
public void setZoomableController(ZoomableController zoomableController) {
Preconditions.checkNotNull(zoomableController);
mZoomableController.setListener(null);
mZoomableController = zoomableController;
mZoomableController.setListener(mZoomableListener);
}
/** /**
* Gets the zoomable controller. * Gets the zoomable controller.
* *
@ -171,16 +153,6 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
return mZoomableController; return mZoomableController;
} }
/**
* Check whether the parent view can intercept touch events while zoomed. This can be used, for
* example, to swipe between images in a view pager while zoomed.
*
* @return true if touch events can be intercepted
*/
public boolean allowsTouchInterceptionWhileZoomed() {
return mAllowTouchInterceptionWhileZoomed;
}
/** /**
* If this is set to true, parent views can intercept touch events while the view is zoomed. For * If this is set to true, parent views can intercept touch events while the view is zoomed. For
* example, this can be used to swipe between images in a view pager while zoomed. * example, this can be used to swipe between images in a view pager while zoomed.
@ -204,11 +176,6 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
mTapGestureDetector.setIsLongpressEnabled(enabled); mTapGestureDetector.setIsLongpressEnabled(enabled);
} }
public void setZoomingEnabled(boolean zoomingEnabled) {
mZoomingEnabled = zoomingEnabled;
mZoomableController.setEnabled(false);
}
/** Sets the image controller. */ /** Sets the image controller. */
@Override @Override
public void setController(@Nullable DraweeController controller) { public void setController(@Nullable DraweeController controller) {

View file

@ -1,19 +1,13 @@
package fr.free.nrw.commons.mwapi; package fr.free.nrw.commons.mwapi;
import org.wikipedia.dataclient.mwapi.MwQueryLogEvent; import io.reactivex.Single;
import java.util.Date;
import javax.inject.Inject;
import org.wikipedia.dataclient.mwapi.MwQueryResponse; import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import org.wikipedia.dataclient.mwapi.MwQueryResult; import org.wikipedia.dataclient.mwapi.MwQueryResult;
import org.wikipedia.dataclient.mwapi.UserInfo; import org.wikipedia.dataclient.mwapi.UserInfo;
import org.wikipedia.util.DateUtil; import org.wikipedia.util.DateUtil;
import java.util.Collections;
import java.util.Date;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.Single;
public class UserClient { public class UserClient {
private final UserInterface userInterface; private final UserInterface userInterface;
@ -45,15 +39,4 @@ public class UserClient {
}).single(false); }).single(false);
} }
public Observable<MwQueryLogEvent> logEvents(String user) {
try {
return userInterface.getUserLogEvents(user, Collections.emptyMap())
.map(MwQueryResponse::query)
.map(MwQueryResult::logevents)
.flatMap(Observable::fromIterable);
} catch (Throwable throwable) {
return Observable.empty();
}
}
} }

View file

@ -1,28 +1,13 @@
package fr.free.nrw.commons.mwapi; package fr.free.nrw.commons.mwapi;
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import java.util.Map;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import static org.wikipedia.dataclient.Service.MW_API_PREFIX; import static org.wikipedia.dataclient.Service.MW_API_PREFIX;
import io.reactivex.Observable;
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import retrofit2.http.GET;
public interface UserInterface { public interface UserInterface {
/**
* Gets the log events of user
* @param user name of user without prefix
* @param continuation continuation params returned in previous query
* @return query response
*/
@GET(MW_API_PREFIX+"action=query&list=logevents&letype=upload&leprop=title|timestamp|ids&lelimit=500")
Observable<MwQueryResponse> getUserLogEvents(@Query("leuser") String user, @QueryMap Map<String, String> continuation);
/** /**
* Checks to see if a user is currently blocked from Commons * Checks to see if a user is currently blocked from Commons
*/ */

View file

@ -1,16 +1,12 @@
package fr.free.nrw.commons.nearby; package fr.free.nrw.commons.nearby;
import android.os.Parcel;
import androidx.annotation.DrawableRes; import androidx.annotation.DrawableRes;
import fr.free.nrw.commons.R;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import fr.free.nrw.commons.R;
/** /**
* See https://github.com/commons-app/apps-android-commons/issues/250 * See https://github.com/commons-app/apps-android-commons/issues/250
* Most common types of desc: building, house, cottage, farmhouse, * Most common types of desc: building, house, cottage, farmhouse,
@ -65,11 +61,6 @@ public enum Label {
this.icon = icon; this.icon = icon;
} }
Label(Parcel in) {
this.text = in.readString();
this.icon = in.readInt();
}
/** /**
* Will be used for nearby filter, to determine if place type is selected or not * Will be used for nearby filter, to determine if place type is selected or not
* @param isSelected true if user selected the place type * @param isSelected true if user selected the place type

View file

@ -49,7 +49,7 @@ public class NearbyBaseMarker extends BaseMarkerOptions<NearbyMarker, NearbyBase
@Override @Override
public NearbyMarker getMarker() { public NearbyMarker getMarker() {
return new NearbyMarker(this, place); return new NearbyMarker(this);
} }
public Place getPlace() { public Place getPlace() {

View file

@ -1,15 +1,18 @@
package fr.free.nrw.commons.nearby; package fr.free.nrw.commons.nearby;
import static fr.free.nrw.commons.utils.LengthUtils.computeDistanceBetween;
import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween;
import android.content.Context; import android.content.Context;
import android.content.res.Resources; import android.content.res.Resources;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import androidx.annotation.MainThread; import androidx.annotation.MainThread;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import com.mapbox.mapboxsdk.annotations.IconFactory; import com.mapbox.mapboxsdk.annotations.IconFactory;
import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.Marker;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.utils.UiUtils;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -18,17 +21,9 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.utils.UiUtils;
import timber.log.Timber; import timber.log.Timber;
import static fr.free.nrw.commons.utils.LengthUtils.computeDistanceBetween;
import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween;
public class NearbyController { public class NearbyController {
private static final int MAX_RESULTS = 1000; private static final int MAX_RESULTS = 1000;
private final NearbyPlaces nearbyPlaces; private final NearbyPlaces nearbyPlaces;
@ -102,9 +97,7 @@ public class NearbyController {
); );
} }
nearbyPlacesInfo.curLatLng = curLatLng; nearbyPlacesInfo.curLatLng = curLatLng;
nearbyPlacesInfo.searchLatLng = searchLatLng;
nearbyPlacesInfo.placeList = places; nearbyPlacesInfo.placeList = places;
nearbyPlacesInfo.boundaryCoordinates = boundaryCoordinates;
// Returning closes result means we use the controller for nearby card. So no need to set search this area flags // Returning closes result means we use the controller for nearby card. So no need to set search this area flags
if (!returnClosestResult) { if (!returnClosestResult) {
@ -127,24 +120,6 @@ public class NearbyController {
} }
} }
/**
* Loads attractions from location for list view, we need to return Place data type.
*
* @param curLatLng users current location
* @param placeList list of nearby places in Place data type
* @return Place list that holds nearby places
*/
public static List<Place> loadAttractionsFromLocationToPlaces(
LatLng curLatLng,
List<Place> placeList) {
placeList = placeList.subList(0, Math.min(placeList.size(), MAX_RESULTS));
for (Place place : placeList) {
String distance = formatDistanceBetween(curLatLng, place.location);
place.setDistance(distance);
}
return placeList;
}
/** /**
* Loads attractions from location for map view, we need to return BaseMarkerOption data type. * Loads attractions from location for map view, we need to return BaseMarkerOption data type.
* *
@ -155,8 +130,7 @@ public class NearbyController {
public static List<NearbyBaseMarker> loadAttractionsFromLocationToBaseMarkerOptions( public static List<NearbyBaseMarker> loadAttractionsFromLocationToBaseMarkerOptions(
LatLng curLatLng, LatLng curLatLng,
List<Place> placeList, List<Place> placeList,
Context context, Context context) {
List<Place> bookmarkplacelist) {
List<NearbyBaseMarker> baseMarkerOptions = new ArrayList<>(); List<NearbyBaseMarker> baseMarkerOptions = new ArrayList<>();
if (placeList == null) { if (placeList == null) {
@ -168,7 +142,6 @@ public class NearbyController {
VectorDrawableCompat vectorDrawable = null; VectorDrawableCompat vectorDrawable = null;
VectorDrawableCompat vectorDrawableGreen = null; VectorDrawableCompat vectorDrawableGreen = null;
VectorDrawableCompat vectorDrawableGrey = null; VectorDrawableCompat vectorDrawableGrey = null;
vectorDrawable = null;
try { try {
vectorDrawable = VectorDrawableCompat.create( vectorDrawable = VectorDrawableCompat.create(
context.getResources(), R.drawable.ic_custom_map_marker, context.getTheme()); context.getResources(), R.drawable.ic_custom_map_marker, context.getTheme());
@ -223,9 +196,7 @@ public class NearbyController {
*/ */
public class NearbyPlacesInfo { public class NearbyPlacesInfo {
public List<Place> placeList; // List of nearby places public List<Place> placeList; // List of nearby places
public LatLng[] boundaryCoordinates; // Corners of nearby area
public LatLng curLatLng; // Current location when this places are populated public LatLng curLatLng; // Current location when this places are populated
public LatLng searchLatLng; // Search location for finding this places
} }
/** /**

View file

@ -1,7 +1,6 @@
package fr.free.nrw.commons.nearby; package fr.free.nrw.commons.nearby;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -10,48 +9,29 @@ import android.widget.Filterable;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.nearby.presenter.NearbyParentFragmentPresenter; import java.util.ArrayList;
import java.util.Collections;
public class NearbyFilterSearchRecyclerViewAdapter public class NearbyFilterSearchRecyclerViewAdapter
extends RecyclerView.Adapter<NearbyFilterSearchRecyclerViewAdapter.RecyclerViewHolder> extends RecyclerView.Adapter<NearbyFilterSearchRecyclerViewAdapter.RecyclerViewHolder>
implements Filterable { implements Filterable {
private final LayoutInflater inflater; private final LayoutInflater inflater;
private Context context;
private ArrayList<Label> labels; private ArrayList<Label> labels;
private ArrayList<Label> displayedLabels; private ArrayList<Label> displayedLabels;
public ArrayList<Label> selectedLabels = new ArrayList<>(); public ArrayList<Label> selectedLabels = new ArrayList<>();
private int state;
private Callback callback; private Callback callback;
RecyclerView.SmoothScroller smoothScroller;
public void setCallback(Callback callback) { public void setCallback(Callback callback) {
this.callback = callback; this.callback = callback;
} }
public NearbyFilterSearchRecyclerViewAdapter(Context context, ArrayList<Label> labels, RecyclerView recyclerView) { public NearbyFilterSearchRecyclerViewAdapter(Context context, ArrayList<Label> labels) {
this.context = context;
this.labels = labels; this.labels = labels;
this.displayedLabels = labels; this.displayedLabels = labels;
smoothScroller = new
LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
inflater = LayoutInflater.from(context); inflater = LayoutInflater.from(context);
} }
@ -150,7 +130,6 @@ public class NearbyFilterSearchRecyclerViewAdapter
} }
public void setRecyclerViewAdapterItemsGreyedOut() { public void setRecyclerViewAdapterItemsGreyedOut() {
state = CheckBoxTriStates.UNCHECKED;
for (Label label : labels) { for (Label label : labels) {
label.setSelected(false); label.setSelected(false);
selectedLabels.remove(label); selectedLabels.remove(label);
@ -159,7 +138,6 @@ public class NearbyFilterSearchRecyclerViewAdapter
} }
public void setRecyclerViewAdapterAllSelected() { public void setRecyclerViewAdapterAllSelected() {
state = CheckBoxTriStates.CHECKED;
for (Label label : labels) { for (Label label : labels) {
label.setSelected(true); label.setSelected(true);
if (!selectedLabels.contains(label)) { if (!selectedLabels.contains(label)) {

View file

@ -1,12 +1,8 @@
package fr.free.nrw.commons.nearby; package fr.free.nrw.commons.nearby;
import java.util.ArrayList;
public class NearbyFilterState { public class NearbyFilterState {
private boolean existsSelected; private boolean existsSelected;
private boolean needPhotoSelected; private boolean needPhotoSelected;
private int checkBoxTriState;
private ArrayList<Label> selectedLabels;
private static NearbyFilterState nearbyFılterStateInstance; private static NearbyFilterState nearbyFılterStateInstance;
@ -16,8 +12,6 @@ public class NearbyFilterState {
private NearbyFilterState() { private NearbyFilterState() {
existsSelected = false; existsSelected = false;
needPhotoSelected = true; needPhotoSelected = true;
checkBoxTriState = -1; // Unknown
selectedLabels = new ArrayList<>(); // Initially empty
} }
public static NearbyFilterState getInstance() { public static NearbyFilterState getInstance() {
@ -27,10 +21,6 @@ public class NearbyFilterState {
return nearbyFılterStateInstance; return nearbyFılterStateInstance;
} }
public static void setSelectedLabels(ArrayList<Label> selectedLabels) {
getInstance().selectedLabels = selectedLabels;
}
public static void setExistsSelected(boolean existsSelected) { public static void setExistsSelected(boolean existsSelected) {
getInstance().existsSelected = existsSelected; getInstance().existsSelected = existsSelected;
} }
@ -47,11 +37,4 @@ public class NearbyFilterState {
return needPhotoSelected; return needPhotoSelected;
} }
public int getCheckBoxTriState() {
return checkBoxTriState;
}
public ArrayList<Label> getSelectedLabels() {
return selectedLabels;
}
} }

View file

@ -3,7 +3,7 @@ package fr.free.nrw.commons.nearby;
import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.Marker;
public class NearbyMarker extends Marker { public class NearbyMarker extends Marker {
private final Place place;
private NearbyBaseMarker nearbyBaseMarker; private NearbyBaseMarker nearbyBaseMarker;
/** /**
@ -11,9 +11,8 @@ public class NearbyMarker extends Marker {
* *
* @param baseMarkerOptions The builder used to construct the Marker. * @param baseMarkerOptions The builder used to construct the Marker.
*/ */
NearbyMarker(NearbyBaseMarker baseMarkerOptions, Place place) { NearbyMarker(NearbyBaseMarker baseMarkerOptions) {
super(baseMarkerOptions); super(baseMarkerOptions);
this.place = place;
this.nearbyBaseMarker = baseMarkerOptions; this.nearbyBaseMarker = baseMarkerOptions;
} }
@ -21,7 +20,4 @@ public class NearbyMarker extends Marker {
return nearbyBaseMarker; return nearbyBaseMarker;
} }
public Place getPlace() {
return place;
}
} }

View file

@ -1,5 +1,7 @@
package fr.free.nrw.commons.nearby; package fr.free.nrw.commons.nearby;
import static fr.free.nrw.commons.contributions.MainActivity.NEARBY_TAB_POSITION;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.View; import android.view.View;
@ -8,10 +10,8 @@ import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.contributions.MainActivity; import fr.free.nrw.commons.contributions.MainActivity;
import fr.free.nrw.commons.nearby.fragments.NearbyParentFragment; import fr.free.nrw.commons.nearby.fragments.NearbyParentFragment;
@ -19,8 +19,6 @@ import fr.free.nrw.commons.utils.SwipableCardView;
import fr.free.nrw.commons.utils.ViewUtil; import fr.free.nrw.commons.utils.ViewUtil;
import timber.log.Timber; import timber.log.Timber;
import static fr.free.nrw.commons.contributions.MainActivity.NEARBY_TAB_POSITION;
/** /**
* Custom card view for nearby notification card view on main screen, above contributions list * Custom card view for nearby notification card view on main screen, above contributions list
*/ */
@ -34,8 +32,6 @@ public class NearbyNotificationCardView extends SwipableCardView {
public CardViewVisibilityState cardViewVisibilityState; public CardViewVisibilityState cardViewVisibilityState;
public PermissionType permissionType;
public NearbyNotificationCardView(@NonNull Context context) { public NearbyNotificationCardView(@NonNull Context context) {
super(context); super(context);
cardViewVisibilityState = CardViewVisibilityState.INVISIBLE; cardViewVisibilityState = CardViewVisibilityState.INVISIBLE;
@ -105,20 +101,6 @@ public class NearbyNotificationCardView extends SwipableCardView {
return true; return true;
} }
/**
* Time is up, data for card view is not ready, so do not display it
*/
private void errorOccurred() {
this.setVisibility(GONE);
}
/**
* Data for card view is ready, display card view
*/
private void succeeded() {
this.setVisibility(VISIBLE);
}
/** /**
* Pass place information to views. * Pass place information to views.
* @param place Closes place where we will get information from * @param place Closes place where we will get information from
@ -189,16 +171,6 @@ public class NearbyNotificationCardView extends SwipableCardView {
READY, READY,
INVISIBLE, INVISIBLE,
ASK_PERMISSION, ASK_PERMISSION,
ERROR_OCCURRED
} }
/**
* We need to know which kind of permission we need to request, then update permission request
* button action accordingly
*/
public enum PermissionType {
ENABLE_GPS,
ENABLE_LOCATION_PERMISSION, // For only after Marshmallow
NO_PERMISSION_NEEDED
}
} }

View file

@ -1,19 +1,14 @@
package fr.free.nrw.commons.nearby.contract; package fr.free.nrw.commons.nearby.contract;
import android.content.Context; import android.content.Context;
import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import java.util.List;
import fr.free.nrw.commons.kvstore.JsonKvStore; import fr.free.nrw.commons.kvstore.JsonKvStore;
import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager; import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.nearby.Label; import fr.free.nrw.commons.nearby.Label;
import fr.free.nrw.commons.nearby.NearbyBaseMarker; import fr.free.nrw.commons.nearby.NearbyBaseMarker;
import fr.free.nrw.commons.nearby.Place; import fr.free.nrw.commons.nearby.Place;
import fr.free.nrw.commons.nearby.presenter.NearbyParentFragmentPresenter; import java.util.List;
public interface NearbyParentFragmentContract { public interface NearbyParentFragmentContract {
@ -40,7 +35,7 @@ public interface NearbyParentFragmentContract {
void setTabItemContributions(); void setTabItemContributions();
boolean isDetailsBottomSheetVisible(); boolean isDetailsBottomSheetVisible();
void setBottomSheetDetailsSmaller(); void setBottomSheetDetailsSmaller();
boolean isSearchThisAreaButtonVisible();
void setRecyclerViewAdapterAllSelected(); void setRecyclerViewAdapterAllSelected();
void setRecyclerViewAdapterItemsGreyedOut(); void setRecyclerViewAdapterItemsGreyedOut();
void setCheckBoxAction(); void setCheckBoxAction();
@ -58,9 +53,8 @@ public interface NearbyParentFragmentContract {
void filterOutAllMarkers(); void filterOutAllMarkers();
void displayAllMarkers(); void filterMarkersByLabels(List<Label> selectedLabels, boolean existsSelected,
boolean needPhotoSelected, boolean filterForPlaceState);
void filterMarkersByLabels(List<Label> selectedLabels, boolean existsSelected, boolean needPhotoSelected, boolean filterForPlaceState, boolean filterForAllNoneType);
LatLng getCameraTarget(); LatLng getCameraTarget();
@ -76,10 +70,6 @@ public interface NearbyParentFragmentContract {
void setProjectorLatLngBounds(); void setProjectorLatLngBounds();
} }
interface NearbyListView {
void updateListFragment(List<Place> placeList);
}
interface UserActions { interface UserActions {
void updateMapAndList(LocationServiceManager.LocationChangeType locationChangeType); void updateMapAndList(LocationServiceManager.LocationChangeType locationChangeType);
void lockUnlockNearby(boolean isNearbyLocked); void lockUnlockNearby(boolean isNearbyLocked);

View file

@ -4,7 +4,6 @@ import static fr.free.nrw.commons.contributions.MainActivity.CONTRIBUTIONS_TAB_P
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED; import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SLIGHTLY_CHANGED; import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SLIGHTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.MAP_UPDATED; import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.MAP_UPDATED;
import static fr.free.nrw.commons.nearby.Label.TEXT_TO_DESCRIPTION;
import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween; import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween;
import static fr.free.nrw.commons.wikidata.WikidataConstants.PLACE_OBJECT; import static fr.free.nrw.commons.wikidata.WikidataConstants.PLACE_OBJECT;
@ -16,7 +15,6 @@ import android.content.IntentFilter;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.drawable.VectorDrawable;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Settings; import android.provider.Settings;
import android.util.Log; import android.util.Log;
@ -38,7 +36,6 @@ import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
@ -47,7 +44,6 @@ import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.chip.Chip; import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.jakewharton.rxbinding2.view.RxView; import com.jakewharton.rxbinding2.view.RxView;
@ -75,7 +71,6 @@ import fr.free.nrw.commons.auth.LoginActivity;
import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao; import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao;
import fr.free.nrw.commons.contributions.ContributionController; import fr.free.nrw.commons.contributions.ContributionController;
import fr.free.nrw.commons.contributions.MainActivity; import fr.free.nrw.commons.contributions.MainActivity;
import fr.free.nrw.commons.di.ApplicationlessInjection;
import fr.free.nrw.commons.di.CommonsDaggerSupportFragment; import fr.free.nrw.commons.di.CommonsDaggerSupportFragment;
import fr.free.nrw.commons.kvstore.JsonKvStore; import fr.free.nrw.commons.kvstore.JsonKvStore;
import fr.free.nrw.commons.location.LocationServiceManager; import fr.free.nrw.commons.location.LocationServiceManager;
@ -104,7 +99,6 @@ import fr.free.nrw.commons.utils.ViewUtil;
import fr.free.nrw.commons.wikidata.WikidataEditListener; import fr.free.nrw.commons.wikidata.WikidataEditListener;
import io.reactivex.Observable; import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -144,7 +138,6 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
@BindView(R.id.map_progress_bar) ProgressBar progressBar; @BindView(R.id.map_progress_bar) ProgressBar progressBar;
@BindView(R.id.choice_chip_exists) Chip chipExists; @BindView(R.id.choice_chip_exists) Chip chipExists;
@BindView(R.id.choice_chip_needs_photo) Chip chipNeedsPhoto; @BindView(R.id.choice_chip_needs_photo) Chip chipNeedsPhoto;
@BindView(R.id.choice_chip_group) ChipGroup choiceChipGroup;
@BindView(R.id.search_view) SearchView searchView; @BindView(R.id.search_view) SearchView searchView;
@BindView(R.id.search_list_view) RecyclerView recyclerView; @BindView(R.id.search_list_view) RecyclerView recyclerView;
@BindView(R.id.nearby_filter_list) View nearbyFilterList; @BindView(R.id.nearby_filter_list) View nearbyFilterList;
@ -429,7 +422,7 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setLayoutManager(linearLayoutManager);
nearbyFilterSearchRecyclerViewAdapter = new NearbyFilterSearchRecyclerViewAdapter(getContext(), new ArrayList<>(Label.valuesAsList()), recyclerView); nearbyFilterSearchRecyclerViewAdapter = new NearbyFilterSearchRecyclerViewAdapter(getContext(), new ArrayList<>(Label.valuesAsList()));
nearbyFilterSearchRecyclerViewAdapter.setCallback(new NearbyFilterSearchRecyclerViewAdapter.Callback() { nearbyFilterSearchRecyclerViewAdapter.setCallback(new NearbyFilterSearchRecyclerViewAdapter.Callback() {
@Override @Override
public void setCheckboxUnknown() { public void setCheckboxUnknown() {
@ -814,11 +807,6 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
} }
} }
@Override
public boolean isSearchThisAreaButtonVisible() {
return searchThisAreaButton.getVisibility() == View.VISIBLE;
}
@Override @Override
public void setRecyclerViewAdapterAllSelected() { public void setRecyclerViewAdapterAllSelected() {
if (nearbyFilterSearchRecyclerViewAdapter != null && NearbyController.currentLocation != null) { if (nearbyFilterSearchRecyclerViewAdapter != null && NearbyController.currentLocation != null) {
@ -1096,30 +1084,18 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
hideAllMarkers(); hideAllMarkers();
} }
/**
* Displays all markers
*/
@Override
public void displayAllMarkers() {
for (final MarkerPlaceGroup markerPlaceGroup : NearbyController.markerLabelList) {
updateMarker(markerPlaceGroup.getIsBookmarked(), markerPlaceGroup.getPlace(), NearbyController.currentLocation);
}
}
/** /**
* Filters markers based on selectedLabels and chips * Filters markers based on selectedLabels and chips
* @param selectedLabels label list that user clicked * @param selectedLabels label list that user clicked
* @param displayExists chip for displaying only existing places * @param displayExists chip for displaying only existing places
* @param displayNeedsPhoto chip for displaying only places need photos * @param displayNeedsPhoto chip for displaying only places need photos
* @param filterForPlaceState true if we filter places for place state * @param filterForPlaceState true if we filter places for place state
* @param filterForAllNoneType true if we filter places with all none button
*/ */
@Override @Override
public void filterMarkersByLabels(final List<Label> selectedLabels, public void filterMarkersByLabels(final List<Label> selectedLabels,
final boolean displayExists, final boolean displayExists,
final boolean displayNeedsPhoto, final boolean displayNeedsPhoto,
final boolean filterForPlaceState, final boolean filterForPlaceState) {
final boolean filterForAllNoneType) {
// Remove the previous markers before updating them // Remove the previous markers before updating them
hideAllMarkers(); hideAllMarkers();

View file

@ -1,15 +1,16 @@
package fr.free.nrw.commons.nearby.presenter; package fr.free.nrw.commons.nearby.presenter;
import android.util.Log; import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED;
import android.view.View; import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SLIGHTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.MAP_UPDATED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.SEARCH_CUSTOM_AREA;
import static fr.free.nrw.commons.nearby.CheckBoxTriStates.CHECKED;
import static fr.free.nrw.commons.nearby.CheckBoxTriStates.UNCHECKED;
import static fr.free.nrw.commons.nearby.CheckBoxTriStates.UNKNOWN;
import android.view.View;
import androidx.annotation.MainThread; import androidx.annotation.MainThread;
import com.mapbox.mapboxsdk.annotations.Marker; import com.mapbox.mapboxsdk.annotations.Marker;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao; import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao;
import fr.free.nrw.commons.kvstore.JsonKvStore; import fr.free.nrw.commons.kvstore.JsonKvStore;
import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.location.LatLng;
@ -24,16 +25,11 @@ import fr.free.nrw.commons.nearby.NearbyFilterState;
import fr.free.nrw.commons.nearby.contract.NearbyParentFragmentContract; import fr.free.nrw.commons.nearby.contract.NearbyParentFragmentContract;
import fr.free.nrw.commons.utils.LocationUtils; import fr.free.nrw.commons.utils.LocationUtils;
import fr.free.nrw.commons.wikidata.WikidataEditListener; import fr.free.nrw.commons.wikidata.WikidataEditListener;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import timber.log.Timber; import timber.log.Timber;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SLIGHTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.MAP_UPDATED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.SEARCH_CUSTOM_AREA;
import static fr.free.nrw.commons.nearby.CheckBoxTriStates.CHECKED;
import static fr.free.nrw.commons.nearby.CheckBoxTriStates.UNCHECKED;
import static fr.free.nrw.commons.nearby.CheckBoxTriStates.UNKNOWN;
public class NearbyParentFragmentPresenter public class NearbyParentFragmentPresenter
implements NearbyParentFragmentContract.UserActions, implements NearbyParentFragmentContract.UserActions,
WikidataEditListener.WikidataP18EditListener, WikidataEditListener.WikidataP18EditListener,
@ -208,8 +204,7 @@ public class NearbyParentFragmentPresenter
List<NearbyBaseMarker> nearbyBaseMarkers = NearbyController List<NearbyBaseMarker> nearbyBaseMarkers = NearbyController
.loadAttractionsFromLocationToBaseMarkerOptions(nearbyPlacesInfo.curLatLng, // Curlatlang will be used to calculate distances .loadAttractionsFromLocationToBaseMarkerOptions(nearbyPlacesInfo.curLatLng, // Curlatlang will be used to calculate distances
nearbyPlacesInfo.placeList, nearbyPlacesInfo.placeList,
nearbyParentFragmentView.getContext(), nearbyParentFragmentView.getContext());
bookmarkLocationDao.getAllBookmarksLocations());
nearbyParentFragmentView.updateMapMarkers(nearbyBaseMarkers, selectedMarker); nearbyParentFragmentView.updateMapMarkers(nearbyBaseMarkers, selectedMarker);
nearbyParentFragmentView.addCurrentLocationMarker(nearbyPlacesInfo.curLatLng); nearbyParentFragmentView.addCurrentLocationMarker(nearbyPlacesInfo.curLatLng);
if(shouldTrackPosition){ if(shouldTrackPosition){
@ -290,7 +285,7 @@ public class NearbyParentFragmentPresenter
nearbyParentFragmentView.filterMarkersByLabels(selectedLabels, nearbyParentFragmentView.filterMarkersByLabels(selectedLabels,
NearbyFilterState.getInstance().isExistsSelected(), NearbyFilterState.getInstance().isExistsSelected(),
NearbyFilterState.getInstance().isNeedPhotoSelected(), NearbyFilterState.getInstance().isNeedPhotoSelected(),
filterForPlaceState, false); filterForPlaceState);
nearbyParentFragmentView.setRecyclerViewAdapterAllSelected(); nearbyParentFragmentView.setRecyclerViewAdapterAllSelected();
break; break;
} }
@ -298,7 +293,7 @@ public class NearbyParentFragmentPresenter
nearbyParentFragmentView.filterMarkersByLabels(selectedLabels, nearbyParentFragmentView.filterMarkersByLabels(selectedLabels,
NearbyFilterState.getInstance().isExistsSelected(), NearbyFilterState.getInstance().isExistsSelected(),
NearbyFilterState.getInstance().isNeedPhotoSelected(), NearbyFilterState.getInstance().isNeedPhotoSelected(),
filterForPlaceState, false); filterForPlaceState);
} }
} }

View file

@ -5,23 +5,26 @@ import org.wikipedia.util.DateUtil
/** /**
* Created by root on 18.12.2017. * Created by root on 18.12.2017.
*/ */
data class Notification(var notificationType: NotificationType, data class Notification(
var notificationText: String, var notificationText: String,
var date: String, var date: String,
var link: String, var link: String,
var iconUrl: String, var iconUrl: String,
var notificationId: String) { var notificationId: String
) {
companion object { companion object {
@JvmStatic @JvmStatic
fun from(wikiNotification: org.wikipedia.notifications.Notification): Notification { fun from(wikiNotification: org.wikipedia.notifications.Notification): Notification {
val contents = wikiNotification.contents val contents = wikiNotification.contents
val notificationLink = if (contents == null || contents.links == null || contents.links!!.primary == null) "" else contents.links!!.primary!!.url val notificationLink = if (contents == null || contents.links == null || contents.links!!.primary == null) "" else contents.links!!.primary!!.url
return Notification(NotificationType.UNKNOWN, return Notification(
contents?.compactHeader ?: "", contents?.compactHeader ?: "",
DateUtil.getMonthOnlyDateString(wikiNotification.timestamp), DateUtil.getMonthOnlyDateString(wikiNotification.timestamp),
notificationLink, notificationLink,
"", wikiNotification.id().toString()) "",
wikiNotification.id().toString()
)
} }
} }

View file

@ -56,8 +56,6 @@ public class NotificationActivity extends NavigationBaseActivity {
@Inject @Inject
NotificationController controller; NotificationController controller;
private static final String TAG_NOTIFICATION_WORKER_FRAGMENT = "NotificationWorkerFragment";
private NotificationWorkerFragment mNotificationWorkerFragment;
private NotificatinAdapter adapter; private NotificatinAdapter adapter;
private List<Notification> notificationList; private List<Notification> notificationList;
MenuItem notificationMenuItem; MenuItem notificationMenuItem;
@ -67,8 +65,6 @@ public class NotificationActivity extends NavigationBaseActivity {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification); setContentView(R.layout.activity_notification);
ButterKnife.bind(this); ButterKnife.bind(this);
mNotificationWorkerFragment = (NotificationWorkerFragment) getFragmentManager()
.findFragmentByTag(TAG_NOTIFICATION_WORKER_FRAGMENT);
initListView(); initListView();
initDrawer(); initDrawer();
setPageTitle(); setPageTitle();
@ -145,7 +141,6 @@ public class NotificationActivity extends NavigationBaseActivity {
@SuppressLint("CheckResult") @SuppressLint("CheckResult")
private void addNotifications(boolean archived) { private void addNotifications(boolean archived) {
Timber.d("Add notifications"); Timber.d("Add notifications");
if (mNotificationWorkerFragment == null) {
progressBar.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE);
compositeDisposable.add(controller.getNotifications(archived) compositeDisposable.add(controller.getNotifications(archived)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
@ -167,10 +162,6 @@ public class NotificationActivity extends NavigationBaseActivity {
ViewUtil.showShortSnackbar(relativeLayout, R.string.error_notifications); ViewUtil.showShortSnackbar(relativeLayout, R.string.error_notifications);
progressBar.setVisibility(View.GONE); progressBar.setVisibility(View.GONE);
})); }));
} else {
notificationList = mNotificationWorkerFragment.getNotificationList();
setItems(notificationList);
}
} }
@Override @Override

View file

@ -1,27 +0,0 @@
package fr.free.nrw.commons.notification;
public enum NotificationType {
THANK_YOU_EDIT("thank-you-edit"),
EDIT_USER_TALK("edit-user-talk"),
MENTION("mention"),
WELCOME("welcome"),
UNKNOWN("unknown");
private String type;
NotificationType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public static NotificationType handledValueOf(String name) {
for (NotificationType e : values()) {
if (e.getType().equals(name)) {
return e;
}
}
return UNKNOWN;
}
}

View file

@ -1,30 +0,0 @@
package fr.free.nrw.commons.notification;
import android.app.Fragment;
import android.os.Bundle;
import androidx.annotation.Nullable;
import java.util.List;
/**
* Created by knightshade on 25/2/18.
*/
public class NotificationWorkerFragment extends Fragment {
private List<Notification> notificationList;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public void setNotificationList(List<Notification> notificationList){
this.notificationList = notificationList;
}
public List<Notification> getNotificationList(){
return notificationList;
}
}

View file

@ -3,7 +3,6 @@ package fr.free.nrw.commons.quiz;
import android.app.Activity; import android.app.Activity;
import android.view.View; import android.view.View;
import android.widget.CompoundButton; import android.widget.CompoundButton;
import android.widget.RadioButton;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -16,17 +15,6 @@ public class RadioGroupHelper {
public List<CompoundButton> radioButtons = new ArrayList<>(); public List<CompoundButton> radioButtons = new ArrayList<>();
/**
* Constructor to group radio buttons
* @param radios
*/
public RadioGroupHelper(RadioButton... radios) {
super();
for (RadioButton rb : radios) {
add(rb);
}
}
/** /**
* Constructor to group radio buttons * Constructor to group radio buttons
* @param activity * @param activity

View file

@ -38,8 +38,6 @@ public class ReviewActivity extends NavigationBaseActivity {
public CirclePageIndicator pagerIndicator; public CirclePageIndicator pagerIndicator;
@BindView(R.id.toolbar) @BindView(R.id.toolbar)
Toolbar toolbar; Toolbar toolbar;
@BindView(R.id.navigation_view)
NavigationView navigationView;
@BindView(R.id.drawer_layout) @BindView(R.id.drawer_layout)
DrawerLayout drawerLayout; DrawerLayout drawerLayout;
@BindView(R.id.view_pager_review) @BindView(R.id.view_pager_review)
@ -72,11 +70,10 @@ public class ReviewActivity extends NavigationBaseActivity {
/** /**
* Consumers should be simply using this method to use this activity. * Consumers should be simply using this method to use this activity.
*
* @param context * @param context
* @param title Page title *
*/ */
public static void startYourself(Context context, String title) { public static void startYourself(Context context) {
Intent reviewActivity = new Intent(context, ReviewActivity.class); Intent reviewActivity = new Intent(context, ReviewActivity.class);
reviewActivity.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); reviewActivity.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
reviewActivity.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); reviewActivity.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

View file

@ -4,20 +4,9 @@ import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.content.Context; import android.content.Context;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import org.wikipedia.dataclient.mwapi.MwQueryPage;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Media; import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
@ -30,13 +19,17 @@ import io.reactivex.Observable;
import io.reactivex.ObservableSource; import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.wikipedia.dataclient.mwapi.MwQueryPage;
import timber.log.Timber; import timber.log.Timber;
@Singleton @Singleton
public class ReviewController { public class ReviewController {
private static final int NOTIFICATION_SEND_THANK = 0x102; private static final int NOTIFICATION_SEND_THANK = 0x102;
private static final int NOTIFICATION_CHECK_CATEGORY = 0x101; private static final int NOTIFICATION_CHECK_CATEGORY = 0x101;
protected static ArrayList<String> categories;
@Inject @Inject
ThanksClient thanksClient; ThanksClient thanksClient;
private final DeleteHelper deleteHelper; private final DeleteHelper deleteHelper;
@ -60,10 +53,6 @@ public class ReviewController {
this.media = media; this.media = media;
} }
public Media getMedia() {
return media;
}
public enum DeleteReason { public enum DeleteReason {
SPAM, SPAM,
COPYRIGHT_VIOLATION COPYRIGHT_VIOLATION
@ -115,7 +104,6 @@ public class ReviewController {
} else { } else {
title = context.getString(R.string.check_category_failure_title); title = context.getString(R.string.check_category_failure_title);
message = context.getString(R.string.check_category_failure_message, media.getDisplayTitle()); message = context.getString(R.string.check_category_failure_message, media.getDisplayTitle());
reviewCallback.onFailure();
} }
showNotification(title, message); showNotification(title, message);
@ -186,6 +174,5 @@ public class ReviewController {
public interface ReviewCallback { public interface ReviewCallback {
void onSuccess(); void onSuccess();
void onFailure();
} }
} }

View file

@ -29,8 +29,6 @@ public class ReviewImageFragment extends CommonsDaggerSupportFragment {
private int position; private int position;
public ProgressBar progressBar;
@BindView(R.id.tv_review_question) @BindView(R.id.tv_review_question)
TextView textViewQuestion; TextView textViewQuestion;
@BindView(R.id.tv_review_question_context) @BindView(R.id.tv_review_question_context)
@ -173,10 +171,6 @@ public class ReviewImageFragment extends CommonsDaggerSupportFragment {
getReviewActivity().runRandomizer(); getReviewActivity().runRandomizer();
} }
@Override
public void onFailure() {
//do nothing
}
}; };
} }

View file

@ -1,9 +1,7 @@
package fr.free.nrw.commons.settings; package fr.free.nrw.commons.settings;
public class Prefs { public class Prefs {
public static String GLOBAL_PREFS = "fr.free.nrw.commons.preferences";
public static String TRACKING_ENABLED = "eventLogging";
public static final String DEFAULT_LICENSE = "defaultLicense"; public static final String DEFAULT_LICENSE = "defaultLicense";
public static final String UPLOADS_SHOWING = "uploadsshowing"; public static final String UPLOADS_SHOWING = "uploadsshowing";
public static final String MANAGED_EXIF_TAGS = "managed_exif_tags"; public static final String MANAGED_EXIF_TAGS = "managed_exif_tags";

View file

@ -16,22 +16,14 @@ import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar; import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat; import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout; import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
import org.wikipedia.dataclient.Service;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import com.google.android.material.navigation.NavigationView;
import fr.free.nrw.commons.AboutActivity; import fr.free.nrw.commons.AboutActivity;
import fr.free.nrw.commons.BuildConfig; import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
@ -50,6 +42,8 @@ import fr.free.nrw.commons.settings.SettingsActivity;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import javax.inject.Inject;
import javax.inject.Named;
import timber.log.Timber; import timber.log.Timber;
public abstract class NavigationBaseActivity extends BaseActivity public abstract class NavigationBaseActivity extends BaseActivity
@ -76,7 +70,6 @@ public abstract class NavigationBaseActivity extends BaseActivity
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private Service service;
private ProgressDialog progressDialog; private ProgressDialog progressDialog;
@ -159,12 +152,6 @@ public abstract class NavigationBaseActivity extends BaseActivity
toggle.setToolbarNavigationClickListener(v -> onBackPressed()); toggle.setToolbarNavigationClickListener(v -> onBackPressed());
} }
public void initBack() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override @Override
public boolean onNavigationItemSelected(@NonNull final MenuItem item) { public boolean onNavigationItemSelected(@NonNull final MenuItem item) {
final int itemId = item.getItemId(); final int itemId = item.getItemId();
@ -238,7 +225,7 @@ public abstract class NavigationBaseActivity extends BaseActivity
case R.id.action_review: case R.id.action_review:
drawerLayout.closeDrawer(navigationView); drawerLayout.closeDrawer(navigationView);
ReviewActivity.startYourself(this, getString(R.string.title_activity_review)); ReviewActivity.startYourself(this);
return true; return true;
default: default:
Timber.e("Unknown option [%s] selected from the navigation menu", itemId); Timber.e("Unknown option [%s] selected from the navigation menu", itemId);

View file

@ -1,70 +0,0 @@
package fr.free.nrw.commons.ui.widget;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
/**
* a formatted dialog fragment
* This class is used by NearbyInfoDialog
*/
public abstract class OverlayDialog extends DialogFragment {
/**
* creates a DialogFragment with the correct style and theme
* @param savedInstanceState bundle re-constructed from a previous saved state
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
}
/**
* When the view is created, sets the dialog layout to full screen
*
* @param view the view being used
* @param savedInstanceState bundle re-constructed from a previous saved state
*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
setDialogLayoutToFullScreen();
super.onViewCreated(view, savedInstanceState);
}
/**
* sets the dialog layout to fullscreen
*/
private void setDialogLayoutToFullScreen() {
Window window = getDialog().getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
window.requestFeature(Window.FEATURE_NO_TITLE);
wlp.gravity = Gravity.BOTTOM;
wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
wlp.height = WindowManager.LayoutParams.MATCH_PARENT;
window.setAttributes(wlp);
}
/**
* builds custom dialog container
*
* @param savedInstanceState the previously saved state
* @return the dialog
*/
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
Window window = dialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
}

View file

@ -143,17 +143,6 @@ public class FileUtils {
return mimeType; return mimeType;
} }
static String getFileExt(String fileName) {
//Default filePath extension
String extension = ".jpg";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i + 1);
}
return extension;
}
static FileInputStream getFileInputStream(String filePath) throws FileNotFoundException { static FileInputStream getFileInputStream(String filePath) throws FileNotFoundException {
return new FileInputStream(filePath); return new FileInputStream(filePath);
} }
@ -166,16 +155,4 @@ public class FileUtils {
return true; return true;
} }
/**
* Check if file exists in local dirs
*/
public static boolean fileExists(Uri localUri) {
try {
File file = new File(localUri.getPath());
return file.exists();
} catch (Exception e) {
Timber.d(e);
return false;
}
}
} }

View file

@ -15,10 +15,6 @@ public class FileUtilsWrapper {
} }
public String getFileExt(String fileName) {
return FileUtils.getFileExt(fileName);
}
public String getSHA1(InputStream is) { public String getSHA1(InputStream is) {
return FileUtils.getSHA1(is); return FileUtils.getSHA1(is);
} }

View file

@ -4,7 +4,6 @@ import static fr.free.nrw.commons.utils.ImageUtils.EMPTY_CAPTION;
import static fr.free.nrw.commons.utils.ImageUtils.FILE_NAME_EXISTS; import static fr.free.nrw.commons.utils.ImageUtils.FILE_NAME_EXISTS;
import static fr.free.nrw.commons.utils.ImageUtils.IMAGE_OK; import static fr.free.nrw.commons.utils.ImageUtils.IMAGE_OK;
import android.content.Context;
import fr.free.nrw.commons.media.MediaClient; import fr.free.nrw.commons.media.MediaClient;
import fr.free.nrw.commons.nearby.Place; import fr.free.nrw.commons.nearby.Place;
import fr.free.nrw.commons.utils.ImageUtils; import fr.free.nrw.commons.utils.ImageUtils;
@ -32,7 +31,7 @@ public class ImageProcessingService {
public ImageProcessingService(FileUtilsWrapper fileUtilsWrapper, public ImageProcessingService(FileUtilsWrapper fileUtilsWrapper,
ImageUtilsWrapper imageUtilsWrapper, ImageUtilsWrapper imageUtilsWrapper,
ReadFBMD readFBMD, EXIFReader EXIFReader, ReadFBMD readFBMD, EXIFReader EXIFReader,
MediaClient mediaClient, Context context) { MediaClient mediaClient) {
this.fileUtilsWrapper = fileUtilsWrapper; this.fileUtilsWrapper = fileUtilsWrapper;
this.imageUtilsWrapper = imageUtilsWrapper; this.imageUtilsWrapper = imageUtilsWrapper;
this.readFBMD = readFBMD; this.readFBMD = readFBMD;

View file

@ -8,7 +8,6 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.Window; import android.view.Window;
import android.widget.Button;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
@ -30,10 +29,6 @@ public class SimilarImageDialogFragment extends DialogFragment {
SimpleDraweeView originalImage; SimpleDraweeView originalImage;
@BindView(R.id.possibleImage) @BindView(R.id.possibleImage)
SimpleDraweeView possibleImage; SimpleDraweeView possibleImage;
@BindView(R.id.postive_button)
Button positiveButton;
@BindView(R.id.negative_button)
Button negativeButton;
Callback callback;//Implemented interface from shareActivity Callback callback;//Implemented interface from shareActivity
Boolean gotResponse = false; Boolean gotResponse = false;

View file

@ -1,7 +0,0 @@
package fr.free.nrw.commons.upload;
import fr.free.nrw.commons.filepicker.UploadableFile;
public interface ThumbnailClickedListener {
void thumbnailClicked(UploadableFile content);
}

View file

@ -6,23 +6,18 @@ import android.os.Build.VERSION_CODES;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.drawee.view.SimpleDraweeView;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.filepicker.UploadableFile;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.filepicker.UploadableFile;
/** /**
* The adapter class for image thumbnails to be shown while uploading. * The adapter class for image thumbnails to be shown while uploading.
*/ */
@ -69,8 +64,6 @@ class ThumbnailsAdapter extends RecyclerView.Adapter<ThumbnailsAdapter.ViewHolde
RelativeLayout rlContainer; RelativeLayout rlContainer;
@BindView(R.id.iv_thumbnail) @BindView(R.id.iv_thumbnail)
SimpleDraweeView background; SimpleDraweeView background;
@BindView(R.id.iv_error)
ImageView ivError;
public ViewHolder(@NonNull View itemView) { public ViewHolder(@NonNull View itemView) {
super(itemView); super(itemView);

View file

@ -12,7 +12,6 @@ import android.os.Bundle;
import android.view.View; import android.view.View;
import android.widget.ImageButton; import android.widget.ImageButton;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView; import androidx.cardview.widget.CardView;
@ -73,9 +72,6 @@ public class UploadActivity extends BaseActivity implements UploadContract.View,
@BindView(R.id.ll_container_top_card) @BindView(R.id.ll_container_top_card)
LinearLayout llContainerTopCard; LinearLayout llContainerTopCard;
@BindView(R.id.rl_container_title)
RelativeLayout rlContainerTitle;
@BindView(R.id.tv_top_card_title) @BindView(R.id.tv_top_card_title)
TextView tvTopCardTitle; TextView tvTopCardTitle;
@ -211,11 +207,6 @@ public class UploadActivity extends BaseActivity implements UploadContract.View,
} }
@Override
protected void onStop() {
super.onStop();
}
/** /**
* Show/Hide the progress dialog * Show/Hide the progress dialog
*/ */

View file

@ -55,8 +55,7 @@ public class UploadClient {
} }
} }
Observable<UploadResult> uploadFileFromStash(Context context, Observable<UploadResult> uploadFileFromStash(Contribution contribution,
Contribution contribution,
String uniqueFileName, String uniqueFileName,
String fileKey) { String fileKey) {
try { try {

View file

@ -67,15 +67,6 @@ public class UploadMediaDetailAdapter extends RecyclerView.Adapter<UploadMediaDe
return uploadMediaDetails.size(); return uploadMediaDetails.size();
} }
/**
* Gets descriptions
*
* @return List of descriptions
*/
public List<UploadMediaDetail> getUploadMediaDetails() {
return uploadMediaDetails;
}
public void addDescription(UploadMediaDetail uploadMediaDetail) { public void addDescription(UploadMediaDetail uploadMediaDetail) {
this.uploadMediaDetails.add(uploadMediaDetail); this.uploadMediaDetails.add(uploadMediaDetail);
notifyItemInserted(uploadMediaDetails.size()); notifyItemInserted(uploadMediaDetails.size());

View file

@ -21,24 +21,16 @@ import fr.free.nrw.commons.contributions.MainActivity;
import fr.free.nrw.commons.di.CommonsApplicationModule; import fr.free.nrw.commons.di.CommonsApplicationModule;
import fr.free.nrw.commons.di.CommonsDaggerService; import fr.free.nrw.commons.di.CommonsDaggerService;
import fr.free.nrw.commons.media.MediaClient; import fr.free.nrw.commons.media.MediaClient;
import fr.free.nrw.commons.utils.CommonsDateUtil;
import fr.free.nrw.commons.wikidata.WikidataEditService; import fr.free.nrw.commons.wikidata.WikidataEditService;
import io.reactivex.Completable;
import io.reactivex.Observable; import io.reactivex.Observable;
import io.reactivex.Scheduler; import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.processors.PublishProcessor; import io.reactivex.processors.PublishProcessor;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Callable;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.inject.Inject; import javax.inject.Inject;
@ -275,7 +267,6 @@ public class UploadService extends CommonsDaggerService {
String uniqueFilename = findUniqueFilename(filename); String uniqueFilename = findUniqueFilename(filename);
unfinishedUploads.add(uniqueFilename); unfinishedUploads.add(uniqueFilename);
return uploadClient.uploadFileFromStash( return uploadClient.uploadFileFromStash(
getApplicationContext(),
contribution, contribution,
uniqueFilename, uniqueFilename,
uploadStash.getFilekey()); uploadStash.getFilekey());

View file

@ -1,88 +0,0 @@
package fr.free.nrw.commons.upload;
import android.net.Uri;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.util.List;
import fr.free.nrw.commons.location.LatLng;
import static java.lang.annotation.RetentionPolicy.SOURCE;
public interface UploadView {
// Dummy implementation of the view interface to allow us to have a 'null object pattern'
// in the presenter and avoid constant NULL checking.
// UploadView DUMMY = (UploadView) Proxy.newProxyInstance(UploadView.class.getClassLoader(),
// new Class[]{UploadView.class}, (proxy, method, methodArgs) -> null);
@Retention(SOURCE)
@IntDef({PLEASE_WAIT, TITLE_CARD, CATEGORIES, LICENSE})
@interface UploadPage {}
int PLEASE_WAIT = 0;
int TITLE_CARD = 1;
int CATEGORIES = 2;
int LICENSE = 3;
boolean checkIfLoggedIn();
void updateThumbnails(List<UploadItem> uploads);
void setNextEnabled(boolean available);
void setSubmitEnabled(boolean available);
void setPreviousEnabled(boolean available);
void setTopCardState(boolean state);
void setRightCardVisibility(boolean visible);
void setBottomCardState(boolean state);
void setBackground(Uri mediaUri);
void setTopCardVisibility(boolean visible);
void setBottomCardVisibility(boolean visible);
void setBottomCardVisibility(@UploadPage int page, int uploadCount);
void updateRightCardContent(boolean gpsPresent);
void updateBottomCardContent(int currentStep, int stepCount, UploadItem uploadItem, boolean isShowingItem);
void updateLicenses(List<String> licenses, String selectedLicense);
void updateLicenseSummary(String selectedLicense, int imageCount);
void updateTopCardContent();
void updateSubtitleVisibility(int imageCount);
void dismissKeyboard();
void showBadPicturePopup(String errorMessage);
void showDuplicatePicturePopup();
void finish();
void launchMapActivity(LatLng decCoords);
void showErrorMessage(int resourceId);
void initDefaultCategories();
void showNoCategorySelectedWarning();
void showProgressDialog();
void hideProgressDialog();
void askUserToLogIn();
}

View file

@ -44,11 +44,6 @@ public interface DepictsContract {
interface UserActionListener extends BasePresenter<View> { interface UserActionListener extends BasePresenter<View> {
/**
* Takes to previous screen
*/
void onPreviousButtonClicked();
/** /**
* Listener for the depicted items selected from the list * Listener for the depicted items selected from the list
*/ */

View file

@ -76,7 +76,7 @@ class DepictsPresenter @Inject constructor(
compositeDisposable.clear() compositeDisposable.clear()
} }
override fun onPreviousButtonClicked() { fun onPreviousButtonClicked() {
view.goToPreviousScreen() view.goToPreviousScreen()
} }

View file

@ -35,8 +35,6 @@ import fr.free.nrw.commons.upload.UploadItem;
import fr.free.nrw.commons.utils.DialogUtil; import fr.free.nrw.commons.utils.DialogUtil;
import fr.free.nrw.commons.utils.ImageUtils; import fr.free.nrw.commons.utils.ImageUtils;
import fr.free.nrw.commons.utils.ViewUtil; import fr.free.nrw.commons.utils.ViewUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import javax.inject.Inject; import javax.inject.Inject;
@ -214,18 +212,17 @@ public class UploadMediaDetailFragment extends UploadBaseFragment implements
} }
@Override @Override
public void onImageProcessed(UploadItem uploadItem, Place place) { public void onImageProcessed(UploadItem uploadItem) {
photoViewBackgroundImage.setImageURI(uploadItem.getMediaUri()); photoViewBackgroundImage.setImageURI(uploadItem.getMediaUri());
} }
/** /**
* Shows popup if any nearby location needing pictures matches uploadable picture's GPS location * Shows popup if any nearby location needing pictures matches uploadable picture's GPS location
* @param uploadItem
* @param place * @param place
*/ */
@SuppressLint("StringFormatInvalid") @SuppressLint("StringFormatInvalid")
@Override @Override
public void onNearbyPlaceFound(UploadItem uploadItem, Place place) { public void onNearbyPlaceFound(Place place) {
DialogUtil.showAlertDialog(getActivity(), DialogUtil.showAlertDialog(getActivity(),
getString(R.string.upload_nearby_place_found_title), getString(R.string.upload_nearby_place_found_title),
String.format(Locale.getDefault(), String.format(Locale.getDefault(),
@ -250,12 +247,12 @@ public class UploadMediaDetailFragment extends UploadBaseFragment implements
} }
@Override @Override
public void showMessage(int stringResourceId, int colorResourceId) { public void showMessage(int stringResourceId) {
ViewUtil.showLongToast(getContext(), stringResourceId); ViewUtil.showLongToast(getContext(), stringResourceId);
} }
@Override @Override
public void showMessage(String message, int colorResourceId) { public void showMessage(String message) {
ViewUtil.showLongToast(getContext(), message); ViewUtil.showLongToast(getContext(), message);
} }

View file

@ -16,17 +16,17 @@ public interface UploadMediaDetailsContract {
interface View extends SimilarImageInterface { interface View extends SimilarImageInterface {
void onImageProcessed(UploadItem uploadItem, Place place); void onImageProcessed(UploadItem uploadItem);
void onNearbyPlaceFound(UploadItem uploadItem, Place place); void onNearbyPlaceFound(Place place);
void showProgress(boolean shouldShow); void showProgress(boolean shouldShow);
void onImageValidationSuccess(); void onImageValidationSuccess();
void showMessage(int stringResourceId, int colorResourceId); void showMessage(int stringResourceId);
void showMessage(String message, int colorResourceId); void showMessage(String message);
void showDuplicatePicturePopup(UploadItem uploadItem); void showDuplicatePicturePopup(UploadItem uploadItem);

View file

@ -85,7 +85,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
.observeOn(mainThreadScheduler) .observeOn(mainThreadScheduler)
.subscribe(uploadItem -> .subscribe(uploadItem ->
{ {
view.onImageProcessed(uploadItem, place); view.onImageProcessed(uploadItem);
view.updateMediaDetails(uploadItem.getUploadMediaDetails()); view.updateMediaDetails(uploadItem.getUploadMediaDetails());
ImageCoordinates gpsCoords = uploadItem.getGpsCoords(); ImageCoordinates gpsCoords = uploadItem.getGpsCoords();
final boolean hasImageCoordinates = final boolean hasImageCoordinates =
@ -111,7 +111,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
.observeOn(mainThreadScheduler) .observeOn(mainThreadScheduler)
.subscribe(place -> { .subscribe(place -> {
if (place != null) { if (place != null) {
view.onNearbyPlaceFound(uploadItem, place); view.onNearbyPlaceFound(place);
} }
}, },
throwable -> Timber.e(throwable, "Error occurred in processing images")); throwable -> Timber.e(throwable, "Error occurred in processing images"));
@ -138,8 +138,8 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
}, },
throwable -> { throwable -> {
view.showProgress(false); view.showProgress(false);
view.showMessage("" + throwable.getLocalizedMessage(), view.showMessage("" + throwable.getLocalizedMessage()
R.color.color_error); );
Timber.e(throwable, "Error occurred while handling image"); Timber.e(throwable, "Error occurred while handling image");
}) })
); );
@ -159,7 +159,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
currentUploadItem.setMediaDetails(deepCopy(previousUploadItem.getUploadMediaDetails())); currentUploadItem.setMediaDetails(deepCopy(previousUploadItem.getUploadMediaDetails()));
view.updateMediaDetails(currentUploadItem.getUploadMediaDetails()); view.updateMediaDetails(currentUploadItem.getUploadMediaDetails());
} else { } else {
view.showMessage(R.string.previous_image_title_description_not_found, R.color.color_error); view.showMessage(R.string.previous_image_title_description_not_found);
} }
} }
@ -222,7 +222,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
switch (errorCode) { switch (errorCode) {
case EMPTY_CAPTION: case EMPTY_CAPTION:
Timber.d("Captions are empty. Showing toast"); Timber.d("Captions are empty. Showing toast");
view.showMessage(R.string.add_caption_toast, R.color.color_error); view.showMessage(R.string.add_caption_toast);
break; break;
case FILE_NAME_EXISTS: case FILE_NAME_EXISTS:
Timber.d("Trying to show duplicate picture popup"); Timber.d("Trying to show duplicate picture popup");

View file

@ -1,8 +0,0 @@
package fr.free.nrw.commons.upload.structure.depictions;
/**
* Listener to trigger callback whenever a depicts item is clicked
*/
public interface UploadDepictsCallback {
void depictsClicked(DepictedItem item);
}

View file

@ -1,12 +1,8 @@
package fr.free.nrw.commons.utils; package fr.free.nrw.commons.utils;
import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.util.DisplayMetrics;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -26,17 +22,6 @@ public class UiUtils {
return bitmap; return bitmap;
} }
/**
* Converts dp unit to equivalent pixels.
* @param dp density independent pixels
* @param context Context to access display metrics
* @return px equivalent to dp value
*/
public static float convertDpToPixel(float dp, Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
/** /**
* Creates a series of points that create a circle on the map. * Creates a series of points that create a circle on the map.
* Takes the center latitude, center longitude of the circle, * Takes the center latitude, center longitude of the circle,

View file

@ -1,7 +0,0 @@
package fr.free.nrw.commons.widget;
import android.content.Context;
public interface ViewHolder<T> {
void bindModel(Context context, T model);
}

View file

@ -1,82 +0,0 @@
package android.text;
import androidx.annotation.Nullable;
/**
* This Class Mocks TextUtils for the purpose of testing.
* NOTE: This class would not change the function of the TextUtils used in app
* it onlt mocks it for the unit tests
*
*/
public class TextUtils {
/**
* mocks TextUtils.isEmpty
*/
public static boolean isEmpty(@Nullable CharSequence str) {
return str == null || str.length() == 0;
}
/**
* mocks TextUtils.equals
*/
public static boolean equals(CharSequence a, CharSequence b) {
if (a == b) return true;
int length;
if (a != null && b != null && (length = a.length()) == b.length()) {
if (a instanceof String && b instanceof String) {
return a.equals(b);
} else {
for (int i = 0; i < length; i++) {
if (a.charAt(i) != b.charAt(i)) return false;
}
return true;
}
}
return false;
}
/**
* mocks TextUtils.isDigitsOnly
*/
public static boolean isDigitsOnly(CharSequence str) {
final int len = str.length();
for (int cp, i = 0; i < len; i += Character.charCount(cp)) {
cp = Character.codePointAt(str, i);
if (!Character.isDigit(cp)) {
return false;
}
}
return true;
}
/**
* mocks TextUtils.isNewline
*/
private static boolean isNewline(int codePoint) {
int type = Character.getType(codePoint);
return type == Character.PARAGRAPH_SEPARATOR || type == Character.LINE_SEPARATOR
|| codePoint == 10;
}
/**
* Returns whether the given CharSequence contains any printable characters.
*/
public static boolean isGraphic(CharSequence str) {
final int len = str.length();
for (int cp, i=0; i<len; i+=Character.charCount(cp)) {
cp = Character.codePointAt(str, i);
int gc = Character.getType(cp);
if (gc != Character.CONTROL
&& gc != Character.FORMAT
&& gc != Character.SURROGATE
&& gc != Character.UNASSIGNED
&& gc != Character.LINE_SEPARATOR
&& gc != Character.PARAGRAPH_SEPARATOR
&& gc != Character.SPACE_SEPARATOR) {
return true;
}
}
return false;
}
}

View file

@ -18,7 +18,8 @@ class NearbyControllerTest {
val location = LatLng(0.0, 0.0, 0f) val location = LatLng(0.0, 0.0, 0f)
val options = loadAttractionsFromLocationToBaseMarkerOptions( val options = loadAttractionsFromLocationToBaseMarkerOptions(
location, null, ApplicationProvider.getApplicationContext(), null) location, null, ApplicationProvider.getApplicationContext()
)
assertEquals(0, options.size.toLong()) assertEquals(0, options.size.toLong())
} }
@ -28,7 +29,8 @@ class NearbyControllerTest {
val location = LatLng(0.0, 0.0, 0f) val location = LatLng(0.0, 0.0, 0f)
val options = loadAttractionsFromLocationToBaseMarkerOptions( val options = loadAttractionsFromLocationToBaseMarkerOptions(
location, emptyList(), ApplicationProvider.getApplicationContext(), emptyList()) location, emptyList(), ApplicationProvider.getApplicationContext()
)
assertEquals(0, options.size.toLong()) assertEquals(0, options.size.toLong())
} }

View file

@ -27,7 +27,7 @@ class PageEditClientTest {
@Throws(Exception::class) @Throws(Exception::class)
fun setUp() { fun setUp() {
MockitoAnnotations.initMocks(this) MockitoAnnotations.initMocks(this)
pageEditClient = PageEditClient(csrfTokenClient, pageEditInterface, service) pageEditClient = PageEditClient(csrfTokenClient, pageEditInterface)
} }
/** /**

View file

@ -2,28 +2,21 @@ package fr.free.nrw.commons.contributions
import android.database.Cursor import android.database.Cursor
import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.loader.content.CursorLoader import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader import androidx.loader.content.Loader
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Completable import io.reactivex.Completable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler import io.reactivex.schedulers.TestScheduler
import org.junit.Before import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.*
import org.mockito.Mock import org.mockito.Mock
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.MockitoAnnotations import org.mockito.MockitoAnnotations
import java.util.concurrent.TimeUnit
/** /**
* The unit test class for ContributionsPresenter * The unit test class for ContributionsPresenter
@ -58,7 +51,7 @@ class ContributionsPresenterTest {
scheduler=TestScheduler() scheduler=TestScheduler()
cursor = Mockito.mock(Cursor::class.java) cursor = Mockito.mock(Cursor::class.java)
contribution = Mockito.mock(Contribution::class.java) contribution = Mockito.mock(Contribution::class.java)
contributionsPresenter = ContributionsPresenter(repository,scheduler,scheduler) contributionsPresenter = ContributionsPresenter(repository, scheduler)
loader = Mockito.mock(CursorLoader::class.java) loader = Mockito.mock(CursorLoader::class.java)
contributionsPresenter.onAttachView(view) contributionsPresenter.onAttachView(view)
liveData=MutableLiveData() liveData=MutableLiveData()

View file

@ -38,7 +38,7 @@ class DeleteHelperTest {
@Before @Before
fun setup() { fun setup() {
MockitoAnnotations.initMocks(this) MockitoAnnotations.initMocks(this)
deleteHelper = DeleteHelper(mock(), pageEditClient, mock(), "") deleteHelper = DeleteHelper(mock(), pageEditClient, mock())
} }
/** /**

View file

@ -86,8 +86,7 @@ class UploadMediaPresenterTest {
verify(view).showProgress(true) verify(view).showProgress(true)
testScheduler.triggerActions() testScheduler.triggerActions()
verify(view).onImageProcessed( verify(view).onImageProcessed(
ArgumentMatchers.any(UploadItem::class.java), ArgumentMatchers.any(UploadItem::class.java)
ArgumentMatchers.any(Place::class.java)
) )
verify(view).showProgress(false) verify(view).showProgress(false)
} }
@ -122,7 +121,7 @@ class UploadMediaPresenterTest {
//Empty Caption test //Empty Caption test
uploadMediaPresenter.handleImageResult(EMPTY_CAPTION, uploadItem) uploadMediaPresenter.handleImageResult(EMPTY_CAPTION, uploadItem)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()) verify(view).showMessage(ArgumentMatchers.anyInt())
//Bad Picture test //Bad Picture test
//Empty Caption test //Empty Caption test
@ -185,7 +184,7 @@ class UploadMediaPresenterTest {
whenever(repository.getPreviousUploadItem(ArgumentMatchers.anyInt())) whenever(repository.getPreviousUploadItem(ArgumentMatchers.anyInt()))
.thenReturn(null) .thenReturn(null)
uploadMediaPresenter.fetchPreviousTitleAndDescription(0) uploadMediaPresenter.fetchPreviousTitleAndDescription(0)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()) verify(view).showMessage(ArgumentMatchers.anyInt())
} }
/** /**
@ -204,7 +203,7 @@ class UploadMediaPresenterTest {
@Test @Test
fun handleBadImageBaseTestEmptyTitle() { fun handleBadImageBaseTestEmptyTitle() {
uploadMediaPresenter.handleBadImage(-3, uploadItem) uploadMediaPresenter.handleBadImage(-3, uploadItem)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()) verify(view).showMessage(ArgumentMatchers.anyInt())
} }
/** /**

View file

@ -1,17 +1,5 @@
package fr.free.nrw.commons.utils; package fr.free.nrw.commons.utils;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import fr.free.nrw.commons.utils.model.NetworkConnectionType;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE; import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPA; import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_LTE; import static android.telephony.TelephonyManager.NETWORK_TYPE_LTE;
@ -21,11 +9,16 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class NetworkUtilsTest { import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import fr.free.nrw.commons.utils.model.NetworkConnectionType;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
@Before public class NetworkUtilsTest {
public void setUp() throws Exception {
}
@Test @Test
public void testInternetConnectionEstablished() { public void testInternetConnectionEstablished() {

View file

@ -1,4 +0,0 @@
package org.wikipedia.wikidata
data class ClaimsResponse(val claims: Map<String, List<Statement_partial>>)