#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="UnnecessaryThis" 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>
</component>

View file

@ -97,12 +97,6 @@ public class CommonsApplication extends MultiDexApplication {
public static final String FEEDBACK_EMAIL_TEMPLATE_HEADER = "-- Technical information --";
/**
* Constants End
*/
private RefWatcher refWatcher;
private static CommonsApplication INSTANCE;
public static CommonsApplication getInstance() {
return INSTANCE;
@ -191,10 +185,6 @@ public class CommonsApplication extends MultiDexApplication {
Timber.plant(new Timber.DebugTree());
}
public static boolean isRoboUnitTest() {
return "robolectric".equals(Build.FINGERPRINT);
}
private ThreadPoolService getFileLoggingThreadPool() {
return new ThreadPoolService.Builder("file-logging-thread")
.setPriority(Process.THREAD_PRIORITY_LOWEST)
@ -230,17 +220,6 @@ public class CommonsApplication extends MultiDexApplication {
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
* @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
*/
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;
import org.wikipedia.csrf.CsrfTokenClient;
import org.wikipedia.dataclient.Service;
import io.reactivex.Observable;
import org.wikipedia.csrf.CsrfTokenClient;
/**
* This class acts as a Client to facilitate wiki page editing
@ -16,14 +14,11 @@ public class PageEditClient {
private final CsrfTokenClient csrfTokenClient;
private final PageEditInterface pageEditInterface;
private final Service service;
public PageEditClient(CsrfTokenClient csrfTokenClient,
PageEditInterface pageEditInterface,
Service service) {
PageEditInterface pageEditInterface) {
this.csrfTokenClient = csrfTokenClient;
this.pageEditInterface = pageEditInterface;
this.service = service;
}
/**

View file

@ -1,5 +1,10 @@
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.app.ProgressDialog;
import android.content.Context;
@ -17,7 +22,6 @@ import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@ -26,25 +30,12 @@ import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.NavUtils;
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.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnFocusChange;
import com.google.android.material.textfield.TextInputLayout;
import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.R;
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.ViewUtil;
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.Callback;
import retrofit2.Response;
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 {
@Inject
@ -246,7 +241,6 @@ public class LoginActivity extends AccountAuthenticatorActivity {
public void performLogin() {
Timber.d("Login to start!");
final String username = usernameEdit.getText().toString();
final String rawUsername = usernameEdit.getText().toString().trim();
final String password = passwordEdit.getText().toString();
String twoFactorCode = twoFactorEdit.getText().toString();

View file

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

View file

@ -54,10 +54,4 @@ public class BookmarkPicturesController {
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();
}
@Override
public void onStop() {
super.onStop();
controller.stop();
}
@Override
public void onDestroy() {

View file

@ -13,9 +13,6 @@ public class Category {
private Date lastUsed;
private int timesUsed;
public Category() {
}
public Category(Uri contentUri, String name, Date lastUsed, int timesUsed) {
this.contentUri = contentUri;
this.name = name;
@ -32,15 +29,6 @@ public class Category {
return name;
}
/**
* Modifies name
*
* @param name Category name
*/
public void setName(String name) {
this.name = name;
}
/**
* 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;
import androidx.annotation.NonNull;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* This class is a thread pool which provides some additional features:
@ -36,31 +32,6 @@ public class ThreadPoolService implements Executor {
}, 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
public void execute(Runnable command) {
backgroundPool.execute(command);

View file

@ -76,7 +76,6 @@ class ContributionBoundaryCallback @Inject constructor(
repository.save(contributions)
.subscribeOn(ioThreadScheduler)
.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) {
FilePicker.handleActivityResult(requestCode, resultCode, data, activity, new DefaultCallback() {
@Override
public void onImagePickerError(Exception e, FilePicker.ImageSource source, int type) {
public void onImagePickerError() {
ViewUtil.showShortToast(activity, R.string.error_occurred_in_picking_images);
}
@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);
activity.startActivity(intent);
}

View file

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

View file

@ -15,7 +15,6 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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.NearbyNotificationCardView;
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.utils.ConfigUtils;
import fr.free.nrw.commons.utils.DialogUtil;
@ -109,7 +107,6 @@ public class ContributionsFragment
}
};
private boolean shouldShowMediaDetailsFragment;
private boolean isAuthCookieAcquired;
@Override
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
public void onBackStackChanged() {
((MainActivity)getActivity()).initBackButton();
@ -213,7 +204,6 @@ public class ContributionsFragment
*/
void onAuthCookieAcquired() {
// 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
getActivity().bindService(getUploadServiceIntent(), uploadServiceConnection, Context.BIND_AUTO_CREATE);
isUploadServiceConnected = true;
@ -315,7 +305,6 @@ public class ContributionsFragment
} else if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)
&& store.getBoolean("displayLocationPermissionForCardView", true)
&& (((MainActivity) getActivity()).viewPager.getCurrentItem() == CONTRIBUTIONS_TAB_POSITION)) {
nearbyNotificationCardView.permissionType = NearbyNotificationCardView.PermissionType.ENABLE_LOCATION_PERMISSION;
showNearbyCardPermissionRationale();
}
}
@ -330,7 +319,6 @@ public class ContributionsFragment
}
private void onLocationPermissionGranted() {
nearbyNotificationCardView.permissionType = NearbyNotificationCardView.PermissionType.NO_PERMISSION_NEEDED;
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) {
if (campaign != null) {
campaignView.setCampaign(campaign);

View file

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

View file

@ -1,7 +1,5 @@
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 android.content.Context;
@ -15,8 +13,6 @@ import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
@ -47,16 +43,12 @@ public class ContributionsListFragment extends CommonsDaggerSupportFragment impl
@BindView(R.id.contributionsList)
RecyclerView rvContributionsList;
@BindView(R.id.loadingContributionsProgressBar)
ProgressBar progressBar;
@BindView(R.id.fab_plus)
FloatingActionButton fabPlus;
@BindView(R.id.fab_camera)
FloatingActionButton fabCamera;
@BindView(R.id.fab_gallery)
FloatingActionButton fabGallery;
@BindView(R.id.noContributionsYet)
TextView noContributionsYet;
@BindView(R.id.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
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);

View file

@ -2,14 +2,10 @@ package fr.free.nrw.commons.contributions;
import androidx.paging.DataSource.Factory;
import io.reactivex.Completable;
import io.reactivex.Single;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import fr.free.nrw.commons.kvstore.JsonKvStore;
import io.reactivex.Single;
/**
* The LocalDataSource class for Contributions
@ -17,30 +13,12 @@ import io.reactivex.Single;
class ContributionsLocalDataSource {
private final ContributionDao contributionDao;
private final JsonKvStore defaultKVStore;
@Inject
public ContributionsLocalDataSource(
@Named("default_preferences") JsonKvStore defaultKVStore,
ContributionDao contributionDao) {
this.defaultKVStore = defaultKVStore;
public ContributionsLocalDataSource(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
* @param uri
@ -79,11 +57,5 @@ class ContributionsLocalDataSource {
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 {
private final ContributionsRepository repository;
private final Scheduler mainThreadScheduler;
private final Scheduler ioThreadScheduler;
private CompositeDisposable compositeDisposable;
private ContributionsContract.View view;
@Inject
MediaDataExtractor mediaDataExtractor;
@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.mainThreadScheduler=mainThreadScheduler;
this.ioThreadScheduler=ioThreadScheduler;
}
@Override
public void onAttachView(ContributionsContract.View view) {
this.view = view;
compositeDisposable=new CompositeDisposable();
}
@Override
public void onDetachView() {
this.view = null;
compositeDisposable.clear();
}

View file

@ -20,13 +20,6 @@ public class ContributionsRepository {
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
* @param contribution
@ -53,11 +46,4 @@ public class ContributionsRepository {
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 boolean isContributionsFragmentVisible = true; // False means nearby fragment is visible
public boolean onOrientationChanged;
private Menu menu;
private MenuItem notificationsMenuItem;
@ -80,14 +79,10 @@ public class MainActivity extends NavigationBaseActivity implements FragmentMana
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 (savedInstanceState.getInt("viewPagerCurrentItem") == 1) {
//If nearby map was visible, call on Tab Selected to call all nearby operations
/*if (savedInstanceState.getInt("viewPagerCurrentItem") == 1) {
((NearbyFragment)contributionsActivityPagerAdapter.getItem(1)).onTabSelected(onOrientationChanged);
}*/
}
}
@Override

View file

@ -37,17 +37,14 @@ public class DeleteHelper {
private final NotificationHelper notificationHelper;
private final PageEditClient pageEditClient;
private final ViewUtilWrapper viewUtil;
private final String username;
@Inject
public DeleteHelper(NotificationHelper notificationHelper,
@Named("commons-page-edit") PageEditClient pageEditClient,
ViewUtilWrapper viewUtil,
@Named("username") String username) {
@Named("commons-page-edit") PageEditClient pageEditClient,
ViewUtilWrapper viewUtil) {
this.notificationHelper = notificationHelper;
this.pageEditClient = pageEditClient;
this.viewUtil = viewUtil;
this.username = username;
}
/**
@ -198,13 +195,11 @@ public class DeleteHelper {
.subscribe(aBoolean -> {
if (aBoolean) {
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();
d.show();
}

View file

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

View file

@ -7,10 +7,7 @@ package fr.free.nrw.commons.filepicker;
public abstract class DefaultCallback implements FilePicker.Callbacks {
@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;
import static fr.free.nrw.commons.filepicker.PickedFiles.singleFileList;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
@ -8,21 +10,17 @@ import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import androidx.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.PreferenceManager;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import static fr.free.nrw.commons.filepicker.PickedFiles.singleFileList;
public class FilePicker implements Constants {
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();
}
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
*
@ -150,14 +144,6 @@ public class FilePicker implements Constants {
} else {
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 {
Uri photoPath = data.getData();
UploadableFile photoFile = PickedFiles.pickedExistingPicture(activity, photoPath);
callbacks.onImagesPicked(singleFileList(photoFile), FilePicker.ImageSource.DOCUMENTS, restoreType(activity));
callbacks.onImagesPicked(singleFileList(photoFile));
if (configuration(activity).shouldCopyPickedImagesToPublicGalleryAppFolder()) {
PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile));
}
} catch (Exception e) {
e.printStackTrace();
callbacks.onImagePickerError(e, FilePicker.ImageSource.DOCUMENTS, restoreType(activity));
callbacks.onImagePickerError();
}
}
private static void onPictureReturnedFromGallery(Intent data, Activity activity, @NonNull FilePicker.Callbacks callbacks) {
try {
List<UploadableFile> files = getFilesFromGalleryPictures(data, activity);
callbacks.onImagesPicked(files, FilePicker.ImageSource.GALLERY, restoreType(activity));
callbacks.onImagesPicked(files);
} catch (Exception e) {
e.printStackTrace();
callbacks.onImagePickerError(e, FilePicker.ImageSource.GALLERY, restoreType(activity));
callbacks.onImagePickerError();
}
}
@ -241,14 +227,13 @@ public class FilePicker implements Constants {
files.add(photoFile);
if (photoFile == null) {
Exception e = new IllegalStateException("Unable to get the picture returned from camera");
callbacks.onImagePickerError(e, FilePicker.ImageSource.CAMERA_IMAGE, restoreType(activity));
callbacks.onImagePickerError();
} else {
if (configuration(activity).shouldCopyTakenPhotosToPublicGalleryAppFolder()) {
PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile));
}
callbacks.onImagesPicked(files, FilePicker.ImageSource.CAMERA_IMAGE, restoreType(activity));
callbacks.onImagesPicked(files);
}
PreferenceManager.getDefaultSharedPreferences(activity)
@ -258,7 +243,7 @@ public class FilePicker implements Constants {
.apply();
} catch (Exception e) {
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);
if (photoFile == null) {
Exception e = new IllegalStateException("Unable to get the video returned from camera");
callbacks.onImagePickerError(e, FilePicker.ImageSource.CAMERA_VIDEO, restoreType(activity));
callbacks.onImagePickerError();
} else {
if (configuration(activity).shouldCopyTakenPhotosToPublicGalleryAppFolder()) {
PickedFiles.copyFilesInSeparateThread(activity, singleFileList(photoFile));
}
callbacks.onImagesPicked(files, FilePicker.ImageSource.CAMERA_VIDEO, restoreType(activity));
callbacks.onImagesPicked(files);
}
PreferenceManager.getDefaultSharedPreferences(activity)
@ -291,7 +275,7 @@ public class FilePicker implements Constants {
.apply();
} catch (Exception e) {
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 {
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();
}
public Uri getContentUri() {
return contentUri;
}
public File getFile() {
return file;
}

View file

@ -2,16 +2,9 @@ package fr.free.nrw.commons.kvstore;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import timber.log.Timber;
public class BasicKvStore implements KeyValueStore {
private static final String KEY_VERSION = "__version__";
/*
@ -25,53 +18,6 @@ public class BasicKvStore implements KeyValueStore {
_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
public String getString(String key) {
return getString(key, null);
@ -82,11 +28,6 @@ public class BasicKvStore implements KeyValueStore {
return getBoolean(key, false);
}
@Override
public long getLong(String key) {
return getLong(key, 0);
}
@Override
public int getInt(String key) {
return getInt(key, 0);
@ -102,24 +43,11 @@ public class BasicKvStore implements KeyValueStore {
return _store.getBoolean(key, defaultValue);
}
@Override
public long getLong(String key, long defaultValue) {
return _store.getLong(key, defaultValue);
}
@Override
public int getInt(String key, int 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
public void putString(String key, String value) {
SharedPreferences.Editor editor = _store.edit();
@ -143,14 +71,6 @@ public class BasicKvStore implements KeyValueStore {
editor.apply();
}
@Override
public void putLong(String key, long value) {
assertKeyNotReserved(key);
SharedPreferences.Editor editor = _store.edit();
editor.putLong(key, value);
editor.apply();
}
@Override
public void putInt(String key, int value) {
assertKeyNotReserved(key);
@ -178,13 +98,6 @@ public class BasicKvStore implements KeyValueStore {
putIntInternal(KEY_VERSION, version);
}
@Override
public void clearAllWithVersion() {
SharedPreferences.Editor editor = _store.edit();
editor.clear();
editor.apply();
}
private void putIntInternal(String key, int value) {
SharedPreferences.Editor editor = _store.edit();
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){
return _store.getStringSet(key, new HashSet<>());
}

View file

@ -1,16 +1,10 @@
package fr.free.nrw.commons.kvstore;
import android.content.Context;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class JsonKvStore extends BasicKvStore {
private final Gson gson;
@ -19,33 +13,11 @@ public class JsonKvStore extends BasicKvStore {
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) {
putString(key, gson.toJson(object));
}
public <T> void putJsonWithTypeInfo(String key, T object, Type type) {
putString(key, gson.toJson(object, type));
}
@Nullable
public <T> T getJson(String key, Class<T> clazz) {
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);
long getLong(String key);
int getInt(String key);
String getString(String key, String defaultValue);
boolean getBoolean(String key, boolean defaultValue);
long getLong(String key, long defaultValue);
int getInt(String key, int defaultValue);
void putString(String key, String value);
void putBoolean(String key, boolean value);
void putLong(String key, long value);
void putInt(String key, int value);
boolean contains(String key);
@ -31,5 +25,4 @@ public interface KeyValueStore {
void clearAll();
void clearAllWithVersion();
}

View file

@ -1,16 +1,12 @@
package fr.free.nrw.commons.location;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import timber.log.Timber;
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 final List<LocationUpdateListener> locationListeners = new CopyOnWriteArrayList<>();
private boolean isLocationManagerRegistered = false;
private Set<Activity> locationExplanationDisplayed = new HashSet<>();
/**
* Constructs a new instance of LocationServiceManager.
@ -143,7 +138,6 @@ public class LocationServiceManager implements LocationListener {
*/
public void unregisterLocationManager() {
isLocationManagerRegistered = false;
locationExplanationDisplayed.clear();
try {
locationManager.removeUpdates(this);
} catch (SecurityException e) {
@ -224,9 +218,7 @@ public class LocationServiceManager implements LocationListener {
public enum LocationChangeType{
LOCATION_SIGNIFICANTLY_CHANGED, //Went out of borders of nearby markers
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,
PERMISSION_JUST_GRANTED,
MAP_UPDATED,
SEARCH_CUSTOM_AREA
}

View file

@ -21,7 +21,7 @@ import timber.log.Timber;
/**
* 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 int logLevel;
private final String logFileName;
@ -41,15 +41,6 @@ public class FileLoggingTree extends Timber.DebugTree implements LogLevelSettabl
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
* @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;
import io.reactivex.Observable;
import io.reactivex.Single;
import org.wikipedia.wikidata.Entities;
import retrofit2.http.GET;
@ -11,14 +10,6 @@ import retrofit2.http.Query;
*/
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
* @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")
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 onDataSetChanged() {
if (null != adapter) {
adapter.notifyDataSetChanged();
}
}
public interface MediaDetailProvider {
Media getMediaAtPosition(int i);

View file

@ -107,14 +107,6 @@ public interface MediaInterface {
@GET("w/api.php?format=json&action=parse&prop=text")
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
* @param query depictionEntityId

View file

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

View file

@ -14,20 +14,19 @@ public class MultiPointerGestureDetector {
/** The listener for receiving notifications when gestures occur. */
public interface Listener {
/** 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. */
public void onGestureUpdate(MultiPointerGestureDetector detector);
public void onGestureUpdate();
/** 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 boolean mGestureInProgress;
private int mPointerCount;
private int mNewPointerCount;
private final int mId[] = new int[MAX_POINTERS];
private final float mStartX[] = new float[MAX_POINTERS];
private final float mStartY[] = new float[MAX_POINTERS];
@ -76,7 +75,7 @@ public class MultiPointerGestureDetector {
private void startGesture() {
if (!mGestureInProgress) {
if (mListener != null) {
mListener.onGestureBegin(this);
mListener.onGestureBegin();
}
mGestureInProgress = true;
}
@ -87,7 +86,7 @@ public class MultiPointerGestureDetector {
if (mGestureInProgress) {
mGestureInProgress = false;
if (mListener != null) {
mListener.onGestureEnd(this);
mListener.onGestureEnd();
}
}
}
@ -110,16 +109,6 @@ public class MultiPointerGestureDetector {
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) {
mPointerCount = 0;
for (int i = 0; i < MAX_POINTERS; i++) {
@ -163,7 +152,7 @@ public class MultiPointerGestureDetector {
}
// notify listener
if (mGestureInProgress && mListener != null) {
mListener.onGestureUpdate(this);
mListener.onGestureUpdate();
}
break;
}
@ -174,7 +163,6 @@ public class MultiPointerGestureDetector {
case MotionEvent.ACTION_UP:
{
// restart gesture whenever the number of pointers changes
mNewPointerCount = getPressedPointerCount(event);
stopGesture();
updatePointersOnTap(event);
if (mPointerCount > 0 && shouldStartGesture()) {
@ -185,7 +173,6 @@ public class MultiPointerGestureDetector {
case MotionEvent.ACTION_CANCEL:
{
mNewPointerCount = 0;
stopGesture();
reset();
break;
@ -207,16 +194,6 @@ public class MultiPointerGestureDetector {
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 */
public int getPointerCount() {
return mPointerCount;

View file

@ -20,7 +20,7 @@ public class TransformGestureDetector implements MultiPointerGestureDetector.Lis
public void onGestureUpdate(TransformGestureDetector detector);
/** A callback called right after the gesture has finished. */
public void onGestureEnd(TransformGestureDetector detector);
public void onGestureEnd();
}
private final MultiPointerGestureDetector mDetector;
@ -62,23 +62,23 @@ public class TransformGestureDetector implements MultiPointerGestureDetector.Lis
}
@Override
public void onGestureBegin(MultiPointerGestureDetector detector) {
public void onGestureBegin() {
if (mListener != null) {
mListener.onGestureBegin(this);
}
}
@Override
public void onGestureUpdate(MultiPointerGestureDetector detector) {
public void onGestureUpdate() {
if (mListener != null) {
mListener.onGestureUpdate(this);
}
}
@Override
public void onGestureEnd(MultiPointerGestureDetector detector) {
public void onGestureEnd() {
if (mListener != null) {
mListener.onGestureEnd(this);
mListener.onGestureEnd();
}
}
@ -95,21 +95,6 @@ public class TransformGestureDetector implements MultiPointerGestureDetector.Lis
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 */
public float getPivotX() {
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 viewPoint 2D point in view's absolute coordinate system
*/
@Override
public void zoomToPoint(float scale, PointF imagePoint, PointF viewPoint) {
zoomToPoint(scale, imagePoint, viewPoint, LIMIT_ALL, 0, null);
}

View file

@ -15,11 +15,6 @@ import java.lang.annotation.RetentionPolicy;
public class DefaultZoomableController
implements ZoomableController, TransformGestureDetector.Listener {
/** Interface for handling call backs when the image bounds are set. */
public interface ImageBoundsListener {
void onImageBoundsSet(RectF imageBounds);
}
@IntDef(
flag = true,
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_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 RectF IDENTITY_RECT = new RectF(0, 0, 1, 1);
private TransformGestureDetector mGestureDetector;
private @Nullable ImageBoundsListener mImageBoundsListener;
private @Nullable Listener mListener = null;
private boolean mIsEnabled = false;
@ -65,11 +54,6 @@ public class DefaultZoomableController
private final Matrix mActiveTransformInverse = new Matrix();
private final float[] mTempValues = new float[9];
private final RectF mTempRect = new RectF();
private boolean mWasTransformCorrected;
public static DefaultZoomableController newInstance() {
return new DefaultZoomableController(TransformGestureDetector.newInstance());
}
public DefaultZoomableController(TransformGestureDetector gestureDetector) {
mGestureDetector = gestureDetector;
@ -106,74 +90,16 @@ public class DefaultZoomableController
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. */
public float getMinScaleFactor() {
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. */
public float getMaxScaleFactor() {
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. */
@Override
public float getScaleFactor() {
@ -186,60 +112,21 @@ public class DefaultZoomableController
if (!imageBounds.equals(mImageBounds)) {
mImageBounds.set(imageBounds);
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. */
@Override
public void setViewBounds(RectF 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. */
@Override
public boolean isIdentity() {
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
* zoomable transformation is taken into account.
@ -251,14 +138,6 @@ public class DefaultZoomableController
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
* zoomable transformation.
@ -273,19 +152,6 @@ public class DefaultZoomableController
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
* 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
* so that the given image point corresponds to the given view point.
@ -391,12 +243,6 @@ public class DefaultZoomableController
public void onGestureBegin(TransformGestureDetector detector) {
FLog.v(TAG, "onGestureBegin");
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
@ -408,11 +254,10 @@ public class DefaultZoomableController
mGestureDetector.restartGesture();
}
// A transformation happened, but was it without correction?
mWasTransformCorrected = transformCorrected;
}
@Override
public void onGestureEnd(TransformGestureDetector detector) {
public void onGestureEnd() {
FLog.v(TAG, "onGestureEnd");
onTransformEnd();
}
@ -445,12 +290,6 @@ public class DefaultZoomableController
return transformCorrected;
}
private void onTransformBegin() {
if (mListener != null && isEnabled()) {
mListener.onTransformBegin(mActiveTransform);
}
}
private void onTransformChanged() {
mActiveTransform.mapRect(mTransformedImageBounds, mImageBounds);
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.
*
@ -602,14 +435,6 @@ public class DefaultZoomableController
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
public int computeHorizontalScrollRange() {
return (int) mTransformedImageBounds.width();
@ -640,7 +465,4 @@ public class DefaultZoomableController
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. */
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.
*
@ -27,12 +20,6 @@ public interface ZoomableController {
*/
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. */
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}. */
int computeHorizontalScrollRange();

View file

@ -9,10 +9,8 @@ import android.graphics.drawable.Animatable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import androidx.annotation.Nullable;
import androidx.core.view.ScrollingView;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.logging.FLog;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.controller.BaseControllerListener;
@ -64,16 +62,12 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
private final ZoomableController.Listener mZoomableListener =
new ZoomableController.Listener() {
@Override
public void onTransformBegin(Matrix transform) {}
@Override
@Override
public void onTransformChanged(Matrix transform) {
ZoomableDraweeView.this.onTransformChanged(transform);
}
@Override
public void onTransformEnd(Matrix transform) {}
};
private final GestureListenerWrapper mTapListenerWrapper = new GestureListenerWrapper();
@ -118,10 +112,6 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper);
}
public void setIsDialtoneEnabled(boolean isDialtoneEnabled) {
mIsDialtoneEnabled = isDialtoneEnabled;
}
/**
* 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());
}
/** 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.
*
@ -171,16 +153,6 @@ public class ZoomableDraweeView extends DraweeView<GenericDraweeHierarchy>
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
* 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);
}
public void setZoomingEnabled(boolean zoomingEnabled) {
mZoomingEnabled = zoomingEnabled;
mZoomableController.setEnabled(false);
}
/** Sets the image controller. */
@Override
public void setController(@Nullable DraweeController controller) {

View file

@ -1,19 +1,13 @@
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.MwQueryResult;
import org.wikipedia.dataclient.mwapi.UserInfo;
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 {
private final UserInterface userInterface;
@ -45,15 +39,4 @@ public class UserClient {
}).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;
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 io.reactivex.Observable;
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import retrofit2.http.GET;
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
*/

View file

@ -1,16 +1,12 @@
package fr.free.nrw.commons.nearby;
import android.os.Parcel;
import androidx.annotation.DrawableRes;
import fr.free.nrw.commons.R;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import fr.free.nrw.commons.R;
/**
* See https://github.com/commons-app/apps-android-commons/issues/250
* Most common types of desc: building, house, cottage, farmhouse,
@ -65,11 +61,6 @@ public enum Label {
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
* @param isSelected true if user selected the place type

View file

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

View file

@ -1,15 +1,18 @@
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.res.Resources;
import android.graphics.Bitmap;
import androidx.annotation.MainThread;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import com.mapbox.mapboxsdk.annotations.IconFactory;
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.util.ArrayList;
import java.util.Collections;
@ -18,17 +21,9 @@ import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
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 static fr.free.nrw.commons.utils.LengthUtils.computeDistanceBetween;
import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween;
public class NearbyController {
private static final int MAX_RESULTS = 1000;
private final NearbyPlaces nearbyPlaces;
@ -102,9 +97,7 @@ public class NearbyController {
);
}
nearbyPlacesInfo.curLatLng = curLatLng;
nearbyPlacesInfo.searchLatLng = searchLatLng;
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
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.
*
@ -153,10 +128,9 @@ public class NearbyController {
* @return BaseMarkerOptions list that holds nearby places
*/
public static List<NearbyBaseMarker> loadAttractionsFromLocationToBaseMarkerOptions(
LatLng curLatLng,
List<Place> placeList,
Context context,
List<Place> bookmarkplacelist) {
LatLng curLatLng,
List<Place> placeList,
Context context) {
List<NearbyBaseMarker> baseMarkerOptions = new ArrayList<>();
if (placeList == null) {
@ -168,7 +142,6 @@ public class NearbyController {
VectorDrawableCompat vectorDrawable = null;
VectorDrawableCompat vectorDrawableGreen = null;
VectorDrawableCompat vectorDrawableGrey = null;
vectorDrawable = null;
try {
vectorDrawable = VectorDrawableCompat.create(
context.getResources(), R.drawable.ic_custom_map_marker, context.getTheme());
@ -223,9 +196,7 @@ public class NearbyController {
*/
public class NearbyPlacesInfo {
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 searchLatLng; // Search location for finding this places
}
/**

View file

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

View file

@ -1,12 +1,8 @@
package fr.free.nrw.commons.nearby;
import java.util.ArrayList;
public class NearbyFilterState {
private boolean existsSelected;
private boolean needPhotoSelected;
private int checkBoxTriState;
private ArrayList<Label> selectedLabels;
private static NearbyFilterState nearbyFılterStateInstance;
@ -16,8 +12,6 @@ public class NearbyFilterState {
private NearbyFilterState() {
existsSelected = false;
needPhotoSelected = true;
checkBoxTriState = -1; // Unknown
selectedLabels = new ArrayList<>(); // Initially empty
}
public static NearbyFilterState getInstance() {
@ -27,10 +21,6 @@ public class NearbyFilterState {
return nearbyFılterStateInstance;
}
public static void setSelectedLabels(ArrayList<Label> selectedLabels) {
getInstance().selectedLabels = selectedLabels;
}
public static void setExistsSelected(boolean existsSelected) {
getInstance().existsSelected = existsSelected;
}
@ -47,11 +37,4 @@ public class NearbyFilterState {
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;
public class NearbyMarker extends Marker {
private final Place place;
private NearbyBaseMarker nearbyBaseMarker;
/**
@ -11,9 +11,8 @@ public class NearbyMarker extends Marker {
*
* @param baseMarkerOptions The builder used to construct the Marker.
*/
NearbyMarker(NearbyBaseMarker baseMarkerOptions, Place place) {
NearbyMarker(NearbyBaseMarker baseMarkerOptions) {
super(baseMarkerOptions);
this.place = place;
this.nearbyBaseMarker = baseMarkerOptions;
}
@ -21,7 +20,4 @@ public class NearbyMarker extends Marker {
return nearbyBaseMarker;
}
public Place getPlace() {
return place;
}
}

View file

@ -1,5 +1,7 @@
package fr.free.nrw.commons.nearby;
import static fr.free.nrw.commons.contributions.MainActivity.NEARBY_TAB_POSITION;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
@ -8,10 +10,8 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.contributions.MainActivity;
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 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
*/
@ -34,8 +32,6 @@ public class NearbyNotificationCardView extends SwipableCardView {
public CardViewVisibilityState cardViewVisibilityState;
public PermissionType permissionType;
public NearbyNotificationCardView(@NonNull Context context) {
super(context);
cardViewVisibilityState = CardViewVisibilityState.INVISIBLE;
@ -105,20 +101,6 @@ public class NearbyNotificationCardView extends SwipableCardView {
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.
* @param place Closes place where we will get information from
@ -189,16 +171,6 @@ public class NearbyNotificationCardView extends SwipableCardView {
READY,
INVISIBLE,
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;
import android.content.Context;
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.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.nearby.Label;
import fr.free.nrw.commons.nearby.NearbyBaseMarker;
import fr.free.nrw.commons.nearby.Place;
import fr.free.nrw.commons.nearby.presenter.NearbyParentFragmentPresenter;
import java.util.List;
public interface NearbyParentFragmentContract {
@ -40,7 +35,7 @@ public interface NearbyParentFragmentContract {
void setTabItemContributions();
boolean isDetailsBottomSheetVisible();
void setBottomSheetDetailsSmaller();
boolean isSearchThisAreaButtonVisible();
void setRecyclerViewAdapterAllSelected();
void setRecyclerViewAdapterItemsGreyedOut();
void setCheckBoxAction();
@ -58,9 +53,8 @@ public interface NearbyParentFragmentContract {
void filterOutAllMarkers();
void displayAllMarkers();
void filterMarkersByLabels(List<Label> selectedLabels, boolean existsSelected, boolean needPhotoSelected, boolean filterForPlaceState, boolean filterForAllNoneType);
void filterMarkersByLabels(List<Label> selectedLabels, boolean existsSelected,
boolean needPhotoSelected, boolean filterForPlaceState);
LatLng getCameraTarget();
@ -76,10 +70,6 @@ public interface NearbyParentFragmentContract {
void setProjectorLatLngBounds();
}
interface NearbyListView {
void updateListFragment(List<Place> placeList);
}
interface UserActions {
void updateMapAndList(LocationServiceManager.LocationChangeType locationChangeType);
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_SLIGHTLY_CHANGED;
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.wikidata.WikidataConstants.PLACE_OBJECT;
@ -16,7 +15,6 @@ import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.VectorDrawable;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
@ -38,7 +36,6 @@ import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -47,7 +44,6 @@ import butterknife.BindView;
import butterknife.ButterKnife;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
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.snackbar.Snackbar;
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.contributions.ContributionController;
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.kvstore.JsonKvStore;
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 io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.List;
@ -144,7 +138,6 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
@BindView(R.id.map_progress_bar) ProgressBar progressBar;
@BindView(R.id.choice_chip_exists) Chip chipExists;
@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_list_view) RecyclerView recyclerView;
@BindView(R.id.nearby_filter_list) View nearbyFilterList;
@ -429,7 +422,7 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
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() {
@Override
public void setCheckboxUnknown() {
@ -814,11 +807,6 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
}
}
@Override
public boolean isSearchThisAreaButtonVisible() {
return searchThisAreaButton.getVisibility() == View.VISIBLE;
}
@Override
public void setRecyclerViewAdapterAllSelected() {
if (nearbyFilterSearchRecyclerViewAdapter != null && NearbyController.currentLocation != null) {
@ -1096,30 +1084,18 @@ public class NearbyParentFragment extends CommonsDaggerSupportFragment
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
* @param selectedLabels label list that user clicked
* @param displayExists chip for displaying only existing places
* @param displayNeedsPhoto chip for displaying only places need photos
* @param filterForPlaceState true if we filter places for place state
* @param filterForAllNoneType true if we filter places with all none button
*/
@Override
public void filterMarkersByLabels(final List<Label> selectedLabels,
final boolean displayExists,
final boolean displayNeedsPhoto,
final boolean filterForPlaceState,
final boolean filterForAllNoneType) {
final boolean filterForPlaceState) {
// Remove the previous markers before updating them
hideAllMarkers();

View file

@ -1,15 +1,16 @@
package fr.free.nrw.commons.nearby.presenter;
import android.util.Log;
import android.view.View;
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;
import android.view.View;
import androidx.annotation.MainThread;
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.kvstore.JsonKvStore;
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.utils.LocationUtils;
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 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
implements NearbyParentFragmentContract.UserActions,
WikidataEditListener.WikidataP18EditListener,
@ -208,8 +204,7 @@ public class NearbyParentFragmentPresenter
List<NearbyBaseMarker> nearbyBaseMarkers = NearbyController
.loadAttractionsFromLocationToBaseMarkerOptions(nearbyPlacesInfo.curLatLng, // Curlatlang will be used to calculate distances
nearbyPlacesInfo.placeList,
nearbyParentFragmentView.getContext(),
bookmarkLocationDao.getAllBookmarksLocations());
nearbyParentFragmentView.getContext());
nearbyParentFragmentView.updateMapMarkers(nearbyBaseMarkers, selectedMarker);
nearbyParentFragmentView.addCurrentLocationMarker(nearbyPlacesInfo.curLatLng);
if(shouldTrackPosition){
@ -290,7 +285,7 @@ public class NearbyParentFragmentPresenter
nearbyParentFragmentView.filterMarkersByLabels(selectedLabels,
NearbyFilterState.getInstance().isExistsSelected(),
NearbyFilterState.getInstance().isNeedPhotoSelected(),
filterForPlaceState, false);
filterForPlaceState);
nearbyParentFragmentView.setRecyclerViewAdapterAllSelected();
break;
}
@ -298,7 +293,7 @@ public class NearbyParentFragmentPresenter
nearbyParentFragmentView.filterMarkersByLabels(selectedLabels,
NearbyFilterState.getInstance().isExistsSelected(),
NearbyFilterState.getInstance().isNeedPhotoSelected(),
filterForPlaceState, false);
filterForPlaceState);
}
}

View file

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

View file

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

View file

@ -38,8 +38,6 @@ public class ReviewActivity extends NavigationBaseActivity {
public CirclePageIndicator pagerIndicator;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.navigation_view)
NavigationView navigationView;
@BindView(R.id.drawer_layout)
DrawerLayout drawerLayout;
@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.
* @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);
reviewActivity.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
reviewActivity.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

View file

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

View file

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

View file

@ -1,9 +1,7 @@
package fr.free.nrw.commons.settings;
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 UPLOADS_SHOWING = "uploadsshowing";
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.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
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 com.google.android.material.navigation.NavigationView;
import fr.free.nrw.commons.AboutActivity;
import fr.free.nrw.commons.BuildConfig;
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.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import javax.inject.Inject;
import javax.inject.Named;
import timber.log.Timber;
public abstract class NavigationBaseActivity extends BaseActivity
@ -76,7 +70,6 @@ public abstract class NavigationBaseActivity extends BaseActivity
private CompositeDisposable disposable = new CompositeDisposable();
private Service service;
private ProgressDialog progressDialog;
@ -159,12 +152,6 @@ public abstract class NavigationBaseActivity extends BaseActivity
toggle.setToolbarNavigationClickListener(v -> onBackPressed());
}
public void initBack() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override
public boolean onNavigationItemSelected(@NonNull final MenuItem item) {
final int itemId = item.getItemId();
@ -238,7 +225,7 @@ public abstract class NavigationBaseActivity extends BaseActivity
case R.id.action_review:
drawerLayout.closeDrawer(navigationView);
ReviewActivity.startYourself(this, getString(R.string.title_activity_review));
ReviewActivity.startYourself(this);
return true;
default:
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;
}
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 {
return new FileInputStream(filePath);
}
@ -166,16 +155,4 @@ public class FileUtils {
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) {
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.IMAGE_OK;
import android.content.Context;
import fr.free.nrw.commons.media.MediaClient;
import fr.free.nrw.commons.nearby.Place;
import fr.free.nrw.commons.utils.ImageUtils;
@ -30,9 +29,9 @@ public class ImageProcessingService {
@Inject
public ImageProcessingService(FileUtilsWrapper fileUtilsWrapper,
ImageUtilsWrapper imageUtilsWrapper,
ReadFBMD readFBMD, EXIFReader EXIFReader,
MediaClient mediaClient, Context context) {
ImageUtilsWrapper imageUtilsWrapper,
ReadFBMD readFBMD, EXIFReader EXIFReader,
MediaClient mediaClient) {
this.fileUtilsWrapper = fileUtilsWrapper;
this.imageUtilsWrapper = imageUtilsWrapper;
this.readFBMD = readFBMD;

View file

@ -8,7 +8,6 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
@ -30,10 +29,6 @@ public class SimilarImageDialogFragment extends DialogFragment {
SimpleDraweeView originalImage;
@BindView(R.id.possibleImage)
SimpleDraweeView possibleImage;
@BindView(R.id.postive_button)
Button positiveButton;
@BindView(R.id.negative_button)
Button negativeButton;
Callback callback;//Implemented interface from shareActivity
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.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
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.util.ArrayList;
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.
*/
@ -69,8 +64,6 @@ class ThumbnailsAdapter extends RecyclerView.Adapter<ThumbnailsAdapter.ViewHolde
RelativeLayout rlContainer;
@BindView(R.id.iv_thumbnail)
SimpleDraweeView background;
@BindView(R.id.iv_error)
ImageView ivError;
public ViewHolder(@NonNull View itemView) {
super(itemView);

View file

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

View file

@ -55,10 +55,9 @@ public class UploadClient {
}
}
Observable<UploadResult> uploadFileFromStash(Context context,
Contribution contribution,
String uniqueFileName,
String fileKey) {
Observable<UploadResult> uploadFileFromStash(Contribution contribution,
String uniqueFileName,
String fileKey) {
try {
return uploadInterface
.uploadFileFromStash(csrfTokenClient.getTokenBlocking(),

View file

@ -67,15 +67,6 @@ public class UploadMediaDetailAdapter extends RecyclerView.Adapter<UploadMediaDe
return uploadMediaDetails.size();
}
/**
* Gets descriptions
*
* @return List of descriptions
*/
public List<UploadMediaDetail> getUploadMediaDetails() {
return uploadMediaDetails;
}
public void addDescription(UploadMediaDetail uploadMediaDetail) {
this.uploadMediaDetails.add(uploadMediaDetail);
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.CommonsDaggerService;
import fr.free.nrw.commons.media.MediaClient;
import fr.free.nrw.commons.utils.CommonsDateUtil;
import fr.free.nrw.commons.wikidata.WikidataEditService;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.Single;
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.schedulers.Schedulers;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
@ -275,7 +267,6 @@ public class UploadService extends CommonsDaggerService {
String uniqueFilename = findUniqueFilename(filename);
unfinishedUploads.add(uniqueFilename);
return uploadClient.uploadFileFromStash(
getApplicationContext(),
contribution,
uniqueFilename,
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> {
/**
* Takes to previous screen
*/
void onPreviousButtonClicked();
/**
* Listener for the depicted items selected from the list
*/

View file

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

View file

@ -16,17 +16,17 @@ public interface UploadMediaDetailsContract {
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 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);

View file

@ -85,7 +85,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
.observeOn(mainThreadScheduler)
.subscribe(uploadItem ->
{
view.onImageProcessed(uploadItem, place);
view.onImageProcessed(uploadItem);
view.updateMediaDetails(uploadItem.getUploadMediaDetails());
ImageCoordinates gpsCoords = uploadItem.getGpsCoords();
final boolean hasImageCoordinates =
@ -111,7 +111,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
.observeOn(mainThreadScheduler)
.subscribe(place -> {
if (place != null) {
view.onNearbyPlaceFound(uploadItem, place);
view.onNearbyPlaceFound(place);
}
},
throwable -> Timber.e(throwable, "Error occurred in processing images"));
@ -138,8 +138,8 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
},
throwable -> {
view.showProgress(false);
view.showMessage("" + throwable.getLocalizedMessage(),
R.color.color_error);
view.showMessage("" + throwable.getLocalizedMessage()
);
Timber.e(throwable, "Error occurred while handling image");
})
);
@ -159,7 +159,7 @@ public class UploadMediaPresenter implements UserActionListener, SimilarImageInt
currentUploadItem.setMediaDetails(deepCopy(previousUploadItem.getUploadMediaDetails()));
view.updateMediaDetails(currentUploadItem.getUploadMediaDetails());
} 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) {
case EMPTY_CAPTION:
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;
case FILE_NAME_EXISTS:
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;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.DisplayMetrics;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import java.util.ArrayList;
import java.util.List;
@ -26,17 +22,6 @@ public class UiUtils {
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.
* 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 options = loadAttractionsFromLocationToBaseMarkerOptions(
location, null, ApplicationProvider.getApplicationContext(), null)
location, null, ApplicationProvider.getApplicationContext()
)
assertEquals(0, options.size.toLong())
}
@ -28,7 +29,8 @@ class NearbyControllerTest {
val location = LatLng(0.0, 0.0, 0f)
val options = loadAttractionsFromLocationToBaseMarkerOptions(
location, emptyList(), ApplicationProvider.getApplicationContext(), emptyList())
location, emptyList(), ApplicationProvider.getApplicationContext()
)
assertEquals(0, options.size.toLong())
}

View file

@ -27,7 +27,7 @@ class PageEditClientTest {
@Throws(Exception::class)
fun setUp() {
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 androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Completable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.*
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import java.util.concurrent.TimeUnit
/**
* The unit test class for ContributionsPresenter
@ -58,7 +51,7 @@ class ContributionsPresenterTest {
scheduler=TestScheduler()
cursor = Mockito.mock(Cursor::class.java)
contribution = Mockito.mock(Contribution::class.java)
contributionsPresenter = ContributionsPresenter(repository,scheduler,scheduler)
contributionsPresenter = ContributionsPresenter(repository, scheduler)
loader = Mockito.mock(CursorLoader::class.java)
contributionsPresenter.onAttachView(view)
liveData=MutableLiveData()

View file

@ -38,7 +38,7 @@ class DeleteHelperTest {
@Before
fun setup() {
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)
testScheduler.triggerActions()
verify(view).onImageProcessed(
ArgumentMatchers.any(UploadItem::class.java),
ArgumentMatchers.any(Place::class.java)
ArgumentMatchers.any(UploadItem::class.java)
)
verify(view).showProgress(false)
}
@ -122,7 +121,7 @@ class UploadMediaPresenterTest {
//Empty Caption test
uploadMediaPresenter.handleImageResult(EMPTY_CAPTION, uploadItem)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())
verify(view).showMessage(ArgumentMatchers.anyInt())
//Bad Picture test
//Empty Caption test
@ -185,7 +184,7 @@ class UploadMediaPresenterTest {
whenever(repository.getPreviousUploadItem(ArgumentMatchers.anyInt()))
.thenReturn(null)
uploadMediaPresenter.fetchPreviousTitleAndDescription(0)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())
verify(view).showMessage(ArgumentMatchers.anyInt())
}
/**
@ -204,7 +203,7 @@ class UploadMediaPresenterTest {
@Test
fun handleBadImageBaseTestEmptyTitle() {
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;
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_HSPA;
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.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 void setUp() throws Exception {
}
public class NetworkUtilsTest {
@Test
public void testInternetConnectionEstablished() {

View file

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