From 00b2ee25f7627461e11bd772325a1440974db06c Mon Sep 17 00:00:00 2001 From: Federico Iosue Date: Mon, 21 Oct 2019 16:54:44 +0200 Subject: [PATCH] Code style refactoring and added instructions on how to do it on README --- README.md | 5 + .../GeocodeProviderFactory.java | 5 - .../android/omninotes/utils/Constants.java | 8 +- .../android/omninotes/AutoBackupTest.java | 421 +- .../omninotes/BaseAndroidTestCase.java | 47 +- .../android/omninotes/BaseEspressoTest.java | 189 +- .../omninotes/CategoryLifecycleTest.java | 378 +- .../android/omninotes/FabCameraNoteTest.java | 90 +- .../android/omninotes/FabLifecycleTest.java | 97 +- .../omninotes/RemindersLifecycleTest.java | 136 +- .../android/omninotes/db/DbHelperTest.java | 68 +- .../helpers/AppVersionHelperTest.java | 100 +- .../omninotes/helpers/BackupHelperTest.java | 159 +- .../omninotes/helpers/LanguageHelperTest.java | 118 +- .../helpers/count/CountFactoryTest.java | 55 +- .../omninotes/utils/GeocodeHelperTest.java | 2 +- .../omninotes/utils/ParcelableUtilTest.java | 52 +- .../omninotes/utils/ReminderHelperTest.java | 97 +- .../android/omninotes/utils/SecurityTest.java | 52 +- .../omninotes/utils/date/DateHelperTest.java | 37 +- .../android/omninotes/utils/Constants.java | 8 +- .../helpers/GeocodeProviderFactory.java | 7 +- .../android/omninotes/utils/Constants.java | 2 +- .../GeocodeProviderBaseFactory.java | 7 +- .../feio/android/omninotes/AboutActivity.java | 48 +- .../feio/android/omninotes/BaseActivity.java | 280 +- .../feio/android/omninotes/BaseFragment.java | 37 +- .../android/omninotes/CategoryActivity.java | 299 +- .../android/omninotes/DetailFragment.java | 4322 +++++++++-------- .../omninotes/FontSizeListPreference.java | 101 +- .../android/omninotes/GalleryActivity.java | 310 +- .../feio/android/omninotes/ListFragment.java | 3220 ++++++------ .../feio/android/omninotes/MainActivity.java | 903 ++-- .../omninotes/NavigationDrawerFragment.java | 304 +- .../android/omninotes/NoteInfosActivity.java | 117 +- .../it/feio/android/omninotes/OmniNotes.java | 186 +- .../android/omninotes/PasswordActivity.java | 400 +- .../android/omninotes/SettingsActivity.java | 168 +- .../android/omninotes/SettingsFragment.java | 1265 +++-- .../android/omninotes/ShortcutActivity.java | 29 +- .../android/omninotes/SketchFragment.java | 525 +- .../android/omninotes/SnoozeActivity.java | 225 +- .../feio/android/omninotes/StatsActivity.java | 107 +- .../async/AlarmRestoreOnRebootService.java | 34 +- .../omninotes/async/AttachmentTask.java | 77 +- .../omninotes/async/CategoryMenuTask.java | 210 +- .../async/DataBackupIntentService.java | 254 +- .../android/omninotes/async/MainMenuTask.java | 186 +- .../omninotes/async/TextWorkerTask.java | 94 +- .../omninotes/async/UpdateWidgetsTask.java | 35 +- .../android/omninotes/async/UpdaterTask.java | 349 +- .../async/bus/NavigationUpdatedEvent.java | 10 +- ...NavigationUpdatedNavDrawerClosedEvent.java | 10 +- .../async/bus/NotesDeletedEvent.java | 13 +- .../omninotes/async/bus/NotesLoadedEvent.java | 13 +- .../omninotes/async/bus/NotesMergeEvent.java | 10 +- .../async/bus/NotesUpdatedEvent.java | 13 +- .../async/bus/NotificationRemovedEvent.java | 11 +- .../async/bus/PasswordRemovedEvent.java | 6 +- .../async/bus/PushbulletReplyEvent.java | 10 +- .../async/bus/SwitchFragmentEvent.java | 16 +- .../omninotes/async/notes/NoteLoaderTask.java | 121 +- .../omninotes/async/notes/NoteProcessor.java | 53 +- .../async/notes/NoteProcessorArchive.java | 21 +- .../async/notes/NoteProcessorCategorize.java | 23 +- .../async/notes/NoteProcessorDelete.java | 45 +- .../async/notes/NoteProcessorTrash.java | 31 +- .../omninotes/async/notes/SaveNoteTask.java | 136 +- .../async/upgrade/UpgradeProcessor.java | 255 +- .../feio/android/omninotes/db/DbHelper.java | 1858 +++---- .../feio/android/omninotes/db/SqlParser.java | 159 +- .../omninotes/exceptions/BackupException.java | 8 +- .../exceptions/GenericException.java | 6 +- .../exceptions/NotesLoadingException.java | 8 +- .../extensions/ONDashClockExtension.java | 176 +- .../extensions/PushBulletExtension.java | 23 +- .../omninotes/factory/MediaStoreFactory.java | 24 +- .../omninotes/helpers/AppVersionHelper.java | 58 +- .../omninotes/helpers/AttachmentsHelper.java | 57 +- .../omninotes/helpers/BackupHelper.java | 620 +-- .../omninotes/helpers/LanguageHelper.java | 113 +- .../omninotes/helpers/LogDelegate.java | 129 +- .../omninotes/helpers/NotesHelper.java | 275 +- .../omninotes/helpers/PermissionsHelper.java | 66 +- .../omninotes/helpers/SpringImportHelper.java | 543 +-- .../omninotes/helpers/count/CountFactory.java | 34 +- .../helpers/count/DefaultWordCounter.java | 60 +- .../helpers/count/IdeogramsWordCounter.java | 24 +- .../omninotes/helpers/count/WordCounter.java | 21 +- .../omninotes/helpers/date/DateHelper.java | 281 +- .../omninotes/intro/IntroActivity.java | 58 +- .../omninotes/intro/IntroFragment.java | 33 +- .../android/omninotes/intro/IntroSlide1.java | 20 +- .../android/omninotes/intro/IntroSlide2.java | 16 +- .../android/omninotes/intro/IntroSlide3.java | 16 +- .../android/omninotes/intro/IntroSlide4.java | 16 +- .../android/omninotes/intro/IntroSlide5.java | 16 +- .../android/omninotes/intro/IntroSlide6.java | 30 +- .../android/omninotes/models/Attachment.java | 95 +- .../android/omninotes/models/Category.java | 90 +- .../omninotes/models/NavigationItem.java | 68 +- .../feio/android/omninotes/models/Note.java | 273 +- .../android/omninotes/models/ONStyle.java | 96 +- .../omninotes/models/PasswordValidator.java | 8 +- .../omninotes/models/PushBulletMessage.java | 8 +- .../feio/android/omninotes/models/Stats.java | 238 +- .../omninotes/models/StatsSingleNote.java | 218 +- .../it/feio/android/omninotes/models/Tag.java | 70 +- .../omninotes/models/UndoBarController.java | 171 +- .../models/adapters/AttachmentAdapter.java | 175 +- .../models/adapters/ImageAndTextAdapter.java | 101 +- .../models/adapters/NavDrawerAdapter.java | 144 +- .../adapters/NavDrawerCategoryAdapter.java | 199 +- .../models/adapters/NoteAdapter.java | 441 +- .../adapters/PlacesAutoCompleteAdapter.java | 77 +- .../models/holders/ImageAndTextItem.java | 38 +- .../models/holders/NoteViewHolder.java | 48 +- .../listeners/AbsListViewScrollDetector.java | 90 +- .../listeners/OnAttachingFileListener.java | 4 +- .../listeners/OnCABItemClickedListener.java | 2 +- .../listeners/OnDrawChangedListener.java | 2 +- .../listeners/OnFabItemClickedListener.java | 2 +- .../listeners/OnGeoUtilResultListener.java | 8 +- .../models/listeners/OnNoteSaved.java | 2 +- .../OnPermissionRequestedListener.java | 2 +- .../listeners/OnReminderPickedListener.java | 4 +- .../listeners/OnViewTouchedListener.java | 2 +- .../misc/DynamicNavigationLookupTable.java | 99 +- .../misc/PlayStoreMetadataFetcherResult.java | 108 +- .../views/ExpandableHeightGridView.java | 65 +- .../android/omninotes/models/views/Fab.java | 308 +- .../models/views/InterceptorFrameLayout.java | 33 +- .../models/views/InterceptorLinearLayout.java | 33 +- .../models/views/NonScrollableListView.java | 52 +- .../omninotes/models/views/SketchView.java | 397 +- .../models/views/SquareImageView.java | 51 +- .../models/views/VerticalSeekBar.java | 154 +- .../omninotes/receiver/AlarmReceiver.java | 195 +- .../receiver/BootCompleteReceiver.java | 13 +- .../services/NotificationListener.java | 69 +- .../android/omninotes/utils/AlphaManager.java | 14 +- .../omninotes/utils/AnimationsHelper.java | 174 +- .../android/omninotes/utils/AssetUtils.java | 31 +- .../android/omninotes/utils/BitmapHelper.java | 135 +- .../android/omninotes/utils/ColorsUtil.java | 20 +- .../omninotes/utils/ConnectionManager.java | 20 +- .../omninotes/utils/ConstantsBase.java | 216 +- .../feio/android/omninotes/utils/Display.java | 188 +- .../android/omninotes/utils/FileHelper.java | 355 +- .../omninotes/utils/FileProviderHelper.java | 37 +- .../feio/android/omninotes/utils/Fonts.java | 55 +- .../omninotes/utils/GeocodeHelper.java | 404 +- .../omninotes/utils/IntentChecker.java | 101 +- .../omninotes/utils/KeyboardUtils.java | 67 +- .../omninotes/utils/LoadingDialog.java | 20 +- .../android/omninotes/utils/MiscUtils.java | 41 +- .../android/omninotes/utils/Navigation.java | 161 +- .../omninotes/utils/ParcelableUtil.java | 47 +- .../omninotes/utils/PasswordHelper.java | 230 +- .../omninotes/utils/ReminderHelper.java | 121 +- .../omninotes/utils/ResourcesUtils.java | 8 +- .../android/omninotes/utils/Security.java | 129 +- .../omninotes/utils/ShortcutHelper.java | 106 +- .../omninotes/utils/StorageHelper.java | 811 ++-- .../android/omninotes/utils/SystemHelper.java | 55 +- .../android/omninotes/utils/TagsHelper.java | 207 +- .../android/omninotes/utils/TextHelper.java | 226 +- .../utils/date/DatePickerDialogFragment.java | 139 +- .../omninotes/utils/date/DateUtils.java | 304 +- .../omninotes/utils/date/ReminderPickers.java | 246 +- .../utils/date/TimePickerFragment.java | 60 +- .../notifications/NotificationChannel.java | 16 +- .../notifications/NotificationChannels.java | 38 +- .../notifications/NotificationsHelper.java | 302 +- .../widget/ListRemoteViewsFactory.java | 284 +- .../omninotes/widget/ListWidgetProvider.java | 85 +- .../omninotes/widget/ListWidgetService.java | 8 +- .../widget/SimpleWidgetProvider.java | 29 +- .../widget/WidgetConfigurationActivity.java | 172 +- .../omninotes/widget/WidgetProvider.java | 142 +- .../helpers/GeocodeProviderFactory.java | 7 +- .../feio/android/omninotes/BaseUnitTest.java | 14 +- .../android/omninotes/ResourceAwareTest.java | 24 +- .../omninotes/helpers/NotesHelperTest.java | 99 +- .../helpers/count/DefaultWordCounterTest.java | 69 +- .../count/IdeogramsWordCounterTest.java | 69 +- .../omninotes/utils/TagsHelperTest.java | 144 +- .../omninotes/utils/date/DateUtilsTest.java | 111 +- 188 files changed, 16105 insertions(+), 16259 deletions(-) diff --git a/README.md b/README.md index 466dcb16f3..1e46ed4263 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,11 @@ Feel free to add yourself to [contributors.md](https://github.com/federicoiosue/ This kind of contributions **must** have screenshots or screencast as demonstration of the new additions. +### Code style + +If you plan to manipulate the code then you'll have to do it by following a [specific code style](https://gist.github.com/federicoiosue/dee53e882b3c70d544f8608769eb02fc). +Also pay attention if you're using any plugin that automatically formats/cleans/rearrange your code and set it to only change that code that you touched and not the whole files. + ### Test your code contributions! All code changes and additions **must** be tested. diff --git a/omniNotes/src/alpha/java/it.feio.android.omninotes.helpers/GeocodeProviderFactory.java b/omniNotes/src/alpha/java/it.feio.android.omninotes.helpers/GeocodeProviderFactory.java index c55bdab78b..d4d8a58eb3 100644 --- a/omniNotes/src/alpha/java/it.feio.android.omninotes.helpers/GeocodeProviderFactory.java +++ b/omniNotes/src/alpha/java/it.feio.android.omninotes.helpers/GeocodeProviderFactory.java @@ -17,11 +17,6 @@ package it.feio.android.omninotes.helpers; -import android.content.Context; - -import io.nlopez.smartlocation.location.LocationProvider; - - public class GeocodeProviderFactory extends GeocodeProviderBaseFactory { } \ No newline at end of file diff --git a/omniNotes/src/alpha/java/it/feio/android/omninotes/utils/Constants.java b/omniNotes/src/alpha/java/it/feio/android/omninotes/utils/Constants.java index 06fe182576..115ee7bc63 100644 --- a/omniNotes/src/alpha/java/it/feio/android/omninotes/utils/Constants.java +++ b/omniNotes/src/alpha/java/it/feio/android/omninotes/utils/Constants.java @@ -3,9 +3,9 @@ public interface Constants extends ConstantsBase { - String TAG = "Omni Notes Alpha"; - String EXTERNAL_STORAGE_FOLDER = "Omni Notes Alpha"; - String PACKAGE = "it.feio.android.omninotes.alpha"; - String PREFS_NAME = PACKAGE + "_preferences"; + String TAG = "Omni Notes Alpha"; + String EXTERNAL_STORAGE_FOLDER = "Omni Notes Alpha"; + String PACKAGE = "it.feio.android.omninotes.alpha"; + String PREFS_NAME = PACKAGE + "_preferences"; } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/AutoBackupTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/AutoBackupTest.java index 012134aeb8..3c83ab5586 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/AutoBackupTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/AutoBackupTest.java @@ -17,27 +17,6 @@ package it.feio.android.omninotes; -import android.support.test.espresso.ViewInteraction; -import android.support.test.filters.LargeTest; -import android.support.test.runner.AndroidJUnit4; - -import org.apache.commons.io.FileUtils; -import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.File; -import java.util.LinkedList; -import java.util.List; - -import it.feio.android.omninotes.helpers.BackupHelper; -import it.feio.android.omninotes.models.Note; -import it.feio.android.omninotes.utils.Constants; -import it.feio.android.omninotes.utils.ConstantsBase; -import it.feio.android.omninotes.utils.StorageHelper; - import static android.support.test.espresso.Espresso.onData; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; @@ -57,222 +36,240 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import android.support.test.espresso.ViewInteraction; +import android.support.test.filters.LargeTest; +import android.support.test.runner.AndroidJUnit4; +import it.feio.android.omninotes.helpers.BackupHelper; +import it.feio.android.omninotes.models.Note; +import it.feio.android.omninotes.utils.Constants; +import it.feio.android.omninotes.utils.ConstantsBase; +import it.feio.android.omninotes.utils.StorageHelper; +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import org.apache.commons.io.FileUtils; +import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + @LargeTest @RunWith(AndroidJUnit4.class) public class AutoBackupTest extends BaseEspressoTest { - @Before - @Override - public void setUp() throws Exception { - super.setUp(); - prefs.edit().putBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false).apply(); + @Before + @Override + public void setUp () throws Exception { + super.setUp(); + prefs.edit().putBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false).apply(); + } + + @After + public void tearDown () throws Exception { + File backupFolder = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); + FileUtils.deleteDirectory(backupFolder); + } + + @Test + public void autoBackupPreferenceActivation () { + assertFalse(prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)); + autoBackupActivationFromPreferences(); + assertTrue(prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)); + } + + @Test + public void autoBackupWithNotesCheck () throws InterruptedException { + createNote("A Title", "A content"); + enableAutobackup(); + createNote("B Title", "B content"); + + // Waiting a little to ensure background service completes auto backup + Thread.sleep(2000); + + List currentNotes = dbHelper.getAllNotes(false); + assertEquals(2, currentNotes.size()); + for (Note currentNote : currentNotes) { + File backupNoteFile = BackupHelper.getBackupNoteFile(StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR) + , currentNote); + assertTrue(backupNoteFile.exists()); + Note backupNote = BackupHelper.getImportNote(backupNoteFile); + assertEquals(backupNote, currentNote); } - @After - public void tearDown() throws Exception { - File backupFolder = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); - FileUtils.deleteDirectory(backupFolder); - } + } - @Test - public void autoBackupPreferenceActivation() { - assertFalse(prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)); - autoBackupActivationFromPreferences(); - assertTrue(prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)); - } - - @Test - public void autoBackupWithNotesCheck() throws InterruptedException { - createNote("A Title", "A content"); - enableAutobackup(); - createNote("B Title", "B content"); - - // Waiting a little to ensure background service completes auto backup - Thread.sleep(2000); - - List currentNotes = dbHelper.getAllNotes(false); - assertEquals(2, currentNotes.size()); - for (Note currentNote : currentNotes) { - File backupNoteFile = BackupHelper.getBackupNoteFile(StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR) - , currentNote); - assertTrue(backupNoteFile.exists()); - Note backupNote = BackupHelper.getImportNote(backupNoteFile); - assertEquals(backupNote, currentNote); - } - - } - - @Test - public void everyUpdateToNotesShouldTriggerAutobackup() throws InterruptedException { - - enableAutobackup(); - - createNote("C Title", "C content"); - - assertAutobackupIsCorrect(); - - // Category addition - - onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).perform(click()); + @Test + public void everyUpdateToNotesShouldTriggerAutobackup () throws InterruptedException { - onView(allOf(withId(R.id.menu_category), withContentDescription(R.string.category), - childAtPosition( - childAtPosition( - withId(R.id.toolbar), - 1), - 1), - isDisplayed())).perform(click()); - - onView(allOf(withId(R.id.buttonDefaultPositive), withText(R.string.add_category), - childAtPosition( - childAtPosition( - withId(android.R.id.content), - 0), - 4), - isDisplayed())).perform(click()); - - onView(allOf(withId(R.id.category_title), - childAtPosition( - childAtPosition( - withId(android.R.id.content), - 0), - 0), - isDisplayed())).perform(replaceText("cat1"), closeSoftKeyboard()); + enableAutobackup(); - onView(allOf(withId(R.id.save), withText("Ok"), isDisplayed())).perform(click()); + createNote("C Title", "C content"); - navigateUp(); + assertAutobackupIsCorrect(); - assertAutobackupIsCorrect(); + // Category addition - // Reminder addition + onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).perform(click()); - onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).perform(click()); + onView(allOf(withId(R.id.menu_category), withContentDescription(R.string.category), + childAtPosition( + childAtPosition( + withId(R.id.toolbar), + 1), + 1), + isDisplayed())).perform(click()); - onView(allOf(withId(R.id.reminder_layout), - childAtPosition( - childAtPosition( - withClassName(is("android.widget.LinearLayout")), - 1), - 2))).perform(scrollTo(), click()); + onView(allOf(withId(R.id.buttonDefaultPositive), withText(R.string.add_category), + childAtPosition( + childAtPosition( + withId(android.R.id.content), + 0), + 4), + isDisplayed())).perform(click()); - onView(allOf(withId(R.id.done), - childAtPosition( - childAtPosition( - withClassName(is("android.widget.LinearLayout")), - 3), - 0), - isDisplayed())).perform(click()); + onView(allOf(withId(R.id.category_title), + childAtPosition( + childAtPosition( + withId(android.R.id.content), + 0), + 0), + isDisplayed())).perform(replaceText("cat1"), closeSoftKeyboard()); - onView(allOf(withId(R.id.done_button), - childAtPosition( - childAtPosition( - withId(R.id.time_picker_dialog), - 3), - 0), - isDisplayed())).perform(click()); + onView(allOf(withId(R.id.save), withText("Ok"), isDisplayed())).perform(click()); - onView(allOf(withId(R.id.done), - childAtPosition( - childAtPosition( - withClassName(is("android.widget.LinearLayout")), - 2), - 0), - isDisplayed())).perform(click()); + navigateUp(); - navigateUp(); + assertAutobackupIsCorrect(); - assertAutobackupIsCorrect(); + // Reminder addition - onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).perform(click()); + onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).perform(click()); - onView(allOf(withId(R.id.menu_attachment), - childAtPosition( - childAtPosition( - withId(R.id.toolbar), - 1), - 0), - isDisplayed())).perform(click()); + onView(allOf(withId(R.id.reminder_layout), + childAtPosition( + childAtPosition( + withClassName(is("android.widget.LinearLayout")), + 1), + 2))).perform(scrollTo(), click()); + + onView(allOf(withId(R.id.done), + childAtPosition( + childAtPosition( + withClassName(is("android.widget.LinearLayout")), + 3), + 0), + isDisplayed())).perform(click()); + + onView(allOf(withId(R.id.done_button), + childAtPosition( + childAtPosition( + withId(R.id.time_picker_dialog), + 3), + 0), + isDisplayed())).perform(click()); + + onView(allOf(withId(R.id.done), + childAtPosition( + childAtPosition( + withClassName(is("android.widget.LinearLayout")), + 2), + 0), + isDisplayed())).perform(click()); + + navigateUp(); + + assertAutobackupIsCorrect(); + + onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).perform(click()); + + onView(allOf(withId(R.id.menu_attachment), + childAtPosition( + childAtPosition( + withId(R.id.toolbar), + 1), + 0), + isDisplayed())).perform(click()); - onView(allOf(withId(R.id.recording), withText(R.string.record), + onView(allOf(withId(R.id.recording), withText(R.string.record), + childAtPosition( + allOf(withId(R.id.attachment_dialog_root), childAtPosition( - allOf(withId(R.id.attachment_dialog_root), - childAtPosition( - withId(R.id.customViewFrame), - 0)), - 3), - isDisplayed())).perform(click()); + withId(R.id.customViewFrame), + 0)), + 3), + isDisplayed())).perform(click()); - Thread.sleep(1000); + Thread.sleep(1000); - onView(allOf(withId(R.id.recording), + onView(allOf(withId(R.id.recording), + childAtPosition( + allOf(withId(R.id.attachment_dialog_root), childAtPosition( - allOf(withId(R.id.attachment_dialog_root), - childAtPosition( - withId(R.id.customViewFrame), - 0)), - 3), - isDisplayed())).perform(click()); - - navigateUp(); - navigateUp(); - - assertAutobackupIsCorrect(); - - } - - private void enableAutobackup() { - prefs.edit().putBoolean(Constants.PREF_ENABLE_AUTOBACKUP, true).apply(); - BackupHelper.startBackupService(Constants.AUTO_BACKUP_DIR); - } - - private void assertAutobackupIsCorrect() { - List> autobackupDifferences = BackupHelper - .integrityCheck(StorageHelper.getBackupDir(ConstantsBase.AUTO_BACKUP_DIR)); - assertEquals(0, autobackupDifferences.size()); - - } - - private void autoBackupActivationFromPreferences() { - - onView(allOf(childAtPosition(allOf(withId(R.id.toolbar), - childAtPosition( - withClassName(is("android.widget.RelativeLayout")), - 0)), - 1), - isDisplayed())).perform(click()); - - getSettingsMenuItemView() - .perform(scrollTo(), click()); - - onView(allOf(childAtPosition( - allOf(withId(android.R.id.list), - withParent(withClassName(is("android.widget.FrameLayout")))), - 1), isDisplayed())) - .perform(click()); - - onView(allOf(childAtPosition( - allOf(withId(android.R.id.list), - withParent(withClassName(is("android.widget.FrameLayout")))), - 0), isDisplayed())) - .perform(click()); - - onView(allOf(childAtPosition( - allOf(withId(android.R.id.list), - withParent(withClassName(is("android.widget.FrameLayout")))), - 4), - isDisplayed())).perform(click()); - - onView(allOf(withId(R.id.buttonDefaultPositive), isDisplayed())).perform(click()); - - navigateUpSettings(); - navigateUpSettings(); - navigateUpSettings(); - } - - private ViewInteraction getSettingsMenuItemView() { - boolean existsAtLeastOneCategory = dbHelper.getCategories().size() > 0; - return existsAtLeastOneCategory ? onView(withId(R.id.drawer_tag_list)) : onView(withId(R.id.settings_view)); - } + withId(R.id.customViewFrame), + 0)), + 3), + isDisplayed())).perform(click()); + + navigateUp(); + navigateUp(); + + assertAutobackupIsCorrect(); + + } + + private void enableAutobackup () { + prefs.edit().putBoolean(Constants.PREF_ENABLE_AUTOBACKUP, true).apply(); + BackupHelper.startBackupService(Constants.AUTO_BACKUP_DIR); + } + + private void assertAutobackupIsCorrect () { + List> autobackupDifferences = BackupHelper + .integrityCheck(StorageHelper.getBackupDir(ConstantsBase.AUTO_BACKUP_DIR)); + assertEquals(0, autobackupDifferences.size()); + + } + + private void autoBackupActivationFromPreferences () { + + onView(allOf(childAtPosition(allOf(withId(R.id.toolbar), + childAtPosition( + withClassName(is("android.widget.RelativeLayout")), + 0)), + 1), + isDisplayed())).perform(click()); + + getSettingsMenuItemView() + .perform(scrollTo(), click()); + + onView(allOf(childAtPosition( + allOf(withId(android.R.id.list), + withParent(withClassName(is("android.widget.FrameLayout")))), + 1), isDisplayed())) + .perform(click()); + + onView(allOf(childAtPosition( + allOf(withId(android.R.id.list), + withParent(withClassName(is("android.widget.FrameLayout")))), + 0), isDisplayed())) + .perform(click()); + + onView(allOf(childAtPosition( + allOf(withId(android.R.id.list), + withParent(withClassName(is("android.widget.FrameLayout")))), + 4), + isDisplayed())).perform(click()); + + onView(allOf(withId(R.id.buttonDefaultPositive), isDisplayed())).perform(click()); + + navigateUpSettings(); + navigateUpSettings(); + navigateUpSettings(); + } + + private ViewInteraction getSettingsMenuItemView () { + boolean existsAtLeastOneCategory = dbHelper.getCategories().size() > 0; + return existsAtLeastOneCategory ? onView(withId(R.id.drawer_tag_list)) : onView(withId(R.id.settings_view)); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseAndroidTestCase.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseAndroidTestCase.java index 01ee09f75c..26ca8a8924 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseAndroidTestCase.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseAndroidTestCase.java @@ -18,7 +18,6 @@ package it.feio.android.omninotes; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import android.content.Context; import android.content.SharedPreferences; @@ -31,35 +30,35 @@ public class BaseAndroidTestCase { - private final static String DB_PATH_REGEX = ".*it\\.feio\\.android\\.omninotes.*\\/databases\\/test_omni-notes.*"; - private final static String DB_PREFIX = "test_"; + private final static String DB_PATH_REGEX = ".*it\\.feio\\.android\\.omninotes.*\\/databases\\/test_omni-notes.*"; + private final static String DB_PREFIX = "test_"; - protected static DbHelper dbHelper; - protected static Context testContext; - protected static SharedPreferences prefs; + protected static DbHelper dbHelper; + protected static Context testContext; + protected static SharedPreferences prefs; - @BeforeClass - public static void setUpBeforeClass() { - testContext = InstrumentationRegistry.getTargetContext(); - prefs = testContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - dbHelper = DbHelper.getInstance(testContext); - prefs = testContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); + @BeforeClass + public static void setUpBeforeClass () { + testContext = InstrumentationRegistry.getTargetContext(); + prefs = testContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + dbHelper = DbHelper.getInstance(testContext); + prefs = testContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); // assertTrue("Database used for tests MUST not be the default one but prefixed by '" + DB_PREFIX + "'", dbHelper // .getDatabase().getPath().matches(DB_PATH_REGEX)); - assertFalse("Database MUST be writable", dbHelper.getDatabase().isReadOnly()); - cleanDatabase(); - } + assertFalse("Database MUST be writable", dbHelper.getDatabase().isReadOnly()); + cleanDatabase(); + } - @AfterClass - public static void tearDownAfterClass() { - testContext.deleteDatabase(DbHelper.getInstance().getDatabaseName()); - } + @AfterClass + public static void tearDownAfterClass () { + testContext.deleteDatabase(DbHelper.getInstance().getDatabaseName()); + } - private static void cleanDatabase() { - dbHelper.getDatabase(true).delete(DbHelper.TABLE_NOTES, null, null); - dbHelper.getDatabase(true).delete(DbHelper.TABLE_CATEGORY, null, null); - dbHelper.getDatabase(true).delete(DbHelper.TABLE_ATTACHMENTS, null, null); - } + private static void cleanDatabase () { + dbHelper.getDatabase(true).delete(DbHelper.TABLE_NOTES, null, null); + dbHelper.getDatabase(true).delete(DbHelper.TABLE_CATEGORY, null, null); + dbHelper.getDatabase(true).delete(DbHelper.TABLE_ATTACHMENTS, null, null); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseEspressoTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseEspressoTest.java index e9a112f1dd..77005e478f 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseEspressoTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/BaseEspressoTest.java @@ -18,6 +18,19 @@ package it.feio.android.omninotes; +import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.action.ViewActions.click; +import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; +import static android.support.test.espresso.action.ViewActions.replaceText; +import static android.support.test.espresso.action.ViewActions.scrollTo; +import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; +import static android.support.test.espresso.matcher.ViewMatchers.withClassName; +import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription; +import static android.support.test.espresso.matcher.ViewMatchers.withId; +import static android.support.test.espresso.matcher.ViewMatchers.withParent; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.is; + import android.Manifest; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; @@ -26,110 +39,96 @@ import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; - import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Before; import org.junit.Rule; -import static android.support.test.espresso.Espresso.onView; -import static android.support.test.espresso.action.ViewActions.click; -import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; -import static android.support.test.espresso.action.ViewActions.replaceText; -import static android.support.test.espresso.action.ViewActions.scrollTo; -import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; -import static android.support.test.espresso.matcher.ViewMatchers.withClassName; -import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription; -import static android.support.test.espresso.matcher.ViewMatchers.withId; -import static android.support.test.espresso.matcher.ViewMatchers.withParent; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.is; - public class BaseEspressoTest extends BaseAndroidTestCase { - @Rule - public GrantPermissionRule permissionRule = GrantPermissionRule.grant( - Manifest.permission.ACCESS_COARSE_LOCATION, - Manifest.permission.READ_EXTERNAL_STORAGE, - Manifest.permission.WRITE_EXTERNAL_STORAGE, - Manifest.permission.RECORD_AUDIO - ); - - @Rule - public ActivityTestRule activityRule = new ActivityTestRule<>(MainActivity.class, false, false); - - static Matcher childAtPosition( - final Matcher parentMatcher, final int position) { - - return new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("Child at position " + position + " in parent "); - parentMatcher.describeTo(description); - } - - - @Override - public boolean matchesSafely(View view) { - ViewParent parent = view.getParent(); - return parent instanceof ViewGroup && parentMatcher.matches(parent) - && view.equals(((ViewGroup) parent).getChildAt(position)); - } - }; - } - - @Before - public void setUp() throws Exception { - activityRule.launchActivity(null); - } - - void createNote(String title, String content) { - ViewInteraction viewInteraction = onView( - allOf(withId(R.id.fab_expand_menu_button), - withParent(withId(R.id.fab)), - isDisplayed())); - - if (activityRule.getActivity().getDrawerLayout().isDrawerOpen(GravityCompat.START)) { - viewInteraction.perform(click()); - } - viewInteraction.perform(click()); - - ViewInteraction floatingActionButton = onView( - allOf(withId(R.id.fab_note), - withParent(withId(R.id.fab)), - isDisplayed())); - floatingActionButton.perform(click()); - - ViewInteraction editText = onView( - allOf(withId(R.id.detail_title), - withParent(allOf(withId(R.id.title_wrapper), - withParent(withId(R.id.detail_tile_card)))), - isDisplayed())); - editText.perform(click()); - - onView(allOf(withId(R.id.detail_title), - withParent(allOf(withId(R.id.title_wrapper), - withParent(withId(R.id.detail_tile_card)))), - isDisplayed())).perform(replaceText(title), closeSoftKeyboard()); - - onView(withId(R.id.detail_content)).perform(scrollTo(), replaceText(content), closeSoftKeyboard()); - - navigateUp(); - } - - void navigateUp() { - onView(allOf(childAtPosition(allOf(withId(R.id.toolbar), - childAtPosition(withClassName(is("android.widget.RelativeLayout")), 0) - ), 0), isDisplayed())).perform(click()); - } - - void navigateUpSettings() { - onView(allOf(withContentDescription(R.string.abc_action_bar_up_description), - childAtPosition(allOf(withId(R.id.toolbar), - childAtPosition(withClassName(is("android.widget.RelativeLayout")), 0)), - 1), isDisplayed())).perform(click()); + @Rule + public GrantPermissionRule permissionRule = GrantPermissionRule.grant( + Manifest.permission.ACCESS_COARSE_LOCATION, + Manifest.permission.READ_EXTERNAL_STORAGE, + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.RECORD_AUDIO + ); + + @Rule + public ActivityTestRule activityRule = new ActivityTestRule<>(MainActivity.class, false, false); + + static Matcher childAtPosition ( + final Matcher parentMatcher, final int position) { + + return new TypeSafeMatcher() { + @Override + public void describeTo (Description description) { + description.appendText("Child at position " + position + " in parent "); + parentMatcher.describeTo(description); + } + + + @Override + public boolean matchesSafely (View view) { + ViewParent parent = view.getParent(); + return parent instanceof ViewGroup && parentMatcher.matches(parent) + && view.equals(((ViewGroup) parent).getChildAt(position)); + } + }; + } + + @Before + public void setUp () throws Exception { + activityRule.launchActivity(null); + } + + void createNote (String title, String content) { + ViewInteraction viewInteraction = onView( + allOf(withId(R.id.fab_expand_menu_button), + withParent(withId(R.id.fab)), + isDisplayed())); + + if (activityRule.getActivity().getDrawerLayout().isDrawerOpen(GravityCompat.START)) { + viewInteraction.perform(click()); } + viewInteraction.perform(click()); + + ViewInteraction floatingActionButton = onView( + allOf(withId(R.id.fab_note), + withParent(withId(R.id.fab)), + isDisplayed())); + floatingActionButton.perform(click()); + + ViewInteraction editText = onView( + allOf(withId(R.id.detail_title), + withParent(allOf(withId(R.id.title_wrapper), + withParent(withId(R.id.detail_tile_card)))), + isDisplayed())); + editText.perform(click()); + + onView(allOf(withId(R.id.detail_title), + withParent(allOf(withId(R.id.title_wrapper), + withParent(withId(R.id.detail_tile_card)))), + isDisplayed())).perform(replaceText(title), closeSoftKeyboard()); + + onView(withId(R.id.detail_content)).perform(scrollTo(), replaceText(content), closeSoftKeyboard()); + + navigateUp(); + } + + void navigateUp () { + onView(allOf(childAtPosition(allOf(withId(R.id.toolbar), + childAtPosition(withClassName(is("android.widget.RelativeLayout")), 0) + ), 0), isDisplayed())).perform(click()); + } + + void navigateUpSettings () { + onView(allOf(withContentDescription(R.string.abc_action_bar_up_description), + childAtPosition(allOf(withId(R.id.toolbar), + childAtPosition(withClassName(is("android.widget.RelativeLayout")), 0)), + 1), isDisplayed())).perform(click()); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/CategoryLifecycleTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/CategoryLifecycleTest.java index d24b007608..6b5b5861e1 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/CategoryLifecycleTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/CategoryLifecycleTest.java @@ -18,6 +18,21 @@ package it.feio.android.omninotes; +import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.action.ViewActions.click; +import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; +import static android.support.test.espresso.action.ViewActions.longClick; +import static android.support.test.espresso.action.ViewActions.replaceText; +import static android.support.test.espresso.action.ViewActions.scrollTo; +import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist; +import static android.support.test.espresso.assertion.ViewAssertions.matches; +import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; +import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription; +import static android.support.test.espresso.matcher.ViewMatchers.withId; +import static android.support.test.espresso.matcher.ViewMatchers.withParent; +import static android.support.test.espresso.matcher.ViewMatchers.withText; +import static org.hamcrest.Matchers.allOf; + import android.annotation.TargetApi; import android.graphics.Color; import android.graphics.ColorFilter; @@ -29,212 +44,195 @@ import android.support.test.runner.AndroidJUnit4; import android.support.v7.widget.AppCompatImageView; import android.view.View; - +import java.util.Calendar; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Test; import org.junit.runner.RunWith; -import java.util.Calendar; - -import static android.support.test.espresso.Espresso.onView; -import static android.support.test.espresso.action.ViewActions.click; -import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; -import static android.support.test.espresso.action.ViewActions.longClick; -import static android.support.test.espresso.action.ViewActions.replaceText; -import static android.support.test.espresso.action.ViewActions.scrollTo; -import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist; -import static android.support.test.espresso.assertion.ViewAssertions.matches; -import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; -import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription; -import static android.support.test.espresso.matcher.ViewMatchers.withId; -import static android.support.test.espresso.matcher.ViewMatchers.withParent; -import static android.support.test.espresso.matcher.ViewMatchers.withText; -import static org.hamcrest.Matchers.allOf; - @LargeTest @RunWith(AndroidJUnit4.class) public class CategoryLifecycleTest extends BaseEspressoTest { - private String categoryName; - - @Test - public void addNewCategory() { - - categoryName = "Cat_" + Calendar.getInstance().getTimeInMillis(); - - ViewInteraction viewInteraction = onView( - allOf(withId(R.id.fab_expand_menu_button), - withParent(withId(R.id.fab)), - isDisplayed())); - viewInteraction.perform(click()); - - ViewInteraction floatingActionButton = onView( - allOf(withId(R.id.fab_note), - withParent(withId(R.id.fab)), - isDisplayed())); - floatingActionButton.perform(click()); - - ViewInteraction actionMenuItemView = onView( - allOf(withId(R.id.menu_category), withContentDescription(R.string.category), isDisplayed())); - actionMenuItemView.perform(click()); - - ViewInteraction mDButton = onView( - allOf(withId(R.id.buttonDefaultPositive), withText(R.string.add_category), isDisplayed())); - mDButton.perform(click()); - - ViewInteraction appCompatEditText = onView( - allOf(withId(R.id.category_title), isDisplayed())); - appCompatEditText.perform(replaceText(categoryName), closeSoftKeyboard()); - - ViewInteraction appCompatButton = onView( - allOf(withId(R.id.save), withText("Ok"), isDisplayed())); - appCompatButton.perform(click()); - - ViewInteraction editText = onView( - allOf(withId(R.id.detail_title), - withParent(allOf(withId(R.id.title_wrapper), - withParent(withId(R.id.detail_tile_card)))), - isDisplayed())); - editText.perform(click()); - - ViewInteraction editText2 = onView( - allOf(withId(R.id.detail_title), - withParent(allOf(withId(R.id.title_wrapper), - withParent(withId(R.id.detail_tile_card)))), - isDisplayed())); - editText2.perform(replaceText("Note with new category"), closeSoftKeyboard()); - - ViewInteraction navigationUp = onView( - allOf(withContentDescription(R.string.drawer_open), - withParent(withId(R.id.toolbar)), - isDisplayed())); - navigationUp.perform(click()); - - } - - @Test - public void checkCategoryCreation() { - - addNewCategory(); - - ViewInteraction drawerToggle = onView( - allOf(withContentDescription(R.string.drawer_open), - withParent(withId(R.id.toolbar)), - isDisplayed())); - drawerToggle.perform(click()); + private String categoryName; - ViewInteraction textView = onView(allOf(withId(R.id.title), withText(categoryName))); - textView.check(matches(withText(categoryName))); - } - - @Test - public void categoryColorChange() { - - addNewCategory(); - - ViewInteraction drawerToggle = onView( - allOf(withContentDescription(R.string.drawer_open), - withParent(withId(R.id.toolbar)))); - drawerToggle.perform(click()); - - ViewInteraction categoryView = onView(allOf(withId(R.id.title), withText(categoryName))); - categoryView.perform(longClick()); - - ViewInteraction imageView = onView(allOf(withId(R.id.color_chooser), isDisplayed())); - imageView.check(matches(isDisplayed())); - - ViewInteraction appCompatImageView = onView(allOf(withId(R.id.color_chooser), isDisplayed())); - appCompatImageView.perform(click()); - - ViewInteraction mDButton2 = onView( - allOf(withId(R.id.buttonDefaultNeutral), withText("Custom"), - withParent(allOf(withId(R.id.root), - withParent(withId(android.R.id.content)))), - isDisplayed())); - mDButton2.perform(click()); - - ViewInteraction mDButton3 = onView( - allOf(withId(R.id.buttonDefaultNeutral), withText(R.string.md_presets_label), - withParent(allOf(withId(R.id.root), - withParent(withId(android.R.id.content)))), - isDisplayed())); - mDButton3.perform(click()); - - ViewInteraction circleView = onView( - childAtPosition( - withId(R.id.grid), - 18)); - circleView.perform(scrollTo(), click()); - - ViewInteraction circleView2 = onView( - childAtPosition( - withId(R.id.grid), - 9)); - circleView2.perform(scrollTo(), click()); - - ViewInteraction mDButton4 = onView( - allOf(withId(R.id.buttonDefaultPositive), withText(R.string.md_done_label), - withParent(allOf(withId(R.id.root), - withParent(withId(android.R.id.content)))), - isDisplayed())); - mDButton4.perform(click()); - - ViewInteraction appCompatImageViewColorChanged = onView(allOf(withId(R.id.color_chooser), isDisplayed())); - appCompatImageViewColorChanged.check(matches(withBackgroundColor(Color.parseColor("#FF263238")))); + @Test + public void addNewCategory () { + categoryName = "Cat_" + Calendar.getInstance().getTimeInMillis(); + + ViewInteraction viewInteraction = onView( + allOf(withId(R.id.fab_expand_menu_button), + withParent(withId(R.id.fab)), + isDisplayed())); + viewInteraction.perform(click()); + + ViewInteraction floatingActionButton = onView( + allOf(withId(R.id.fab_note), + withParent(withId(R.id.fab)), + isDisplayed())); + floatingActionButton.perform(click()); + + ViewInteraction actionMenuItemView = onView( + allOf(withId(R.id.menu_category), withContentDescription(R.string.category), isDisplayed())); + actionMenuItemView.perform(click()); + + ViewInteraction mDButton = onView( + allOf(withId(R.id.buttonDefaultPositive), withText(R.string.add_category), isDisplayed())); + mDButton.perform(click()); + + ViewInteraction appCompatEditText = onView( + allOf(withId(R.id.category_title), isDisplayed())); + appCompatEditText.perform(replaceText(categoryName), closeSoftKeyboard()); + + ViewInteraction appCompatButton = onView( + allOf(withId(R.id.save), withText("Ok"), isDisplayed())); + appCompatButton.perform(click()); + + ViewInteraction editText = onView( + allOf(withId(R.id.detail_title), + withParent(allOf(withId(R.id.title_wrapper), + withParent(withId(R.id.detail_tile_card)))), + isDisplayed())); + editText.perform(click()); + + ViewInteraction editText2 = onView( + allOf(withId(R.id.detail_title), + withParent(allOf(withId(R.id.title_wrapper), + withParent(withId(R.id.detail_tile_card)))), + isDisplayed())); + editText2.perform(replaceText("Note with new category"), closeSoftKeyboard()); + + ViewInteraction navigationUp = onView( + allOf(withContentDescription(R.string.drawer_open), + withParent(withId(R.id.toolbar)), + isDisplayed())); + navigationUp.perform(click()); + + } + + @Test + public void checkCategoryCreation () { + + addNewCategory(); + + ViewInteraction drawerToggle = onView( + allOf(withContentDescription(R.string.drawer_open), + withParent(withId(R.id.toolbar)), + isDisplayed())); + drawerToggle.perform(click()); + + ViewInteraction textView = onView(allOf(withId(R.id.title), withText(categoryName))); + textView.check(matches(withText(categoryName))); + } + + @Test + public void categoryColorChange () { + + addNewCategory(); + + ViewInteraction drawerToggle = onView( + allOf(withContentDescription(R.string.drawer_open), + withParent(withId(R.id.toolbar)))); + drawerToggle.perform(click()); + + ViewInteraction categoryView = onView(allOf(withId(R.id.title), withText(categoryName))); + categoryView.perform(longClick()); + + ViewInteraction imageView = onView(allOf(withId(R.id.color_chooser), isDisplayed())); + imageView.check(matches(isDisplayed())); + + ViewInteraction appCompatImageView = onView(allOf(withId(R.id.color_chooser), isDisplayed())); + appCompatImageView.perform(click()); + + ViewInteraction mDButton2 = onView( + allOf(withId(R.id.buttonDefaultNeutral), withText("Custom"), + withParent(allOf(withId(R.id.root), + withParent(withId(android.R.id.content)))), + isDisplayed())); + mDButton2.perform(click()); + + ViewInteraction mDButton3 = onView( + allOf(withId(R.id.buttonDefaultNeutral), withText(R.string.md_presets_label), + withParent(allOf(withId(R.id.root), + withParent(withId(android.R.id.content)))), + isDisplayed())); + mDButton3.perform(click()); + + ViewInteraction circleView = onView( + childAtPosition( + withId(R.id.grid), + 18)); + circleView.perform(scrollTo(), click()); + + ViewInteraction circleView2 = onView( + childAtPosition( + withId(R.id.grid), + 9)); + circleView2.perform(scrollTo(), click()); + + ViewInteraction mDButton4 = onView( + allOf(withId(R.id.buttonDefaultPositive), withText(R.string.md_done_label), + withParent(allOf(withId(R.id.root), + withParent(withId(android.R.id.content)))), + isDisplayed())); + mDButton4.perform(click()); + + ViewInteraction appCompatImageViewColorChanged = onView(allOf(withId(R.id.color_chooser), isDisplayed())); + appCompatImageViewColorChanged.check(matches(withBackgroundColor(Color.parseColor("#FF263238")))); + + } + + @Test + public void categoryDeletion () { + + addNewCategory(); + + ViewInteraction drawerToggle = onView( + allOf(withContentDescription(R.string.drawer_open), + withParent(withId(R.id.toolbar)), + isDisplayed())); + drawerToggle.perform(click()); + + ViewInteraction categoryView = onView(allOf(withId(R.id.title), withText(categoryName))); + categoryView.perform(longClick()); + + ViewInteraction deleteBtn = onView( + allOf(withId(R.id.delete), withText(R.string.delete), isDisplayed())); + deleteBtn.perform(click()); + + ViewInteraction deleteConfirmBtn = onView( + allOf(withId(R.id.buttonDefaultPositive), withText(R.string.confirm), isDisplayed())); + deleteConfirmBtn.perform(click()); + + // Waiting a little to ensure Eventbus post propagation + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } - @Test - public void categoryDeletion() { - - addNewCategory(); + ViewInteraction categoryDeletedView = onView(allOf(withId(R.id.title), withText(categoryName))); + categoryDeletedView.check(doesNotExist()); - ViewInteraction drawerToggle = onView( - allOf(withContentDescription(R.string.drawer_open), - withParent(withId(R.id.toolbar)), - isDisplayed())); - drawerToggle.perform(click()); + } - ViewInteraction categoryView = onView(allOf(withId(R.id.title), withText(categoryName))); - categoryView.perform(longClick()); + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + private static Matcher withBackgroundColor (final int backgroundColor) { + return new TypeSafeMatcher() { - ViewInteraction deleteBtn = onView( - allOf(withId(R.id.delete), withText(R.string.delete), isDisplayed())); - deleteBtn.perform(click()); + @Override + public boolean matchesSafely (View view) { + ColorFilter cf = new PorterDuffColorFilter(Color.parseColor("#FF263238"), PorterDuff.Mode.SRC_ATOP); + ColorFilter cf1 = ((AppCompatImageView) view).getDrawable().getColorFilter(); + return cf.equals(cf1); + } - ViewInteraction deleteConfirmBtn = onView( - allOf(withId(R.id.buttonDefaultPositive), withText(R.string.confirm), isDisplayed())); - deleteConfirmBtn.perform(click()); - - // Waiting a little to ensure Eventbus post propagation - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - ViewInteraction categoryDeletedView = onView(allOf(withId(R.id.title), withText(categoryName))); - categoryDeletedView.check(doesNotExist()); - - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private static Matcher withBackgroundColor(final int backgroundColor) { - return new TypeSafeMatcher() { - - @Override - public boolean matchesSafely(View view) { - ColorFilter cf = new PorterDuffColorFilter(Color.parseColor("#FF263238"), PorterDuff.Mode.SRC_ATOP); - ColorFilter cf1 = ((AppCompatImageView) view).getDrawable().getColorFilter(); - return cf.equals(cf1); - } - - @Override - public void describeTo(Description description) { - description.appendText("with background color from id: " + backgroundColor); - } - }; - } + @Override + public void describeTo (Description description) { + description.appendText("with background color from id: " + backgroundColor); + } + }; + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabCameraNoteTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabCameraNoteTest.java index 28b0900ec0..a185786790 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabCameraNoteTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabCameraNoteTest.java @@ -17,6 +17,18 @@ package it.feio.android.omninotes; +import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.Espresso.pressBack; +import static android.support.test.espresso.action.ViewActions.click; +import static android.support.test.espresso.intent.Intents.intending; +import static android.support.test.espresso.intent.matcher.IntentMatchers.hasAction; +import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; +import static android.support.test.espresso.matcher.ViewMatchers.withClassName; +import static android.support.test.espresso.matcher.ViewMatchers.withId; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + import android.app.Activity; import android.app.Instrumentation; import android.content.Intent; @@ -25,68 +37,58 @@ import android.provider.MediaStore; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.intent.Intents; -import android.support.test.runner.AndroidJUnit4; import android.support.test.filters.LargeTest; +import android.support.test.runner.AndroidJUnit4; import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.bus.NotesUpdatedEvent; import it.feio.android.omninotes.utils.Constants; import org.junit.Test; import org.junit.runner.RunWith; -import static android.support.test.espresso.Espresso.onView; -import static android.support.test.espresso.Espresso.pressBack; -import static android.support.test.espresso.action.ViewActions.click; -import static android.support.test.espresso.intent.Intents.intending; -import static android.support.test.espresso.intent.matcher.IntentMatchers.hasAction; -import static android.support.test.espresso.matcher.ViewMatchers.*; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; - @LargeTest @RunWith(AndroidJUnit4.class) public class FabCameraNoteTest extends BaseEspressoTest { - @Test - public void fabCameraNoteTest() { - EventBus.getDefault().register(this); - Intents.init(); - Bitmap icon = BitmapFactory.decodeResource( - InstrumentationRegistry.getTargetContext().getResources(), - R.mipmap.ic_launcher); + @Test + public void fabCameraNoteTest () { + EventBus.getDefault().register(this); + Intents.init(); + Bitmap icon = BitmapFactory.decodeResource( + InstrumentationRegistry.getTargetContext().getResources(), + R.mipmap.ic_launcher); - Intent resultData = new Intent(); - resultData.putExtra("data", icon); - Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData); + Intent resultData = new Intent(); + resultData.putExtra("data", icon); + Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData); - intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result); + intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result); - onView(allOf(withId(R.id.fab_expand_menu_button), - childAtPosition( - allOf(withId(R.id.fab), - childAtPosition( - withClassName(is("android.widget.FrameLayout")), - 2)), - 3), - isDisplayed())).perform(click()); + onView(allOf(withId(R.id.fab_expand_menu_button), + childAtPosition( + allOf(withId(R.id.fab), + childAtPosition( + withClassName(is("android.widget.FrameLayout")), + 2)), + 3), + isDisplayed())).perform(click()); - onView(allOf(withId(R.id.fab_camera), - childAtPosition( - allOf(withId(R.id.fab), - childAtPosition( - withClassName(is("android.widget.FrameLayout")), - 2)), - 0), - isDisplayed())).perform(click()); + onView(allOf(withId(R.id.fab_camera), + childAtPosition( + allOf(withId(R.id.fab), + childAtPosition( + withClassName(is("android.widget.FrameLayout")), + 2)), + 0), + isDisplayed())).perform(click()); - pressBack(); + pressBack(); - } + } - public void onEvent(NotesUpdatedEvent notesUpdatedEvent) { - assertEquals(0, notesUpdatedEvent.notes.get(0).getAttachmentsList().size()); - assertEquals(Constants.MIME_TYPE_IMAGE, notesUpdatedEvent.notes.get(0).getAttachmentsList().get(0).getMime_type()); - } + public void onEvent (NotesUpdatedEvent notesUpdatedEvent) { + assertEquals(0, notesUpdatedEvent.notes.get(0).getAttachmentsList().size()); + assertEquals(Constants.MIME_TYPE_IMAGE, notesUpdatedEvent.notes.get(0).getAttachmentsList().get(0).getMime_type()); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabLifecycleTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabLifecycleTest.java index ae046f4054..343a167a60 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabLifecycleTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/FabLifecycleTest.java @@ -18,16 +18,6 @@ package it.feio.android.omninotes; -import android.support.test.espresso.ViewInteraction; -import android.support.test.filters.LargeTest; -import android.support.test.runner.AndroidJUnit4; - -import org.hamcrest.core.IsInstanceOf; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.IOException; - import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; @@ -36,55 +26,62 @@ import static org.hamcrest.Matchers.allOf; import static org.junit.Assert.assertNotNull; +import android.support.test.espresso.ViewInteraction; +import android.support.test.filters.LargeTest; +import android.support.test.runner.AndroidJUnit4; +import java.io.IOException; +import org.hamcrest.core.IsInstanceOf; +import org.junit.Test; +import org.junit.runner.RunWith; + @LargeTest @RunWith(AndroidJUnit4.class) public class FabLifecycleTest extends BaseEspressoTest { - @Test - public void fabOpenCloseTest() { + @Test + public void fabOpenCloseTest () { - ViewInteraction viewInteraction = onView( - allOf(withId(R.id.fab_expand_menu_button), - withParent(withId(R.id.fab)))); - viewInteraction.perform(click()); + ViewInteraction viewInteraction = onView( + allOf(withId(R.id.fab_expand_menu_button), + withParent(withId(R.id.fab)))); + viewInteraction.perform(click()); + ViewInteraction viewInteraction2 = onView( + allOf(withId(R.id.fab_expand_menu_button), + withParent(withId(R.id.fab)))); + viewInteraction2.perform(click()); + } - ViewInteraction viewInteraction2 = onView( - allOf(withId(R.id.fab_expand_menu_button), - withParent(withId(R.id.fab)))); - viewInteraction2.perform(click()); - } - - @Test - public void fabActionsTest() throws IOException { + @Test + public void fabActionsTest () throws IOException { - ViewInteraction viewInteraction = onView( - allOf(withId(R.id.fab_expand_menu_button), - withParent(withId(R.id.fab)), - isDisplayed())); - viewInteraction.perform(click()); + ViewInteraction viewInteraction = onView( + allOf(withId(R.id.fab_expand_menu_button), + withParent(withId(R.id.fab)), + isDisplayed())); + viewInteraction.perform(click()); - ViewInteraction checklistFabAction = onView( - allOf(withId(R.id.fab_checklist), - childAtPosition( - allOf(withId(R.id.fab), - childAtPosition( - IsInstanceOf.instanceOf(android.widget.FrameLayout.class), - 4)), - 3), - isDisplayed())); - assertNotNull(checklistFabAction); + ViewInteraction checklistFabAction = onView( + allOf(withId(R.id.fab_checklist), + childAtPosition( + allOf(withId(R.id.fab), + childAtPosition( + IsInstanceOf.instanceOf(android.widget.FrameLayout.class), + 4)), + 3), + isDisplayed())); + assertNotNull(checklistFabAction); - ViewInteraction cameraFabAction = onView( - allOf(withId(R.id.fab_camera), - childAtPosition( - allOf(withId(R.id.fab), - childAtPosition( - IsInstanceOf.instanceOf(android.widget.FrameLayout.class), - 4)), - 1), - isDisplayed())); - assertNotNull(cameraFabAction); - } + ViewInteraction cameraFabAction = onView( + allOf(withId(R.id.fab_camera), + childAtPosition( + allOf(withId(R.id.fab), + childAtPosition( + IsInstanceOf.instanceOf(android.widget.FrameLayout.class), + 4)), + 1), + isDisplayed())); + assertNotNull(cameraFabAction); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/RemindersLifecycleTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/RemindersLifecycleTest.java index 534d705cf3..8495a17445 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/RemindersLifecycleTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/RemindersLifecycleTest.java @@ -18,14 +18,24 @@ package it.feio.android.omninotes; +import static android.support.test.espresso.Espresso.onView; +import static android.support.test.espresso.action.ViewActions.click; +import static android.support.test.espresso.action.ViewActions.scrollTo; +import static android.support.test.espresso.assertion.ViewAssertions.matches; +import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; +import static android.support.test.espresso.matcher.ViewMatchers.withId; +import static android.support.test.espresso.matcher.ViewMatchers.withParent; +import static android.support.test.espresso.matcher.ViewMatchers.withText; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.startsWith; + import android.support.test.espresso.ViewInteraction; +import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; -import android.support.test.filters.LargeTest; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; - import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -33,74 +43,64 @@ import org.junit.Test; import org.junit.runner.RunWith; -import static android.support.test.espresso.Espresso.onView; -import static android.support.test.espresso.action.ViewActions.click; -import static android.support.test.espresso.action.ViewActions.scrollTo; -import static android.support.test.espresso.assertion.ViewAssertions.matches; -import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; -import static android.support.test.espresso.matcher.ViewMatchers.withId; -import static android.support.test.espresso.matcher.ViewMatchers.withParent; -import static android.support.test.espresso.matcher.ViewMatchers.withText; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.startsWith; - @LargeTest @RunWith(AndroidJUnit4.class) public class RemindersLifecycleTest { - @Rule - public ActivityTestRule mActivityTestRule = new ActivityTestRule<>(MainActivity.class); - - @Test - public void remindersLifecycle() { - ViewInteraction viewInteraction = onView( - allOf(withId(R.id.fab_expand_menu_button), - withParent(withId(R.id.fab)), - isDisplayed())); - viewInteraction.perform(click()); - - ViewInteraction floatingActionButton = onView( - allOf(withId(R.id.fab_note), - withParent(withId(R.id.fab)), - isDisplayed())); - floatingActionButton.perform(click()); - - ViewInteraction linearLayout = onView( - withId(R.id.reminder_layout)); - linearLayout.perform(scrollTo(), click()); - - ViewInteraction appCompatButton = onView( - allOf(withId(R.id.done), withText(R.string.done_label), isDisplayed())); - appCompatButton.perform(click()); - - ViewInteraction appCompatButton2 = onView( - allOf(withId(R.id.done_button), withText(R.string.done_label), isDisplayed())); - appCompatButton2.perform(click()); - - ViewInteraction appCompatButton3 = onView( - allOf(withId(R.id.done), withText(R.string.save_label), isDisplayed())); - appCompatButton3.perform(click()); - - ViewInteraction textView = onView(withId(R.id.datetime)); - textView.check(matches(withText(startsWith(OmniNotes.getAppContext().getResources().getString(R.string.alarm_set_on))))); - } - - private static Matcher childAtPosition( - final Matcher parentMatcher, final int position) { - - return new TypeSafeMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("Child at position " + position + " in parent "); - parentMatcher.describeTo(description); - } - - @Override - public boolean matchesSafely(View view) { - ViewParent parent = view.getParent(); - return parent instanceof ViewGroup && parentMatcher.matches(parent) - && view.equals(((ViewGroup) parent).getChildAt(position)); - } - }; - } + @Rule + public ActivityTestRule mActivityTestRule = new ActivityTestRule<>(MainActivity.class); + + @Test + public void remindersLifecycle () { + ViewInteraction viewInteraction = onView( + allOf(withId(R.id.fab_expand_menu_button), + withParent(withId(R.id.fab)), + isDisplayed())); + viewInteraction.perform(click()); + + ViewInteraction floatingActionButton = onView( + allOf(withId(R.id.fab_note), + withParent(withId(R.id.fab)), + isDisplayed())); + floatingActionButton.perform(click()); + + ViewInteraction linearLayout = onView( + withId(R.id.reminder_layout)); + linearLayout.perform(scrollTo(), click()); + + ViewInteraction appCompatButton = onView( + allOf(withId(R.id.done), withText(R.string.done_label), isDisplayed())); + appCompatButton.perform(click()); + + ViewInteraction appCompatButton2 = onView( + allOf(withId(R.id.done_button), withText(R.string.done_label), isDisplayed())); + appCompatButton2.perform(click()); + + ViewInteraction appCompatButton3 = onView( + allOf(withId(R.id.done), withText(R.string.save_label), isDisplayed())); + appCompatButton3.perform(click()); + + ViewInteraction textView = onView(withId(R.id.datetime)); + textView.check( + matches(withText(startsWith(OmniNotes.getAppContext().getResources().getString(R.string.alarm_set_on))))); + } + + private static Matcher childAtPosition ( + final Matcher parentMatcher, final int position) { + + return new TypeSafeMatcher() { + @Override + public void describeTo (Description description) { + description.appendText("Child at position " + position + " in parent "); + parentMatcher.describeTo(description); + } + + @Override + public boolean matchesSafely (View view) { + ViewParent parent = view.getParent(); + return parent instanceof ViewGroup && parentMatcher.matches(parent) + && view.equals(((ViewGroup) parent).getChildAt(position)); + } + }; + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/db/DbHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/db/DbHelperTest.java index 7a97a76ed6..5cd8392495 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/db/DbHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/db/DbHelperTest.java @@ -29,40 +29,40 @@ @RunWith(AndroidJUnit4.class) public class DbHelperTest extends BaseAndroidTestCase { - @Test - public void testGetNotesByTag() { - Note note = new Note(); - note.setTitle("title with #tag inside"); - note.setContent("useless content"); - dbHelper.updateNote(note, true); - Note note1 = new Note(); - note1.setTitle("simple title"); - note1.setContent("content with #tag"); - dbHelper.updateNote(note1, true); - Note note2 = new Note(); - note2.setTitle("title without tags in it"); - note2.setContent("some \n #tagged content"); - dbHelper.updateNote(note2, true); - assertEquals(2, dbHelper.getNotesByTag("#tag").size()); - assertEquals(1, dbHelper.getNotesByTag("#tagged").size()); - } + @Test + public void testGetNotesByTag () { + Note note = new Note(); + note.setTitle("title with #tag inside"); + note.setContent("useless content"); + dbHelper.updateNote(note, true); + Note note1 = new Note(); + note1.setTitle("simple title"); + note1.setContent("content with #tag"); + dbHelper.updateNote(note1, true); + Note note2 = new Note(); + note2.setTitle("title without tags in it"); + note2.setContent("some \n #tagged content"); + dbHelper.updateNote(note2, true); + assertEquals(2, dbHelper.getNotesByTag("#tag").size()); + assertEquals(1, dbHelper.getNotesByTag("#tagged").size()); + } - @Test - public void getNotesByPatternEscaped() { - Note note1 = new Note(); - note1.setTitle("title one"); - note1.setContent("content with _ (underscore) inside"); - dbHelper.updateNote(note1, true); - Note note2 = new Note(); - note2.setTitle("title two"); - note2.setContent("useless content"); - dbHelper.updateNote(note2, true); - Note note3 = new Note(); - note3.setTitle("title three"); - note3.setContent("content with % (percentage) inside"); - dbHelper.updateNote(note3, true); - assertEquals(1, dbHelper.getNotesByPattern("_").size()); - assertEquals(1, dbHelper.getNotesByPattern("%").size()); - } + @Test + public void getNotesByPatternEscaped () { + Note note1 = new Note(); + note1.setTitle("title one"); + note1.setContent("content with _ (underscore) inside"); + dbHelper.updateNote(note1, true); + Note note2 = new Note(); + note2.setTitle("title two"); + note2.setContent("useless content"); + dbHelper.updateNote(note2, true); + Note note3 = new Note(); + note3.setTitle("title three"); + note3.setContent("content with % (percentage) inside"); + dbHelper.updateNote(note3, true); + assertEquals(1, dbHelper.getNotesByPattern("_").size()); + assertEquals(1, dbHelper.getNotesByPattern("%").size()); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/AppVersionHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/AppVersionHelperTest.java index 15fc4afaf6..421ebf73bc 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/AppVersionHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/AppVersionHelperTest.java @@ -23,63 +23,61 @@ import android.content.pm.PackageManager; import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - import it.feio.android.omninotes.BaseAndroidTestCase; import it.feio.android.omninotes.utils.Constants; +import org.junit.Test; +import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class AppVersionHelperTest extends BaseAndroidTestCase { - private static final String VERSION_NAME_REGEX = "\\d{1}(\\.\\d)*( Alpha| Beta)*( \\d+)*"; - - @Test - public void shouldGetCurrentAppVersion() throws PackageManager.NameNotFoundException { - int currentAppVersion = AppVersionHelper.getCurrentAppVersion(testContext); - assertTrue(currentAppVersion > 0); - assertTrue(currentAppVersion < Integer.MAX_VALUE); - } - - @Test - public void shouldaVerifyAppUpdatedFalse() throws PackageManager.NameNotFoundException { - AppVersionHelper.updateAppVersionInPreferences(testContext); - assertFalse(AppVersionHelper.isAppUpdated(testContext)); - } - - @Test - public void shouldVerifyAppUpdatedTrue() throws PackageManager.NameNotFoundException { - int currentAppVersion = AppVersionHelper.getCurrentAppVersion(testContext); - prefs.edit().putInt(Constants.PREF_CURRENT_APP_VERSION, currentAppVersion - 1).commit(); - assertTrue(AppVersionHelper.isAppUpdated(testContext)); - } - - @Test - public void shouldGetAppVersionFromPreferences() throws PackageManager.NameNotFoundException { - prefs.edit().clear().commit(); - assertEquals(1, AppVersionHelper.getAppVersionFromPreferences(testContext)); - } - - @Test - public void shouldGetCurrentAppVersionName() throws PackageManager.NameNotFoundException { - String currentAppVersionName = AppVersionHelper.getCurrentAppVersionName(testContext); - assertTrue(currentAppVersionName.matches(VERSION_NAME_REGEX)); - } - - @Test - public void shouldWorkLegacyVersionManagementRetrieval() throws PackageManager.NameNotFoundException { - prefs.edit().putString(Constants.PREF_CURRENT_APP_VERSION, "5.2.6 Beta 1").commit(); - int currentAppVersion = AppVersionHelper.getCurrentAppVersion(testContext); - int saveAppVersion = AppVersionHelper.getAppVersionFromPreferences(testContext); - assertEquals(currentAppVersion - 1, saveAppVersion); - } - - @Test - public void shouldWorkLegacyVersionManagementUpdateCheck() throws PackageManager.NameNotFoundException { - prefs.edit().putString(Constants.PREF_CURRENT_APP_VERSION, "5.2.6 Beta 1").commit(); - assertTrue(AppVersionHelper.isAppUpdated(testContext)); - } + private static final String VERSION_NAME_REGEX = "\\d{1}(\\.\\d)*( Alpha| Beta)*( \\d+)*"; + + @Test + public void shouldGetCurrentAppVersion () throws PackageManager.NameNotFoundException { + int currentAppVersion = AppVersionHelper.getCurrentAppVersion(testContext); + assertTrue(currentAppVersion > 0); + assertTrue(currentAppVersion < Integer.MAX_VALUE); + } + + @Test + public void shouldaVerifyAppUpdatedFalse () throws PackageManager.NameNotFoundException { + AppVersionHelper.updateAppVersionInPreferences(testContext); + assertFalse(AppVersionHelper.isAppUpdated(testContext)); + } + + @Test + public void shouldVerifyAppUpdatedTrue () throws PackageManager.NameNotFoundException { + int currentAppVersion = AppVersionHelper.getCurrentAppVersion(testContext); + prefs.edit().putInt(Constants.PREF_CURRENT_APP_VERSION, currentAppVersion - 1).commit(); + assertTrue(AppVersionHelper.isAppUpdated(testContext)); + } + + @Test + public void shouldGetAppVersionFromPreferences () throws PackageManager.NameNotFoundException { + prefs.edit().clear().commit(); + assertEquals(1, AppVersionHelper.getAppVersionFromPreferences(testContext)); + } + + @Test + public void shouldGetCurrentAppVersionName () throws PackageManager.NameNotFoundException { + String currentAppVersionName = AppVersionHelper.getCurrentAppVersionName(testContext); + assertTrue(currentAppVersionName.matches(VERSION_NAME_REGEX)); + } + + @Test + public void shouldWorkLegacyVersionManagementRetrieval () throws PackageManager.NameNotFoundException { + prefs.edit().putString(Constants.PREF_CURRENT_APP_VERSION, "5.2.6 Beta 1").commit(); + int currentAppVersion = AppVersionHelper.getCurrentAppVersion(testContext); + int saveAppVersion = AppVersionHelper.getAppVersionFromPreferences(testContext); + assertEquals(currentAppVersion - 1, saveAppVersion); + } + + @Test + public void shouldWorkLegacyVersionManagementUpdateCheck () throws PackageManager.NameNotFoundException { + prefs.edit().putString(Constants.PREF_CURRENT_APP_VERSION, "5.2.6 Beta 1").commit(); + assertTrue(AppVersionHelper.isAppUpdated(testContext)); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/BackupHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/BackupHelperTest.java index bbcf6e989a..018f4f3e45 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/BackupHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/BackupHelperTest.java @@ -23,7 +23,16 @@ import android.net.Uri; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; - +import it.feio.android.omninotes.BaseAndroidTestCase; +import it.feio.android.omninotes.models.Attachment; +import it.feio.android.omninotes.models.Note; +import it.feio.android.omninotes.utils.StorageHelper; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; @@ -33,89 +42,77 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; - -import it.feio.android.omninotes.BaseAndroidTestCase; -import it.feio.android.omninotes.models.Attachment; -import it.feio.android.omninotes.models.Note; -import it.feio.android.omninotes.utils.StorageHelper; import rx.Observable; @RunWith(AndroidJUnit4.class) public class BackupHelperTest extends BaseAndroidTestCase { - private File targetDir; - private File targetAttachmentsDir; - - - @Before - public void setUp() throws Exception { - targetDir = new File(StorageHelper.getCacheDir(InstrumentationRegistry.getTargetContext()), "_autobackupTest"); - if (targetDir.exists()) { - FileUtils.forceDelete(targetDir); - } - targetAttachmentsDir = new File(targetDir, StorageHelper.getAttachmentDir().getName()); - targetAttachmentsDir.mkdirs(); - } - - @Test - public void testExportNote() throws IOException { - Note note = new Note(); - note.setTitle("test title"); - note.setContent("test content"); - long now = Calendar.getInstance().getTimeInMillis(); - note.setCreation(now); - note.setLastModification(now); - BackupHelper.exportNote(targetDir, note); - Collection noteFiles = FileUtils.listFiles(targetDir, new RegexFileFilter("\\d{13}.json"), - TrueFileFilter.INSTANCE); - assertEquals(1, noteFiles.size()); - Note retrievedNote = rx.Observable.from(noteFiles).map(BackupHelper::importNote).toBlocking().first(); - assertTrue(note.equals(retrievedNote)); - } - - @Test - public void testExportNoteWithAttachment() throws IOException { - Note note = new Note(); - note.setTitle("test title"); - note.setContent("test content"); - File testAttachment = File.createTempFile("testAttachment", ".txt"); - IOUtils.write("some test content for attachment".toCharArray(), new FileOutputStream(testAttachment)); - Attachment attachment = new Attachment(Uri.fromFile(testAttachment), "attachmentName"); - note.setAttachmentsList(Collections.singletonList(attachment)); - - long now = Calendar.getInstance().getTimeInMillis(); - note.setCreation(now); - note.setLastModification(now); - BackupHelper.exportNote(targetDir, note); - BackupHelper.exportAttachments(null, targetAttachmentsDir, - note.getAttachmentsList(), note.getAttachmentsListOld()); - Collection files = FileUtils.listFiles(targetDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); - - Note retrievedNote = rx.Observable.from(files).filter(file -> file.getName().equals(String.valueOf(note - .getCreation() + ".json"))).map(BackupHelper::importNote).toBlocking().first(); - String retrievedAttachmentContent = Observable.from(files).filter(file -> file.getName().equals(FilenameUtils - .getName(attachment.getUriPath()))).map(file -> { - try { - return FileUtils.readFileToString(file); - } catch (IOException e) { - return "bau"; - } - }).toBlocking().first(); - assertEquals(2, files.size()); - assertTrue(note.equals(retrievedNote)); - assertEquals(retrievedAttachmentContent, FileUtils.readFileToString(new File(attachment.getUri().getPath()))); - } - - - @After - public void tearDown() throws Exception { - FileUtils.forceDelete(targetDir); - } + private File targetDir; + private File targetAttachmentsDir; + + + @Before + public void setUp () throws Exception { + targetDir = new File(StorageHelper.getCacheDir(InstrumentationRegistry.getTargetContext()), "_autobackupTest"); + if (targetDir.exists()) { + FileUtils.forceDelete(targetDir); + } + targetAttachmentsDir = new File(targetDir, StorageHelper.getAttachmentDir().getName()); + targetAttachmentsDir.mkdirs(); + } + + @Test + public void testExportNote () throws IOException { + Note note = new Note(); + note.setTitle("test title"); + note.setContent("test content"); + long now = Calendar.getInstance().getTimeInMillis(); + note.setCreation(now); + note.setLastModification(now); + BackupHelper.exportNote(targetDir, note); + Collection noteFiles = FileUtils.listFiles(targetDir, new RegexFileFilter("\\d{13}.json"), + TrueFileFilter.INSTANCE); + assertEquals(1, noteFiles.size()); + Note retrievedNote = rx.Observable.from(noteFiles).map(BackupHelper::importNote).toBlocking().first(); + assertTrue(note.equals(retrievedNote)); + } + + @Test + public void testExportNoteWithAttachment () throws IOException { + Note note = new Note(); + note.setTitle("test title"); + note.setContent("test content"); + File testAttachment = File.createTempFile("testAttachment", ".txt"); + IOUtils.write("some test content for attachment".toCharArray(), new FileOutputStream(testAttachment)); + Attachment attachment = new Attachment(Uri.fromFile(testAttachment), "attachmentName"); + note.setAttachmentsList(Collections.singletonList(attachment)); + + long now = Calendar.getInstance().getTimeInMillis(); + note.setCreation(now); + note.setLastModification(now); + BackupHelper.exportNote(targetDir, note); + BackupHelper.exportAttachments(null, targetAttachmentsDir, + note.getAttachmentsList(), note.getAttachmentsListOld()); + Collection files = FileUtils.listFiles(targetDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); + + Note retrievedNote = rx.Observable.from(files).filter(file -> file.getName().equals(note + .getCreation() + ".json")).map(BackupHelper::importNote).toBlocking().first(); + String retrievedAttachmentContent = Observable.from(files).filter(file -> file.getName().equals(FilenameUtils + .getName(attachment.getUriPath()))).map(file -> { + try { + return FileUtils.readFileToString(file); + } catch (IOException e) { + return "bau"; + } + }).toBlocking().first(); + assertEquals(2, files.size()); + assertTrue(note.equals(retrievedNote)); + assertEquals(retrievedAttachmentContent, FileUtils.readFileToString(new File(attachment.getUri().getPath()))); + } + + + @After + public void tearDown () throws Exception { + FileUtils.forceDelete(targetDir); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/LanguageHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/LanguageHelperTest.java index c96ab2ec37..92bdb369c4 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/LanguageHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/LanguageHelperTest.java @@ -19,78 +19,76 @@ import static org.junit.Assert.assertEquals; +import android.content.Context; import android.content.SharedPreferences; import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - import it.feio.android.omninotes.BaseAndroidTestCase; import it.feio.android.omninotes.R; import it.feio.android.omninotes.utils.Constants; - import java.util.Locale; +import org.junit.Test; +import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class LanguageHelperTest extends BaseAndroidTestCase { - @Test - public void shouldChangeSharedPrefrencesLanguage() { - LanguageHelper.updateLanguage(testContext, Locale.ITALY.toString()); - SharedPreferences prefs = testContext.getSharedPreferences(Constants.PREFS_NAME, testContext - .MODE_MULTI_PROCESS); - String language = prefs.getString(Constants.PREF_LANG, ""); - assertEquals(Locale.ITALY.toString(), language); - } + @Test + public void shouldChangeSharedPrefrencesLanguage () { + LanguageHelper.updateLanguage(testContext, Locale.ITALY.toString()); + SharedPreferences prefs = testContext.getSharedPreferences(Constants.PREFS_NAME, Context + .MODE_MULTI_PROCESS); + String language = prefs.getString(Constants.PREF_LANG, ""); + assertEquals(Locale.ITALY.toString(), language); + } - @Test - public void shouldChangeAppLanguage() { - LanguageHelper.updateLanguage(testContext, Locale.ITALY.toString()); - assertTranslationMatches(Locale.ITALY.toString(), R.string.add_note); - } + @Test + public void shouldChangeAppLanguage () { + LanguageHelper.updateLanguage(testContext, Locale.ITALY.toString()); + assertTranslationMatches(Locale.ITALY.toString(), R.string.add_note); + } - @Test - public void sameStaticStringToEnsureTranslationsAreCorrect() { - assertTranslationMatches("ar_SA", R.string.add_note, "إضافة نقطة"); - assertTranslationMatches("es_XA", R.string.add_note, "Amestar Nota"); - assertTranslationMatches("ca_ES", R.string.add_note, "Afegeix una nota"); - assertTranslationMatches("zh_CN", R.string.add_note, "添加记事"); - assertTranslationMatches("zh_TW", R.string.add_note, "新增筆記"); - assertTranslationMatches("hr_HR", R.string.add_note, "Dodaj Bilješku"); - assertTranslationMatches("cs_CZ", R.string.add_note, "Přidat poznámku"); - assertTranslationMatches("nl_NL", R.string.add_note, "Notitie toevoegen"); - assertTranslationMatches("en_US", R.string.add_note, "Add Note"); - assertTranslationMatches("fr_FR", R.string.add_note, "Ajouter une note"); - assertTranslationMatches("km_KH", R.string.add_note, "បង្កើត"); - assertTranslationMatches("de_DE", R.string.add_note, "Notiz hinzufügen"); - assertTranslationMatches("gl_ES", R.string.add_note, "Engadir nota"); - assertTranslationMatches("el_GR", R.string.add_note, "Προσθήκη σημείωσης"); - assertTranslationMatches("iw_IL", R.string.add_note, "הוספת הערה"); - assertTranslationMatches("hi_IN", R.string.add_note, "नोट जोड़ें"); - assertTranslationMatches("hu_HU", R.string.add_note, "Jegyzet hozzáadása"); - assertTranslationMatches("in_ID", R.string.add_note, "Tambahkan Catatan"); - assertTranslationMatches("it_IT", R.string.add_note, "Aggiungi nota"); - assertTranslationMatches("ja_JP", R.string.add_note, "ノートを追加"); - assertTranslationMatches("lo_LA", R.string.add_note, "ເພີ່ມບັນທຶກ"); - assertTranslationMatches("lv_LV", R.string.add_note, "Pievienot piezīmi"); - assertTranslationMatches("pl_PL", R.string.add_note, "Dodaj Notatkę"); - assertTranslationMatches("pt_BR", R.string.add_note, "Adicionar nota"); - assertTranslationMatches("pt_PT", R.string.add_note, "Adicionar nota"); - assertTranslationMatches("ru_RU", R.string.add_note, "Создать заметку"); - assertTranslationMatches("sr_SP", R.string.add_note, "Додај белешку"); - assertTranslationMatches("sk_SK", R.string.add_note, "Pridať poznámku"); - assertTranslationMatches("sl_SI", R.string.add_note, "Dodaj beležko"); - assertTranslationMatches("es_ES", R.string.add_note, "Añadir Nota"); - assertTranslationMatches("sv_SE", R.string.add_note, "Lägg till Anteckning"); - assertTranslationMatches("tr_TR", R.string.add_note, "Not Ekle"); - assertTranslationMatches("uk_UA", R.string.add_note, "Додати нотатку"); - } + @Test + public void sameStaticStringToEnsureTranslationsAreCorrect () { + assertTranslationMatches("ar_SA", R.string.add_note, "إضافة نقطة"); + assertTranslationMatches("es_XA", R.string.add_note, "Amestar Nota"); + assertTranslationMatches("ca_ES", R.string.add_note, "Afegeix una nota"); + assertTranslationMatches("zh_CN", R.string.add_note, "添加记事"); + assertTranslationMatches("zh_TW", R.string.add_note, "新增筆記"); + assertTranslationMatches("hr_HR", R.string.add_note, "Dodaj Bilješku"); + assertTranslationMatches("cs_CZ", R.string.add_note, "Přidat poznámku"); + assertTranslationMatches("nl_NL", R.string.add_note, "Notitie toevoegen"); + assertTranslationMatches("en_US", R.string.add_note, "Add Note"); + assertTranslationMatches("fr_FR", R.string.add_note, "Ajouter une note"); + assertTranslationMatches("km_KH", R.string.add_note, "បង្កើត"); + assertTranslationMatches("de_DE", R.string.add_note, "Notiz hinzufügen"); + assertTranslationMatches("gl_ES", R.string.add_note, "Engadir nota"); + assertTranslationMatches("el_GR", R.string.add_note, "Προσθήκη σημείωσης"); + assertTranslationMatches("iw_IL", R.string.add_note, "הוספת הערה"); + assertTranslationMatches("hi_IN", R.string.add_note, "नोट जोड़ें"); + assertTranslationMatches("hu_HU", R.string.add_note, "Jegyzet hozzáadása"); + assertTranslationMatches("in_ID", R.string.add_note, "Tambahkan Catatan"); + assertTranslationMatches("it_IT", R.string.add_note, "Aggiungi nota"); + assertTranslationMatches("ja_JP", R.string.add_note, "ノートを追加"); + assertTranslationMatches("lo_LA", R.string.add_note, "ເພີ່ມບັນທຶກ"); + assertTranslationMatches("lv_LV", R.string.add_note, "Pievienot piezīmi"); + assertTranslationMatches("pl_PL", R.string.add_note, "Dodaj Notatkę"); + assertTranslationMatches("pt_BR", R.string.add_note, "Adicionar nota"); + assertTranslationMatches("pt_PT", R.string.add_note, "Adicionar nota"); + assertTranslationMatches("ru_RU", R.string.add_note, "Создать заметку"); + assertTranslationMatches("sr_SP", R.string.add_note, "Додај белешку"); + assertTranslationMatches("sk_SK", R.string.add_note, "Pridať poznámku"); + assertTranslationMatches("sl_SI", R.string.add_note, "Dodaj beležko"); + assertTranslationMatches("es_ES", R.string.add_note, "Añadir Nota"); + assertTranslationMatches("sv_SE", R.string.add_note, "Lägg till Anteckning"); + assertTranslationMatches("tr_TR", R.string.add_note, "Not Ekle"); + assertTranslationMatches("uk_UA", R.string.add_note, "Додати нотатку"); + } - private void assertTranslationMatches(String locale, int resourceId) { - assertTranslationMatches(locale, resourceId, testContext.getString(resourceId)); - } + private void assertTranslationMatches (String locale, int resourceId) { + assertTranslationMatches(locale, resourceId, testContext.getString(resourceId)); + } - private void assertTranslationMatches(String locale, int resourceId, String string) { - assertEquals(LanguageHelper.getLocalizedString(testContext, locale, resourceId), string); - } + private void assertTranslationMatches (String locale, int resourceId, String string) { + assertEquals(LanguageHelper.getLocalizedString(testContext, locale, resourceId), string); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/count/CountFactoryTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/count/CountFactoryTest.java index 0b99095d2a..b9865fae90 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/count/CountFactoryTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/helpers/count/CountFactoryTest.java @@ -20,41 +20,38 @@ import static org.junit.Assert.assertEquals; import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.util.Locale; - import it.feio.android.omninotes.BaseAndroidTestCase; import it.feio.android.omninotes.OmniNotes; +import java.util.Locale; +import org.junit.Test; +import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class CountFactoryTest extends BaseAndroidTestCase { - @Test - public void getWordCounterForEnglish() { - OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.US); - assertEquals(DefaultWordCounter.class, CountFactory.getWordCounter().getClass()); - } - - @Test - public void getWordCounterForItalian() { - OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.ITALY); - assertEquals(DefaultWordCounter.class, CountFactory.getWordCounter().getClass()); - } - - @Test - public void getWordCounterForChineseSimplified() { - OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.SIMPLIFIED_CHINESE); - assertEquals(IdeogramsWordCounter.class, CountFactory.getWordCounter().getClass()); - } - - @Test - public void getWordCounterForChineseTraditional() { - OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.TRADITIONAL_CHINESE); - assertEquals(IdeogramsWordCounter.class, CountFactory.getWordCounter().getClass()); - } + @Test + public void getWordCounterForEnglish () { + OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.US); + assertEquals(DefaultWordCounter.class, CountFactory.getWordCounter().getClass()); + } + + @Test + public void getWordCounterForItalian () { + OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.ITALY); + assertEquals(DefaultWordCounter.class, CountFactory.getWordCounter().getClass()); + } + + @Test + public void getWordCounterForChineseSimplified () { + OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.SIMPLIFIED_CHINESE); + assertEquals(IdeogramsWordCounter.class, CountFactory.getWordCounter().getClass()); + } + + @Test + public void getWordCounterForChineseTraditional () { + OmniNotes.getAppContext().getResources().getConfiguration().setLocale(Locale.TRADITIONAL_CHINESE); + assertEquals(IdeogramsWordCounter.class, CountFactory.getWordCounter().getClass()); + } } \ No newline at end of file diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/GeocodeHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/GeocodeHelperTest.java index e4bb55d06e..6f0ea8bde9 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/GeocodeHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/GeocodeHelperTest.java @@ -34,7 +34,7 @@ public class GeocodeHelperTest extends BaseAndroidTestCase { @Test @Suppress - public void testGetAddressFromCoordinates() throws IOException { + public void testGetAddressFromCoordinates () throws IOException { if (ConnectionManager.internetAvailable(OmniNotes.getAppContext())) { Double LAT = 43.799328; Double LON = 11.171552; diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ParcelableUtilTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ParcelableUtilTest.java index 9ed5c44753..97579eab18 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ParcelableUtilTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ParcelableUtilTest.java @@ -17,41 +17,39 @@ package it.feio.android.omninotes.utils; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + import android.net.Uri; import android.support.test.runner.AndroidJUnit4; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - import edu.emory.mathcs.backport.java.util.Collections; import it.feio.android.omninotes.BaseAndroidTestCase; import it.feio.android.omninotes.models.Attachment; import it.feio.android.omninotes.models.Note; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class ParcelableUtilTest extends BaseAndroidTestCase { - Note testNote; - private byte[] marshalledNote; - - @Before - public void setUp() { - testNote = new Note(); - testNote.setAttachmentsList(Collections.singletonList(new Attachment(Uri.EMPTY, ""))); - marshalledNote = ParcelableUtil.marshall(testNote); - } - - @Test - public void unmarshall() { - assertEquals(testNote, ParcelableUtil.unmarshall(marshalledNote, Note.CREATOR)); - } - - @Test - public void marshall() { - assertArrayEquals(marshalledNote, ParcelableUtil.marshall(testNote)); - } + Note testNote; + private byte[] marshalledNote; + + @Before + public void setUp () { + testNote = new Note(); + testNote.setAttachmentsList(Collections.singletonList(new Attachment(Uri.EMPTY, ""))); + marshalledNote = ParcelableUtil.marshall(testNote); + } + + @Test + public void unmarshall () { + assertEquals(testNote, ParcelableUtil.unmarshall(marshalledNote, Note.CREATOR)); + } + + @Test + public void marshall () { + assertArrayEquals(marshalledNote, ParcelableUtil.marshall(testNote)); + } } \ No newline at end of file diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ReminderHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ReminderHelperTest.java index 5d9823c23e..e19002df18 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ReminderHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/ReminderHelperTest.java @@ -17,67 +17,64 @@ package it.feio.android.omninotes.utils; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; - import it.feio.android.omninotes.models.Note; - +import java.util.Calendar; import org.junit.Test; import org.junit.runner.RunWith; -import java.util.Calendar; - -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; -import static org.junit.Assert.assertEquals; - @RunWith(AndroidJUnit4.class) public class ReminderHelperTest { - @Test - public void shouldGetRequestCode() { - Long now = Calendar.getInstance().getTimeInMillis(); - Note note = new Note(); - note.setAlarm(now); - int requestCode = ReminderHelper.getRequestCode(note); - int requestCode2 = ReminderHelper.getRequestCode(note); - assertEquals(requestCode, requestCode2); - assertTrue(String.valueOf(now).startsWith(String.valueOf(requestCode))); - } + @Test + public void shouldGetRequestCode () { + Long now = Calendar.getInstance().getTimeInMillis(); + Note note = new Note(); + note.setAlarm(now); + int requestCode = ReminderHelper.getRequestCode(note); + int requestCode2 = ReminderHelper.getRequestCode(note); + assertEquals(requestCode, requestCode2); + assertTrue(String.valueOf(now).startsWith(String.valueOf(requestCode))); + } - @Test - public void shouldAddReminder() { - Note note = buildNote(); - ReminderHelper.addReminder(InstrumentationRegistry.getTargetContext(), note); - boolean reminderActive = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); - assertTrue(reminderActive); - } + @Test + public void shouldAddReminder () { + Note note = buildNote(); + ReminderHelper.addReminder(InstrumentationRegistry.getTargetContext(), note); + boolean reminderActive = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); + assertTrue(reminderActive); + } - @Test - public void shouldNotAddReminderWithPassedTime() { - Note note = buildNote(); - note.setAlarm(Calendar.getInstance().getTimeInMillis()); - ReminderHelper.addReminder(InstrumentationRegistry.getTargetContext(), note); - boolean reminderActive = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); - assertFalse(reminderActive); - } + @Test + public void shouldNotAddReminderWithPassedTime () { + Note note = buildNote(); + note.setAlarm(Calendar.getInstance().getTimeInMillis()); + ReminderHelper.addReminder(InstrumentationRegistry.getTargetContext(), note); + boolean reminderActive = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); + assertFalse(reminderActive); + } - @Test - public void shouldRemoveReminder() { - Note note = buildNote(); - ReminderHelper.addReminder(InstrumentationRegistry.getTargetContext(), note); - boolean reminderActive = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); - ReminderHelper.removeReminder(InstrumentationRegistry.getTargetContext(), note); - boolean reminderRemoved = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); - assertTrue(reminderActive); - assertFalse(reminderRemoved); - } + @Test + public void shouldRemoveReminder () { + Note note = buildNote(); + ReminderHelper.addReminder(InstrumentationRegistry.getTargetContext(), note); + boolean reminderActive = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); + ReminderHelper.removeReminder(InstrumentationRegistry.getTargetContext(), note); + boolean reminderRemoved = ReminderHelper.checkReminder(InstrumentationRegistry.getTargetContext(), note); + assertTrue(reminderActive); + assertFalse(reminderRemoved); + } - private Note buildNote() { - Long now = Calendar.getInstance().getTimeInMillis(); - Note note = new Note(); - note.setCreation(now); - note.setAlarm(now + 1000); - return note; - } + private Note buildNote () { + Long now = Calendar.getInstance().getTimeInMillis(); + Note note = new Note(); + note.setCreation(now); + note.setAlarm(now + 1000); + return note; + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/SecurityTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/SecurityTest.java index 74b92071b9..03dcce859b 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/SecurityTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/SecurityTest.java @@ -17,38 +17,38 @@ package it.feio.android.omninotes.utils; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; + import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; - @RunWith(AndroidJUnit4.class) public class SecurityTest { - private final String PASS = "12345uselessPasswords"; - private final String TEXT = "Today is a - good - day to test useless things!"; - private final String LOREM = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " + - "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; - - @Test - public void testEncrypt(){ - String encryptedText = Security.encrypt(TEXT, PASS); - assertFalse(TEXT.equals(encryptedText)); - } - - @Test - public void testDecrypt(){ - String encryptedText = Security.encrypt(TEXT, PASS); - assertEquals(TEXT, Security.decrypt(encryptedText, PASS)); - assertFalse(TEXT.equals(Security.decrypt(encryptedText, "zaza" + PASS))); - } - - @Test - public void testDecryptUnencrypted(){ - String result = Security.decrypt(LOREM, PASS); - assertFalse(result.length() == 0); - } + private final String PASS = "12345uselessPasswords"; + private final String TEXT = "Today is a - good - day to test useless things!"; + private final String LOREM = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " + + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; + + @Test + public void testEncrypt () { + String encryptedText = Security.encrypt(TEXT, PASS); + assertFalse(TEXT.equals(encryptedText)); + } + + @Test + public void testDecrypt () { + String encryptedText = Security.encrypt(TEXT, PASS); + assertEquals(TEXT, Security.decrypt(encryptedText, PASS)); + assertFalse(TEXT.equals(Security.decrypt(encryptedText, "zaza" + PASS))); + } + + @Test + public void testDecryptUnencrypted () { + String result = Security.decrypt(LOREM, PASS); + assertFalse(result.length() == 0); + } } diff --git a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/date/DateHelperTest.java b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/date/DateHelperTest.java index 90e3757be3..69110f152b 100644 --- a/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/date/DateHelperTest.java +++ b/omniNotes/src/androidTest/java/it/feio/android/omninotes/utils/date/DateHelperTest.java @@ -18,33 +18,32 @@ package it.feio.android.omninotes.utils.date; import it.feio.android.omninotes.helpers.date.DateHelper; -import org.junit.Assert; - import java.util.Calendar; +import org.junit.Assert; public class DateHelperTest { - private int TEN_MINUTES = 10 * 60 * 1000; - private int MILLISEC_TO_HOURS_RATIO = 60 * 60 * 1000; + private int TEN_MINUTES = 10 * 60 * 1000; + private int MILLISEC_TO_HOURS_RATIO = 60 * 60 * 1000; - public void testNextReminderFromRecurrenceRule() { - long currentTime = Calendar.getInstance().getTimeInMillis(); - long reminder = Calendar.getInstance().getTimeInMillis() + TEN_MINUTES; + public void testNextReminderFromRecurrenceRule () { + long currentTime = Calendar.getInstance().getTimeInMillis(); + long reminder = Calendar.getInstance().getTimeInMillis() + TEN_MINUTES; - // Daily test - String rruleDaily = "FREQ=DAILY;COUNT=30;WKST=MO"; - long nextReminder = DateHelper.nextReminderFromRecurrenceRule(reminder, currentTime, rruleDaily); - Assert.assertNotEquals(0, nextReminder); - Assert.assertEquals(24-1, (nextReminder - reminder) / MILLISEC_TO_HOURS_RATIO); + // Daily test + String rruleDaily = "FREQ=DAILY;COUNT=30;WKST=MO"; + long nextReminder = DateHelper.nextReminderFromRecurrenceRule(reminder, currentTime, rruleDaily); + Assert.assertNotEquals(0, nextReminder); + Assert.assertEquals(24 - 1, (nextReminder - reminder) / MILLISEC_TO_HOURS_RATIO); - // 3-Daily test - String rruleDaily2 = "FREQ=DAILY;COUNT=30;INTERVAL=3"; - long nextReminder2 = DateHelper.nextReminderFromRecurrenceRule(reminder, currentTime, rruleDaily2); - Assert.assertNotEquals(0, nextReminder2); - long delta = (nextReminder2 - reminder) / MILLISEC_TO_HOURS_RATIO; - Assert.assertTrue(delta == 3*24-2 || delta == 3*24-1); // The results depends on the day of week + // 3-Daily test + String rruleDaily2 = "FREQ=DAILY;COUNT=30;INTERVAL=3"; + long nextReminder2 = DateHelper.nextReminderFromRecurrenceRule(reminder, currentTime, rruleDaily2); + Assert.assertNotEquals(0, nextReminder2); + long delta = (nextReminder2 - reminder) / MILLISEC_TO_HOURS_RATIO; + Assert.assertTrue(delta == 3 * 24 - 2 || delta == 3 * 24 - 1); // The results depends on the day of week - } + } } diff --git a/omniNotes/src/beta/java/it/feio/android/omninotes/utils/Constants.java b/omniNotes/src/beta/java/it/feio/android/omninotes/utils/Constants.java index 7789b1c1cf..492b9651dd 100644 --- a/omniNotes/src/beta/java/it/feio/android/omninotes/utils/Constants.java +++ b/omniNotes/src/beta/java/it/feio/android/omninotes/utils/Constants.java @@ -3,9 +3,9 @@ public interface Constants extends ConstantsBase { - String TAG = "Omni Notes Beta"; - String EXTERNAL_STORAGE_FOLDER = "Omni Notes Beta"; - String PACKAGE = "it.feio.android.omninotes"; - String PREFS_NAME = PACKAGE + "_preferences"; + String TAG = "Omni Notes Beta"; + String EXTERNAL_STORAGE_FOLDER = "Omni Notes Beta"; + String PACKAGE = "it.feio.android.omninotes"; + String PREFS_NAME = PACKAGE + "_preferences"; } diff --git a/omniNotes/src/foss/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java b/omniNotes/src/foss/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java index c27b64cefb..b21818d999 100644 --- a/omniNotes/src/foss/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java +++ b/omniNotes/src/foss/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java @@ -18,13 +18,12 @@ package it.feio.android.omninotes.helpers; import android.content.Context; - import io.nlopez.smartlocation.location.LocationProvider; import io.nlopez.smartlocation.location.providers.LocationManagerProvider; public class GeocodeProviderFactory { - public static LocationProvider getProvider(Context context) { - return new LocationManagerProvider(); - } + public static LocationProvider getProvider (Context context) { + return new LocationManagerProvider(); + } } \ No newline at end of file diff --git a/omniNotes/src/foss/java/it/feio/android/omninotes/utils/Constants.java b/omniNotes/src/foss/java/it/feio/android/omninotes/utils/Constants.java index d9b4662040..b4885d69e7 100644 --- a/omniNotes/src/foss/java/it/feio/android/omninotes/utils/Constants.java +++ b/omniNotes/src/foss/java/it/feio/android/omninotes/utils/Constants.java @@ -18,7 +18,7 @@ public interface Constants extends ConstantsBase { - String TAG = "Omni Notes FOSS"; + String TAG = "Omni Notes FOSS"; String EXTERNAL_STORAGE_FOLDER = "Omni Notes Foss"; String PACKAGE = "it.feio.android.omninotes.foss"; String PREFS_NAME = PACKAGE + "_preferences"; diff --git a/omniNotes/src/main/java/it.feio.android.omninotes.helpers/GeocodeProviderBaseFactory.java b/omniNotes/src/main/java/it.feio.android.omninotes.helpers/GeocodeProviderBaseFactory.java index 5f23eb8e78..683132b236 100644 --- a/omniNotes/src/main/java/it.feio.android.omninotes.helpers/GeocodeProviderBaseFactory.java +++ b/omniNotes/src/main/java/it.feio.android.omninotes.helpers/GeocodeProviderBaseFactory.java @@ -18,13 +18,12 @@ package it.feio.android.omninotes.helpers; import android.content.Context; - import io.nlopez.smartlocation.location.LocationProvider; import io.nlopez.smartlocation.location.providers.LocationGooglePlayServicesWithFallbackProvider; public class GeocodeProviderBaseFactory { - public static LocationProvider getProvider(Context context) { - return new LocationGooglePlayServicesWithFallbackProvider(context); - } + public static LocationProvider getProvider (Context context) { + return new LocationGooglePlayServicesWithFallbackProvider(context); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/AboutActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/AboutActivity.java index ef312677c5..f2170f4836 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/AboutActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/AboutActivity.java @@ -23,37 +23,37 @@ public class AboutActivity extends BaseActivity { - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_about); + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_about); - WebView webview = findViewById(R.id.webview); - webview.loadUrl("file:///android_asset/html/about.html"); + WebView webview = findViewById(R.id.webview); + webview.loadUrl("file:///android_asset/html/about.html"); - initUI(); - } + initUI(); + } - @Override - public void onStart() { - ((OmniNotes)getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); - super.onStart(); - } + @Override + public void onStart () { + ((OmniNotes) getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); + super.onStart(); + } - @Override - public boolean onNavigateUp() { - onBackPressed(); - return true; - } + @Override + public boolean onNavigateUp () { + onBackPressed(); + return true; + } - private void initUI() { - Toolbar toolbar = findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); - toolbar.setNavigationOnClickListener(v -> onNavigateUp()); - } + private void initUI () { + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setHomeButtonEnabled(true); + toolbar.setNavigationOnClickListener(v -> onNavigateUp()); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/BaseActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/BaseActivity.java index 2c498eebb3..dce189c0ed 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/BaseActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/BaseActivity.java @@ -34,11 +34,6 @@ import android.view.MenuInflater; import android.view.ViewConfiguration; import android.widget.Toast; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.List; - import it.feio.android.omninotes.helpers.LanguageHelper; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Note; @@ -47,167 +42,168 @@ import it.feio.android.omninotes.utils.Navigation; import it.feio.android.omninotes.utils.PasswordHelper; import it.feio.android.omninotes.widget.ListWidgetProvider; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; @SuppressLint("Registered") public class BaseActivity extends AppCompatActivity { - protected final int TRANSITION_VERTICAL = 0; - protected final int TRANSITION_HORIZONTAL = 1; + protected final int TRANSITION_VERTICAL = 0; + protected final int TRANSITION_HORIZONTAL = 1; + + protected SharedPreferences prefs; + + protected String navigation; + protected String navigationTmp; // used for widget navigation + + + @Override + public boolean onCreateOptionsMenu (Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.menu_list, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + protected void attachBaseContext (Context newBase) { + Context context = LanguageHelper.updateLanguage(newBase, null); + super.attachBaseContext(context); + } + + @Override + protected void onCreate (Bundle savedInstanceState) { + prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); + // Forces menu overflow icon + try { + ViewConfiguration config = ViewConfiguration.get(this.getApplicationContext()); + Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); + if (menuKeyField != null) { + menuKeyField.setAccessible(true); + menuKeyField.setBoolean(config, false); + } + } catch (Exception e) { + LogDelegate.w("Just a little issue in physical menu button management", e); + } + super.onCreate(savedInstanceState); + } - protected SharedPreferences prefs; - protected String navigation; - protected String navigationTmp; // used for widget navigation + @Override + protected void onResume () { + super.onResume(); + String navNotes = getResources().getStringArray(R.array.navigation_list_codes)[0]; + navigation = prefs.getString(Constants.PREF_NAVIGATION, navNotes); + LogDelegate.d(prefs.getAll().toString()); + } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.menu_list, menu); - return super.onCreateOptionsMenu(menu); + protected void showToast (CharSequence text, int duration) { + if (prefs.getBoolean("settings_enable_info", true)) { + Toast.makeText(getApplicationContext(), text, duration).show(); } - - @Override - protected void attachBaseContext(Context newBase) { - Context context = LanguageHelper.updateLanguage(newBase, null); - super.attachBaseContext(context); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); - // Forces menu overflow icon - try { - ViewConfiguration config = ViewConfiguration.get(this.getApplicationContext()); - Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); - if (menuKeyField != null) { - menuKeyField.setAccessible(true); - menuKeyField.setBoolean(config, false); - } - } catch (Exception e) { - LogDelegate.w("Just a little issue in physical menu button management", e); - } - super.onCreate(savedInstanceState); + } + + + /** + * Method to validate security password to protect a list of notes. When "Request password on access" in switched on + * this check not required all the times. It uses an interface callback. + */ + public void requestPassword (final Activity mActivity, List notes, + final PasswordValidator mPasswordValidator) { + if (prefs.getBoolean("settings_password_access", false)) { + mPasswordValidator.onPasswordValidated(PasswordValidator.Result.SUCCEED); + return; } - - @Override - protected void onResume() { - super.onResume(); - String navNotes = getResources().getStringArray(R.array.navigation_list_codes)[0]; - navigation = prefs.getString(Constants.PREF_NAVIGATION, navNotes); - LogDelegate.d(prefs.getAll().toString()); + boolean askForPassword = false; + for (Note note : notes) { + if (note.isLocked()) { + askForPassword = true; + break; + } } - - - protected void showToast(CharSequence text, int duration) { - if (prefs.getBoolean("settings_enable_info", true)) { - Toast.makeText(getApplicationContext(), text, duration).show(); - } + if (askForPassword) { + PasswordHelper.requestPassword(mActivity, mPasswordValidator); + } else { + mPasswordValidator.onPasswordValidated(PasswordValidator.Result.SUCCEED); } + } - /** - * Method to validate security password to protect a list of notes. - * When "Request password on access" in switched on this check not required all the times. - * It uses an interface callback. - */ - public void requestPassword(final Activity mActivity, List notes, - final PasswordValidator mPasswordValidator) { - if (prefs.getBoolean("settings_password_access", false)) { - mPasswordValidator.onPasswordValidated(PasswordValidator.Result.SUCCEED); - return; - } - - boolean askForPassword = false; - for (Note note : notes) { - if (note.isLocked()) { - askForPassword = true; - break; - } - } - if (askForPassword) { - PasswordHelper.requestPassword(mActivity, mPasswordValidator); - } else { - mPasswordValidator.onPasswordValidated(PasswordValidator.Result.SUCCEED); - } - } - - - public boolean updateNavigation(String nav) { - if (nav.equals(navigationTmp) || (navigationTmp == null && Navigation.getNavigationText().equals(nav))) { - return false; - } - prefs.edit().putString(Constants.PREF_NAVIGATION, nav).apply(); - navigation = nav; - navigationTmp = null; - return true; - } - - - /** - * Retrieves resource by name - * - * @param aString - * @returnnotifyAppWidgets - */ - private String getStringResourceByName(String aString) { - String packageName = getApplicationContext().getPackageName(); - int resId = getResources().getIdentifier(aString, "string", packageName); - return getString(resId); + public boolean updateNavigation (String nav) { + if (nav.equals(navigationTmp) || (navigationTmp == null && Navigation.getNavigationText().equals(nav))) { + return false; } - - - /** - * Notifies App Widgets about data changes so they can update theirselves - */ - public static void notifyAppWidgets(Context context) { - // Home widgets - AppWidgetManager mgr = AppWidgetManager.getInstance(context); - int[] ids = mgr.getAppWidgetIds(new ComponentName(context, ListWidgetProvider.class)); - LogDelegate.d("Notifies AppWidget data changed for widgets " + Arrays.toString(ids)); - mgr.notifyAppWidgetViewDataChanged(ids, R.id.widget_list); - - // Dashclock - LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(Constants.INTENT_UPDATE_DASHCLOCK)); + prefs.edit().putString(Constants.PREF_NAVIGATION, nav).apply(); + navigation = nav; + navigationTmp = null; + return true; + } + + + /** + * Retrieves resource by name + * + * @returnnotifyAppWidgets + */ + private String getStringResourceByName (String aString) { + String packageName = getApplicationContext().getPackageName(); + int resId = getResources().getIdentifier(aString, "string", packageName); + return getString(resId); + } + + + /** + * Notifies App Widgets about data changes so they can update theirselves + */ + public static void notifyAppWidgets (Context context) { + // Home widgets + AppWidgetManager mgr = AppWidgetManager.getInstance(context); + int[] ids = mgr.getAppWidgetIds(new ComponentName(context, ListWidgetProvider.class)); + LogDelegate.d("Notifies AppWidget data changed for widgets " + Arrays.toString(ids)); + mgr.notifyAppWidgetViewDataChanged(ids, R.id.widget_list); + + // Dashclock + LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(Constants.INTENT_UPDATE_DASHCLOCK)); + } + + + @SuppressLint("InlinedApi") + protected void animateTransition (FragmentTransaction transaction, int direction) { + if (direction == TRANSITION_HORIZONTAL) { + transaction.setCustomAnimations(R.anim.fade_in_support, R.anim.fade_out_support, + R.anim.fade_in_support, R.anim.fade_out_support); } - - - @SuppressLint("InlinedApi") - protected void animateTransition(FragmentTransaction transaction, int direction) { - if (direction == TRANSITION_HORIZONTAL) { - transaction.setCustomAnimations(R.anim.fade_in_support, R.anim.fade_out_support, - R.anim.fade_in_support, R.anim.fade_out_support); - } - if (direction == TRANSITION_VERTICAL) { - transaction.setCustomAnimations( - R.anim.anim_in, R.anim.anim_out, R.anim.anim_in_pop, R.anim.anim_out_pop); - } + if (direction == TRANSITION_VERTICAL) { + transaction.setCustomAnimations( + R.anim.anim_in, R.anim.anim_out, R.anim.anim_in_pop, R.anim.anim_out_pop); } + } - protected void setActionBarTitle(String title) { - // Creating a spannable to support custom fonts on ActionBar - int actionBarTitle = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); - android.widget.TextView actionBarTitleView = (android.widget.TextView) getWindow().findViewById(actionBarTitle); - Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf"); - if (actionBarTitleView != null) { - actionBarTitleView.setTypeface(font); - } + protected void setActionBarTitle (String title) { + // Creating a spannable to support custom fonts on ActionBar + int actionBarTitle = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); + android.widget.TextView actionBarTitleView = getWindow().findViewById(actionBarTitle); + Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf"); + if (actionBarTitleView != null) { + actionBarTitleView.setTypeface(font); + } - if (getSupportActionBar() != null) { - getSupportActionBar().setTitle(title); - } + if (getSupportActionBar() != null) { + getSupportActionBar().setTitle(title); } + } - public String getNavigationTmp() { - return navigationTmp; - } + public String getNavigationTmp () { + return navigationTmp; + } - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - return keyCode == KeyEvent.KEYCODE_MENU || super.onKeyDown(keyCode, event); - } + @Override + public boolean onKeyDown (int keyCode, KeyEvent event) { + return keyCode == KeyEvent.KEYCODE_MENU || super.onKeyDown(keyCode, event); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/BaseFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/BaseFragment.java index 02f49ed93e..cfd2b878ba 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/BaseFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/BaseFragment.java @@ -19,33 +19,32 @@ import android.os.SystemClock; import android.support.v4.app.Fragment; - import com.squareup.leakcanary.LeakCanary; public class BaseFragment extends Fragment { - private static final long OPTIONS_ITEM_CLICK_DELAY_TIME = 1000; - private long mLastClickTime; + private static final long OPTIONS_ITEM_CLICK_DELAY_TIME = 1000; + private long mLastClickTime; - @Override - public void onStart() { - super.onStart(); - ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); - } + @Override + public void onStart () { + super.onStart(); + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); + } - @Override - public void onDestroy() { - super.onDestroy(); - LeakCanary.installedRefWatcher().watch(this); - } + @Override + public void onDestroy () { + super.onDestroy(); + LeakCanary.installedRefWatcher().watch(this); + } - protected boolean isOptionsItemFastClick() { - if (SystemClock.elapsedRealtime() - mLastClickTime < OPTIONS_ITEM_CLICK_DELAY_TIME){ - return true; - } - mLastClickTime = SystemClock.elapsedRealtime(); - return false; + protected boolean isOptionsItemFastClick () { + if (SystemClock.elapsedRealtime() - mLastClickTime < OPTIONS_ITEM_CLICK_DELAY_TIME) { + return true; } + mLastClickTime = SystemClock.elapsedRealtime(); + return false; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/CategoryActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/CategoryActivity.java index 1f0e6bd1ee..020879bc83 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/CategoryActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/CategoryActivity.java @@ -17,6 +17,8 @@ package it.feio.android.omninotes; +import static java.lang.Integer.parseInt; + import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; @@ -32,19 +34,12 @@ import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; - -import com.afollestad.materialdialogs.DialogAction; -import com.afollestad.materialdialogs.MaterialDialog; -import com.afollestad.materialdialogs.color.ColorChooserDialog; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Random; - import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; +import com.afollestad.materialdialogs.DialogAction; +import com.afollestad.materialdialogs.MaterialDialog; +import com.afollestad.materialdialogs.color.ColorChooserDialog; import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.bus.CategoriesUpdatedEvent; import it.feio.android.omninotes.db.DbHelper; @@ -52,173 +47,181 @@ import it.feio.android.omninotes.models.Category; import it.feio.android.omninotes.utils.Constants; import it.feio.android.simplegallery.util.BitmapUtils; - -import static java.lang.Integer.parseInt; +import java.io.File; +import java.io.FileOutputStream; +import java.util.Calendar; +import java.util.Random; -public class CategoryActivity extends AppCompatActivity implements ColorChooserDialog.ColorCallback{ +public class CategoryActivity extends AppCompatActivity implements ColorChooserDialog.ColorCallback { - @BindView(R.id.category_title) EditText title; - @BindView(R.id.category_description) EditText description; - @BindView(R.id.delete) Button deleteBtn; - @BindView(R.id.save) Button saveBtn; - @BindView(R.id.color_chooser) ImageView colorChooser; + @BindView(R.id.category_title) + EditText title; + @BindView(R.id.category_description) + EditText description; + @BindView(R.id.delete) + Button deleteBtn; + @BindView(R.id.save) + Button saveBtn; + @BindView(R.id.color_chooser) + ImageView colorChooser; - Category category; - private int selectedColor; + Category category; + private int selectedColor; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_category); - ButterKnife.bind(this); + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_category); + ButterKnife.bind(this); - category = getIntent().getParcelableExtra(Constants.INTENT_CATEGORY); + category = getIntent().getParcelableExtra(Constants.INTENT_CATEGORY); - if (category == null) { - LogDelegate.d("Adding new category"); - category = new Category(); - category.setColor(String.valueOf(getRandomPaletteColor())); - } else { - LogDelegate.d("Editing category " + category.getName()); - } - selectedColor = parseInt(category.getColor()); - populateViews(); + if (category == null) { + LogDelegate.d("Adding new category"); + category = new Category(); + category.setColor(String.valueOf(getRandomPaletteColor())); + } else { + LogDelegate.d("Editing category " + category.getName()); } + selectedColor = parseInt(category.getColor()); + populateViews(); + } - private int getRandomPaletteColor() { - int[] paletteArray = getResources().getIntArray(R.array.material_colors); - return paletteArray[new Random().nextInt((paletteArray.length))]; - } + private int getRandomPaletteColor () { + int[] paletteArray = getResources().getIntArray(R.array.material_colors); + return paletteArray[new Random().nextInt((paletteArray.length))]; + } - @OnClick(R.id.color_chooser) - public void showColorChooserCustomColors() { + @OnClick(R.id.color_chooser) + public void showColorChooserCustomColors () { - new ColorChooserDialog.Builder(this, R.string.colors) - .dynamicButtonColor(false) - .preselect(selectedColor) - .show(); - } + new ColorChooserDialog.Builder(this, R.string.colors) + .dynamicButtonColor(false) + .preselect(selectedColor) + .show(); + } - @Override - public void onColorSelection(ColorChooserDialog colorChooserDialog, int color) { - BitmapUtils.changeImageViewDrawableColor(colorChooser, color); - selectedColor = color; - } + @Override + public void onColorSelection (ColorChooserDialog colorChooserDialog, int color) { + BitmapUtils.changeImageViewDrawableColor(colorChooser, color); + selectedColor = color; + } - private void populateViews() { - title.setText(category.getName()); - description.setText(category.getDescription()); - // Reset picker to saved color - String color = category.getColor(); - if (color != null && color.length() > 0) { - colorChooser.getDrawable().mutate().setColorFilter(parseInt(color), PorterDuff.Mode.SRC_ATOP); - } - deleteBtn.setVisibility(TextUtils.isEmpty(category.getName()) ? View.INVISIBLE : View.VISIBLE); + private void populateViews () { + title.setText(category.getName()); + description.setText(category.getDescription()); + // Reset picker to saved color + String color = category.getColor(); + if (color != null && color.length() > 0) { + colorChooser.getDrawable().mutate().setColorFilter(parseInt(color), PorterDuff.Mode.SRC_ATOP); } + deleteBtn.setVisibility(TextUtils.isEmpty(category.getName()) ? View.INVISIBLE : View.VISIBLE); + } - /** - * Category saving - */ - @OnClick(R.id.save) - public void saveCategory() { - - if (title.getText().toString().length() == 0) { - title.setError(getString(R.string.category_missing_title)); - return; - } - - Long id = category.getId() != null ? category.getId() : Calendar.getInstance().getTimeInMillis(); - category.setId(id); - category.setName(title.getText().toString()); - category.setDescription(description.getText().toString()); - if (selectedColor != 0 || category.getColor() == null) { - category.setColor(String.valueOf(selectedColor)); - } - - // Saved to DB and new id or update result catched - DbHelper db = DbHelper.getInstance(); - category = db.updateCategory(category); - - // Sets result to show proper message - getIntent().putExtra(Constants.INTENT_CATEGORY, category); - setResult(RESULT_OK, getIntent()); - finish(); - } + /** + * Category saving + */ + @OnClick(R.id.save) + public void saveCategory () { + if (title.getText().toString().length() == 0) { + title.setError(getString(R.string.category_missing_title)); + return; + } - @OnClick(R.id.delete) - public void deleteCategory() { - - new MaterialDialog.Builder(this) - .title(R.string.delete_unused_category_confirmation) - .content(R.string.delete_category_confirmation) - .positiveText(R.string.confirm) - .positiveColorRes(R.color.colorAccent) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick( - @NonNull MaterialDialog dialog, @NonNull DialogAction which) { - // Changes navigation if actually are shown notes associated with this category - SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); - String navNotes = getResources().getStringArray(R.array.navigation_list_codes)[0]; - String navigation = prefs.getString(Constants.PREF_NAVIGATION, navNotes); - if (String.valueOf(category.getId()).equals(navigation)) - prefs.edit().putString(Constants.PREF_NAVIGATION, navNotes).apply(); - // Removes category and edit notes associated with it - DbHelper db = DbHelper.getInstance(); - db.deleteCategory(category); - - EventBus.getDefault().post(new CategoriesUpdatedEvent()); - BaseActivity.notifyAppWidgets(OmniNotes.getAppContext()); - - setResult(RESULT_FIRST_USER); - finish(); - } - }).build().show(); + Long id = category.getId() != null ? category.getId() : Calendar.getInstance().getTimeInMillis(); + category.setId(id); + category.setName(title.getText().toString()); + category.setDescription(description.getText().toString()); + if (selectedColor != 0 || category.getColor() == null) { + category.setColor(String.valueOf(selectedColor)); } + // Saved to DB and new id or update result catched + DbHelper db = DbHelper.getInstance(); + category = db.updateCategory(category); + + // Sets result to show proper message + getIntent().putExtra(Constants.INTENT_CATEGORY, category); + setResult(RESULT_OK, getIntent()); + finish(); + } + + + @OnClick(R.id.delete) + public void deleteCategory () { + + new MaterialDialog.Builder(this) + .title(R.string.delete_unused_category_confirmation) + .content(R.string.delete_category_confirmation) + .positiveText(R.string.confirm) + .positiveColorRes(R.color.colorAccent) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick ( + @NonNull MaterialDialog dialog, @NonNull DialogAction which) { + // Changes navigation if actually are shown notes associated with this category + SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); + String navNotes = getResources().getStringArray(R.array.navigation_list_codes)[0]; + String navigation = prefs.getString(Constants.PREF_NAVIGATION, navNotes); + if (String.valueOf(category.getId()).equals(navigation)) { + prefs.edit().putString(Constants.PREF_NAVIGATION, navNotes).apply(); + } + // Removes category and edit notes associated with it + DbHelper db = DbHelper.getInstance(); + db.deleteCategory(category); + + EventBus.getDefault().post(new CategoriesUpdatedEvent()); + BaseActivity.notifyAppWidgets(OmniNotes.getAppContext()); - public void goHome() { - // In this case the caller activity is DetailActivity - if (getIntent().getBooleanExtra("noHome", false)) { - setResult(RESULT_OK); - super.finish(); - } - NavUtils.navigateUpFromSameTask(this); + setResult(RESULT_FIRST_USER); + finish(); + } + }).build().show(); + } + + + public void goHome () { + // In this case the caller activity is DetailActivity + if (getIntent().getBooleanExtra("noHome", false)) { + setResult(RESULT_OK); + super.finish(); } + NavUtils.navigateUpFromSameTask(this); + } - public void save(Bitmap bitmap) { - if (bitmap == null) { - setResult(RESULT_CANCELED); - super.finish(); - } - - try { - Uri uri = getIntent().getParcelableExtra(MediaStore.EXTRA_OUTPUT); - File bitmapFile = new File(uri.getPath()); - FileOutputStream out = new FileOutputStream(bitmapFile); - assert bitmap != null; - bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); - - if (bitmapFile.exists()) { - Intent localIntent = new Intent().setData(Uri - .fromFile(bitmapFile)); - setResult(RESULT_OK, localIntent); - } else { - setResult(RESULT_CANCELED); - } - super.finish(); + public void save (Bitmap bitmap) { + if (bitmap == null) { + setResult(RESULT_CANCELED); + super.finish(); + } - } catch (Exception e) { - LogDelegate.w("Bitmap not found", e); - } + try { + Uri uri = getIntent().getParcelableExtra(MediaStore.EXTRA_OUTPUT); + File bitmapFile = new File(uri.getPath()); + FileOutputStream out = new FileOutputStream(bitmapFile); + assert bitmap != null; + bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); + + if (bitmapFile.exists()) { + Intent localIntent = new Intent().setData(Uri + .fromFile(bitmapFile)); + setResult(RESULT_OK, localIntent); + } else { + setResult(RESULT_CANCELED); + } + super.finish(); + + } catch (Exception e) { + LogDelegate.w("Bitmap not found", e); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/DetailFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/DetailFragment.java index c4e00be360..d2f6abb1a0 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/DetailFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/DetailFragment.java @@ -16,6 +16,10 @@ */ package it.feio.android.omninotes; +import static com.nineoldandroids.view.ViewPropertyAnimator.animate; +import static java.lang.Integer.parseInt; +import static java.lang.Long.parseLong; + import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; @@ -74,28 +78,13 @@ import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.Toast; - +import butterknife.BindView; +import butterknife.ButterKnife; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.neopixl.pixlui.components.edittext.EditText; import com.neopixl.pixlui.components.textview.TextView; import com.pushbullet.android.extension.MessagingExtension; - -import org.apache.commons.lang.StringUtils; - -import java.io.File; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; import de.greenrobot.event.EventBus; import de.keyboardsurfer.android.widget.crouton.Style; import it.feio.android.checklistview.exceptions.ViewNotSupportedException; @@ -146,2154 +135,2171 @@ import it.feio.android.omninotes.utils.date.DateUtils; import it.feio.android.omninotes.utils.date.ReminderPickers; import it.feio.android.pixlui.links.TextLinkClickListener; +import java.io.File; +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import org.apache.commons.lang.StringUtils; import rx.Observable; -import static com.nineoldandroids.view.ViewPropertyAnimator.animate; -import static java.lang.Integer.parseInt; -import static java.lang.Long.parseLong; - public class DetailFragment extends BaseFragment implements OnReminderPickedListener, OnTouchListener, - OnAttachingFileListener, TextWatcher, CheckListChangedListener, OnNoteSaved, - OnGeoUtilResultListener { - - private static final int TAKE_PHOTO = 1; - private static final int TAKE_VIDEO = 2; - private static final int SET_PASSWORD = 3; - private static final int SKETCH = 4; - private static final int CATEGORY = 5; - private static final int DETAIL = 6; - private static final int FILES = 7; - private static final int RC_READ_EXTERNAL_STORAGE_PERMISSION = 1; - public OnDateSetListener onDateSetListener; - public OnTimeSetListener onTimeSetListener; - public boolean goBack = false; - @BindView(R.id.detail_root) - ViewGroup root; - @BindView(R.id.detail_title) - EditText title; - @BindView(R.id.detail_content) - EditText content; - @BindView(R.id.detail_attachments_above) - ViewStub attachmentsAbove; - @BindView(R.id.detail_attachments_below) - ViewStub attachmentsBelow; - @Nullable - @BindView(R.id.gridview) - ExpandableHeightGridView mGridView; - @BindView(R.id.location) - TextView locationTextView; - @BindView(R.id.detail_timestamps) - View timestampsView; - @BindView(R.id.reminder_layout) - LinearLayout reminder_layout; - @BindView(R.id.reminder_icon) - ImageView reminderIcon; - @BindView(R.id.datetime) - TextView datetime; - @BindView(R.id.detail_tile_card) - View titleCardView; - @BindView(R.id.content_wrapper) - ScrollView scrollView; - @BindView(R.id.creation) - TextView creationTextView; - @BindView(R.id.last_modification) - TextView lastModificationTextView; - @BindView(R.id.title_wrapper) - View titleWrapperView; - @BindView(R.id.tag_marker) - View tagMarkerView; - @BindView(R.id.detail_wrapper) - ViewManager detailWrapperView; - @BindView(R.id.snackbar_placeholder) - View snackBarPlaceholder; - View toggleChecklistView; - private Uri attachmentUri; - private AttachmentAdapter mAttachmentAdapter; - private MaterialDialog attachmentDialog; - private Note note; - private Note noteTmp; - private Note noteOriginal; - // Audio recording - private String recordName; - private MediaRecorder mRecorder = null; - private MediaPlayer mPlayer = null; - private boolean isRecording = false; - private View isPlayingView = null; - private Bitmap recordingBitmap; - private ChecklistManager mChecklistManager; - // Values to print result - private String exitMessage; - private Style exitCroutonStyle = ONStyle.CONFIRM; - // Flag to check if after editing it will return to ListActivity or not - // and in the last case a Toast will be shown instead than Crouton - private boolean afterSavedReturnsToList = true; - private boolean showKeyboard = false; - private boolean swiping; - private int startSwipeX; - private SharedPreferences prefs; - private boolean orientationChanged; - private long audioRecordingTimeStart; - private long audioRecordingTime; - private DetailFragment mFragment; - private Attachment sketchEdited; - private int contentLineCounter = 1; - private int contentCursorPosition; - private ArrayList mergedNotesIds; - private MainActivity mainActivity; - TextLinkClickListener textLinkClickListener = new TextLinkClickListener() { - @Override - public void onTextLinkClick(View view, final String clickedString, final String url) { - new MaterialDialog.Builder(mainActivity) - .content(clickedString) - .negativeColorRes(R.color.colorPrimary) - .positiveText(R.string.open) - .negativeText(R.string.copy) - .onPositive((dialog, which) -> { - boolean error = false; - Intent intent = null; - try { - intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - intent.addCategory(Intent.CATEGORY_BROWSABLE); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - } catch (NullPointerException e) { - error = true; - } - - if (intent == null - || error - || !IntentChecker - .isAvailable( - mainActivity, - intent, - new String[]{PackageManager.FEATURE_CAMERA})) { - mainActivity.showMessage(R.string.no_application_can_perform_this_action, - ONStyle.ALERT); - - } else { - startActivity(intent); - } - }) - .onNegative((dialog, which) -> { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager) - mainActivity - .getSystemService(Activity.CLIPBOARD_SERVICE); - android.content.ClipData clip = android.content.ClipData.newPlainText("text label", - clickedString); - clipboard.setPrimaryClip(clip); - }).build().show(); - View clickedView = noteTmp.isChecklist() ? toggleChecklistView : content; - clickedView.clearFocus(); - KeyboardUtils.hideKeyboard(clickedView); - new Handler().post(() -> { - View clickedView1 = noteTmp.isChecklist() ? toggleChecklistView : content; - KeyboardUtils.hideKeyboard(clickedView1); - }); - } - }; - private boolean activityPausing; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mFragment = this; - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.CHILDREN)); - } - - @Override - public void onStop() { - super.onStop(); - GeocodeHelper.stop(); - } - - @Override - public void onResume() { - super.onResume(); - activityPausing = false; - EventBus.getDefault().register(this); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_detail, container, false); - ButterKnife.bind(this, view); - return view; - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - mainActivity = (MainActivity) getActivity(); - - prefs = mainActivity.prefs; - - mainActivity.getSupportActionBar().setDisplayShowTitleEnabled(false); - mainActivity.getToolbar().setNavigationOnClickListener(v -> navigateUp()); - - // Force the navigation drawer to stay opened if tablet mode is on, otherwise has to stay closed - if (NavigationDrawerFragment.isDoublePanelActive()) { - mainActivity.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN); - } else { - mainActivity.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); - } - - // Restored temp note after orientation change - if (savedInstanceState != null) { - noteTmp = savedInstanceState.getParcelable("noteTmp"); - note = savedInstanceState.getParcelable("note"); - noteOriginal = savedInstanceState.getParcelable("noteOriginal"); - attachmentUri = savedInstanceState.getParcelable("attachmentUri"); - orientationChanged = savedInstanceState.getBoolean("orientationChanged"); - } - - // Added the sketched image if present returning from SketchFragment - if (mainActivity.sketchUri != null) { - Attachment mAttachment = new Attachment(mainActivity.sketchUri, Constants.MIME_TYPE_SKETCH); - addAttachment(mAttachment); - mainActivity.sketchUri = null; - // Removes previous version of edited image - if (sketchEdited != null) { - noteTmp.getAttachmentsList().remove(sketchEdited); - sketchEdited = null; - } - } - - init(); - - setHasOptionsMenu(true); - setRetainInstance(false); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - if (noteTmp != null) { - noteTmp.setTitle(getNoteTitle()); - noteTmp.setContent(getNoteContent()); - outState.putParcelable("noteTmp", noteTmp); - outState.putParcelable("note", note); - outState.putParcelable("noteOriginal", noteOriginal); - outState.putParcelable("attachmentUri", attachmentUri); - outState.putBoolean("orientationChanged", orientationChanged); - } - super.onSaveInstanceState(outState); - } - - @Override - public void onPause() { - super.onPause(); - - //to prevent memory leak fragment keep refernce of event but until deregister - EventBus.getDefault().unregister(this); - - activityPausing = true; - - // Checks "goBack" value to avoid performing a double saving - if (!goBack) { - saveNote(this); - } - - if (toggleChecklistView != null) { - KeyboardUtils.hideKeyboard(toggleChecklistView); - content.clearFocus(); - } - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - if (getResources().getConfiguration().orientation != newConfig.orientation) { - orientationChanged = true; - } - } - - private void init() { - - // Handling of Intent actions - handleIntents(); - - if (noteOriginal == null) { - noteOriginal = getArguments().getParcelable(Constants.INTENT_NOTE); - } - - if (note == null) { - note = new Note(noteOriginal); - } - - if (noteTmp == null) { - noteTmp = new Note(note); - } - - if (noteTmp.isLocked() && !noteTmp.isPasswordChecked()) { - checkNoteLock(noteTmp); - return; - } - - initViews(); - } - - /** - * Checks note lock and password before showing note content - */ - private void checkNoteLock(Note note) { - // If note is locked security password will be requested - if (note.isLocked() - && prefs.getString(Constants.PREF_PASSWORD, null) != null - && !prefs.getBoolean("settings_password_access", false)) { - PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { - switch (passwordConfirmed) { - case SUCCEED: - noteTmp.setPasswordChecked(true); - init(); - break; - case FAIL: - goBack = true; - goHome(); - break; - case RESTORE: - goBack = true; - goHome(); - PasswordHelper.resetPassword(mainActivity); - break; - } - }); - } else { - noteTmp.setPasswordChecked(true); - init(); - } - } - - private void handleIntents() { - Intent i = mainActivity.getIntent(); - - if (IntentChecker.checkAction(i, Constants.ACTION_MERGE)) { - noteOriginal = new Note(); - note = new Note(noteOriginal); - noteTmp = getArguments().getParcelable(Constants.INTENT_NOTE); - if (i.getStringArrayListExtra("merged_notes") != null) { - mergedNotesIds = i.getStringArrayListExtra("merged_notes"); - } - } - - // Action called from home shortcut - if (IntentChecker.checkAction(i, Constants.ACTION_SHORTCUT, Constants.ACTION_NOTIFICATION_CLICK)) { - afterSavedReturnsToList = false; - noteOriginal = DbHelper.getInstance().getNote(i.getLongExtra(Constants.INTENT_KEY, 0)); - // Checks if the note pointed from the shortcut has been deleted - try { - note = new Note(noteOriginal); - noteTmp = new Note(noteOriginal); - } catch (NullPointerException e) { - mainActivity.showToast(getText(R.string.shortcut_note_deleted), Toast.LENGTH_LONG); - mainActivity.finish(); - } - } - - // Check if is launched from a widget - if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET, Constants.ACTION_WIDGET_TAKE_PHOTO)) { - - afterSavedReturnsToList = false; - showKeyboard = true; - - // with tags to set tag - if (i.hasExtra(Constants.INTENT_WIDGET)) { - String widgetId = i.getExtras().get(Constants.INTENT_WIDGET).toString(); - if (widgetId != null) { - String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, ""); - String categoryId = TextHelper.checkIntentCategory(sqlCondition); - if (categoryId != null) { - Category category; - try { - category = DbHelper.getInstance().getCategory(parseLong(categoryId)); - noteTmp = new Note(); - noteTmp.setCategory(category); - } catch (NumberFormatException e) { - LogDelegate.e("Category with not-numeric value!", e); - } - } - } - } - - // Sub-action is to take a photo - if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET_TAKE_PHOTO)) { - takePhoto(); - } - } - - if (IntentChecker.checkAction(i, Constants.ACTION_FAB_TAKE_PHOTO)) { - takePhoto(); - } - - // Handles third party apps requests of sharing - if (IntentChecker.checkAction(i, Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE, Constants.INTENT_GOOGLE_NOW) - && i.getType() != null) { - - afterSavedReturnsToList = false; - - if (noteTmp == null) noteTmp = new Note(); - - // Text title - String title = i.getStringExtra(Intent.EXTRA_SUBJECT); - if (title != null) { - noteTmp.setTitle(title); - } - - // Text content - String content = i.getStringExtra(Intent.EXTRA_TEXT); - if (content != null) { - noteTmp.setContent(content); - } - - importAttachments(i); - - } - - if (IntentChecker.checkAction(i, Intent.ACTION_MAIN, Constants.ACTION_WIDGET_SHOW_LIST, Constants - .ACTION_SHORTCUT_WIDGET, Constants.ACTION_WIDGET)) { - showKeyboard = true; - } - - i.setAction(null); - } - - private void importAttachments(Intent i) { - - if (!i.hasExtra(Intent.EXTRA_STREAM)) return; - - if (i.getExtras().get(Intent.EXTRA_STREAM) instanceof Uri) { - Uri uri = i.getParcelableExtra(Intent.EXTRA_STREAM); - // Google Now passes Intent as text but with audio recording attached the case must be handled like this - if (!Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) { - String name = FileHelper.getNameFromUri(mainActivity, uri); - new AttachmentTask(this, uri, name, this).execute(); - } - } else { - ArrayList uris = i.getParcelableArrayListExtra(Intent.EXTRA_STREAM); - for (Uri uriSingle :uris) { - String name = FileHelper.getNameFromUri(mainActivity, uriSingle); - new AttachmentTask(this, uriSingle, name, this).execute(); - } - } - } - - @SuppressLint("NewApi") - private void initViews() { - - // Sets onTouchListener to the whole activity to swipe notes - root.setOnTouchListener(this); - - // Overrides font sizes with the one selected from user - Fonts.overrideTextSize(mainActivity, prefs, root); - - // Color of tag marker if note is tagged a function is active in preferences - setTagMarkerColor(noteTmp.getCategory()); - - initViewTitle(); - - initViewContent(); - - initViewLocation(); - - initViewAttachments(); - - initViewReminder(); - - initViewFooter(); - } - - private void initViewFooter() { - // Footer dates of creation... - String creation = DateHelper.getFormattedDate(noteTmp.getCreation(), prefs.getBoolean(Constants - .PREF_PRETTIFIED_DATES, true)); - creationTextView.append(creation.length() > 0 ? getString(R.string.creation) + " " + creation : ""); - if (creationTextView.getText().length() == 0) - creationTextView.setVisibility(View.GONE); - - // ... and last modification - String lastModification = DateHelper.getFormattedDate(noteTmp.getLastModification(), prefs.getBoolean(Constants - .PREF_PRETTIFIED_DATES, true)); - lastModificationTextView.append(lastModification.length() > 0 ? getString(R.string.last_update) + " " + - lastModification : ""); - if (lastModificationTextView.getText().length() == 0) - lastModificationTextView.setVisibility(View.GONE); - } - - private void initViewReminder() { - - // Preparation for reminder icon - reminder_layout.setOnClickListener(v -> { - int pickerType = prefs.getBoolean("settings_simple_calendar", false) ? ReminderPickers.TYPE_AOSP : - ReminderPickers.TYPE_GOOGLE; - ReminderPickers reminderPicker = new ReminderPickers(mainActivity, mFragment, pickerType); - reminderPicker.pick(DateUtils.getPresetReminder(noteTmp.getAlarm()), noteTmp - .getRecurrenceRule()); - onDateSetListener = reminderPicker; - onTimeSetListener = reminderPicker; - }); - - reminder_layout.setOnLongClickListener(v -> { - MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) - .content(R.string.remove_reminder) - .positiveText(R.string.ok) - .onPositive((dialog1, which) -> { - ReminderHelper.removeReminder(OmniNotes.getAppContext(), noteTmp); - noteTmp.setAlarm(null); - reminderIcon.setImageResource(R.drawable.ic_alarm_black_18dp); - datetime.setText(""); - }).build(); - dialog.show(); - return true; - }); - - // Reminder - String reminderString = initReminder(noteTmp); - if (!StringUtils.isEmpty(reminderString)) { - reminderIcon.setImageResource(R.drawable.ic_alarm_add_black_18dp); - datetime.setText(reminderString); - } - } - - private void initViewLocation() { - - DetailFragment detailFragment = this; - - if (isNoteLocationValid()) { - if (TextUtils.isEmpty(noteTmp.getAddress())) { - //FIXME: What's this "sasd"? - GeocodeHelper.getAddressFromCoordinates(new Location("sasd"), detailFragment); - } else { - locationTextView.setText(noteTmp.getAddress()); - locationTextView.setVisibility(View.VISIBLE); - } - } - - // Automatic location insertion - if (prefs.getBoolean(Constants.PREF_AUTO_LOCATION, false) && noteTmp.get_id() == null) { - getLocation(detailFragment); - } - - locationTextView.setOnClickListener(v -> { - String uriString = "geo:" + noteTmp.getLatitude() + ',' + noteTmp.getLongitude() - + "?q=" + noteTmp.getLatitude() + ',' + noteTmp.getLongitude(); - Intent locationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString)); - if (!IntentChecker.isAvailable(mainActivity, locationIntent, null)) { - uriString = "http://maps.google.com/maps?q=" + noteTmp.getLatitude() + ',' + noteTmp - .getLongitude(); - locationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString)); - } - startActivity(locationIntent); - }); - locationTextView.setOnLongClickListener(v -> { - MaterialDialog.Builder builder = new MaterialDialog.Builder(mainActivity); - builder.content(R.string.remove_location); - builder.positiveText(R.string.ok); - builder.onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - noteTmp.setLatitude(""); - noteTmp.setLongitude(""); - fade(locationTextView, false); - } - }); - MaterialDialog dialog = builder.build(); - dialog.show(); - return true; - }); - } - - private void getLocation(OnGeoUtilResultListener onGeoUtilResultListener) { - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, R.string - .permission_coarse_location, snackBarPlaceholder, () -> GeocodeHelper.getLocation - (onGeoUtilResultListener)); - } - - private void initViewAttachments() { - - // Attachments position based on preferences - if (prefs.getBoolean(Constants.PREF_ATTACHMENTS_ON_BOTTOM, false)) { - attachmentsBelow.inflate(); - } else { - attachmentsAbove.inflate(); - } - mGridView = (ExpandableHeightGridView) root.findViewById(R.id.gridview); - - // Some fields can be filled by third party application and are always shown - mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView); - - // Initialzation of gridview for images - mGridView.setAdapter(mAttachmentAdapter); - mGridView.autoresize(); - - // Click events for images in gridview (zooms image) - mGridView.setOnItemClickListener((parent, v, position, id) -> { - Attachment attachment = (Attachment) parent.getAdapter().getItem(position); - Uri sharableUri = FileProviderHelper.getShareableUri(attachment); - Intent attachmentIntent; - if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) { - - attachmentIntent = new Intent(Intent.ACTION_VIEW); - attachmentIntent.setDataAndType(sharableUri, StorageHelper.getMimeType(mainActivity, - sharableUri)); - attachmentIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent - .FLAG_GRANT_WRITE_URI_PERMISSION); - if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) { - startActivity(attachmentIntent); - } else { - mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN); - } - - // Media files will be opened in internal gallery - } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type()) - || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type()) - || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) { - // Title - noteTmp.setTitle(getNoteTitle()); - noteTmp.setContent(getNoteContent()); - String title1 = TextHelper.parseTitleAndContent(mainActivity, - noteTmp)[0].toString(); - // Images - int clickedImage = 0; - ArrayList images = new ArrayList<>(); - for (Attachment mAttachment : noteTmp.getAttachmentsList()) { - if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type()) - || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type()) - || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) { - images.add(mAttachment); - if (mAttachment.equals(attachment)) { - clickedImage = images.size() - 1; - } - } - } - // Intent - attachmentIntent = new Intent(mainActivity, GalleryActivity.class); - attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1); - attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images); - attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage); - startActivity(attachmentIntent); - - } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) { - playback(v, attachment.getUri()); - } - - }); - - mGridView.setOnItemLongClickListener((parent, v, position, id) -> { - // To avoid deleting audio attachment during playback - if (mPlayer != null) return false; - List items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions)); - if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) { - items = items.subList(0, items.size() - 1); - } - Attachment attachment = mAttachmentAdapter.getItem(position); - new MaterialDialog.Builder(mainActivity) - .title(attachment.getName() + " (" + AttachmentsHelper.getSize(attachment) + ")") - .items(items.toArray(new String[items.size()])) - .itemsCallback((materialDialog, view, i, charSequence) -> - performAttachmentAction(position, i)) - .build() - .show(); - return true; - }); - } - - /** - * Performs an action when long-click option is selected - * - * @param attachmentPosition - * @param i item index - */ - private void performAttachmentAction(int attachmentPosition, int i) { - switch (getResources().getStringArray(R.array.attachments_actions_values)[i]) { - case "share": - Intent shareIntent = new Intent(Intent.ACTION_SEND); - Attachment attachment = mAttachmentAdapter.getItem(attachmentPosition); - shareIntent.setType(StorageHelper.getMimeType(OmniNotes.getAppContext(), attachment.getUri())); - shareIntent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment)); - if (IntentChecker.isAvailable(OmniNotes.getAppContext(), shareIntent, null)) { - startActivity(shareIntent); - } else { - mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN); - } - break; - case "delete": - removeAttachment(attachmentPosition); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - break; - case "delete all": - new MaterialDialog.Builder(mainActivity) - .title(R.string.delete_all_attachments) - .positiveText(R.string.confirm) - .onPositive((materialDialog, dialogAction) -> removeAllAttachments()) - .build() - .show(); - break; - case "edit": - takeSketch(mAttachmentAdapter.getItem(attachmentPosition)); - break; - default: - LogDelegate.w("No action available"); - } - } - - private void initViewTitle() { - title.setText(noteTmp.getTitle()); - title.gatherLinksForText(); - title.setOnTextLinkClickListener(textLinkClickListener); - // To avoid dropping here the dragged checklist items - title.setOnDragListener((v, event) -> { + OnAttachingFileListener, TextWatcher, CheckListChangedListener, OnNoteSaved, + OnGeoUtilResultListener { + + private static final int TAKE_PHOTO = 1; + private static final int TAKE_VIDEO = 2; + private static final int SET_PASSWORD = 3; + private static final int SKETCH = 4; + private static final int CATEGORY = 5; + private static final int DETAIL = 6; + private static final int FILES = 7; + private static final int RC_READ_EXTERNAL_STORAGE_PERMISSION = 1; + public OnDateSetListener onDateSetListener; + public OnTimeSetListener onTimeSetListener; + public boolean goBack = false; + @BindView(R.id.detail_root) + ViewGroup root; + @BindView(R.id.detail_title) + EditText title; + @BindView(R.id.detail_content) + EditText content; + @BindView(R.id.detail_attachments_above) + ViewStub attachmentsAbove; + @BindView(R.id.detail_attachments_below) + ViewStub attachmentsBelow; + @Nullable + @BindView(R.id.gridview) + ExpandableHeightGridView mGridView; + @BindView(R.id.location) + TextView locationTextView; + @BindView(R.id.detail_timestamps) + View timestampsView; + @BindView(R.id.reminder_layout) + LinearLayout reminder_layout; + @BindView(R.id.reminder_icon) + ImageView reminderIcon; + @BindView(R.id.datetime) + TextView datetime; + @BindView(R.id.detail_tile_card) + View titleCardView; + @BindView(R.id.content_wrapper) + ScrollView scrollView; + @BindView(R.id.creation) + TextView creationTextView; + @BindView(R.id.last_modification) + TextView lastModificationTextView; + @BindView(R.id.title_wrapper) + View titleWrapperView; + @BindView(R.id.tag_marker) + View tagMarkerView; + @BindView(R.id.detail_wrapper) + ViewManager detailWrapperView; + @BindView(R.id.snackbar_placeholder) + View snackBarPlaceholder; + View toggleChecklistView; + private Uri attachmentUri; + private AttachmentAdapter mAttachmentAdapter; + private MaterialDialog attachmentDialog; + private Note note; + private Note noteTmp; + private Note noteOriginal; + // Audio recording + private String recordName; + private MediaRecorder mRecorder = null; + private MediaPlayer mPlayer = null; + private boolean isRecording = false; + private View isPlayingView = null; + private Bitmap recordingBitmap; + private ChecklistManager mChecklistManager; + // Values to print result + private String exitMessage; + private Style exitCroutonStyle = ONStyle.CONFIRM; + // Flag to check if after editing it will return to ListActivity or not + // and in the last case a Toast will be shown instead than Crouton + private boolean afterSavedReturnsToList = true; + private boolean showKeyboard = false; + private boolean swiping; + private int startSwipeX; + private SharedPreferences prefs; + private boolean orientationChanged; + private long audioRecordingTimeStart; + private long audioRecordingTime; + private DetailFragment mFragment; + private Attachment sketchEdited; + private int contentLineCounter = 1; + private int contentCursorPosition; + private ArrayList mergedNotesIds; + private MainActivity mainActivity; + TextLinkClickListener textLinkClickListener = new TextLinkClickListener() { + @Override + public void onTextLinkClick (View view, final String clickedString, final String url) { + new MaterialDialog.Builder(mainActivity) + .content(clickedString) + .negativeColorRes(R.color.colorPrimary) + .positiveText(R.string.open) + .negativeText(R.string.copy) + .onPositive((dialog, which) -> { + boolean error = false; + Intent intent = null; + try { + intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); + intent.addCategory(Intent.CATEGORY_BROWSABLE); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } catch (NullPointerException e) { + error = true; + } + + if (intent == null + || error + || !IntentChecker + .isAvailable( + mainActivity, + intent, + new String[]{PackageManager.FEATURE_CAMERA})) { + mainActivity.showMessage(R.string.no_application_can_perform_this_action, + ONStyle.ALERT); + + } else { + startActivity(intent); + } + }) + .onNegative((dialog, which) -> { + android.content.ClipboardManager clipboard = (android.content.ClipboardManager) + mainActivity + .getSystemService(Activity.CLIPBOARD_SERVICE); + android.content.ClipData clip = android.content.ClipData.newPlainText("text label", + clickedString); + clipboard.setPrimaryClip(clip); + }).build().show(); + View clickedView = noteTmp.isChecklist() ? toggleChecklistView : content; + clickedView.clearFocus(); + KeyboardUtils.hideKeyboard(clickedView); + new Handler().post(() -> { + View clickedView1 = noteTmp.isChecklist() ? toggleChecklistView : content; + KeyboardUtils.hideKeyboard(clickedView1); + }); + } + }; + private boolean activityPausing; + + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mFragment = this; + } + + @Override + public void onAttach (Context context) { + super.onAttach(context); + EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.CHILDREN)); + } + + @Override + public void onStop () { + super.onStop(); + GeocodeHelper.stop(); + } + + @Override + public void onResume () { + super.onResume(); + activityPausing = false; + EventBus.getDefault().register(this); + } + + @Override + public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_detail, container, false); + ButterKnife.bind(this, view); + return view; + } + + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + mainActivity = (MainActivity) getActivity(); + + prefs = mainActivity.prefs; + + mainActivity.getSupportActionBar().setDisplayShowTitleEnabled(false); + mainActivity.getToolbar().setNavigationOnClickListener(v -> navigateUp()); + + // Force the navigation drawer to stay opened if tablet mode is on, otherwise has to stay closed + if (NavigationDrawerFragment.isDoublePanelActive()) { + mainActivity.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN); + } else { + mainActivity.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); + } + + // Restored temp note after orientation change + if (savedInstanceState != null) { + noteTmp = savedInstanceState.getParcelable("noteTmp"); + note = savedInstanceState.getParcelable("note"); + noteOriginal = savedInstanceState.getParcelable("noteOriginal"); + attachmentUri = savedInstanceState.getParcelable("attachmentUri"); + orientationChanged = savedInstanceState.getBoolean("orientationChanged"); + } + + // Added the sketched image if present returning from SketchFragment + if (mainActivity.sketchUri != null) { + Attachment mAttachment = new Attachment(mainActivity.sketchUri, Constants.MIME_TYPE_SKETCH); + addAttachment(mAttachment); + mainActivity.sketchUri = null; + // Removes previous version of edited image + if (sketchEdited != null) { + noteTmp.getAttachmentsList().remove(sketchEdited); + sketchEdited = null; + } + } + + init(); + + setHasOptionsMenu(true); + setRetainInstance(false); + } + + @Override + public void onSaveInstanceState (Bundle outState) { + if (noteTmp != null) { + noteTmp.setTitle(getNoteTitle()); + noteTmp.setContent(getNoteContent()); + outState.putParcelable("noteTmp", noteTmp); + outState.putParcelable("note", note); + outState.putParcelable("noteOriginal", noteOriginal); + outState.putParcelable("attachmentUri", attachmentUri); + outState.putBoolean("orientationChanged", orientationChanged); + } + super.onSaveInstanceState(outState); + } + + @Override + public void onPause () { + super.onPause(); + + //to prevent memory leak fragment keep refernce of event but until deregister + EventBus.getDefault().unregister(this); + + activityPausing = true; + + // Checks "goBack" value to avoid performing a double saving + if (!goBack) { + saveNote(this); + } + + if (toggleChecklistView != null) { + KeyboardUtils.hideKeyboard(toggleChecklistView); + content.clearFocus(); + } + } + + @Override + public void onConfigurationChanged (Configuration newConfig) { + super.onConfigurationChanged(newConfig); + if (getResources().getConfiguration().orientation != newConfig.orientation) { + orientationChanged = true; + } + } + + private void init () { + + // Handling of Intent actions + handleIntents(); + + if (noteOriginal == null) { + noteOriginal = getArguments().getParcelable(Constants.INTENT_NOTE); + } + + if (note == null) { + note = new Note(noteOriginal); + } + + if (noteTmp == null) { + noteTmp = new Note(note); + } + + if (noteTmp.isLocked() && !noteTmp.isPasswordChecked()) { + checkNoteLock(noteTmp); + return; + } + + initViews(); + } + + /** + * Checks note lock and password before showing note content + */ + private void checkNoteLock (Note note) { + // If note is locked security password will be requested + if (note.isLocked() + && prefs.getString(Constants.PREF_PASSWORD, null) != null + && !prefs.getBoolean("settings_password_access", false)) { + PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { + switch (passwordConfirmed) { + case SUCCEED: + noteTmp.setPasswordChecked(true); + init(); + break; + case FAIL: + goBack = true; + goHome(); + break; + case RESTORE: + goBack = true; + goHome(); + PasswordHelper.resetPassword(mainActivity); + break; + } + }); + } else { + noteTmp.setPasswordChecked(true); + init(); + } + } + + private void handleIntents () { + Intent i = mainActivity.getIntent(); + + if (IntentChecker.checkAction(i, Constants.ACTION_MERGE)) { + noteOriginal = new Note(); + note = new Note(noteOriginal); + noteTmp = getArguments().getParcelable(Constants.INTENT_NOTE); + if (i.getStringArrayListExtra("merged_notes") != null) { + mergedNotesIds = i.getStringArrayListExtra("merged_notes"); + } + } + + // Action called from home shortcut + if (IntentChecker.checkAction(i, Constants.ACTION_SHORTCUT, Constants.ACTION_NOTIFICATION_CLICK)) { + afterSavedReturnsToList = false; + noteOriginal = DbHelper.getInstance().getNote(i.getLongExtra(Constants.INTENT_KEY, 0)); + // Checks if the note pointed from the shortcut has been deleted + try { + note = new Note(noteOriginal); + noteTmp = new Note(noteOriginal); + } catch (NullPointerException e) { + mainActivity.showToast(getText(R.string.shortcut_note_deleted), Toast.LENGTH_LONG); + mainActivity.finish(); + } + } + + // Check if is launched from a widget + if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET, Constants.ACTION_WIDGET_TAKE_PHOTO)) { + + afterSavedReturnsToList = false; + showKeyboard = true; + + // with tags to set tag + if (i.hasExtra(Constants.INTENT_WIDGET)) { + String widgetId = i.getExtras().get(Constants.INTENT_WIDGET).toString(); + if (widgetId != null) { + String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, ""); + String categoryId = TextHelper.checkIntentCategory(sqlCondition); + if (categoryId != null) { + Category category; + try { + category = DbHelper.getInstance().getCategory(parseLong(categoryId)); + noteTmp = new Note(); + noteTmp.setCategory(category); + } catch (NumberFormatException e) { + LogDelegate.e("Category with not-numeric value!", e); + } + } + } + } + + // Sub-action is to take a photo + if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET_TAKE_PHOTO)) { + takePhoto(); + } + } + + if (IntentChecker.checkAction(i, Constants.ACTION_FAB_TAKE_PHOTO)) { + takePhoto(); + } + + // Handles third party apps requests of sharing + if (IntentChecker.checkAction(i, Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE, Constants.INTENT_GOOGLE_NOW) + && i.getType() != null) { + + afterSavedReturnsToList = false; + + if (noteTmp == null) { + noteTmp = new Note(); + } + + // Text title + String title = i.getStringExtra(Intent.EXTRA_SUBJECT); + if (title != null) { + noteTmp.setTitle(title); + } + + // Text content + String content = i.getStringExtra(Intent.EXTRA_TEXT); + if (content != null) { + noteTmp.setContent(content); + } + + importAttachments(i); + + } + + if (IntentChecker.checkAction(i, Intent.ACTION_MAIN, Constants.ACTION_WIDGET_SHOW_LIST, Constants + .ACTION_SHORTCUT_WIDGET, Constants.ACTION_WIDGET)) { + showKeyboard = true; + } + + i.setAction(null); + } + + private void importAttachments (Intent i) { + + if (!i.hasExtra(Intent.EXTRA_STREAM)) { + return; + } + + if (i.getExtras().get(Intent.EXTRA_STREAM) instanceof Uri) { + Uri uri = i.getParcelableExtra(Intent.EXTRA_STREAM); + // Google Now passes Intent as text but with audio recording attached the case must be handled like this + if (!Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) { + String name = FileHelper.getNameFromUri(mainActivity, uri); + new AttachmentTask(this, uri, name, this).execute(); + } + } else { + ArrayList uris = i.getParcelableArrayListExtra(Intent.EXTRA_STREAM); + for (Uri uriSingle : uris) { + String name = FileHelper.getNameFromUri(mainActivity, uriSingle); + new AttachmentTask(this, uriSingle, name, this).execute(); + } + } + } + + @SuppressLint("NewApi") + private void initViews () { + + // Sets onTouchListener to the whole activity to swipe notes + root.setOnTouchListener(this); + + // Overrides font sizes with the one selected from user + Fonts.overrideTextSize(mainActivity, prefs, root); + + // Color of tag marker if note is tagged a function is active in preferences + setTagMarkerColor(noteTmp.getCategory()); + + initViewTitle(); + + initViewContent(); + + initViewLocation(); + + initViewAttachments(); + + initViewReminder(); + + initViewFooter(); + } + + private void initViewFooter () { + // Footer dates of creation... + String creation = DateHelper.getFormattedDate(noteTmp.getCreation(), prefs.getBoolean(Constants + .PREF_PRETTIFIED_DATES, true)); + creationTextView.append(creation.length() > 0 ? getString(R.string.creation) + " " + creation : ""); + if (creationTextView.getText().length() == 0) { + creationTextView.setVisibility(View.GONE); + } + + // ... and last modification + String lastModification = DateHelper.getFormattedDate(noteTmp.getLastModification(), prefs.getBoolean(Constants + .PREF_PRETTIFIED_DATES, true)); + lastModificationTextView.append(lastModification.length() > 0 ? getString(R.string.last_update) + " " + + lastModification : ""); + if (lastModificationTextView.getText().length() == 0) { + lastModificationTextView.setVisibility(View.GONE); + } + } + + private void initViewReminder () { + + // Preparation for reminder icon + reminder_layout.setOnClickListener(v -> { + int pickerType = prefs.getBoolean("settings_simple_calendar", false) ? ReminderPickers.TYPE_AOSP : + ReminderPickers.TYPE_GOOGLE; + ReminderPickers reminderPicker = new ReminderPickers(mainActivity, mFragment, pickerType); + reminderPicker.pick(DateUtils.getPresetReminder(noteTmp.getAlarm()), noteTmp + .getRecurrenceRule()); + onDateSetListener = reminderPicker; + onTimeSetListener = reminderPicker; + }); + + reminder_layout.setOnLongClickListener(v -> { + MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) + .content(R.string.remove_reminder) + .positiveText(R.string.ok) + .onPositive((dialog1, which) -> { + ReminderHelper.removeReminder(OmniNotes.getAppContext(), noteTmp); + noteTmp.setAlarm(null); + reminderIcon.setImageResource(R.drawable.ic_alarm_black_18dp); + datetime.setText(""); + }).build(); + dialog.show(); + return true; + }); + + // Reminder + String reminderString = initReminder(noteTmp); + if (!StringUtils.isEmpty(reminderString)) { + reminderIcon.setImageResource(R.drawable.ic_alarm_add_black_18dp); + datetime.setText(reminderString); + } + } + + private void initViewLocation () { + + DetailFragment detailFragment = this; + + if (isNoteLocationValid()) { + if (TextUtils.isEmpty(noteTmp.getAddress())) { + //FIXME: What's this "sasd"? + GeocodeHelper.getAddressFromCoordinates(new Location("sasd"), detailFragment); + } else { + locationTextView.setText(noteTmp.getAddress()); + locationTextView.setVisibility(View.VISIBLE); + } + } + + // Automatic location insertion + if (prefs.getBoolean(Constants.PREF_AUTO_LOCATION, false) && noteTmp.get_id() == null) { + getLocation(detailFragment); + } + + locationTextView.setOnClickListener(v -> { + String uriString = "geo:" + noteTmp.getLatitude() + ',' + noteTmp.getLongitude() + + "?q=" + noteTmp.getLatitude() + ',' + noteTmp.getLongitude(); + Intent locationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString)); + if (!IntentChecker.isAvailable(mainActivity, locationIntent, null)) { + uriString = "http://maps.google.com/maps?q=" + noteTmp.getLatitude() + ',' + noteTmp + .getLongitude(); + locationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString)); + } + startActivity(locationIntent); + }); + locationTextView.setOnLongClickListener(v -> { + MaterialDialog.Builder builder = new MaterialDialog.Builder(mainActivity); + builder.content(R.string.remove_location); + builder.positiveText(R.string.ok); + builder.onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + noteTmp.setLatitude(""); + noteTmp.setLongitude(""); + fade(locationTextView, false); + } + }); + MaterialDialog dialog = builder.build(); + dialog.show(); + return true; + }); + } + + private void getLocation (OnGeoUtilResultListener onGeoUtilResultListener) { + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, R.string + .permission_coarse_location, snackBarPlaceholder, () -> GeocodeHelper.getLocation + (onGeoUtilResultListener)); + } + + private void initViewAttachments () { + + // Attachments position based on preferences + if (prefs.getBoolean(Constants.PREF_ATTACHMENTS_ON_BOTTOM, false)) { + attachmentsBelow.inflate(); + } else { + attachmentsAbove.inflate(); + } + mGridView = root.findViewById(R.id.gridview); + + // Some fields can be filled by third party application and are always shown + mAttachmentAdapter = new AttachmentAdapter(mainActivity, noteTmp.getAttachmentsList(), mGridView); + + // Initialzation of gridview for images + mGridView.setAdapter(mAttachmentAdapter); + mGridView.autoresize(); + + // Click events for images in gridview (zooms image) + mGridView.setOnItemClickListener((parent, v, position, id) -> { + Attachment attachment = (Attachment) parent.getAdapter().getItem(position); + Uri sharableUri = FileProviderHelper.getShareableUri(attachment); + Intent attachmentIntent; + if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) { + + attachmentIntent = new Intent(Intent.ACTION_VIEW); + attachmentIntent.setDataAndType(sharableUri, StorageHelper.getMimeType(mainActivity, + sharableUri)); + attachmentIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent + .FLAG_GRANT_WRITE_URI_PERMISSION); + if (IntentChecker.isAvailable(mainActivity.getApplicationContext(), attachmentIntent, null)) { + startActivity(attachmentIntent); + } else { + mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN); + } + + // Media files will be opened in internal gallery + } else if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type()) + || Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type()) + || Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) { + // Title + noteTmp.setTitle(getNoteTitle()); + noteTmp.setContent(getNoteContent()); + String title1 = TextHelper.parseTitleAndContent(mainActivity, + noteTmp)[0].toString(); + // Images + int clickedImage = 0; + ArrayList images = new ArrayList<>(); + for (Attachment mAttachment : noteTmp.getAttachmentsList()) { + if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type()) + || Constants.MIME_TYPE_SKETCH.equals(mAttachment.getMime_type()) + || Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) { + images.add(mAttachment); + if (mAttachment.equals(attachment)) { + clickedImage = images.size() - 1; + } + } + } + // Intent + attachmentIntent = new Intent(mainActivity, GalleryActivity.class); + attachmentIntent.putExtra(Constants.GALLERY_TITLE, title1); + attachmentIntent.putParcelableArrayListExtra(Constants.GALLERY_IMAGES, images); + attachmentIntent.putExtra(Constants.GALLERY_CLICKED_IMAGE, clickedImage); + startActivity(attachmentIntent); + + } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) { + playback(v, attachment.getUri()); + } + + }); + + mGridView.setOnItemLongClickListener((parent, v, position, id) -> { + // To avoid deleting audio attachment during playback + if (mPlayer != null) { + return false; + } + List items = Arrays.asList(getResources().getStringArray(R.array.attachments_actions)); + if (!Constants.MIME_TYPE_SKETCH.equals(mAttachmentAdapter.getItem(position).getMime_type())) { + items = items.subList(0, items.size() - 1); + } + Attachment attachment = mAttachmentAdapter.getItem(position); + new MaterialDialog.Builder(mainActivity) + .title(attachment.getName() + " (" + AttachmentsHelper.getSize(attachment) + ")") + .items(items.toArray(new String[items.size()])) + .itemsCallback((materialDialog, view, i, charSequence) -> + performAttachmentAction(position, i)) + .build() + .show(); + return true; + }); + } + + /** + * Performs an action when long-click option is selected + * + * @param i item index + */ + private void performAttachmentAction (int attachmentPosition, int i) { + switch (getResources().getStringArray(R.array.attachments_actions_values)[i]) { + case "share": + Intent shareIntent = new Intent(Intent.ACTION_SEND); + Attachment attachment = mAttachmentAdapter.getItem(attachmentPosition); + shareIntent.setType(StorageHelper.getMimeType(OmniNotes.getAppContext(), attachment.getUri())); + shareIntent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment)); + if (IntentChecker.isAvailable(OmniNotes.getAppContext(), shareIntent, null)) { + startActivity(shareIntent); + } else { + mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.WARN); + } + break; + case "delete": + removeAttachment(attachmentPosition); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + break; + case "delete all": + new MaterialDialog.Builder(mainActivity) + .title(R.string.delete_all_attachments) + .positiveText(R.string.confirm) + .onPositive((materialDialog, dialogAction) -> removeAllAttachments()) + .build() + .show(); + break; + case "edit": + takeSketch(mAttachmentAdapter.getItem(attachmentPosition)); + break; + default: + LogDelegate.w("No action available"); + } + } + + private void initViewTitle () { + title.setText(noteTmp.getTitle()); + title.gatherLinksForText(); + title.setOnTextLinkClickListener(textLinkClickListener); + // To avoid dropping here the dragged checklist items + title.setOnDragListener((v, event) -> { // ((View)event.getLocalState()).setVisibility(View.VISIBLE); - return true; - }); - //When editor action is pressed focus is moved to last character in content field - title.setOnEditorActionListener((v, actionId, event) -> { - content.requestFocus(); - content.setSelection(content.getText().length()); - return false; - }); - requestFocus(title); - } - - private void initViewContent() { - - content.setText(noteTmp.getContent()); - content.gatherLinksForText(); - content.setOnTextLinkClickListener(textLinkClickListener); - // Avoids focused line goes under the keyboard - content.addTextChangedListener(this); - - // Restore checklist - toggleChecklistView = content; - if (noteTmp.isChecklist()) { - noteTmp.setChecklist(false); - AlphaManager.setAlpha(toggleChecklistView, 0); - toggleChecklist2(); - } - } - - /** - * Force focus and shows soft keyboard. Only happens if it's a new note, without shared content. - * {@link showKeyboard} is used to check if the note is created from shared content. - */ - @SuppressWarnings("JavadocReference") - private void requestFocus(final EditText view) { - if (note.get_id() == null && !noteTmp.isChanged(note) && showKeyboard) { - KeyboardUtils.showKeyboard(view); - } - } - - /** - * Colors tag marker in note's title and content elements - */ - private void setTagMarkerColor(Category tag) { - - String colorsPref = prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT); - - // Checking preference - if (!"disabled".equals(colorsPref)) { - - // Choosing target view depending on another preference - ArrayList target = new ArrayList<>(); - if ("complete".equals(colorsPref)) { - target.add(titleWrapperView); - target.add(scrollView); - } else { - target.add(tagMarkerView); - } - - // Coloring the target - if (tag != null && tag.getColor() != null) { - for (View view : target) { - view.setBackgroundColor(parseInt(tag.getColor())); - } - } else { - for (View view : target) { - view.setBackgroundColor(Color.parseColor("#00000000")); - } - } - } - } - - private void displayLocationDialog() { - getLocation(new OnGeoUtilResultListenerImpl(mainActivity, mFragment, noteTmp)); - } - - @Override - public void onLocationRetrieved(Location location) { - if (location == null) { - mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); - } - if (location != null) { - noteTmp.setLatitude(location.getLatitude()); - noteTmp.setLongitude(location.getLongitude()); - if (!TextUtils.isEmpty(noteTmp.getAddress())) { - locationTextView.setVisibility(View.VISIBLE); - locationTextView.setText(noteTmp.getAddress()); - } else { - GeocodeHelper.getAddressFromCoordinates(location, mFragment); - } - } - } - - @Override - public void onLocationUnavailable() { - mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); - } - - @Override - public void onAddressResolved(String address) { - if (TextUtils.isEmpty(address)) { - if (!isNoteLocationValid()) { - mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); - return; - } - address = noteTmp.getLatitude() + ", " + noteTmp.getLongitude(); - } - if (!GeocodeHelper.areCoordinates(address)) { - noteTmp.setAddress(address); - } - locationTextView.setVisibility(View.VISIBLE); - locationTextView.setText(address); - fade(locationTextView, true); - } - - @Override - public void onCoordinatesResolved(Location location, String address) { - if (location != null) { - noteTmp.setLatitude(location.getLatitude()); - noteTmp.setLongitude(location.getLongitude()); - noteTmp.setAddress(address); - locationTextView.setVisibility(View.VISIBLE); - locationTextView.setText(address); - fade(locationTextView, true); - } else { - mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); - } - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_detail, menu); - super.onCreateOptionsMenu(menu, inflater); - } - - @Override - public void onPrepareOptionsMenu(Menu menu) { - - // Closes search view if left open in List fragment - MenuItem searchMenuItem = menu.findItem(R.id.menu_search); - if (searchMenuItem != null) { - MenuItemCompat.collapseActionView(searchMenuItem); - } - - boolean newNote = noteTmp.get_id() == null; - - menu.findItem(R.id.menu_checklist_on).setVisible(!noteTmp.isChecklist()); - menu.findItem(R.id.menu_checklist_off).setVisible(noteTmp.isChecklist()); - menu.findItem(R.id.menu_lock).setVisible(!noteTmp.isLocked()); - menu.findItem(R.id.menu_unlock).setVisible(noteTmp.isLocked()); - // If note is trashed only this options will be available from menu - if (noteTmp.isTrashed()) { - menu.findItem(R.id.menu_untrash).setVisible(true); - menu.findItem(R.id.menu_delete).setVisible(true); - // Otherwise all other actions will be available - } else { - // Temporary removed until fixed on Oreo and following + return true; + }); + //When editor action is pressed focus is moved to last character in content field + title.setOnEditorActionListener((v, actionId, event) -> { + content.requestFocus(); + content.setSelection(content.getText().length()); + return false; + }); + requestFocus(title); + } + + private void initViewContent () { + + content.setText(noteTmp.getContent()); + content.gatherLinksForText(); + content.setOnTextLinkClickListener(textLinkClickListener); + // Avoids focused line goes under the keyboard + content.addTextChangedListener(this); + + // Restore checklist + toggleChecklistView = content; + if (noteTmp.isChecklist()) { + noteTmp.setChecklist(false); + AlphaManager.setAlpha(toggleChecklistView, 0); + toggleChecklist2(); + } + } + + /** + * Force focus and shows soft keyboard. Only happens if it's a new note, without shared content. {@link showKeyboard} + * is used to check if the note is created from shared content. + */ + @SuppressWarnings("JavadocReference") + private void requestFocus (final EditText view) { + if (note.get_id() == null && !noteTmp.isChanged(note) && showKeyboard) { + KeyboardUtils.showKeyboard(view); + } + } + + /** + * Colors tag marker in note's title and content elements + */ + private void setTagMarkerColor (Category tag) { + + String colorsPref = prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT); + + // Checking preference + if (!"disabled".equals(colorsPref)) { + + // Choosing target view depending on another preference + ArrayList target = new ArrayList<>(); + if ("complete".equals(colorsPref)) { + target.add(titleWrapperView); + target.add(scrollView); + } else { + target.add(tagMarkerView); + } + + // Coloring the target + if (tag != null && tag.getColor() != null) { + for (View view : target) { + view.setBackgroundColor(parseInt(tag.getColor())); + } + } else { + for (View view : target) { + view.setBackgroundColor(Color.parseColor("#00000000")); + } + } + } + } + + private void displayLocationDialog () { + getLocation(new OnGeoUtilResultListenerImpl(mainActivity, mFragment, noteTmp)); + } + + @Override + public void onLocationRetrieved (Location location) { + if (location == null) { + mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); + } + if (location != null) { + noteTmp.setLatitude(location.getLatitude()); + noteTmp.setLongitude(location.getLongitude()); + if (!TextUtils.isEmpty(noteTmp.getAddress())) { + locationTextView.setVisibility(View.VISIBLE); + locationTextView.setText(noteTmp.getAddress()); + } else { + GeocodeHelper.getAddressFromCoordinates(location, mFragment); + } + } + } + + @Override + public void onLocationUnavailable () { + mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); + } + + @Override + public void onAddressResolved (String address) { + if (TextUtils.isEmpty(address)) { + if (!isNoteLocationValid()) { + mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); + return; + } + address = noteTmp.getLatitude() + ", " + noteTmp.getLongitude(); + } + if (!GeocodeHelper.areCoordinates(address)) { + noteTmp.setAddress(address); + } + locationTextView.setVisibility(View.VISIBLE); + locationTextView.setText(address); + fade(locationTextView, true); + } + + @Override + public void onCoordinatesResolved (Location location, String address) { + if (location != null) { + noteTmp.setLatitude(location.getLatitude()); + noteTmp.setLongitude(location.getLongitude()); + noteTmp.setAddress(address); + locationTextView.setVisibility(View.VISIBLE); + locationTextView.setText(address); + fade(locationTextView, true); + } else { + mainActivity.showMessage(R.string.location_not_found, ONStyle.ALERT); + } + } + + @Override + public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) { + inflater.inflate(R.menu.menu_detail, menu); + super.onCreateOptionsMenu(menu, inflater); + } + + @Override + public void onPrepareOptionsMenu (Menu menu) { + + // Closes search view if left open in List fragment + MenuItem searchMenuItem = menu.findItem(R.id.menu_search); + if (searchMenuItem != null) { + MenuItemCompat.collapseActionView(searchMenuItem); + } + + boolean newNote = noteTmp.get_id() == null; + + menu.findItem(R.id.menu_checklist_on).setVisible(!noteTmp.isChecklist()); + menu.findItem(R.id.menu_checklist_off).setVisible(noteTmp.isChecklist()); + menu.findItem(R.id.menu_lock).setVisible(!noteTmp.isLocked()); + menu.findItem(R.id.menu_unlock).setVisible(noteTmp.isLocked()); + // If note is trashed only this options will be available from menu + if (noteTmp.isTrashed()) { + menu.findItem(R.id.menu_untrash).setVisible(true); + menu.findItem(R.id.menu_delete).setVisible(true); + // Otherwise all other actions will be available + } else { + // Temporary removed until fixed on Oreo and following // menu.findItem(R.id.menu_add_shortcut).setVisible(!newNote); - menu.findItem(R.id.menu_archive).setVisible(!newNote && !noteTmp.isArchived()); - menu.findItem(R.id.menu_unarchive).setVisible(!newNote && noteTmp.isArchived()); - menu.findItem(R.id.menu_trash).setVisible(!newNote); - } - } - - @SuppressLint("NewApi") - public boolean goHome() { - stopPlaying(); - - // The activity has managed a shared intent from third party app and - // performs a normal onBackPressed instead of returning back to ListActivity - if (!afterSavedReturnsToList) { - if (!TextUtils.isEmpty(exitMessage)) { - mainActivity.showToast(exitMessage, Toast.LENGTH_SHORT); - } - mainActivity.finish(); - - } else { - - if (!TextUtils.isEmpty(exitMessage) && exitCroutonStyle != null) { - mainActivity.showMessage(exitMessage, exitCroutonStyle); - } - - // Otherwise the result is passed to ListActivity - if (mainActivity != null && mainActivity.getSupportFragmentManager() != null) { - mainActivity.getSupportFragmentManager().popBackStack(); - if (mainActivity.getSupportFragmentManager().getBackStackEntryCount() == 1) { - mainActivity.getSupportActionBar().setDisplayShowTitleEnabled(true); - if (mainActivity.getDrawerToggle() != null) { - mainActivity.getDrawerToggle().setDrawerIndicatorEnabled(true); - } - EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.PARENT)); - } - } - } - - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - - if (isOptionsItemFastClick()) return true; - - switch (item.getItemId()) { - case R.id.menu_attachment: - showAttachmentsPopup(); - break; - case R.id.menu_tag: - addTags(); - break; - case R.id.menu_category: - categorizeNote(); - break; - case R.id.menu_share: - shareNote(); - break; - case R.id.menu_checklist_on: - toggleChecklist(); - break; - case R.id.menu_checklist_off: - toggleChecklist(); - break; - case R.id.menu_lock: - lockNote(); - break; - case R.id.menu_unlock: - lockNote(); - break; - case R.id.menu_add_shortcut: - addShortcut(); - break; - case R.id.menu_archive: - archiveNote(true); - break; - case R.id.menu_unarchive: - archiveNote(false); - break; - case R.id.menu_trash: - trashNote(true); - break; - case R.id.menu_untrash: - trashNote(false); - break; - case R.id.menu_discard_changes: - discard(); - break; - case R.id.menu_delete: - deleteNote(); - break; - case R.id.menu_note_info: - showNoteInfo(); - break; - default: - LogDelegate.w("Invalid menu option selected"); - } - - ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackActionFromResourceId(getActivity(), - item.getItemId()); - - return super.onOptionsItemSelected(item); - } - - private void showNoteInfo() { - noteTmp.setTitle(getNoteTitle()); - noteTmp.setContent(getNoteContent()); - Intent intent = new Intent(getContext(), NoteInfosActivity.class); - intent.putExtra(Constants.INTENT_NOTE, (android.os.Parcelable) noteTmp); - startActivity(intent); - - } - - private void navigateUp() { - afterSavedReturnsToList = true; - saveAndExit(this); - } - - /** - * - */ - private void toggleChecklist() { - - // In case checklist is active a prompt will ask about many options - // to decide hot to convert back to simple text - if (!noteTmp.isChecklist()) { - toggleChecklist2(); - return; - } - - // If checklist is active but no items are checked the conversion in done automatically - // without prompting user - if (mChecklistManager.getCheckedCount() == 0) { - toggleChecklist2(true, false); - return; - } - - // Inflate the popup_layout.xml - LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - final View layout = inflater.inflate(R.layout.dialog_remove_checklist_layout, - (ViewGroup) getView().findViewById(R.id.layout_root)); - - // Retrieves options checkboxes and initialize their values - final CheckBox keepChecked = (CheckBox) layout.findViewById(R.id.checklist_keep_checked); - final CheckBox keepCheckmarks = (CheckBox) layout.findViewById(R.id.checklist_keep_checkmarks); - keepChecked.setChecked(prefs.getBoolean(Constants.PREF_KEEP_CHECKED, true)); - keepCheckmarks.setChecked(prefs.getBoolean(Constants.PREF_KEEP_CHECKMARKS, true)); - - new MaterialDialog.Builder(mainActivity) - .customView(layout, false) - .positiveText(R.string.ok) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - prefs.edit() - .putBoolean(Constants.PREF_KEEP_CHECKED, keepChecked.isChecked()) - .putBoolean(Constants.PREF_KEEP_CHECKMARKS, keepCheckmarks.isChecked()) - .apply(); - toggleChecklist2(); - } - }).build().show(); - } - - /** - * Toggles checklist view - */ - private void toggleChecklist2() { - boolean keepChecked = prefs.getBoolean(Constants.PREF_KEEP_CHECKED, true); - boolean showChecks = prefs.getBoolean(Constants.PREF_KEEP_CHECKMARKS, true); - toggleChecklist2(keepChecked, showChecks); - } - - @SuppressLint("NewApi") - private void toggleChecklist2(final boolean keepChecked, final boolean showChecks) { - // Get instance and set options to convert EditText to CheckListView - - mChecklistManager = mChecklistManager == null ? new ChecklistManager(mainActivity) : mChecklistManager; - int checkedItemsBehavior = Integer.valueOf(prefs.getString("settings_checked_items_behavior", String.valueOf - (it.feio.android.checklistview.Settings.CHECKED_HOLD))); - mChecklistManager - .showCheckMarks(showChecks) - .newEntryHint(getString(R.string.checklist_item_hint)) - .keepChecked(keepChecked) - .undoBarContainerView(scrollView) - .moveCheckedOnBottom(checkedItemsBehavior); - - // Links parsing options - mChecklistManager.setOnTextLinkClickListener(textLinkClickListener); - mChecklistManager.addTextChangedListener(mFragment); - mChecklistManager.setCheckListChangedListener(mFragment); - - // Switches the views - View newView = null; - try { - newView = mChecklistManager.convert(toggleChecklistView); - } catch (ViewNotSupportedException e) { - LogDelegate.e("Error switching checklist view", e); - } - - // Switches the views - if (newView != null) { - mChecklistManager.replaceViews(toggleChecklistView, newView); - toggleChecklistView = newView; - animate(toggleChecklistView).alpha(1).scaleXBy(0).scaleX(1).scaleYBy(0).scaleY(1); - noteTmp.setChecklist(!noteTmp.isChecklist()); - } - } - - /** - * Categorize note choosing from a list of previously created categories - */ - private void categorizeNote() { - - String currentCategory = noteTmp.getCategory() != null ? String.valueOf(noteTmp.getCategory().getId()) : null; - final List categories = Observable.from(DbHelper.getInstance().getCategories()).map(category -> { - if (String.valueOf(category.getId()).equals(currentCategory)) { - category.setCount(category.getCount() + 1); + menu.findItem(R.id.menu_archive).setVisible(!newNote && !noteTmp.isArchived()); + menu.findItem(R.id.menu_unarchive).setVisible(!newNote && noteTmp.isArchived()); + menu.findItem(R.id.menu_trash).setVisible(!newNote); + } + } + + @SuppressLint("NewApi") + public boolean goHome () { + stopPlaying(); + + // The activity has managed a shared intent from third party app and + // performs a normal onBackPressed instead of returning back to ListActivity + if (!afterSavedReturnsToList) { + if (!TextUtils.isEmpty(exitMessage)) { + mainActivity.showToast(exitMessage, Toast.LENGTH_SHORT); + } + mainActivity.finish(); + + } else { + + if (!TextUtils.isEmpty(exitMessage) && exitCroutonStyle != null) { + mainActivity.showMessage(exitMessage, exitCroutonStyle); + } + + // Otherwise the result is passed to ListActivity + if (mainActivity != null && mainActivity.getSupportFragmentManager() != null) { + mainActivity.getSupportFragmentManager().popBackStack(); + if (mainActivity.getSupportFragmentManager().getBackStackEntryCount() == 1) { + mainActivity.getSupportActionBar().setDisplayShowTitleEnabled(true); + if (mainActivity.getDrawerToggle() != null) { + mainActivity.getDrawerToggle().setDrawerIndicatorEnabled(true); + } + EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.PARENT)); + } + } + } + + return true; + } + + @Override + public boolean onOptionsItemSelected (MenuItem item) { + + if (isOptionsItemFastClick()) { + return true; + } + + switch (item.getItemId()) { + case R.id.menu_attachment: + showAttachmentsPopup(); + break; + case R.id.menu_tag: + addTags(); + break; + case R.id.menu_category: + categorizeNote(); + break; + case R.id.menu_share: + shareNote(); + break; + case R.id.menu_checklist_on: + toggleChecklist(); + break; + case R.id.menu_checklist_off: + toggleChecklist(); + break; + case R.id.menu_lock: + lockNote(); + break; + case R.id.menu_unlock: + lockNote(); + break; + case R.id.menu_add_shortcut: + addShortcut(); + break; + case R.id.menu_archive: + archiveNote(true); + break; + case R.id.menu_unarchive: + archiveNote(false); + break; + case R.id.menu_trash: + trashNote(true); + break; + case R.id.menu_untrash: + trashNote(false); + break; + case R.id.menu_discard_changes: + discard(); + break; + case R.id.menu_delete: + deleteNote(); + break; + case R.id.menu_note_info: + showNoteInfo(); + break; + default: + LogDelegate.w("Invalid menu option selected"); + } + + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackActionFromResourceId(getActivity(), + item.getItemId()); + + return super.onOptionsItemSelected(item); + } + + private void showNoteInfo () { + noteTmp.setTitle(getNoteTitle()); + noteTmp.setContent(getNoteContent()); + Intent intent = new Intent(getContext(), NoteInfosActivity.class); + intent.putExtra(Constants.INTENT_NOTE, (android.os.Parcelable) noteTmp); + startActivity(intent); + + } + + private void navigateUp () { + afterSavedReturnsToList = true; + saveAndExit(this); + } + + /** + * + */ + private void toggleChecklist () { + + // In case checklist is active a prompt will ask about many options + // to decide hot to convert back to simple text + if (!noteTmp.isChecklist()) { + toggleChecklist2(); + return; + } + + // If checklist is active but no items are checked the conversion in done automatically + // without prompting user + if (mChecklistManager.getCheckedCount() == 0) { + toggleChecklist2(true, false); + return; + } + + // Inflate the popup_layout.xml + LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); + final View layout = inflater.inflate(R.layout.dialog_remove_checklist_layout, + getView().findViewById(R.id.layout_root)); + + // Retrieves options checkboxes and initialize their values + final CheckBox keepChecked = layout.findViewById(R.id.checklist_keep_checked); + final CheckBox keepCheckmarks = layout.findViewById(R.id.checklist_keep_checkmarks); + keepChecked.setChecked(prefs.getBoolean(Constants.PREF_KEEP_CHECKED, true)); + keepCheckmarks.setChecked(prefs.getBoolean(Constants.PREF_KEEP_CHECKMARKS, true)); + + new MaterialDialog.Builder(mainActivity) + .customView(layout, false) + .positiveText(R.string.ok) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + prefs.edit() + .putBoolean(Constants.PREF_KEEP_CHECKED, keepChecked.isChecked()) + .putBoolean(Constants.PREF_KEEP_CHECKMARKS, keepCheckmarks.isChecked()) + .apply(); + toggleChecklist2(); + } + }).build().show(); + } + + /** + * Toggles checklist view + */ + private void toggleChecklist2 () { + boolean keepChecked = prefs.getBoolean(Constants.PREF_KEEP_CHECKED, true); + boolean showChecks = prefs.getBoolean(Constants.PREF_KEEP_CHECKMARKS, true); + toggleChecklist2(keepChecked, showChecks); + } + + @SuppressLint("NewApi") + private void toggleChecklist2 (final boolean keepChecked, final boolean showChecks) { + // Get instance and set options to convert EditText to CheckListView + + mChecklistManager = mChecklistManager == null ? new ChecklistManager(mainActivity) : mChecklistManager; + int checkedItemsBehavior = Integer.valueOf(prefs.getString("settings_checked_items_behavior", String.valueOf + (it.feio.android.checklistview.Settings.CHECKED_HOLD))); + mChecklistManager + .showCheckMarks(showChecks) + .newEntryHint(getString(R.string.checklist_item_hint)) + .keepChecked(keepChecked) + .undoBarContainerView(scrollView) + .moveCheckedOnBottom(checkedItemsBehavior); + + // Links parsing options + mChecklistManager.setOnTextLinkClickListener(textLinkClickListener); + mChecklistManager.addTextChangedListener(mFragment); + mChecklistManager.setCheckListChangedListener(mFragment); + + // Switches the views + View newView = null; + try { + newView = mChecklistManager.convert(toggleChecklistView); + } catch (ViewNotSupportedException e) { + LogDelegate.e("Error switching checklist view", e); + } + + // Switches the views + if (newView != null) { + mChecklistManager.replaceViews(toggleChecklistView, newView); + toggleChecklistView = newView; + animate(toggleChecklistView).alpha(1).scaleXBy(0).scaleX(1).scaleYBy(0).scaleY(1); + noteTmp.setChecklist(!noteTmp.isChecklist()); + } + } + + /** + * Categorize note choosing from a list of previously created categories + */ + private void categorizeNote () { + + String currentCategory = noteTmp.getCategory() != null ? String.valueOf(noteTmp.getCategory().getId()) : null; + final List categories = Observable.from(DbHelper.getInstance().getCategories()).map(category -> { + if (String.valueOf(category.getId()).equals(currentCategory)) { + category.setCount(category.getCount() + 1); + } + return category; + }).toList().toBlocking().single(); + + final MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) + .title(R.string.categorize_as) + .adapter(new NavDrawerCategoryAdapter(mainActivity, categories, currentCategory), null) + .positiveText(R.string.add_category) + .positiveColorRes(R.color.colorPrimary) + .negativeText(R.string.remove_category) + .negativeColorRes(R.color.colorAccent) + .onPositive((dialog1, which) -> { + Intent intent = new Intent(mainActivity, CategoryActivity.class); + intent.putExtra("noHome", true); + startActivityForResult(intent, CATEGORY); + }) + .onNegative((dialog12, which) -> { + noteTmp.setCategory(null); + setTagMarkerColor(null); + }).build(); + + dialog.getListView().setOnItemClickListener((parent, view, position, id) -> { + noteTmp.setCategory(categories.get(position)); + setTagMarkerColor(categories.get(position)); + dialog.dismiss(); + }); + + dialog.show(); + } + + private void showAttachmentsPopup () { + LayoutInflater inflater = mainActivity.getLayoutInflater(); + final View layout = inflater.inflate(R.layout.attachment_dialog, null); + + attachmentDialog = new MaterialDialog.Builder(mainActivity) + .autoDismiss(false) + .customView(layout, false) + .build(); + attachmentDialog.show(); + + // Camera + android.widget.TextView cameraSelection = layout.findViewById(R.id.camera); + cameraSelection.setOnClickListener(new AttachmentOnClickListener()); + // Audio recording + android.widget.TextView recordingSelection = layout.findViewById(R.id.recording); + toggleAudioRecordingStop(recordingSelection); + recordingSelection.setOnClickListener(new AttachmentOnClickListener()); + // Video recording + android.widget.TextView videoSelection = layout.findViewById(R.id.video); + videoSelection.setOnClickListener(new AttachmentOnClickListener()); + // Files + android.widget.TextView filesSelection = layout.findViewById(R.id.files); + filesSelection.setOnClickListener(new AttachmentOnClickListener()); + // Sketch + android.widget.TextView sketchSelection = layout.findViewById(R.id.sketch); + sketchSelection.setOnClickListener(new AttachmentOnClickListener()); + // Location + android.widget.TextView locationSelection = layout.findViewById(R.id.location); + locationSelection.setOnClickListener(new AttachmentOnClickListener()); + // Time + android.widget.TextView timeStampSelection = layout.findViewById(R.id.timestamp); + timeStampSelection.setOnClickListener(new AttachmentOnClickListener()); + // Desktop note with PushBullet + android.widget.TextView pushbulletSelection = layout.findViewById(R.id.pushbullet); + pushbulletSelection.setVisibility(View.VISIBLE); + pushbulletSelection.setOnClickListener(new AttachmentOnClickListener()); + } + + private void takePhoto () { + // Checks for camera app available + Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + if (!IntentChecker.isAvailable(mainActivity, intent, new String[]{PackageManager.FEATURE_CAMERA})) { + mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.ALERT); + + return; + } + // Checks for created file validity + File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_IMAGE_EXT); + if (f == null) { + mainActivity.showMessage(R.string.error, ONStyle.ALERT); + return; + } + attachmentUri = FileProviderHelper.getFileProvider(f); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + intent.putExtra(MediaStore.EXTRA_OUTPUT, attachmentUri); + startActivityForResult(intent, TAKE_PHOTO); + } + + private void takeVideo () { + Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); + if (!IntentChecker.isAvailable(mainActivity, takeVideoIntent, new String[]{PackageManager.FEATURE_CAMERA})) { + mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.ALERT); + + return; + } + // File is stored in custom ON folder to speedup the attachment + File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_VIDEO_EXT); + if (f == null) { + mainActivity.showMessage(R.string.error, ONStyle.ALERT); + return; + } + attachmentUri = FileProviderHelper.getFileProvider(f); + takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, attachmentUri); + String maxVideoSizeStr = "".equals(prefs.getString("settings_max_video_size", + "")) ? "0" : prefs.getString("settings_max_video_size", ""); + long maxVideoSize = parseLong(maxVideoSizeStr) * 1024L * 1024L; + takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxVideoSize); + startActivityForResult(takeVideoIntent, TAKE_VIDEO); + } + + private void takeSketch (Attachment attachment) { + + File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_SKETCH_EXT); + if (f == null) { + mainActivity.showMessage(R.string.error, ONStyle.ALERT); + return; + } + attachmentUri = Uri.fromFile(f); + + // Forces portrait orientation to this fragment only + mainActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + + // Fragments replacing + FragmentTransaction transaction = mainActivity.getSupportFragmentManager().beginTransaction(); + mainActivity.animateTransition(transaction, mainActivity.TRANSITION_HORIZONTAL); + SketchFragment mSketchFragment = new SketchFragment(); + Bundle b = new Bundle(); + b.putParcelable(MediaStore.EXTRA_OUTPUT, attachmentUri); + if (attachment != null) { + b.putParcelable("base", attachment.getUri()); + } + mSketchFragment.setArguments(b); + transaction.replace(R.id.fragment_container, mSketchFragment, mainActivity.FRAGMENT_SKETCH_TAG) + .addToBackStack(mainActivity.FRAGMENT_DETAIL_TAG).commit(); + } + + private void addTimestamp () { + Editable editable = content.getText(); + int position = content.getSelectionStart(); + DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); + String dateStamp = dateFormat.format(new Date().getTime()) + " "; + if (noteTmp.isChecklist()) { + if (mChecklistManager.getFocusedItemView() != null) { + editable = mChecklistManager.getFocusedItemView().getEditText().getEditableText(); + position = mChecklistManager.getFocusedItemView().getEditText().getSelectionStart(); + } else { + ((CheckListView) toggleChecklistView) + .addItem(dateStamp, false, mChecklistManager.getCount()); + } + } + String leadSpace = position == 0 ? "" : " "; + dateStamp = leadSpace + dateStamp; + editable.insert(position, dateStamp); + Selection.setSelection(editable, position + dateStamp.length()); + } + + @SuppressLint("NewApi") + @Override + public void onActivityResult (int requestCode, int resultCode, Intent intent) { + // Fetch uri from activities, store into adapter and refresh adapter + Attachment attachment; + if (resultCode == Activity.RESULT_OK) { + switch (requestCode) { + case TAKE_PHOTO: + attachment = new Attachment(attachmentUri, Constants.MIME_TYPE_IMAGE); + addAttachment(attachment); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + break; + case TAKE_VIDEO: + attachment = new Attachment(attachmentUri, Constants.MIME_TYPE_VIDEO); + addAttachment(attachment); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + break; + case FILES: + onActivityResultManageReceivedFiles(intent); + break; + case SET_PASSWORD: + noteTmp.setPasswordChecked(true); + lockUnlock(); + break; + case SKETCH: + attachment = new Attachment(attachmentUri, Constants.MIME_TYPE_SKETCH); + addAttachment(attachment); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + break; + case CATEGORY: + mainActivity.showMessage(R.string.category_saved, ONStyle.CONFIRM); + Category category = intent.getParcelableExtra("category"); + noteTmp.setCategory(category); + setTagMarkerColor(category); + break; + case DETAIL: + mainActivity.showMessage(R.string.note_updated, ONStyle.CONFIRM); + break; + default: + LogDelegate.e("Wrong element choosen: " + requestCode); + } + } + } + + private void onActivityResultManageReceivedFiles (Intent intent) { + List uris = new ArrayList<>(); + if (Build.VERSION.SDK_INT > 16 && intent.getClipData() != null) { + for (int i = 0; i < intent.getClipData().getItemCount(); i++) { + uris.add(intent.getClipData().getItemAt(i).getUri()); + } + } else { + uris.add(intent.getData()); + } + for (Uri uri : uris) { + String name = FileHelper.getNameFromUri(mainActivity, uri); + new AttachmentTask(this, uri, name, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + } + + /** + * Discards changes done to the note and eventually delete new attachments + */ + private void discard () { + if (!noteTmp.getAttachmentsList().equals(note.getAttachmentsList())) { + for (Attachment newAttachment : noteTmp.getAttachmentsList()) { + if (!note.getAttachmentsList().contains(newAttachment)) { + StorageHelper.delete(mainActivity, newAttachment.getUri().getPath()); + } + } + } + + goBack = true; + + if (!noteTmp.equals(noteOriginal)) { + if (noteOriginal.get_id() != null) { + new SaveNoteTask(this, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, noteOriginal); + } + MainActivity.notifyAppWidgets(mainActivity); + } else { + goHome(); + } + } + + @SuppressLint("NewApi") + private void archiveNote (boolean archive) { + // Simply go back if is a new note + if (noteTmp.get_id() == null) { + goHome(); + return; + } + + noteTmp.setArchived(archive); + goBack = true; + exitMessage = archive ? getString(R.string.note_archived) : getString(R.string.note_unarchived); + exitCroutonStyle = archive ? ONStyle.WARN : ONStyle.INFO; + saveNote(this); + } + + @SuppressLint("NewApi") + private void trashNote (boolean trash) { + // Simply go back if is a new note + if (noteTmp.get_id() == null) { + goHome(); + return; + } + + noteTmp.setTrashed(trash); + goBack = true; + exitMessage = trash ? getString(R.string.note_trashed) : getString(R.string.note_untrashed); + exitCroutonStyle = trash ? ONStyle.WARN : ONStyle.INFO; + if (trash) { + ShortcutHelper.removeshortCut(OmniNotes.getAppContext(), noteTmp); + ReminderHelper.removeReminder(OmniNotes.getAppContext(), noteTmp); + } else { + ReminderHelper.addReminder(OmniNotes.getAppContext(), note); + } + saveNote(this); + } + + private void deleteNote () { + new MaterialDialog.Builder(mainActivity) + .content(R.string.delete_note_confirmation) + .positiveText(R.string.ok) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + mainActivity.deleteNote(noteTmp); + LogDelegate.d("Deleted note with id '" + noteTmp.get_id() + "'"); + mainActivity.showMessage(R.string.note_deleted, ONStyle.ALERT); + goHome(); + } + }).build().show(); + } + + public void saveAndExit (OnNoteSaved mOnNoteSaved) { + if (isAdded()) { + exitMessage = getString(R.string.note_updated); + exitCroutonStyle = ONStyle.CONFIRM; + goBack = true; + saveNote(mOnNoteSaved); + } + } + + /** + * Save new notes, modify them or archive + */ + void saveNote (OnNoteSaved mOnNoteSaved) { + + // Changed fields + noteTmp.setTitle(getNoteTitle()); + noteTmp.setContent(getNoteContent()); + + // Check if some text or attachments of any type have been inserted or is an empty note + if (goBack && TextUtils.isEmpty(noteTmp.getTitle()) && TextUtils.isEmpty(noteTmp.getContent()) + && noteTmp.getAttachmentsList().size() == 0) { + LogDelegate.d("Empty note not saved"); + exitMessage = getString(R.string.empty_note_not_saved); + exitCroutonStyle = ONStyle.INFO; + goHome(); + return; + } + + if (saveNotNeeded()) { + exitMessage = ""; + if (goBack) { + goHome(); + } + return; + } + + noteTmp.setAttachmentsListOld(note.getAttachmentsList()); + + new SaveNoteTask(mOnNoteSaved, lastModificationUpdatedNeeded()).executeOnExecutor(AsyncTask + .THREAD_POOL_EXECUTOR, noteTmp); + } + + /** + * Checks if nothing is changed to avoid committing if possible (check) + */ + private boolean saveNotNeeded () { + if (noteTmp.get_id() == null && prefs.getBoolean(Constants.PREF_AUTO_LOCATION, false)) { + note.setLatitude(noteTmp.getLatitude()); + note.setLongitude(noteTmp.getLongitude()); + } + return !noteTmp.isChanged(note) || (noteTmp.isLocked() && !noteTmp.isPasswordChecked()); + } + + /** + * Checks if only tag, archive or trash status have been changed and then force to not update last modification date* + */ + private boolean lastModificationUpdatedNeeded () { + note.setCategory(noteTmp.getCategory()); + note.setArchived(noteTmp.isArchived()); + note.setTrashed(noteTmp.isTrashed()); + note.setLocked(noteTmp.isLocked()); + return noteTmp.isChanged(note); + } + + @Override + public void onNoteSaved (Note noteSaved) { + MainActivity.notifyAppWidgets(OmniNotes.getAppContext()); + if (!activityPausing) { + EventBus.getDefault().post(new NotesUpdatedEvent(Collections.singletonList(noteSaved))); + deleteMergedNotes(mergedNotesIds); + if (noteTmp.getAlarm() != null && !noteTmp.getAlarm().equals(note.getAlarm())) { + ReminderHelper.showReminderMessage(String.valueOf(noteTmp.getAlarm())); + } + } + note = new Note(noteSaved); + if (goBack) { + goHome(); + } + } + + private void deleteMergedNotes (List mergedNotesIds) { + ArrayList notesToDelete = new ArrayList<>(); + if (mergedNotesIds != null) { + for (String mergedNoteId : mergedNotesIds) { + Note note = new Note(); + note.set_id(Long.valueOf(mergedNoteId)); + notesToDelete.add(note); + } + new NoteProcessorDelete(notesToDelete).process(); + } + } + + private String getNoteTitle () { + if (title != null && !TextUtils.isEmpty(title.getText())) { + return title.getText().toString(); + } else { + return ""; + } + } + + private String getNoteContent () { + String contentText = ""; + if (!noteTmp.isChecklist()) { + // Due to checklist library introduction the returned EditText class is no more a + // com.neopixl.pixlui.components.edittext.EditText but a standard android.widget.EditText + View contentView = root.findViewById(R.id.detail_content); + if (contentView instanceof EditText) { + contentText = ((EditText) contentView).getText().toString(); + } else if (contentView instanceof android.widget.EditText) { + contentText = ((android.widget.EditText) contentView).getText().toString(); + } + } else { + if (mChecklistManager != null) { + mChecklistManager.keepChecked(true).showCheckMarks(true); + contentText = mChecklistManager.getText(); + } + } + return contentText; + } + + /** + * Updates share intent + */ + private void shareNote () { + Note sharedNote = new Note(noteTmp); + sharedNote.setTitle(getNoteTitle()); + sharedNote.setContent(getNoteContent()); + mainActivity.shareNote(sharedNote); + } + + /** + * Notes locking with security password to avoid viewing, editing or deleting from unauthorized + */ + private void lockNote () { + LogDelegate.d("Locking or unlocking note " + note.get_id()); + + // If security password is not set yes will be set right now + if (prefs.getString(Constants.PREF_PASSWORD, null) == null) { + Intent passwordIntent = new Intent(mainActivity, PasswordActivity.class); + startActivityForResult(passwordIntent, SET_PASSWORD); + return; + } + + // If password has already been inserted will not be asked again + if (noteTmp.isPasswordChecked() || prefs.getBoolean("settings_password_access", false)) { + lockUnlock(); + return; + } + + // Password will be requested here + PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { + switch (passwordConfirmed) { + case SUCCEED: + lockUnlock(); + break; + default: + break; + } + }); + } + + private void lockUnlock () { + // Empty password has been set + if (prefs.getString(Constants.PREF_PASSWORD, null) == null) { + mainActivity.showMessage(R.string.password_not_set, ONStyle.WARN); + return; + } + mainActivity.showMessage(R.string.save_note_to_lock_it, ONStyle.INFO); + mainActivity.supportInvalidateOptionsMenu(); + noteTmp.setLocked(!noteTmp.isLocked()); + noteTmp.setPasswordChecked(true); + } + + /** + * Used to set actual reminder state when initializing a note to be edited + */ + private String initReminder (Note note) { + if (noteTmp.getAlarm() == null) { + return ""; + } + long reminder = parseLong(note.getAlarm()); + String rrule = note.getRecurrenceRule(); + if (!TextUtils.isEmpty(rrule)) { + return DateHelper.getNoteRecurrentReminderText(reminder, rrule); + } else { + return DateHelper.getNoteReminderText(reminder); + } + } + + /** + * Audio recordings playback + */ + private void playback (View v, Uri uri) { + // Some recording is playing right now + if (mPlayer != null && mPlayer.isPlaying()) { + if (isPlayingView != v) { + // If the audio actually played is NOT the one from the click view the last one is played + stopPlaying(); + isPlayingView = v; + startPlaying(uri); + replacePlayingAudioBitmap(v); + } else { + // Otherwise just stops playing + stopPlaying(); + } + } else { + // If nothing is playing audio just plays + isPlayingView = v; + startPlaying(uri); + replacePlayingAudioBitmap(v); + } + } + + private void replacePlayingAudioBitmap (View v) { + Drawable d = ((ImageView) v.findViewById(R.id.gridview_item_picture)).getDrawable(); + if (BitmapDrawable.class.isAssignableFrom(d.getClass())) { + recordingBitmap = ((BitmapDrawable) d).getBitmap(); + } else { + recordingBitmap = ((BitmapDrawable) d.getCurrent()).getBitmap(); + } + ((ImageView) v.findViewById(R.id.gridview_item_picture)).setImageBitmap(ThumbnailUtils + .extractThumbnail(BitmapFactory.decodeResource(mainActivity.getResources(), + R.drawable.stop), Constants.THUMBNAIL_SIZE, Constants.THUMBNAIL_SIZE)); + } + + private void startPlaying (Uri uri) { + if (mPlayer == null) { + mPlayer = new MediaPlayer(); + } + try { + mPlayer.setDataSource(mainActivity, uri); + mPlayer.prepare(); + mPlayer.start(); + mPlayer.setOnCompletionListener(mp -> { + mPlayer = null; + if (isPlayingView != null) { + ((ImageView) isPlayingView.findViewById(R.id.gridview_item_picture)).setImageBitmap + (recordingBitmap); + recordingBitmap = null; + isPlayingView = null; + } + }); + } catch (IOException e) { + LogDelegate.e("prepare() failed", e); + mainActivity.showMessage(R.string.error, ONStyle.ALERT); + } + } + + private void stopPlaying () { + if (mPlayer != null) { + if (isPlayingView != null) { + ((ImageView) isPlayingView.findViewById(R.id.gridview_item_picture)).setImageBitmap(recordingBitmap); + } + isPlayingView = null; + recordingBitmap = null; + mPlayer.release(); + mPlayer = null; + } + } + + private void startRecording (View v) { + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.RECORD_AUDIO, + R.string.permission_audio_recording, snackBarPlaceholder, () -> { + + isRecording = true; + toggleAudioRecordingStop(v); + + File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_AUDIO_EXT); + if (f == null) { + mainActivity.showMessage(R.string.error, ONStyle.ALERT); + return; + } + if (mRecorder == null) { + mRecorder = new MediaRecorder(); + mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); + mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); + mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); + mRecorder.setAudioEncodingBitRate(96000); + mRecorder.setAudioSamplingRate(44100); + } + recordName = f.getAbsolutePath(); + mRecorder.setOutputFile(recordName); + + try { + audioRecordingTimeStart = Calendar.getInstance().getTimeInMillis(); + mRecorder.prepare(); + mRecorder.start(); + } catch (IOException | IllegalStateException e) { + LogDelegate.e("prepare() failed", e); + mainActivity.showMessage(R.string.error, ONStyle.ALERT); + } + }); + } + + private void toggleAudioRecordingStop (View v) { + if (isRecording) { + ((android.widget.TextView) v).setText(getString(R.string.stop)); + ((android.widget.TextView) v).setTextColor(Color.parseColor("#ff0000")); + } + } + + private void stopRecording () { + isRecording = false; + if (mRecorder != null) { + mRecorder.stop(); + audioRecordingTime = Calendar.getInstance().getTimeInMillis() - audioRecordingTimeStart; + mRecorder.release(); + mRecorder = null; + } + } + + private void fade (final View v, boolean fadeIn) { + + int anim = R.animator.fade_out_support; + int visibilityTemp = View.GONE; + + if (fadeIn) { + anim = R.animator.fade_in_support; + visibilityTemp = View.VISIBLE; + } + + final int visibility = visibilityTemp; + + // Checks if user has left the app + if (mainActivity != null) { + Animation mAnimation = AnimationUtils.loadAnimation(mainActivity, anim); + mAnimation.setAnimationListener(new AnimationListener() { + @Override + public void onAnimationStart (Animation animation) { + // Nothing to do + } + + @Override + public void onAnimationRepeat (Animation animation) { + // Nothing to do + } + + @Override + public void onAnimationEnd (Animation animation) { + v.setVisibility(visibility); + } + }); + v.startAnimation(mAnimation); + } + } + + /** + * Adding shortcut on Home screen + */ + private void addShortcut () { + ShortcutHelper.addShortcut(OmniNotes.getAppContext(), noteTmp); + mainActivity.showMessage(R.string.shortcut_added, ONStyle.INFO); + } + + @SuppressLint("NewApi") + @Override + public boolean onTouch (View v, MotionEvent event) { + int x = (int) event.getX(); + int y = (int) event.getY(); + + switch (event.getAction()) { + + case MotionEvent.ACTION_DOWN: + LogDelegate.v("MotionEvent.ACTION_DOWN"); + int w; + + Point displaySize = Display.getUsableSize(mainActivity); + w = displaySize.x; + + if (x < Constants.SWIPE_MARGIN || x > w - Constants.SWIPE_MARGIN) { + swiping = true; + startSwipeX = x; + } + + break; + + case MotionEvent.ACTION_UP: + LogDelegate.v("MotionEvent.ACTION_UP"); + if (swiping) { + swiping = false; + } + break; + + case MotionEvent.ACTION_MOVE: + if (swiping) { + LogDelegate.v("MotionEvent.ACTION_MOVE at position " + x + ", " + y); + if (Math.abs(x - startSwipeX) > Constants.SWIPE_OFFSET) { + swiping = false; + FragmentTransaction transaction = mainActivity.getSupportFragmentManager().beginTransaction(); + mainActivity.animateTransition(transaction, mainActivity.TRANSITION_VERTICAL); + DetailFragment mDetailFragment = new DetailFragment(); + Bundle b = new Bundle(); + b.putParcelable(Constants.INTENT_NOTE, new Note()); + mDetailFragment.setArguments(b); + transaction.replace(R.id.fragment_container, mDetailFragment, + mainActivity.FRAGMENT_DETAIL_TAG).addToBackStack(mainActivity + .FRAGMENT_DETAIL_TAG).commit(); + } + } + break; + + default: + LogDelegate.e("Wrong element choosen: " + event.getAction()); + } + + return true; + } + + @Override + public void onAttachingFileErrorOccurred (Attachment mAttachment) { + mainActivity.showMessage(R.string.error_saving_attachments, ONStyle.ALERT); + if (noteTmp.getAttachmentsList().contains(mAttachment)) { + removeAttachment(mAttachment); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + } + } + + private void addAttachment (Attachment attachment) { + noteTmp.addAttachment(attachment); + } + + private void removeAttachment (Attachment mAttachment) { + noteTmp.removeAttachment(mAttachment); + } + + private void removeAttachment (int position) { + noteTmp.removeAttachment(noteTmp.getAttachmentsList().get(position)); + } + + private void removeAllAttachments () { + noteTmp.setAttachmentsList(new ArrayList<>()); + mAttachmentAdapter = new AttachmentAdapter(mainActivity, new ArrayList<>(), mGridView); + mGridView.invalidateViews(); + mGridView.setAdapter(mAttachmentAdapter); + } + + @Override + public void onAttachingFileFinished (Attachment mAttachment) { + addAttachment(mAttachment); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + } + + @Override + public void onReminderPicked (long reminder) { + noteTmp.setAlarm(reminder); + if (mFragment.isAdded()) { + reminderIcon.setImageResource(R.drawable.ic_alarm_black_18dp); + datetime.setText(DateHelper.getNoteReminderText(reminder)); + } + } + + @Override + public void onRecurrenceReminderPicked (String recurrenceRule) { + noteTmp.setRecurrenceRule(recurrenceRule); + if (!TextUtils.isEmpty(recurrenceRule)) { + LogDelegate.d("Recurrent reminder set: " + recurrenceRule); + datetime.setText(DateHelper.getNoteRecurrentReminderText(Long.parseLong(noteTmp.getAlarm()), recurrenceRule)); + } + } + + @Override + public void onTextChanged (CharSequence s, int start, int before, int count) { + scrollContent(); + } + + @Override + public void beforeTextChanged (CharSequence s, int start, int count, int after) { + // Nothing to do + } + + @Override + public void afterTextChanged (Editable s) { + // Nothing to do + } + + @Override + public void onCheckListChanged () { + scrollContent(); + } + + private void scrollContent () { + if (noteTmp.isChecklist()) { + if (mChecklistManager.getCount() > contentLineCounter) { + scrollView.scrollBy(0, 60); + } + contentLineCounter = mChecklistManager.getCount(); + } else { + if (content.getLineCount() > contentLineCounter) { + scrollView.scrollBy(0, 60); + } + contentLineCounter = content.getLineCount(); + } + } + + /** + * Add previously created tags to content + */ + private void addTags () { + contentCursorPosition = getCursorIndex(); + + // Retrieves all available categories + final List tags = TagsHelper.getAllTags(); + + // If there is no tag a message will be shown + if (tags.size() == 0) { + mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN); + return; + } + + final Note currentNote = new Note(); + currentNote.setTitle(getNoteTitle()); + currentNote.setContent(getNoteContent()); + Integer[] preselectedTags = TagsHelper.getPreselectedTagsArray(currentNote, tags); + + // Dialog and events creation + MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) + .title(R.string.select_tags) + .positiveText(R.string.ok) + .items(TagsHelper.getTagsArray(tags)) + .itemsCallbackMultiChoice(preselectedTags, (dialog1, which, text) -> { + dialog1.dismiss(); + tagNote(tags, which, currentNote); + return false; + }).build(); + dialog.show(); + } + + private void tagNote (List tags, Integer[] selectedTags, Note note) { + Pair> taggingResult = TagsHelper.addTagToNote(tags, selectedTags, note); + + StringBuilder sb; + if (noteTmp.isChecklist()) { + CheckListViewItem mCheckListViewItem = mChecklistManager.getFocusedItemView(); + if (mCheckListViewItem != null) { + sb = new StringBuilder(mCheckListViewItem.getText()); + sb.insert(contentCursorPosition, " " + taggingResult.first + " "); + mCheckListViewItem.setText(sb.toString()); + mCheckListViewItem.getEditText().setSelection(contentCursorPosition + taggingResult.first.length() + + 1); + } else { + title.append(" " + taggingResult.first); + } + } else { + sb = new StringBuilder(getNoteContent()); + if (content.hasFocus()) { + sb.insert(contentCursorPosition, " " + taggingResult.first + " "); + content.setText(sb.toString()); + content.setSelection(contentCursorPosition + taggingResult.first.length() + 1); + } else { + if (getNoteContent().trim().length() > 0) { + sb.append(System.getProperty("line.separator")) + .append(System.getProperty("line.separator")); + } + sb.append(taggingResult.first); + content.setText(sb.toString()); + } + } + + // Removes unchecked tags + if (taggingResult.second.size() > 0) { + if (noteTmp.isChecklist()) { + toggleChecklist2(true, true); + } + Pair titleAndContent = TagsHelper.removeTag(getNoteTitle(), getNoteContent(), + taggingResult.second); + title.setText(titleAndContent.first); + content.setText(titleAndContent.second); + if (noteTmp.isChecklist()) { + toggleChecklist2(); + } + } + } + + private int getCursorIndex () { + if (!noteTmp.isChecklist()) { + return content.getSelectionStart(); + } else { + CheckListViewItem mCheckListViewItem = mChecklistManager.getFocusedItemView(); + if (mCheckListViewItem != null) { + return mCheckListViewItem.getEditText().getSelectionStart(); + } else { + return 0; + } + } + } + + /** + * Used to check currently opened note from activity to avoid openind multiple times the same one + */ + public Note getCurrentNote () { + return note; + } + + private boolean isNoteLocationValid () { + return noteTmp.getLatitude() != null + && noteTmp.getLatitude() != 0 + && noteTmp.getLongitude() != null + && noteTmp.getLongitude() != 0; + } + + public void startGetContentAction () { + Intent filesIntent; + filesIntent = new Intent(Intent.ACTION_GET_CONTENT); + filesIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); + filesIntent.addCategory(Intent.CATEGORY_OPENABLE); + filesIntent.setType("*/*"); + startActivityForResult(filesIntent, FILES); + } + + private void askReadExternalStoragePermission () { + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE, + R.string.permission_external_storage_detail_attachment, + snackBarPlaceholder, this::startGetContentAction); + } + + public void onEventMainThread (PushbulletReplyEvent pushbulletReplyEvent) { + String text = getNoteContent() + System.getProperty("line.separator") + pushbulletReplyEvent.message; + content.setText(text); + } + + private static class OnGeoUtilResultListenerImpl implements OnGeoUtilResultListener { + + private final WeakReference mainActivityWeakReference; + private final WeakReference detailFragmentWeakReference; + private final WeakReference noteTmpWeakReference; + + OnGeoUtilResultListenerImpl (MainActivity activity, DetailFragment mFragment, Note noteTmp) { + mainActivityWeakReference = new WeakReference<>(activity); + detailFragmentWeakReference = new WeakReference<>(mFragment); + noteTmpWeakReference = new WeakReference<>(noteTmp); + } + + @Override + public void onAddressResolved (String address) { + } + + @Override + public void onCoordinatesResolved (Location location, String address) { + } + + @Override + public void onLocationUnavailable () { + mainActivityWeakReference.get().showMessage(R.string.location_not_found, ONStyle.ALERT); + } + + @Override + public void onLocationRetrieved (Location location) { + + if (!checkWeakReferences()) { + return; + } + + if (location == null) { + return; + } + if (!ConnectionManager.internetAvailable(mainActivityWeakReference.get())) { + noteTmpWeakReference.get().setLatitude(location.getLatitude()); + noteTmpWeakReference.get().setLongitude(location.getLongitude()); + onAddressResolved(""); + return; + } + LayoutInflater inflater = mainActivityWeakReference.get().getLayoutInflater(); + View v = inflater.inflate(R.layout.dialog_location, null); + final AutoCompleteTextView autoCompView = v.findViewById(R.id + .auto_complete_location); + autoCompView.setHint(mainActivityWeakReference.get().getString(R.string.search_location)); + autoCompView.setAdapter(new PlacesAutoCompleteAdapter(mainActivityWeakReference.get(), R.layout + .simple_text_layout)); + final MaterialDialog dialog = new MaterialDialog.Builder(mainActivityWeakReference.get()) + .customView(autoCompView, false) + .positiveText(R.string.use_current_location) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + if (TextUtils.isEmpty(autoCompView.getText().toString())) { + noteTmpWeakReference.get().setLatitude(location.getLatitude()); + noteTmpWeakReference.get().setLongitude(location.getLongitude()); + GeocodeHelper.getAddressFromCoordinates(location, detailFragmentWeakReference.get()); + } else { + GeocodeHelper.getCoordinatesFromAddress(autoCompView.getText().toString(), + detailFragmentWeakReference.get()); + } } - return category; - }).toList().toBlocking().single(); - - - final MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) - .title(R.string.categorize_as) - .adapter(new NavDrawerCategoryAdapter(mainActivity, categories, currentCategory), null) - .positiveText(R.string.add_category) - .positiveColorRes(R.color.colorPrimary) - .negativeText(R.string.remove_category) - .negativeColorRes(R.color.colorAccent) - .onPositive((dialog1, which) -> { - Intent intent = new Intent(mainActivity, CategoryActivity.class); - intent.putExtra("noHome", true); - startActivityForResult(intent, CATEGORY); - }) - .onNegative((dialog12, which) -> { - noteTmp.setCategory(null); - setTagMarkerColor(null); - }).build(); - - dialog.getListView().setOnItemClickListener((parent, view, position, id) -> { - noteTmp.setCategory(categories.get(position)); - setTagMarkerColor(categories.get(position)); - dialog.dismiss(); - }); - - dialog.show(); - } - - private void showAttachmentsPopup() { - LayoutInflater inflater = mainActivity.getLayoutInflater(); - final View layout = inflater.inflate(R.layout.attachment_dialog, null); - - attachmentDialog = new MaterialDialog.Builder(mainActivity) - .autoDismiss(false) - .customView(layout, false) - .build(); - attachmentDialog.show(); - - // Camera - android.widget.TextView cameraSelection = (android.widget.TextView) layout.findViewById(R.id.camera); - cameraSelection.setOnClickListener(new AttachmentOnClickListener()); - // Audio recording - android.widget.TextView recordingSelection = (android.widget.TextView) layout.findViewById(R.id.recording); - toggleAudioRecordingStop(recordingSelection); - recordingSelection.setOnClickListener(new AttachmentOnClickListener()); - // Video recording - android.widget.TextView videoSelection = (android.widget.TextView) layout.findViewById(R.id.video); - videoSelection.setOnClickListener(new AttachmentOnClickListener()); - // Files - android.widget.TextView filesSelection = (android.widget.TextView) layout.findViewById(R.id.files); - filesSelection.setOnClickListener(new AttachmentOnClickListener()); - // Sketch - android.widget.TextView sketchSelection = (android.widget.TextView) layout.findViewById(R.id.sketch); - sketchSelection.setOnClickListener(new AttachmentOnClickListener()); - // Location - android.widget.TextView locationSelection = (android.widget.TextView) layout.findViewById(R.id.location); - locationSelection.setOnClickListener(new AttachmentOnClickListener()); - // Time - android.widget.TextView timeStampSelection = (android.widget.TextView) layout.findViewById(R.id.timestamp); - timeStampSelection.setOnClickListener(new AttachmentOnClickListener()); - // Desktop note with PushBullet - android.widget.TextView pushbulletSelection = (android.widget.TextView) layout.findViewById(R.id.pushbullet); - pushbulletSelection.setVisibility(View.VISIBLE); - pushbulletSelection.setOnClickListener(new AttachmentOnClickListener()); - } - - private void takePhoto() { - // Checks for camera app available - Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - if (!IntentChecker.isAvailable(mainActivity, intent, new String[]{PackageManager.FEATURE_CAMERA})) { - mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.ALERT); - - return; - } - // Checks for created file validity - File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_IMAGE_EXT); - if (f == null) { - mainActivity.showMessage(R.string.error, ONStyle.ALERT); - return; - } - attachmentUri = FileProviderHelper.getFileProvider(f); - intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - intent.putExtra(MediaStore.EXTRA_OUTPUT, attachmentUri); - startActivityForResult(intent, TAKE_PHOTO); - } - - private void takeVideo() { - Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); - if (!IntentChecker.isAvailable(mainActivity, takeVideoIntent, new String[]{PackageManager.FEATURE_CAMERA})) { - mainActivity.showMessage(R.string.feature_not_available_on_this_device, ONStyle.ALERT); - - return; - } - // File is stored in custom ON folder to speedup the attachment - File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_VIDEO_EXT); - if (f == null) { - mainActivity.showMessage(R.string.error, ONStyle.ALERT); - return; - } - attachmentUri = FileProviderHelper.getFileProvider(f); - takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, attachmentUri); - String maxVideoSizeStr = "".equals(prefs.getString("settings_max_video_size", - "")) ? "0" : prefs.getString("settings_max_video_size", ""); - long maxVideoSize = parseLong(maxVideoSizeStr) * 1024L * 1024L; - takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxVideoSize); - startActivityForResult(takeVideoIntent, TAKE_VIDEO); - } - - private void takeSketch(Attachment attachment) { - - File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_SKETCH_EXT); - if (f == null) { - mainActivity.showMessage(R.string.error, ONStyle.ALERT); - return; - } - attachmentUri = Uri.fromFile(f); - - // Forces portrait orientation to this fragment only - mainActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - - // Fragments replacing - FragmentTransaction transaction = mainActivity.getSupportFragmentManager().beginTransaction(); - mainActivity.animateTransition(transaction, mainActivity.TRANSITION_HORIZONTAL); - SketchFragment mSketchFragment = new SketchFragment(); - Bundle b = new Bundle(); - b.putParcelable(MediaStore.EXTRA_OUTPUT, attachmentUri); - if (attachment != null) { - b.putParcelable("base", attachment.getUri()); - } - mSketchFragment.setArguments(b); - transaction.replace(R.id.fragment_container, mSketchFragment, mainActivity.FRAGMENT_SKETCH_TAG) - .addToBackStack(mainActivity.FRAGMENT_DETAIL_TAG).commit(); - } - - private void addTimestamp() { - Editable editable = content.getText(); - int position = content.getSelectionStart(); - DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); - String dateStamp = dateFormat.format(new Date().getTime()) + " "; - if (noteTmp.isChecklist()) { - if (mChecklistManager.getFocusedItemView() != null) { - editable = mChecklistManager.getFocusedItemView().getEditText().getEditableText(); - position = mChecklistManager.getFocusedItemView().getEditText().getSelectionStart(); - } else { - ((CheckListView) toggleChecklistView) - .addItem(dateStamp, false, mChecklistManager.getCount()); - } - } - String leadSpace = position == 0 ? "" : " "; - dateStamp = leadSpace + dateStamp; - editable.insert(position, dateStamp); - Selection.setSelection(editable, position + dateStamp.length()); - } - - @SuppressLint("NewApi") - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) { - // Fetch uri from activities, store into adapter and refresh adapter - Attachment attachment; - if (resultCode == Activity.RESULT_OK) { - switch (requestCode) { - case TAKE_PHOTO: - attachment = new Attachment(attachmentUri, Constants.MIME_TYPE_IMAGE); - addAttachment(attachment); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - break; - case TAKE_VIDEO: - attachment = new Attachment(attachmentUri, Constants.MIME_TYPE_VIDEO); - addAttachment(attachment); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - break; - case FILES: - onActivityResultManageReceivedFiles(intent); - break; - case SET_PASSWORD: - noteTmp.setPasswordChecked(true); - lockUnlock(); - break; - case SKETCH: - attachment = new Attachment(attachmentUri, Constants.MIME_TYPE_SKETCH); - addAttachment(attachment); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - break; - case CATEGORY: - mainActivity.showMessage(R.string.category_saved, ONStyle.CONFIRM); - Category category = intent.getParcelableExtra("category"); - noteTmp.setCategory(category); - setTagMarkerColor(category); - break; - case DETAIL: - mainActivity.showMessage(R.string.note_updated, ONStyle.CONFIRM); - break; - default: - LogDelegate.e("Wrong element choosen: " + requestCode); - } - } - } - - private void onActivityResultManageReceivedFiles(Intent intent) { - List uris = new ArrayList<>(); - if (Build.VERSION.SDK_INT > 16 && intent.getClipData() != null) { - for (int i = 0; i < intent.getClipData().getItemCount(); i++) { - uris.add(intent.getClipData().getItemAt(i).getUri()); - } - } else { - uris.add(intent.getData()); - } - for (Uri uri : uris) { - String name = FileHelper.getNameFromUri(mainActivity, uri); - new AttachmentTask(this, uri, name, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - } - - /** - * Discards changes done to the note and eventually delete new attachments - */ - private void discard() { - if (!noteTmp.getAttachmentsList().equals(note.getAttachmentsList())) { - for (Attachment newAttachment : noteTmp.getAttachmentsList()) { - if (!note.getAttachmentsList().contains(newAttachment)) { - StorageHelper.delete(mainActivity, newAttachment.getUri().getPath()); - } - } - } - - goBack = true; - - if (!noteTmp.equals(noteOriginal)) { - if (noteOriginal.get_id() != null) { - new SaveNoteTask(this, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, noteOriginal); - } - MainActivity.notifyAppWidgets(mainActivity); - } else { - goHome(); - } - } - - @SuppressLint("NewApi") - private void archiveNote(boolean archive) { - // Simply go back if is a new note - if (noteTmp.get_id() == null) { - goHome(); - return; - } - - noteTmp.setArchived(archive); - goBack = true; - exitMessage = archive ? getString(R.string.note_archived) : getString(R.string.note_unarchived); - exitCroutonStyle = archive ? ONStyle.WARN : ONStyle.INFO; - saveNote(this); - } - - @SuppressLint("NewApi") - private void trashNote(boolean trash) { - // Simply go back if is a new note - if (noteTmp.get_id() == null) { - goHome(); - return; - } - - noteTmp.setTrashed(trash); - goBack = true; - exitMessage = trash ? getString(R.string.note_trashed) : getString(R.string.note_untrashed); - exitCroutonStyle = trash ? ONStyle.WARN : ONStyle.INFO; - if (trash) { - ShortcutHelper.removeshortCut(OmniNotes.getAppContext(), noteTmp); - ReminderHelper.removeReminder(OmniNotes.getAppContext(), noteTmp); - } else { - ReminderHelper.addReminder(OmniNotes.getAppContext(), note); - } - saveNote(this); - } - - private void deleteNote() { - new MaterialDialog.Builder(mainActivity) - .content(R.string.delete_note_confirmation) - .positiveText(R.string.ok) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - mainActivity.deleteNote(noteTmp); - LogDelegate.d("Deleted note with id '" + noteTmp.get_id() + "'"); - mainActivity.showMessage(R.string.note_deleted, ONStyle.ALERT); - goHome(); - } - }).build().show(); - } - - public void saveAndExit(OnNoteSaved mOnNoteSaved) { - if (isAdded()) { - exitMessage = getString(R.string.note_updated); - exitCroutonStyle = ONStyle.CONFIRM; - goBack = true; - saveNote(mOnNoteSaved); - } - } - - /** - * Save new notes, modify them or archive - */ - void saveNote(OnNoteSaved mOnNoteSaved) { - - // Changed fields - noteTmp.setTitle(getNoteTitle()); - noteTmp.setContent(getNoteContent()); - - // Check if some text or attachments of any type have been inserted or is an empty note - if (goBack && TextUtils.isEmpty(noteTmp.getTitle()) && TextUtils.isEmpty(noteTmp.getContent()) - && noteTmp.getAttachmentsList().size() == 0) { - LogDelegate.d("Empty note not saved"); - exitMessage = getString(R.string.empty_note_not_saved); - exitCroutonStyle = ONStyle.INFO; - goHome(); - return; - } - - if (saveNotNeeded()) { - exitMessage = ""; - if (goBack) { - goHome(); - } - return; - } - - noteTmp.setAttachmentsListOld(note.getAttachmentsList()); - - new SaveNoteTask(mOnNoteSaved, lastModificationUpdatedNeeded()).executeOnExecutor(AsyncTask - .THREAD_POOL_EXECUTOR, noteTmp); - } - - /** - * Checks if nothing is changed to avoid committing if possible (check) - */ - private boolean saveNotNeeded() { - if (noteTmp.get_id() == null && prefs.getBoolean(Constants.PREF_AUTO_LOCATION, false)) { - note.setLatitude(noteTmp.getLatitude()); - note.setLongitude(noteTmp.getLongitude()); - } - return !noteTmp.isChanged(note) || (noteTmp.isLocked() && !noteTmp.isPasswordChecked()); - } - - /** - * Checks if only tag, archive or trash status have been changed - * and then force to not update last modification date* - */ - private boolean lastModificationUpdatedNeeded() { - note.setCategory(noteTmp.getCategory()); - note.setArchived(noteTmp.isArchived()); - note.setTrashed(noteTmp.isTrashed()); - note.setLocked(noteTmp.isLocked()); - return noteTmp.isChanged(note); - } - - @Override - public void onNoteSaved(Note noteSaved) { - MainActivity.notifyAppWidgets(OmniNotes.getAppContext()); - if (!activityPausing) { - EventBus.getDefault().post(new NotesUpdatedEvent(Collections.singletonList(noteSaved))); - deleteMergedNotes(mergedNotesIds); - if (noteTmp.getAlarm() != null && !noteTmp.getAlarm().equals(note.getAlarm())) { - ReminderHelper.showReminderMessage(String.valueOf(noteTmp.getAlarm())); - } - } - note = new Note(noteSaved); - if (goBack) { - goHome(); - } - } - - private void deleteMergedNotes(List mergedNotesIds) { - ArrayList notesToDelete = new ArrayList<>(); - if (mergedNotesIds != null) { - for (String mergedNoteId : mergedNotesIds) { - Note note = new Note(); - note.set_id(Long.valueOf(mergedNoteId)); - notesToDelete.add(note); - } - new NoteProcessorDelete(notesToDelete).process(); - } - } - - private String getNoteTitle() { - if (title != null && !TextUtils.isEmpty(title.getText())) { - return title.getText().toString(); - } else { - return ""; - } - } - - private String getNoteContent() { - String contentText = ""; - if (!noteTmp.isChecklist()) { - // Due to checklist library introduction the returned EditText class is no more a - // com.neopixl.pixlui.components.edittext.EditText but a standard android.widget.EditText - View contentView = root.findViewById(R.id.detail_content); - if (contentView instanceof EditText) { - contentText = ((EditText) contentView).getText().toString(); - } else if (contentView instanceof android.widget.EditText) { - contentText = ((android.widget.EditText) contentView).getText().toString(); - } - } else { - if (mChecklistManager != null) { - mChecklistManager.keepChecked(true).showCheckMarks(true); - contentText = mChecklistManager.getText(); - } - } - return contentText; - } - - /** - * Updates share intent - */ - private void shareNote() { - Note sharedNote = new Note(noteTmp); - sharedNote.setTitle(getNoteTitle()); - sharedNote.setContent(getNoteContent()); - mainActivity.shareNote(sharedNote); - } - - /** - * Notes locking with security password to avoid viewing, editing or deleting from unauthorized - */ - private void lockNote() { - LogDelegate.d("Locking or unlocking note " + note.get_id()); - - // If security password is not set yes will be set right now - if (prefs.getString(Constants.PREF_PASSWORD, null) == null) { - Intent passwordIntent = new Intent(mainActivity, PasswordActivity.class); - startActivityForResult(passwordIntent, SET_PASSWORD); - return; - } - - // If password has already been inserted will not be asked again - if (noteTmp.isPasswordChecked() || prefs.getBoolean("settings_password_access", false)) { - lockUnlock(); - return; - } - - // Password will be requested here - PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { - switch (passwordConfirmed) { - case SUCCEED: - lockUnlock(); - break; - default: - break; - } - }); - } - - private void lockUnlock() { - // Empty password has been set - if (prefs.getString(Constants.PREF_PASSWORD, null) == null) { - mainActivity.showMessage(R.string.password_not_set, ONStyle.WARN); - return; - } - mainActivity.showMessage(R.string.save_note_to_lock_it, ONStyle.INFO); - mainActivity.supportInvalidateOptionsMenu(); - noteTmp.setLocked(!noteTmp.isLocked()); - noteTmp.setPasswordChecked(true); - } - - /** - * Used to set actual reminder state when initializing a note to be edited - */ - private String initReminder(Note note) { - if (noteTmp.getAlarm() == null) { - return ""; - } - long reminder = parseLong(note.getAlarm()); - String rrule = note.getRecurrenceRule(); - if (!TextUtils.isEmpty(rrule)) { - return DateHelper.getNoteRecurrentReminderText(reminder, rrule); - } else { - return DateHelper.getNoteReminderText(reminder); - } - } - - /** - * Audio recordings playback - */ - private void playback(View v, Uri uri) { - // Some recording is playing right now - if (mPlayer != null && mPlayer.isPlaying()) { - if (isPlayingView != v) { - // If the audio actually played is NOT the one from the click view the last one is played - stopPlaying(); - isPlayingView = v; - startPlaying(uri); - replacePlayingAudioBitmap(v); - } else { - // Otherwise just stops playing - stopPlaying(); - } - } else { - // If nothing is playing audio just plays - isPlayingView = v; - startPlaying(uri); - replacePlayingAudioBitmap(v); - } - } - - private void replacePlayingAudioBitmap(View v) { - Drawable d = ((ImageView) v.findViewById(R.id.gridview_item_picture)).getDrawable(); - if (BitmapDrawable.class.isAssignableFrom(d.getClass())) { - recordingBitmap = ((BitmapDrawable) d).getBitmap(); - } else { - recordingBitmap = ((BitmapDrawable) d.getCurrent()).getBitmap(); - } - ((ImageView) v.findViewById(R.id.gridview_item_picture)).setImageBitmap(ThumbnailUtils - .extractThumbnail(BitmapFactory.decodeResource(mainActivity.getResources(), - R.drawable.stop), Constants.THUMBNAIL_SIZE, Constants.THUMBNAIL_SIZE)); - } - - private void startPlaying(Uri uri) { - if (mPlayer == null) { - mPlayer = new MediaPlayer(); - } - try { - mPlayer.setDataSource(mainActivity, uri); - mPlayer.prepare(); - mPlayer.start(); - mPlayer.setOnCompletionListener(mp -> { - mPlayer = null; - if (isPlayingView != null) { - ((ImageView) isPlayingView.findViewById(R.id.gridview_item_picture)).setImageBitmap - (recordingBitmap); - recordingBitmap = null; - isPlayingView = null; - } - }); - } catch (IOException e) { - LogDelegate.e("prepare() failed", e); - mainActivity.showMessage(R.string.error, ONStyle.ALERT); - } - } - - private void stopPlaying() { - if (mPlayer != null) { - if (isPlayingView != null) { - ((ImageView) isPlayingView.findViewById(R.id.gridview_item_picture)).setImageBitmap(recordingBitmap); - } - isPlayingView = null; - recordingBitmap = null; - mPlayer.release(); - mPlayer = null; - } - } - - private void startRecording(View v) { - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.RECORD_AUDIO, - R.string.permission_audio_recording, snackBarPlaceholder, () -> { - - isRecording = true; - toggleAudioRecordingStop(v); - - File f = StorageHelper.createNewAttachmentFile(mainActivity, Constants.MIME_TYPE_AUDIO_EXT); - if (f == null) { - mainActivity.showMessage(R.string.error, ONStyle.ALERT); - return; - } - if (mRecorder == null) { - mRecorder = new MediaRecorder(); - mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); - mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); - mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); - mRecorder.setAudioEncodingBitRate(96000); - mRecorder.setAudioSamplingRate(44100); - } - recordName = f.getAbsolutePath(); - mRecorder.setOutputFile(recordName); - - try { - audioRecordingTimeStart = Calendar.getInstance().getTimeInMillis(); - mRecorder.prepare(); - mRecorder.start(); - } catch (IOException | IllegalStateException e) { - LogDelegate.e("prepare() failed", e); - mainActivity.showMessage(R.string.error, ONStyle.ALERT); - } - }); - } - - private void toggleAudioRecordingStop(View v) { - if (isRecording) { - ((android.widget.TextView) v).setText(getString(R.string.stop)); - ((android.widget.TextView) v).setTextColor(Color.parseColor("#ff0000")); - } - } - - private void stopRecording() { - isRecording = false; - if (mRecorder != null) { - mRecorder.stop(); - audioRecordingTime = Calendar.getInstance().getTimeInMillis() - audioRecordingTimeStart; - mRecorder.release(); - mRecorder = null; - } - } - - private void fade(final View v, boolean fadeIn) { - - int anim = R.animator.fade_out_support; - int visibilityTemp = View.GONE; - - if (fadeIn) { - anim = R.animator.fade_in_support; - visibilityTemp = View.VISIBLE; - } - - final int visibility = visibilityTemp; - - // Checks if user has left the app - if (mainActivity != null) { - Animation mAnimation = AnimationUtils.loadAnimation(mainActivity, anim); - mAnimation.setAnimationListener(new AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - // Nothing to do - } - - @Override - public void onAnimationRepeat(Animation animation) { - // Nothing to do - } - - @Override - public void onAnimationEnd(Animation animation) { - v.setVisibility(visibility); - } - }); - v.startAnimation(mAnimation); - } - } - - /** - * Adding shortcut on Home screen - */ - private void addShortcut() { - ShortcutHelper.addShortcut(OmniNotes.getAppContext(), noteTmp); - mainActivity.showMessage(R.string.shortcut_added, ONStyle.INFO); - } - - @SuppressLint("NewApi") - @Override - public boolean onTouch(View v, MotionEvent event) { - int x = (int) event.getX(); - int y = (int) event.getY(); - - switch (event.getAction()) { - - case MotionEvent.ACTION_DOWN: - LogDelegate.v("MotionEvent.ACTION_DOWN"); - int w; - - Point displaySize = Display.getUsableSize(mainActivity); - w = displaySize.x; - - if (x < Constants.SWIPE_MARGIN || x > w - Constants.SWIPE_MARGIN) { - swiping = true; - startSwipeX = x; - } - - break; - - case MotionEvent.ACTION_UP: - LogDelegate.v("MotionEvent.ACTION_UP"); - if (swiping) - swiping = false; - break; - - case MotionEvent.ACTION_MOVE: - if (swiping) { - LogDelegate.v("MotionEvent.ACTION_MOVE at position " + x + ", " + y); - if (Math.abs(x - startSwipeX) > Constants.SWIPE_OFFSET) { - swiping = false; - FragmentTransaction transaction = mainActivity.getSupportFragmentManager().beginTransaction(); - mainActivity.animateTransition(transaction, mainActivity.TRANSITION_VERTICAL); - DetailFragment mDetailFragment = new DetailFragment(); - Bundle b = new Bundle(); - b.putParcelable(Constants.INTENT_NOTE, new Note()); - mDetailFragment.setArguments(b); - transaction.replace(R.id.fragment_container, mDetailFragment, - mainActivity.FRAGMENT_DETAIL_TAG).addToBackStack(mainActivity - .FRAGMENT_DETAIL_TAG).commit(); - } - } - break; - - default: - LogDelegate.e("Wrong element choosen: " + event.getAction()); - } - - return true; - } - - @Override - public void onAttachingFileErrorOccurred(Attachment mAttachment) { - mainActivity.showMessage(R.string.error_saving_attachments, ONStyle.ALERT); - if (noteTmp.getAttachmentsList().contains(mAttachment)) { - removeAttachment(mAttachment); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - } - } - - private void addAttachment(Attachment attachment) { - noteTmp.addAttachment(attachment); - } - - private void removeAttachment(Attachment mAttachment) { - noteTmp.removeAttachment(mAttachment); - } - - private void removeAttachment(int position) { - noteTmp.removeAttachment(noteTmp.getAttachmentsList().get(position)); - } - - private void removeAllAttachments() { - noteTmp.setAttachmentsList(new ArrayList<>()); - mAttachmentAdapter = new AttachmentAdapter(mainActivity, new ArrayList<>(), mGridView); - mGridView.invalidateViews(); - mGridView.setAdapter(mAttachmentAdapter); - } - - @Override - public void onAttachingFileFinished(Attachment mAttachment) { - addAttachment(mAttachment); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - } - - @Override - public void onReminderPicked(long reminder) { - noteTmp.setAlarm(reminder); - if (mFragment.isAdded()) { - reminderIcon.setImageResource(R.drawable.ic_alarm_black_18dp); - datetime.setText(DateHelper.getNoteReminderText(reminder)); - } - } - - @Override - public void onRecurrenceReminderPicked(String recurrenceRule) { - noteTmp.setRecurrenceRule(recurrenceRule); - if (!TextUtils.isEmpty(recurrenceRule)) { - LogDelegate.d("Recurrent reminder set: " + recurrenceRule); - datetime.setText(DateHelper.getNoteRecurrentReminderText(Long.parseLong(noteTmp.getAlarm()), recurrenceRule)); - } - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - scrollContent(); - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // Nothing to do - } - - @Override - public void afterTextChanged(Editable s) { - // Nothing to do - } - - @Override - public void onCheckListChanged() { - scrollContent(); - } - - private void scrollContent() { - if (noteTmp.isChecklist()) { - if (mChecklistManager.getCount() > contentLineCounter) { - scrollView.scrollBy(0, 60); - } - contentLineCounter = mChecklistManager.getCount(); - } else { - if (content.getLineCount() > contentLineCounter) { - scrollView.scrollBy(0, 60); - } - contentLineCounter = content.getLineCount(); - } - } - - /** - * Add previously created tags to content - */ - private void addTags() { - contentCursorPosition = getCursorIndex(); - - // Retrieves all available categories - final List tags = TagsHelper.getAllTags(); - - // If there is no tag a message will be shown - if (tags.size() == 0) { - mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN); - return; - } - - final Note currentNote = new Note(); - currentNote.setTitle(getNoteTitle()); - currentNote.setContent(getNoteContent()); - Integer[] preselectedTags = TagsHelper.getPreselectedTagsArray(currentNote, tags); - - // Dialog and events creation - MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) - .title(R.string.select_tags) - .positiveText(R.string.ok) - .items(TagsHelper.getTagsArray(tags)) - .itemsCallbackMultiChoice(preselectedTags, (dialog1, which, text) -> { - dialog1.dismiss(); - tagNote(tags, which, currentNote); - return false; - }).build(); - dialog.show(); - } - - private void tagNote(List tags, Integer[] selectedTags, Note note) { - Pair> taggingResult = TagsHelper.addTagToNote(tags, selectedTags, note); - - StringBuilder sb; - if (noteTmp.isChecklist()) { - CheckListViewItem mCheckListViewItem = mChecklistManager.getFocusedItemView(); - if (mCheckListViewItem != null) { - sb = new StringBuilder(mCheckListViewItem.getText()); - sb.insert(contentCursorPosition, " " + taggingResult.first + " "); - mCheckListViewItem.setText(sb.toString()); - mCheckListViewItem.getEditText().setSelection(contentCursorPosition + taggingResult.first.length() - + 1); - } else { - title.append(" " + taggingResult.first); - } - } else { - sb = new StringBuilder(getNoteContent()); - if (content.hasFocus()) { - sb.insert(contentCursorPosition, " " + taggingResult.first + " "); - content.setText(sb.toString()); - content.setSelection(contentCursorPosition + taggingResult.first.length() + 1); - } else { - if (getNoteContent().trim().length() > 0) { - sb.append(System.getProperty("line.separator")) - .append(System.getProperty("line.separator")); - } - sb.append(taggingResult.first); - content.setText(sb.toString()); - } - } - - // Removes unchecked tags - if (taggingResult.second.size() > 0) { - if (noteTmp.isChecklist()) { - toggleChecklist2(true, true); - } - Pair titleAndContent = TagsHelper.removeTag(getNoteTitle(), getNoteContent(), - taggingResult.second); - title.setText(titleAndContent.first); - content.setText(titleAndContent.second); - if (noteTmp.isChecklist()) { - toggleChecklist2(); - } - } - } - - private int getCursorIndex() { - if (!noteTmp.isChecklist()) { - return content.getSelectionStart(); - } else { - CheckListViewItem mCheckListViewItem = mChecklistManager.getFocusedItemView(); - if (mCheckListViewItem != null) { - return mCheckListViewItem.getEditText().getSelectionStart(); - } else { - return 0; - } - } - } - - /** - * Used to check currently opened note from activity to avoid openind multiple times the same one - */ - public Note getCurrentNote() { - return note; - } - - private boolean isNoteLocationValid() { - return noteTmp.getLatitude() != null - && noteTmp.getLatitude() != 0 - && noteTmp.getLongitude() != null - && noteTmp.getLongitude() != 0; - } - - public void startGetContentAction() { - Intent filesIntent; - filesIntent = new Intent(Intent.ACTION_GET_CONTENT); - filesIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); - filesIntent.addCategory(Intent.CATEGORY_OPENABLE); - filesIntent.setType("*/*"); - startActivityForResult(filesIntent, FILES); - } - - private void askReadExternalStoragePermission() { - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE, - R.string.permission_external_storage_detail_attachment, - snackBarPlaceholder, this::startGetContentAction); - } - - public void onEventMainThread(PushbulletReplyEvent pushbulletReplyEvent) { - String text = getNoteContent() + System.getProperty("line.separator") + pushbulletReplyEvent.message; - content.setText(text); - } - - private static class OnGeoUtilResultListenerImpl implements OnGeoUtilResultListener { - - private final WeakReference mainActivityWeakReference; - private final WeakReference detailFragmentWeakReference; - private final WeakReference noteTmpWeakReference; - - OnGeoUtilResultListenerImpl(MainActivity activity, DetailFragment mFragment, Note noteTmp) { - mainActivityWeakReference = new WeakReference<>(activity); - detailFragmentWeakReference = new WeakReference<>(mFragment); - noteTmpWeakReference = new WeakReference<>(noteTmp); - } - - @Override - public void onAddressResolved(String address) { - } - - @Override - public void onCoordinatesResolved(Location location, String address) { - } - - @Override - public void onLocationUnavailable() { - mainActivityWeakReference.get().showMessage(R.string.location_not_found, ONStyle.ALERT); - } - - @Override - public void onLocationRetrieved(Location location) { - - if (!checkWeakReferences()) { - return; - } - - if (location == null) { - return; - } - if (!ConnectionManager.internetAvailable(mainActivityWeakReference.get())) { - noteTmpWeakReference.get().setLatitude(location.getLatitude()); - noteTmpWeakReference.get().setLongitude(location.getLongitude()); - onAddressResolved(""); - return; - } - LayoutInflater inflater = mainActivityWeakReference.get().getLayoutInflater(); - View v = inflater.inflate(R.layout.dialog_location, null); - final AutoCompleteTextView autoCompView = (AutoCompleteTextView) v.findViewById(R.id - .auto_complete_location); - autoCompView.setHint(mainActivityWeakReference.get().getString(R.string.search_location)); - autoCompView.setAdapter(new PlacesAutoCompleteAdapter(mainActivityWeakReference.get(), R.layout - .simple_text_layout)); - final MaterialDialog dialog = new MaterialDialog.Builder(mainActivityWeakReference.get()) - .customView(autoCompView, false) - .positiveText(R.string.use_current_location) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - if (TextUtils.isEmpty(autoCompView.getText().toString())) { - noteTmpWeakReference.get().setLatitude(location.getLatitude()); - noteTmpWeakReference.get().setLongitude(location.getLongitude()); - GeocodeHelper.getAddressFromCoordinates(location, detailFragmentWeakReference.get()); - } else { - GeocodeHelper.getCoordinatesFromAddress(autoCompView.getText().toString(), - detailFragmentWeakReference.get()); - } - } - }) - .build(); - autoCompView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (s.length() != 0) { - dialog.setActionButton(DialogAction.POSITIVE, mainActivityWeakReference.get().getString(R - .string.confirm)); - } else { - dialog.setActionButton(DialogAction.POSITIVE, mainActivityWeakReference.get().getString(R - .string - .use_current_location)); - } - } - - @Override - public void afterTextChanged(Editable s) { - } - }); - dialog.show(); - } - - private boolean checkWeakReferences() { - return mainActivityWeakReference.get() != null && !mainActivityWeakReference.get().isFinishing() - && detailFragmentWeakReference.get() != null && noteTmpWeakReference.get() != null; - } - } - - /** - * Manages clicks on attachment dialog - */ - @SuppressLint("InlinedApi") - private class AttachmentOnClickListener implements OnClickListener { - - @Override - public void onClick(View v) { - - switch (v.getId()) { - // Photo from camera - case R.id.camera: - takePhoto(); - break; - case R.id.recording: - if (!isRecording) { - startRecording(v); - } else { - stopRecording(); - Attachment attachment = new Attachment(Uri.fromFile(new File(recordName)), Constants - .MIME_TYPE_AUDIO); - attachment.setLength(audioRecordingTime); - addAttachment(attachment); - mAttachmentAdapter.notifyDataSetChanged(); - mGridView.autoresize(); - } - break; - case R.id.video: - takeVideo(); - break; - case R.id.files: - if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == - PackageManager.PERMISSION_GRANTED) { - startGetContentAction(); - } else { - askReadExternalStoragePermission(); - } - break; - case R.id.sketch: - takeSketch(null); - break; - case R.id.location: - displayLocationDialog(); - break; - case R.id.timestamp: - addTimestamp(); - break; - case R.id.pushbullet: - MessagingExtension.mirrorMessage(mainActivity, getString(R.string.app_name), - getString(R.string.pushbullet), - getNoteContent(), BitmapFactory.decodeResource(getResources(), - R.drawable.ic_stat_literal_icon), - null, 0); - break; - default: - LogDelegate.e("Wrong element choosen: " + v.getId()); - } - if (!isRecording) attachmentDialog.dismiss(); - } - } + }) + .build(); + autoCompView.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged (CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged (CharSequence s, int start, int before, int count) { + if (s.length() != 0) { + dialog.setActionButton(DialogAction.POSITIVE, mainActivityWeakReference.get().getString(R + .string.confirm)); + } else { + dialog.setActionButton(DialogAction.POSITIVE, mainActivityWeakReference.get().getString(R + .string + .use_current_location)); + } + } + + @Override + public void afterTextChanged (Editable s) { + } + }); + dialog.show(); + } + + private boolean checkWeakReferences () { + return mainActivityWeakReference.get() != null && !mainActivityWeakReference.get().isFinishing() + && detailFragmentWeakReference.get() != null && noteTmpWeakReference.get() != null; + } + } + + /** + * Manages clicks on attachment dialog + */ + @SuppressLint("InlinedApi") + private class AttachmentOnClickListener implements OnClickListener { + + @Override + public void onClick (View v) { + + switch (v.getId()) { + // Photo from camera + case R.id.camera: + takePhoto(); + break; + case R.id.recording: + if (!isRecording) { + startRecording(v); + } else { + stopRecording(); + Attachment attachment = new Attachment(Uri.fromFile(new File(recordName)), Constants + .MIME_TYPE_AUDIO); + attachment.setLength(audioRecordingTime); + addAttachment(attachment); + mAttachmentAdapter.notifyDataSetChanged(); + mGridView.autoresize(); + } + break; + case R.id.video: + takeVideo(); + break; + case R.id.files: + if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == + PackageManager.PERMISSION_GRANTED) { + startGetContentAction(); + } else { + askReadExternalStoragePermission(); + } + break; + case R.id.sketch: + takeSketch(null); + break; + case R.id.location: + displayLocationDialog(); + break; + case R.id.timestamp: + addTimestamp(); + break; + case R.id.pushbullet: + MessagingExtension.mirrorMessage(mainActivity, getString(R.string.app_name), + getString(R.string.pushbullet), + getNoteContent(), BitmapFactory.decodeResource(getResources(), + R.drawable.ic_stat_literal_icon), + null, 0); + break; + default: + LogDelegate.e("Wrong element choosen: " + v.getId()); + } + if (!isRecording) { + attachmentDialog.dismiss(); + } + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/FontSizeListPreference.java b/omniNotes/src/main/java/it/feio/android/omninotes/FontSizeListPreference.java index 9f6f257e1c..34f5fd75ba 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/FontSizeListPreference.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/FontSizeListPreference.java @@ -28,68 +28,67 @@ import android.widget.ArrayAdapter; import android.widget.CheckedTextView; import android.widget.TextView; - import it.feio.android.checklistview.utils.DensityUtil; import it.feio.android.omninotes.utils.Fonts; public class FontSizeListPreference extends ListPreference { - private int clickedDialogEntryIndex; + private int clickedDialogEntryIndex; - public FontSizeListPreference(Context context, AttributeSet attrs) { - super(context, attrs); - } + public FontSizeListPreference (Context context, AttributeSet attrs) { + super(context, attrs); + } - @Override - protected void onBindView(View view) { - super.onBindView(view); - TextView summary = (TextView) view.findViewById(android.R.id.summary); - Fonts.overrideTextSize(getContext(),getSharedPreferences(),summary); - } + @Override + protected void onBindView (View view) { + super.onBindView(view); + TextView summary = view.findViewById(android.R.id.summary); + Fonts.overrideTextSize(getContext(), getSharedPreferences(), summary); + } - @Override - protected void onPrepareDialogBuilder(AlertDialog.Builder builder) { + @Override + protected void onPrepareDialogBuilder (AlertDialog.Builder builder) { - ArrayAdapter adapter = new ArrayAdapter(getContext(), - R.layout.settings_font_size_dialog_item, getEntries()) { - @NonNull - @Override - public View getView(int position, View convertView, @NonNull ViewGroup parent) { - CheckedTextView view = (CheckedTextView) convertView; - if (view == null) { - view = (CheckedTextView) View.inflate(getContext(), - R.layout.settings_font_size_dialog_item, null); - } - view.setText(getEntries()[position]); - Context privateContext = getContext().getApplicationContext(); - float currentSize = DensityUtil.pxToDp(((TextView) View.inflate(getContext(), - R.layout.settings_font_size_dialog_item, null)).getTextSize(), privateContext); - float offset = privateContext.getResources().getIntArray( - R.array.text_size_offset)[position]; - view.setTextSize(currentSize + offset); - return view; - } - }; - clickedDialogEntryIndex = findIndexOfValue(getValue()); - builder.setSingleChoiceItems(adapter, clickedDialogEntryIndex, - (dialog, which) -> { - clickedDialogEntryIndex = which; - FontSizeListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE); - dialog.dismiss(); - }); - builder.setPositiveButton(null, null); - } + ArrayAdapter adapter = new ArrayAdapter(getContext(), + R.layout.settings_font_size_dialog_item, getEntries()) { + @NonNull + @Override + public View getView (int position, View convertView, @NonNull ViewGroup parent) { + CheckedTextView view = (CheckedTextView) convertView; + if (view == null) { + view = (CheckedTextView) View.inflate(getContext(), + R.layout.settings_font_size_dialog_item, null); + } + view.setText(getEntries()[position]); + Context privateContext = getContext().getApplicationContext(); + float currentSize = DensityUtil.pxToDp(((TextView) View.inflate(getContext(), + R.layout.settings_font_size_dialog_item, null)).getTextSize(), privateContext); + float offset = privateContext.getResources().getIntArray( + R.array.text_size_offset)[position]; + view.setTextSize(currentSize + offset); + return view; + } + }; + clickedDialogEntryIndex = findIndexOfValue(getValue()); + builder.setSingleChoiceItems(adapter, clickedDialogEntryIndex, + (dialog, which) -> { + clickedDialogEntryIndex = which; + FontSizeListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE); + dialog.dismiss(); + }); + builder.setPositiveButton(null, null); + } - @Override - protected void onDialogClosed(boolean positiveResult) { - super.onDialogClosed(positiveResult); + @Override + protected void onDialogClosed (boolean positiveResult) { + super.onDialogClosed(positiveResult); - if (positiveResult && clickedDialogEntryIndex >= 0 && getEntryValues() != null) { - String val = getEntryValues()[clickedDialogEntryIndex].toString(); - if (callChangeListener(val)) { - setValue(val); - } - } + if (positiveResult && clickedDialogEntryIndex >= 0 && getEntryValues() != null) { + String val = getEntryValues()[clickedDialogEntryIndex].toString(); + if (callChangeListener(val)) { + setValue(val); + } } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/GalleryActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/GalleryActivity.java index 846c881dc0..f50132f87d 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/GalleryActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/GalleryActivity.java @@ -26,10 +26,6 @@ import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; - -import java.util.ArrayList; -import java.util.List; - import butterknife.BindView; import butterknife.ButterKnife; import it.feio.android.omninotes.helpers.LogDelegate; @@ -41,184 +37,188 @@ import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.simplegallery.models.GalleryPagerAdapter; import it.feio.android.simplegallery.views.GalleryViewPager; +import java.util.ArrayList; +import java.util.List; /** - * An example full-screen activity that shows and hides the system UI (i.e. status bar and navigation/system bar) - * * with user interaction. + * An example full-screen activity that shows and hides the system UI (i.e. status bar and navigation/system bar) * with + * user interaction. */ public class GalleryActivity extends AppCompatActivity { - /** - * Whether or not the system UI should be auto-hidden after {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. - */ - private static final boolean AUTO_HIDE = false; - - /** - * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after user interaction before hiding the - * * system UI. - */ - private static final int AUTO_HIDE_DELAY_MILLIS = 3000; - - /** - * If set, will toggle the system UI visibility upon interaction. Otherwise, will show the system UI visibility - * * upon interaction. - */ - private static final boolean TOGGLE_ON_CLICK = true; - - @BindView(R.id.gallery_root) InterceptorFrameLayout galleryRootView; - @BindView(R.id.fullscreen_content) GalleryViewPager mViewPager; - - private List images; - OnViewTouchedListener screenTouches = new OnViewTouchedListener() { - private final int MOVING_THRESHOLD = 30; - float x; - float y; - private boolean status_pressed = false; - - - @Override - public void onViewTouchOccurred(MotionEvent ev) { - if ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { - x = ev.getX(); - y = ev.getY(); - status_pressed = true; - } - if ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE) { - float dx = Math.abs(x - ev.getX()); - float dy = Math.abs(y - ev.getY()); - double dxy = Math.sqrt(dx * dx + dy * dy); - LogDelegate.d("Moved of " + dxy); - if (dxy >= MOVING_THRESHOLD) { - status_pressed = false; - } - } - if ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { - if (status_pressed) { - click(); - status_pressed = false; - } - } - } + /** + * Whether or not the system UI should be auto-hidden after {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. + */ + private static final boolean AUTO_HIDE = false; + /** + * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after user interaction before hiding the * system + * UI. + */ + private static final int AUTO_HIDE_DELAY_MILLIS = 3000; - private void click() { - Attachment attachment = images.get(mViewPager.getCurrentItem()); - if (attachment.getMime_type().equals(Constants.MIME_TYPE_VIDEO)) { - viewMedia(); - } - } - }; + /** + * If set, will toggle the system UI visibility upon interaction. Otherwise, will show the system UI visibility * upon + * interaction. + */ + private static final boolean TOGGLE_ON_CLICK = true; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_gallery); - ButterKnife.bind(this); + @BindView(R.id.gallery_root) + InterceptorFrameLayout galleryRootView; + @BindView(R.id.fullscreen_content) + GalleryViewPager mViewPager; - initViews(); - initData(); - } + private List images; + OnViewTouchedListener screenTouches = new OnViewTouchedListener() { + private final int MOVING_THRESHOLD = 30; + float x; + float y; + private boolean status_pressed = false; - @Override - public void onStart() { - ((OmniNotes)getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); - super.onStart(); - } @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.menu_gallery, menu); - return true; - } - - private void initViews() { - // Show the Up button in the action bar. - if (getSupportActionBar() != null) { - getSupportActionBar().setDisplayShowTitleEnabled(true); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); + public void onViewTouchOccurred (MotionEvent ev) { + if ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { + x = ev.getX(); + y = ev.getY(); + status_pressed = true; + } + if ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE) { + float dx = Math.abs(x - ev.getX()); + float dy = Math.abs(y - ev.getY()); + double dxy = Math.sqrt(dx * dx + dy * dy); + LogDelegate.d("Moved of " + dxy); + if (dxy >= MOVING_THRESHOLD) { + status_pressed = false; + } + } + if ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { + if (status_pressed) { + click(); + status_pressed = false; } + } + } - galleryRootView.setOnViewTouchedListener(screenTouches); - mViewPager.addOnPageChangeListener(new OnPageChangeListener() { - @Override - public void onPageSelected(int arg0) { - getSupportActionBar().setSubtitle("(" + (arg0 + 1) + "/" + images.size() + ")"); - } + private void click () { + Attachment attachment = images.get(mViewPager.getCurrentItem()); + if (attachment.getMime_type().equals(Constants.MIME_TYPE_VIDEO)) { + viewMedia(); + } + } + }; + + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gallery); + ButterKnife.bind(this); + + initViews(); + initData(); + } + + @Override + public void onStart () { + ((OmniNotes) getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); + super.onStart(); + } + + @Override + public boolean onCreateOptionsMenu (Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.menu_gallery, menu); + return true; + } + + private void initViews () { + // Show the Up button in the action bar. + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayShowTitleEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + galleryRootView.setOnViewTouchedListener(screenTouches); - @Override - public void onPageScrolled(int arg0, float arg1, int arg2) { - } + mViewPager.addOnPageChangeListener(new OnPageChangeListener() { + @Override + public void onPageSelected (int arg0) { + getSupportActionBar().setSubtitle("(" + (arg0 + 1) + "/" + images.size() + ")"); + } - @Override - public void onPageScrollStateChanged(int arg0) { - } - }); - } + @Override + public void onPageScrolled (int arg0, float arg1, int arg2) { + } - /** - * Initializes data received from note detail screen - */ - private void initData() { - String title = getIntent().getStringExtra(Constants.GALLERY_TITLE); - images = getIntent().getParcelableArrayListExtra(Constants.GALLERY_IMAGES); - int clickedImage = getIntent().getIntExtra(Constants.GALLERY_CLICKED_IMAGE, 0); - - ArrayList imageUris = new ArrayList<>(); - for (Attachment mAttachment : images) { - imageUris.add(mAttachment.getUri()); - } - GalleryPagerAdapter pagerAdapter = new GalleryPagerAdapter(this, imageUris); - mViewPager.setOffscreenPageLimit(3); - mViewPager.setAdapter(pagerAdapter); - mViewPager.setCurrentItem(clickedImage); + @Override + public void onPageScrollStateChanged (int arg0) { + } + }); + } - getSupportActionBar().setTitle(title); - getSupportActionBar().setSubtitle("(" + (clickedImage + 1) + "/" + images.size() + ")"); + /** + * Initializes data received from note detail screen + */ + private void initData () { + String title = getIntent().getStringExtra(Constants.GALLERY_TITLE); + images = getIntent().getParcelableArrayListExtra(Constants.GALLERY_IMAGES); + int clickedImage = getIntent().getIntExtra(Constants.GALLERY_CLICKED_IMAGE, 0); - // If selected attachment is a video it will be immediately played - if (images.get(clickedImage).getMime_type().equals(Constants.MIME_TYPE_VIDEO)) { - viewMedia(); - } + ArrayList imageUris = new ArrayList<>(); + for (Attachment mAttachment : images) { + imageUris.add(mAttachment.getUri()); } - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - onBackPressed(); - break; - case R.id.menu_gallery_share: - shareMedia(); - break; - case R.id.menu_gallery: - viewMedia(); - break; - default: - LogDelegate.e("Wrong element choosen: " + item.getItemId()); - } - return super.onOptionsItemSelected(item); - } + GalleryPagerAdapter pagerAdapter = new GalleryPagerAdapter(this, imageUris); + mViewPager.setOffscreenPageLimit(3); + mViewPager.setAdapter(pagerAdapter); + mViewPager.setCurrentItem(clickedImage); - private void viewMedia() { - Attachment attachment = images.get(mViewPager.getCurrentItem()); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - intent.setDataAndType(FileProviderHelper.getShareableUri(attachment), - StorageHelper.getMimeType(this, attachment.getUri())); - startActivity(intent); - } + getSupportActionBar().setTitle(title); + getSupportActionBar().setSubtitle("(" + (clickedImage + 1) + "/" + images.size() + ")"); - private void shareMedia() { - Attachment attachment = images.get(mViewPager.getCurrentItem()); - Intent intent = new Intent(Intent.ACTION_SEND); - intent.setType(StorageHelper.getMimeType(this, attachment.getUri())); - intent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment)); - startActivity(intent); + // If selected attachment is a video it will be immediately played + if (images.get(clickedImage).getMime_type().equals(Constants.MIME_TYPE_VIDEO)) { + viewMedia(); + } + } + + @Override + public boolean onOptionsItemSelected (MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + break; + case R.id.menu_gallery_share: + shareMedia(); + break; + case R.id.menu_gallery: + viewMedia(); + break; + default: + LogDelegate.e("Wrong element choosen: " + item.getItemId()); } + return super.onOptionsItemSelected(item); + } + + private void viewMedia () { + Attachment attachment = images.get(mViewPager.getCurrentItem()); + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + intent.setDataAndType(FileProviderHelper.getShareableUri(attachment), + StorageHelper.getMimeType(this, attachment.getUri())); + startActivity(intent); + } + + private void shareMedia () { + Attachment attachment = images.get(mViewPager.getCurrentItem()); + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType(StorageHelper.getMimeType(this, attachment.getUri())); + intent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment)); + startActivity(intent); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/ListFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/ListFragment.java index b68a6c95bf..3d753bf452 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/ListFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/ListFragment.java @@ -16,6 +16,8 @@ */ package it.feio.android.omninotes; +import static android.support.v4.view.ViewCompat.animate; + import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; @@ -53,25 +55,13 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; - +import butterknife.BindView; +import butterknife.ButterKnife; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.neopixl.pixlui.components.textview.TextView; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView; import com.pnikosis.materialishprogress.ProgressWheel; - -import org.apache.commons.lang.ObjectUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - -import butterknife.BindView; -import butterknife.ButterKnife; import de.greenrobot.event.EventBus; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; @@ -111,1498 +101,1533 @@ import it.feio.android.omninotes.utils.TextHelper; import it.feio.android.pixlui.links.UrlCompleter; import it.feio.android.simplegallery.util.BitmapUtils; - -import static android.support.v4.view.ViewCompat.animate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import org.apache.commons.lang.ObjectUtils; public class ListFragment extends BaseFragment implements OnViewTouchedListener, UndoBarController.UndoListener { - private static final int REQUEST_CODE_CATEGORY = 1; - private static final int REQUEST_CODE_CATEGORY_NOTES = 2; - private static final int REQUEST_CODE_ADD_ALARMS = 3; - - @BindView(R.id.list_root) InterceptorLinearLayout listRoot; - @BindView(R.id.list) DynamicListView list; - @BindView(R.id.search_layout) View searchLayout; - @BindView(R.id.search_query) android.widget.TextView searchQueryView; - @BindView(R.id.search_cancel) ImageView searchCancel; - @BindView(R.id.empty_list) TextView empyListItem; - @BindView(R.id.expanded_image) ImageView expandedImageView; - @BindView(R.id.fab) View fabView; - @BindView(R.id.undobar) View undoBarView; - @BindView(R.id.progress_wheel) ProgressWheel progress_wheel; - @BindView(R.id.snackbar_placeholder) View snackBarPlaceholder; - - NoteViewHolder noteViewHolder; - - private List selectedNotes = new ArrayList<>(); - private SearchView searchView; - private MenuItem searchMenuItem; - private Menu menu; - private AnimationDrawable jinglesAnimation; - private int listViewPosition; - private int listViewPositionOffset = 16; - private boolean sendToArchive; - private SharedPreferences prefs; - private ListFragment mFragment; - private android.support.v7.view.ActionMode actionMode; - private boolean keepActionMode = false; - - // Undo archive/trash - private boolean undoTrash = false; - private boolean undoArchive = false; - private boolean undoCategorize = false; - private Category undoCategorizeCategory = null; - private SortedMap undoNotesMap = new TreeMap<>(); - // Used to remember removed categories from notes - private Map undoCategoryMap = new HashMap<>(); - // Used to remember archived state from notes - private Map undoArchivedMap = new HashMap<>(); - - // Search variables - private String searchQuery; - private String searchQueryInstant; - private String searchTags; - private boolean searchUncompleteChecklists; - private boolean goBackOnToggleSearchLabel = false; - private boolean searchLabelActive = false; - - private NoteAdapter listAdapter; - private UndoBarController ubc; - private Fab fab; - private MainActivity mainActivity; + private static final int REQUEST_CODE_CATEGORY = 1; + private static final int REQUEST_CODE_CATEGORY_NOTES = 2; + private static final int REQUEST_CODE_ADD_ALARMS = 3; + + @BindView(R.id.list_root) + InterceptorLinearLayout listRoot; + @BindView(R.id.list) + DynamicListView list; + @BindView(R.id.search_layout) + View searchLayout; + @BindView(R.id.search_query) + android.widget.TextView searchQueryView; + @BindView(R.id.search_cancel) + ImageView searchCancel; + @BindView(R.id.empty_list) + TextView empyListItem; + @BindView(R.id.expanded_image) + ImageView expandedImageView; + @BindView(R.id.fab) + View fabView; + @BindView(R.id.undobar) + View undoBarView; + @BindView(R.id.progress_wheel) + ProgressWheel progress_wheel; + @BindView(R.id.snackbar_placeholder) + View snackBarPlaceholder; + + NoteViewHolder noteViewHolder; + + private List selectedNotes = new ArrayList<>(); + private SearchView searchView; + private MenuItem searchMenuItem; + private Menu menu; + private AnimationDrawable jinglesAnimation; + private int listViewPosition; + private int listViewPositionOffset = 16; + private boolean sendToArchive; + private SharedPreferences prefs; + private ListFragment mFragment; + private android.support.v7.view.ActionMode actionMode; + private boolean keepActionMode = false; + + // Undo archive/trash + private boolean undoTrash = false; + private boolean undoArchive = false; + private boolean undoCategorize = false; + private Category undoCategorizeCategory = null; + private SortedMap undoNotesMap = new TreeMap<>(); + // Used to remember removed categories from notes + private Map undoCategoryMap = new HashMap<>(); + // Used to remember archived state from notes + private Map undoArchivedMap = new HashMap<>(); + + // Search variables + private String searchQuery; + private String searchQueryInstant; + private String searchTags; + private boolean searchUncompleteChecklists; + private boolean goBackOnToggleSearchLabel = false; + private boolean searchLabelActive = false; + + private NoteAdapter listAdapter; + private UndoBarController ubc; + private Fab fab; + private MainActivity mainActivity; + + + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mFragment = this; + setHasOptionsMenu(true); + setRetainInstance(false); + EventBus.getDefault().register(this, 1); + } + + + @Override + public void onDestroy () { + super.onDestroy(); + EventBus.getDefault().unregister(this); + } + + + @Override + public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + if (savedInstanceState != null) { + if (savedInstanceState.containsKey("listViewPosition")) { + listViewPosition = savedInstanceState.getInt("listViewPosition"); + listViewPositionOffset = savedInstanceState.getInt("listViewPositionOffset"); + searchQuery = savedInstanceState.getString("searchQuery"); + searchTags = savedInstanceState.getString("searchTags"); + } + keepActionMode = false; + } + View view = inflater.inflate(R.layout.fragment_list, container, false); + ButterKnife.bind(this, view); + return view; + } + + + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + mainActivity = (MainActivity) getActivity(); + prefs = mainActivity.prefs; + if (savedInstanceState != null) { + mainActivity.navigationTmp = savedInstanceState.getString("navigationTmp"); + } + init(); + } + + + private void init () { + initEasterEgg(); + initListView(); + ubc = new UndoBarController(undoBarView, this); + + initNotesList(mainActivity.getIntent()); + initFab(); + initTitle(); + + // Restores again DefaultSharedPreferences too reload in case of data erased from Settings + prefs = mainActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + } + + + private void initFab () { + fab = new Fab(fabView, list, prefs.getBoolean(Constants.PREF_FAB_EXPANSION_BEHAVIOR, false)); + fab.setOnFabItemClickedListener(id -> { + View v = mainActivity.findViewById(id); + switch (id) { + case R.id.fab_expand_menu_button: + editNote(new Note(), v); + break; + case R.id.fab_note: + editNote(new Note(), v); + break; + case R.id.fab_camera: + Intent i = mainActivity.getIntent(); + i.setAction(Constants.ACTION_FAB_TAKE_PHOTO); + mainActivity.setIntent(i); + editNote(new Note(), v); + break; + case R.id.fab_checklist: + Note note = new Note(); + note.setChecklist(true); + editNote(note, v); + break; + } + }); + } + + + boolean closeFab () { + if (fab != null && fab.isExpanded()) { + fab.performToggle(); + return true; + } + return false; + } + + + /** + * Activity title initialization based on navigation + */ + private void initTitle () { + String[] navigationList = getResources().getStringArray(R.array.navigation_list); + String[] navigationListCodes = getResources().getStringArray(R.array.navigation_list_codes); + String navigation = mainActivity.navigationTmp != null ? mainActivity.navigationTmp : prefs.getString + (Constants.PREF_NAVIGATION, navigationListCodes[0]); + int index = Arrays.asList(navigationListCodes).indexOf(navigation); + String title; + // If is a traditional navigation item + if (index >= 0 && index < navigationListCodes.length) { + title = navigationList[index]; + } else { + Category category = DbHelper.getInstance().getCategory(Long.parseLong(navigation)); + title = category != null ? category.getName() : ""; + } + title = title == null ? getString(R.string.title_activity_list) : title; + mainActivity.setActionBarTitle(title); + } + + + /** + * Starts a little animation on Mr.Jingles! + */ + private void initEasterEgg () { + empyListItem.setOnClickListener(v -> { + if (jinglesAnimation == null) { + jinglesAnimation = (AnimationDrawable) empyListItem.getCompoundDrawables()[1]; + empyListItem.post(() -> { + if (jinglesAnimation != null) { + jinglesAnimation.start(); + } + }); + } else { + stopJingles(); + } + }); + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mFragment = this; - setHasOptionsMenu(true); - setRetainInstance(false); - EventBus.getDefault().register(this, 1); - } + private void stopJingles () { + if (jinglesAnimation != null) { + jinglesAnimation.stop(); + jinglesAnimation = null; + empyListItem.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.jingles_animation, 0, 0); - - @Override - public void onDestroy() { - super.onDestroy(); - EventBus.getDefault().unregister(this); } + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - if (savedInstanceState != null) { - if (savedInstanceState.containsKey("listViewPosition")) { - listViewPosition = savedInstanceState.getInt("listViewPosition"); - listViewPositionOffset = savedInstanceState.getInt("listViewPositionOffset"); - searchQuery = savedInstanceState.getString("searchQuery"); - searchTags = savedInstanceState.getString("searchTags"); - } - keepActionMode = false; - } - View view = inflater.inflate(R.layout.fragment_list, container, false); - ButterKnife.bind(this, view); - return view; + @Override + public void onPause () { + super.onPause(); + searchQueryInstant = searchQuery; + stopJingles(); + Crouton.cancelAllCroutons(); + closeFab(); + if (!keepActionMode) { + commitPending(); + list.clearChoices(); + if (getActionMode() != null) { + getActionMode().finish(); + } } + } - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - mainActivity = (MainActivity) getActivity(); - prefs = mainActivity.prefs; - if (savedInstanceState != null) { - mainActivity.navigationTmp = savedInstanceState.getString("navigationTmp"); - } - init(); - } - - - private void init() { - initEasterEgg(); - initListView(); - ubc = new UndoBarController(undoBarView, this); - - initNotesList(mainActivity.getIntent()); - initFab(); - initTitle(); - - // Restores again DefaultSharedPreferences too reload in case of data erased from Settings - prefs = mainActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - } - - - private void initFab() { - fab = new Fab(fabView, list, prefs.getBoolean(Constants.PREF_FAB_EXPANSION_BEHAVIOR, false)); - fab.setOnFabItemClickedListener(id -> { - View v = mainActivity.findViewById(id); - switch (id) { - case R.id.fab_expand_menu_button: - editNote(new Note(), v); - break; - case R.id.fab_note: - editNote(new Note(), v); - break; - case R.id.fab_camera: - Intent i = mainActivity.getIntent(); - i.setAction(Constants.ACTION_FAB_TAKE_PHOTO); - mainActivity.setIntent(i); - editNote(new Note(), v); - break; - case R.id.fab_checklist: - Note note = new Note(); - note.setChecklist(true); - editNote(note, v); - break; - } - }); - } - - - boolean closeFab() { - if (fab != null && fab.isExpanded()) { - fab.performToggle(); - return true; - } - return false; - } + @Override + public void onSaveInstanceState (Bundle outState) { + super.onSaveInstanceState(outState); + refreshListScrollPosition(); + outState.putInt("listViewPosition", listViewPosition); + outState.putInt("listViewPositionOffset", listViewPositionOffset); + outState.putString("searchQuery", searchQuery); + outState.putString("searchTags", searchTags); + } - /** - * Activity title initialization based on navigation - */ - private void initTitle() { - String[] navigationList = getResources().getStringArray(R.array.navigation_list); - String[] navigationListCodes = getResources().getStringArray(R.array.navigation_list_codes); - String navigation = mainActivity.navigationTmp != null ? mainActivity.navigationTmp : prefs.getString - (Constants.PREF_NAVIGATION, navigationListCodes[0]); - int index = Arrays.asList(navigationListCodes).indexOf(navigation); - String title; - // If is a traditional navigation item - if (index >= 0 && index < navigationListCodes.length) { - title = navigationList[index]; - } else { - Category category = DbHelper.getInstance().getCategory(Long.parseLong(navigation)); - title = category != null ? category.getName() : ""; - } - title = title == null ? getString(R.string.title_activity_list) : title; - mainActivity.setActionBarTitle(title); + private void refreshListScrollPosition () { + if (list != null) { + listViewPosition = list.getFirstVisiblePosition(); + View v = list.getChildAt(0); + listViewPositionOffset = (v == null) ? (int) getResources().getDimension(R.dimen.vertical_margin) : v.getTop(); } + } - /** - * Starts a little animation on Mr.Jingles! - */ - private void initEasterEgg() { - empyListItem.setOnClickListener(v -> { - if (jinglesAnimation == null) { - jinglesAnimation = (AnimationDrawable) empyListItem.getCompoundDrawables()[1]; - empyListItem.post(() -> { - if (jinglesAnimation != null) jinglesAnimation.start(); - }); - } else { - stopJingles(); - } - }); + @SuppressWarnings("static-access") + @Override + public void onResume () { + super.onResume(); + if (mainActivity.prefsChanged) { + mainActivity.prefsChanged = false; + init(); + } else if (Intent.ACTION_SEARCH.equals(mainActivity.getIntent().getAction())) { + initNotesList(mainActivity.getIntent()); } + } - private void stopJingles() { - if (jinglesAnimation != null) { - jinglesAnimation.stop(); - jinglesAnimation = null; - empyListItem.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.jingles_animation, 0, 0); + private final class ModeCallback implements android.support.v7.view.ActionMode.Callback { - } + @Override + public boolean onCreateActionMode (ActionMode mode, Menu menu) { + // Inflate the menu for the CAB + MenuInflater inflater = mode.getMenuInflater(); + inflater.inflate(R.menu.menu_list, menu); + actionMode = mode; + fab.setAllowed(isFabAllowed()); + fab.hideFab(); + return true; } @Override - public void onPause() { - super.onPause(); - searchQueryInstant = searchQuery; - stopJingles(); - Crouton.cancelAllCroutons(); - closeFab(); - if (!keepActionMode) { - commitPending(); - list.clearChoices(); - if (getActionMode() != null) { - getActionMode().finish(); - } + public void onDestroyActionMode (ActionMode mode) { + // Here you can make any necessary updates to the activity when + // the CAB is removed. By default, selected items are + // deselected/unchecked. + for (int i = 0; i < listAdapter.getSelectedItems().size(); i++) { + int key = listAdapter.getSelectedItems().keyAt(i); + View v = list.getChildAt(key - list.getFirstVisiblePosition()); + if (listAdapter.getCount() > key && listAdapter.getItem(key) != null && v != null) { + listAdapter.restoreDrawable(listAdapter.getItem(key), v.findViewById(R.id.card_layout)); } - } + } + // Clears data structures + selectedNotes.clear(); + listAdapter.clearSelectedItems(); + list.clearChoices(); - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - refreshListScrollPosition(); - outState.putInt("listViewPosition", listViewPosition); - outState.putInt("listViewPositionOffset", listViewPositionOffset); - outState.putString("searchQuery", searchQuery); - outState.putString("searchTags", searchTags); - } - + fab.setAllowed(isFabAllowed(true)); + if (undoNotesMap.size() == 0) { + fab.showFab(); + } - private void refreshListScrollPosition() { - if (list != null) { - listViewPosition = list.getFirstVisiblePosition(); - View v = list.getChildAt(0); - listViewPositionOffset = (v == null) ? (int) getResources().getDimension(R.dimen.vertical_margin) : v.getTop(); - } + actionMode = null; + LogDelegate.d("Closed multiselection contextual menu"); } - @SuppressWarnings("static-access") @Override - public void onResume() { - super.onResume(); - if (mainActivity.prefsChanged) { - mainActivity.prefsChanged = false; - init(); - } else if (Intent.ACTION_SEARCH.equals(mainActivity.getIntent().getAction())) { - initNotesList(mainActivity.getIntent()); - } + public boolean onPrepareActionMode (ActionMode mode, Menu menu) { + prepareActionModeMenu(); + return true; } - private final class ModeCallback implements android.support.v7.view.ActionMode.Callback { - - @Override - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - // Inflate the menu for the CAB - MenuInflater inflater = mode.getMenuInflater(); - inflater.inflate(R.menu.menu_list, menu); - actionMode = mode; - fab.setAllowed(isFabAllowed()); - fab.hideFab(); - return true; - } - - - @Override - public void onDestroyActionMode(ActionMode mode) { - // Here you can make any necessary updates to the activity when - // the CAB is removed. By default, selected items are - // deselected/unchecked. - for (int i = 0; i < listAdapter.getSelectedItems().size(); i++) { - int key = listAdapter.getSelectedItems().keyAt(i); - View v = list.getChildAt(key - list.getFirstVisiblePosition()); - if (listAdapter.getCount() > key && listAdapter.getItem(key) != null && v != null) { - listAdapter.restoreDrawable(listAdapter.getItem(key), v.findViewById(R.id.card_layout)); - } - } - - // Clears data structures - selectedNotes.clear(); - listAdapter.clearSelectedItems(); - list.clearChoices(); - - fab.setAllowed(isFabAllowed(true)); - if (undoNotesMap.size() == 0) { - fab.showFab(); - } - - actionMode = null; - LogDelegate.d("Closed multiselection contextual menu"); - } - - - @Override - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - prepareActionModeMenu(); - return true; - } - - - @Override - public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { - Integer[] protectedActions = {R.id.menu_select_all, R.id.menu_merge}; - if (!Arrays.asList(protectedActions).contains(item.getItemId())) { - mainActivity.requestPassword(mainActivity, getSelectedNotes(), - passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { - performAction(item, mode); - } - }); - } else { + @Override + public boolean onActionItemClicked (final ActionMode mode, final MenuItem item) { + Integer[] protectedActions = {R.id.menu_select_all, R.id.menu_merge}; + if (!Arrays.asList(protectedActions).contains(item.getItemId())) { + mainActivity.requestPassword(mainActivity, getSelectedNotes(), + passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { performAction(item, mode); - } - return true; - } + } + }); + } else { + performAction(item, mode); + } + return true; } + } - public void finishActionMode() { - if (getActionMode() != null) { - getActionMode().finish(); - } + public void finishActionMode () { + if (getActionMode() != null) { + getActionMode().finish(); } + } - /** - * Manage check/uncheck of notes in list during multiple selection phase - */ - private void toggleListViewItem(View view, int position) { - Note note = listAdapter.getItem(position); - LinearLayout cardLayout = (LinearLayout) view.findViewById(R.id.card_layout); - if (!getSelectedNotes().contains(note)) { - getSelectedNotes().add(note); - listAdapter.addSelectedItem(position); - cardLayout.setBackgroundColor(getResources().getColor(R.color.list_bg_selected)); - } else { - getSelectedNotes().remove(note); - listAdapter.removeSelectedItem(position); - listAdapter.restoreDrawable(note, cardLayout); - } - prepareActionModeMenu(); - - // Close CAB if no items are selected - if (getSelectedNotes().size() == 0) { - finishActionMode(); - } - + /** + * Manage check/uncheck of notes in list during multiple selection phase + */ + private void toggleListViewItem (View view, int position) { + Note note = listAdapter.getItem(position); + LinearLayout cardLayout = view.findViewById(R.id.card_layout); + if (!getSelectedNotes().contains(note)) { + getSelectedNotes().add(note); + listAdapter.addSelectedItem(position); + cardLayout.setBackgroundColor(getResources().getColor(R.color.list_bg_selected)); + } else { + getSelectedNotes().remove(note); + listAdapter.removeSelectedItem(position); + listAdapter.restoreDrawable(note, cardLayout); } + prepareActionModeMenu(); - - /** - * Notes list initialization. Data, actions and callback are defined here. - */ - private void initListView() { - list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); - list.setItemsCanFocus(false); - - // Note long click to start CAB mode - list.setOnItemLongClickListener((arg0, view, position, arg3) -> { - if (getActionMode() != null) { - return false; - } - // Start the CAB using the ActionMode.Callback defined above - mainActivity.startSupportActionMode(new ModeCallback()); - toggleListViewItem(view, position); - setCabTitle(); - return true; - }); - - // Note single click listener managed by the activity itself - list.setOnItemClickListener((arg0, view, position, arg3) -> { - if (getActionMode() == null) { - editNote(listAdapter.getItem(position), view); - return; - } - // If in CAB mode - toggleListViewItem(view, position); - setCabTitle(); - }); - - listRoot.setOnViewTouchedListener(this); + // Close CAB if no items are selected + if (getSelectedNotes().size() == 0) { + finishActionMode(); } + } - /** - * Retrieves from the single listview note item the element to be zoomed when opening a note - */ - private ImageView getZoomListItemView(View view, Note note) { - if (expandedImageView != null) { - View targetView = null; - if (note.getAttachmentsList().size() > 0) { - targetView = view.findViewById(R.id.attachmentThumbnail); - } - if (targetView == null && note.getCategory() != null) { - targetView = view.findViewById(R.id.category_marker); - } - if (targetView == null) { - targetView = new ImageView(mainActivity); - targetView.setBackgroundColor(Color.WHITE); - } - targetView.setDrawingCacheEnabled(true); - targetView.buildDrawingCache(); - Bitmap bmp = targetView.getDrawingCache(); - expandedImageView.setBackgroundColor(BitmapUtils.getDominantColor(bmp)); - } - return expandedImageView; - } + /** + * Notes list initialization. Data, actions and callback are defined here. + */ + private void initListView () { + list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + list.setItemsCanFocus(false); - /** - * Listener that fires note opening once the zooming animation is finished - */ - private AnimatorListenerAdapter buildAnimatorListenerAdapter(final Note note) { - return new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - editNote2(note); - } - }; - } - - - @Override - public void onViewTouchOccurred(MotionEvent ev) { - LogDelegate.v("Notes list: onViewTouchOccurred " + ev.getAction()); - commitPending(); - } - - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_list, menu); - super.onCreateOptionsMenu(menu, inflater); - this.menu = menu; - initSearchView(menu); - } + // Note long click to start CAB mode + list.setOnItemLongClickListener((arg0, view, position, arg3) -> { + if (getActionMode() != null) { + return false; + } + // Start the CAB using the ActionMode.Callback defined above + mainActivity.startSupportActionMode(new ModeCallback()); + toggleListViewItem(view, position); + setCabTitle(); + return true; + }); + + // Note single click listener managed by the activity itself + list.setOnItemClickListener((arg0, view, position, arg3) -> { + if (getActionMode() == null) { + editNote(listAdapter.getItem(position), view); + return; + } + // If in CAB mode + toggleListViewItem(view, position); + setCabTitle(); + }); + + listRoot.setOnViewTouchedListener(this); + } + + + /** + * Retrieves from the single listview note item the element to be zoomed when opening a note + */ + private ImageView getZoomListItemView (View view, Note note) { + if (expandedImageView != null) { + View targetView = null; + if (note.getAttachmentsList().size() > 0) { + targetView = view.findViewById(R.id.attachmentThumbnail); + } + if (targetView == null && note.getCategory() != null) { + targetView = view.findViewById(R.id.category_marker); + } + if (targetView == null) { + targetView = new ImageView(mainActivity); + targetView.setBackgroundColor(Color.WHITE); + } + targetView.setDrawingCacheEnabled(true); + targetView.buildDrawingCache(); + Bitmap bmp = targetView.getDrawingCache(); + expandedImageView.setBackgroundColor(BitmapUtils.getDominantColor(bmp)); + } + return expandedImageView; + } + + + /** + * Listener that fires note opening once the zooming animation is finished + */ + private AnimatorListenerAdapter buildAnimatorListenerAdapter (final Note note) { + return new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd (Animator animation) { + editNote2(note); + } + }; + } + + + @Override + public void onViewTouchOccurred (MotionEvent ev) { + LogDelegate.v("Notes list: onViewTouchOccurred " + ev.getAction()); + commitPending(); + } + + + @Override + public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) { + inflater.inflate(R.menu.menu_list, menu); + super.onCreateOptionsMenu(menu, inflater); + this.menu = menu; + initSearchView(menu); + } + + + private void initSortingSubmenu () { + final String[] arrayDb = getResources().getStringArray(R.array.sortable_columns); + final String[] arrayDialog = getResources().getStringArray(R.array.sortable_columns_human_readable); + int selected = Arrays.asList(arrayDb).indexOf(prefs.getString(Constants.PREF_SORTING_COLUMN, arrayDb[0])); + + SubMenu sortMenu = this.menu.findItem(R.id.menu_sort).getSubMenu(); + for (int i = 0; i < arrayDialog.length; i++) { + if (sortMenu.findItem(i) == null) { + sortMenu.add(Constants.MENU_SORT_GROUP_ID, i, i, arrayDialog[i]); + } + if (i == selected) { + sortMenu.getItem(i).setChecked(true); + } + } + sortMenu.setGroupCheckable(Constants.MENU_SORT_GROUP_ID, true, true); + } + + + @Override + public void onPrepareOptionsMenu (Menu menu) { + setActionItemsVisibility(menu, false); + } + + + private void prepareActionModeMenu () { + Menu menu = getActionMode().getMenu(); + int navigation = Navigation.getNavigation(); + boolean showArchive = navigation == Navigation.NOTES || navigation == Navigation.REMINDERS || navigation == + Navigation.UNCATEGORIZED || navigation == Navigation.CATEGORY; + boolean showUnarchive = navigation == Navigation.ARCHIVE || navigation == Navigation.UNCATEGORIZED || + navigation == Navigation.CATEGORY; + + if (navigation == Navigation.TRASH) { + menu.findItem(R.id.menu_untrash).setVisible(true); + menu.findItem(R.id.menu_delete).setVisible(true); + } else { + if (getSelectedCount() == 1) { + menu.findItem(R.id.menu_share).setVisible(true); + menu.findItem(R.id.menu_merge).setVisible(false); + menu.findItem(R.id.menu_archive) + .setVisible(showArchive && !getSelectedNotes().get(0).isArchived + ()); + menu.findItem(R.id.menu_unarchive) + .setVisible(showUnarchive && getSelectedNotes().get(0).isArchived + ()); + } else { + menu.findItem(R.id.menu_share).setVisible(false); + menu.findItem(R.id.menu_merge).setVisible(true); + menu.findItem(R.id.menu_archive).setVisible(showArchive); + menu.findItem(R.id.menu_unarchive).setVisible(showUnarchive); + + } + menu.findItem(R.id.menu_add_reminder).setVisible(true); + menu.findItem(R.id.menu_category).setVisible(true); + menu.findItem(R.id.menu_uncomplete_checklists).setVisible(false); + menu.findItem(R.id.menu_tags).setVisible(true); + menu.findItem(R.id.menu_trash).setVisible(true); + } + menu.findItem(R.id.menu_select_all).setVisible(true); + + setCabTitle(); + } + + + private int getSelectedCount () { + return getSelectedNotes().size(); + } + + + private void setCabTitle () { + if (getActionMode() != null) { + int title = getSelectedCount(); + getActionMode().setTitle(String.valueOf(title)); + } + } + + + /** + * SearchView initialization. It's a little complex because it's not using SearchManager but is implementing on its + * own. + */ + @SuppressLint("NewApi") + private void initSearchView (final Menu menu) { + + // Prevents some mysterious NullPointer on app fast-switching + if (mainActivity == null) { + return; + } + + // Save item as class attribute to make it collapse on drawer opening + searchMenuItem = menu.findItem(R.id.menu_search); + + // Associate searchable configuration with the SearchView + SearchManager searchManager = (SearchManager) mainActivity.getSystemService(Context.SEARCH_SERVICE); + searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_search)); + searchView.setSearchableInfo(searchManager.getSearchableInfo(mainActivity.getComponentName())); + searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH); + // Expands the widget hiding other actionbar icons + searchView.setOnQueryTextFocusChangeListener((v, hasFocus) -> setActionItemsVisibility(menu, hasFocus)); + + MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() { + + boolean searchPerformed = false; + + + @Override + public boolean onMenuItemActionCollapse (MenuItem item) { + // Reinitialize notes list to all notes when search is collapsed + searchQuery = null; + if (searchLayout.getVisibility() == View.VISIBLE) { + toggleSearchLabel(false); + } + mainActivity.getIntent().setAction(Intent.ACTION_MAIN); + initNotesList(mainActivity.getIntent()); + mainActivity.supportInvalidateOptionsMenu(); + return true; + } - private void initSortingSubmenu() { - final String[] arrayDb = getResources().getStringArray(R.array.sortable_columns); - final String[] arrayDialog = getResources().getStringArray(R.array.sortable_columns_human_readable); - int selected = Arrays.asList(arrayDb).indexOf(prefs.getString(Constants.PREF_SORTING_COLUMN, arrayDb[0])); - SubMenu sortMenu = this.menu.findItem(R.id.menu_sort).getSubMenu(); - for (int i = 0; i < arrayDialog.length; i++) { - if (sortMenu.findItem(i) == null) { - sortMenu.add(Constants.MENU_SORT_GROUP_ID, i, i, arrayDialog[i]); - } - if (i == selected) sortMenu.getItem(i).setChecked(true); - } - sortMenu.setGroupCheckable(Constants.MENU_SORT_GROUP_ID, true, true); - } + @Override + public boolean onMenuItemActionExpand (MenuItem item) { + searchView.setOnQueryTextListener(new OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit (String arg0) { - @Override - public void onPrepareOptionsMenu(Menu menu) { - setActionItemsVisibility(menu, false); - } + return prefs.getBoolean("settings_instant_search", false); + } - private void prepareActionModeMenu() { - Menu menu = getActionMode().getMenu(); - int navigation = Navigation.getNavigation(); - boolean showArchive = navigation == Navigation.NOTES || navigation == Navigation.REMINDERS || navigation == - Navigation.UNCATEGORIZED || navigation == Navigation.CATEGORY; - boolean showUnarchive = navigation == Navigation.ARCHIVE || navigation == Navigation.UNCATEGORIZED || - navigation == Navigation.CATEGORY; + @Override + public boolean onQueryTextChange (String pattern) { - if (navigation == Navigation.TRASH) { - menu.findItem(R.id.menu_untrash).setVisible(true); - menu.findItem(R.id.menu_delete).setVisible(true); - } else { - if (getSelectedCount() == 1) { - menu.findItem(R.id.menu_share).setVisible(true); - menu.findItem(R.id.menu_merge).setVisible(false); - menu.findItem(R.id.menu_archive) - .setVisible(showArchive && !getSelectedNotes().get(0).isArchived - ()); - menu.findItem(R.id.menu_unarchive) - .setVisible(showUnarchive && getSelectedNotes().get(0).isArchived - ()); + if (prefs.getBoolean("settings_instant_search", false) && searchLayout != null && + searchPerformed && mFragment.isAdded()) { + searchTags = null; + searchQuery = pattern; + NoteLoaderTask.getInstance().execute("getNotesByPattern", pattern); + return true; } else { - menu.findItem(R.id.menu_share).setVisible(false); - menu.findItem(R.id.menu_merge).setVisible(true); - menu.findItem(R.id.menu_archive).setVisible(showArchive); - menu.findItem(R.id.menu_unarchive).setVisible(showUnarchive); - + searchPerformed = true; + return false; } - menu.findItem(R.id.menu_add_reminder).setVisible(true); - menu.findItem(R.id.menu_category).setVisible(true); - menu.findItem(R.id.menu_uncomplete_checklists).setVisible(false); - menu.findItem(R.id.menu_tags).setVisible(true); - menu.findItem(R.id.menu_trash).setVisible(true); - } - menu.findItem(R.id.menu_select_all).setVisible(true); - - setCabTitle(); - } - - - private int getSelectedCount() { - return getSelectedNotes().size(); - } - - - private void setCabTitle() { - if (getActionMode() != null) { - int title = getSelectedCount(); - getActionMode().setTitle(String.valueOf(title)); - } - } - - - /** - * SearchView initialization. It's a little complex because it's not using SearchManager but is implementing on its - * own. - */ - @SuppressLint("NewApi") - private void initSearchView(final Menu menu) { - - // Prevents some mysterious NullPointer on app fast-switching - if (mainActivity == null) return; - - // Save item as class attribute to make it collapse on drawer opening - searchMenuItem = menu.findItem(R.id.menu_search); - - // Associate searchable configuration with the SearchView - SearchManager searchManager = (SearchManager) mainActivity.getSystemService(Context.SEARCH_SERVICE); - searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.menu_search)); - searchView.setSearchableInfo(searchManager.getSearchableInfo(mainActivity.getComponentName())); - searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH); - - // Expands the widget hiding other actionbar icons - searchView.setOnQueryTextFocusChangeListener((v, hasFocus) -> setActionItemsVisibility(menu, hasFocus)); - - MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() { - - boolean searchPerformed = false; - - - @Override - public boolean onMenuItemActionCollapse(MenuItem item) { - // Reinitialize notes list to all notes when search is collapsed - searchQuery = null; - if (searchLayout.getVisibility() == View.VISIBLE) { - toggleSearchLabel(false); - } - mainActivity.getIntent().setAction(Intent.ACTION_MAIN); - initNotesList(mainActivity.getIntent()); - mainActivity.supportInvalidateOptionsMenu(); - return true; - } - - - @Override - public boolean onMenuItemActionExpand(MenuItem item) { - - searchView.setOnQueryTextListener(new OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String arg0) { - - return prefs.getBoolean("settings_instant_search", false); - } - - - @Override - public boolean onQueryTextChange(String pattern) { - - if (prefs.getBoolean("settings_instant_search", false) && searchLayout != null && - searchPerformed && mFragment.isAdded()) { - searchTags = null; - searchQuery = pattern; - NoteLoaderTask.getInstance().execute("getNotesByPattern", pattern); - return true; - } else { - searchPerformed = true; - return false; - } - } - }); - return true; - } - }); - } - - - private void setActionItemsVisibility(Menu menu, boolean searchViewHasFocus) { - - boolean drawerOpen = mainActivity.getDrawerLayout() != null && mainActivity.getDrawerLayout().isDrawerOpen - (GravityCompat.START); - boolean expandedView = prefs.getBoolean(Constants.PREF_EXPANDED_VIEW, true); - - int navigation = Navigation.getNavigation(); - boolean navigationReminders = navigation == Navigation.REMINDERS; - boolean navigationArchive = navigation == Navigation.ARCHIVE; - boolean navigationTrash = navigation == Navigation.TRASH; - boolean navigationCategory = navigation == Navigation.CATEGORY; - - boolean filterPastReminders = prefs.getBoolean(Constants.PREF_FILTER_PAST_REMINDERS, true); - boolean filterArchivedInCategory = navigationCategory && prefs.getBoolean(Constants - .PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory(), false); - - if (isFabAllowed()) { - fab.setAllowed(true); - fab.showFab(); - } else { - fab.setAllowed(false); - fab.hideFab(); - } - menu.findItem(R.id.menu_search).setVisible(!drawerOpen); - menu.findItem(R.id.menu_filter).setVisible(!drawerOpen && !filterPastReminders && navigationReminders && - !searchViewHasFocus); - menu.findItem(R.id.menu_filter_remove).setVisible(!drawerOpen && filterPastReminders && navigationReminders - && !searchViewHasFocus); - menu.findItem(R.id.menu_filter_category).setVisible(!drawerOpen && !filterArchivedInCategory && - navigationCategory && !searchViewHasFocus); - menu.findItem(R.id.menu_filter_category_remove).setVisible(!drawerOpen && filterArchivedInCategory && - navigationCategory && !searchViewHasFocus); - menu.findItem(R.id.menu_sort).setVisible(!drawerOpen && !navigationReminders && !searchViewHasFocus); - menu.findItem(R.id.menu_expanded_view).setVisible(!drawerOpen && !expandedView && !searchViewHasFocus); - menu.findItem(R.id.menu_contracted_view).setVisible(!drawerOpen && expandedView && !searchViewHasFocus); - menu.findItem(R.id.menu_empty_trash).setVisible(!drawerOpen && navigationTrash); - menu.findItem(R.id.menu_uncomplete_checklists).setVisible(searchViewHasFocus); - menu.findItem(R.id.menu_tags).setVisible(searchViewHasFocus); - } - - - @Override - public boolean onOptionsItemSelected(final MenuItem item) { - Integer[] protectedActions = {R.id.menu_empty_trash}; - if (Arrays.asList(protectedActions).contains(item.getItemId())) { - mainActivity.requestPassword(mainActivity, getSelectedNotes(), passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED) ) { - performAction(item, null); - } - }); - } else { - performAction(item, null); + } + }); + return true; + } + }); + } + + + private void setActionItemsVisibility (Menu menu, boolean searchViewHasFocus) { + + boolean drawerOpen = mainActivity.getDrawerLayout() != null && mainActivity.getDrawerLayout().isDrawerOpen + (GravityCompat.START); + boolean expandedView = prefs.getBoolean(Constants.PREF_EXPANDED_VIEW, true); + + int navigation = Navigation.getNavigation(); + boolean navigationReminders = navigation == Navigation.REMINDERS; + boolean navigationArchive = navigation == Navigation.ARCHIVE; + boolean navigationTrash = navigation == Navigation.TRASH; + boolean navigationCategory = navigation == Navigation.CATEGORY; + + boolean filterPastReminders = prefs.getBoolean(Constants.PREF_FILTER_PAST_REMINDERS, true); + boolean filterArchivedInCategory = navigationCategory && prefs.getBoolean(Constants + .PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory(), false); + + if (isFabAllowed()) { + fab.setAllowed(true); + fab.showFab(); + } else { + fab.setAllowed(false); + fab.hideFab(); + } + menu.findItem(R.id.menu_search).setVisible(!drawerOpen); + menu.findItem(R.id.menu_filter).setVisible(!drawerOpen && !filterPastReminders && navigationReminders && + !searchViewHasFocus); + menu.findItem(R.id.menu_filter_remove).setVisible(!drawerOpen && filterPastReminders && navigationReminders + && !searchViewHasFocus); + menu.findItem(R.id.menu_filter_category).setVisible(!drawerOpen && !filterArchivedInCategory && + navigationCategory && !searchViewHasFocus); + menu.findItem(R.id.menu_filter_category_remove).setVisible(!drawerOpen && filterArchivedInCategory && + navigationCategory && !searchViewHasFocus); + menu.findItem(R.id.menu_sort).setVisible(!drawerOpen && !navigationReminders && !searchViewHasFocus); + menu.findItem(R.id.menu_expanded_view).setVisible(!drawerOpen && !expandedView && !searchViewHasFocus); + menu.findItem(R.id.menu_contracted_view).setVisible(!drawerOpen && expandedView && !searchViewHasFocus); + menu.findItem(R.id.menu_empty_trash).setVisible(!drawerOpen && navigationTrash); + menu.findItem(R.id.menu_uncomplete_checklists).setVisible(searchViewHasFocus); + menu.findItem(R.id.menu_tags).setVisible(searchViewHasFocus); + } + + + @Override + public boolean onOptionsItemSelected (final MenuItem item) { + Integer[] protectedActions = {R.id.menu_empty_trash}; + if (Arrays.asList(protectedActions).contains(item.getItemId())) { + mainActivity.requestPassword(mainActivity, getSelectedNotes(), passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + performAction(item, null); } - return super.onOptionsItemSelected(item); - } - - - /** - * Performs one of the ActionBar button's actions after checked notes protection - */ - public void performAction(MenuItem item, ActionMode actionMode) { - - if (isOptionsItemFastClick()) return; - - if (actionMode == null) { - switch (item.getItemId()) { - case android.R.id.home: - if (mainActivity.getDrawerLayout().isDrawerOpen(GravityCompat.START)) { - mainActivity.getDrawerLayout().closeDrawer(GravityCompat.START); - } else { - mainActivity.getDrawerLayout().openDrawer(GravityCompat.START); - } - break; - case R.id.menu_filter: - filterReminders(true); - break; - case R.id.menu_filter_remove: - filterReminders(false); - break; - case R.id.menu_filter_category: - filterCategoryArchived(true); - break; - case R.id.menu_filter_category_remove: - filterCategoryArchived(false); - break; - case R.id.menu_uncomplete_checklists: - filterByUncompleteChecklists(); - break; - case R.id.menu_tags: - filterByTags(); - break; - case R.id.menu_sort: - initSortingSubmenu(); - break; - case R.id.menu_expanded_view: - switchNotesView(); - break; - case R.id.menu_contracted_view: - switchNotesView(); - break; - case R.id.menu_empty_trash: - emptyTrash(); - break; - default: - LogDelegate.e("Wrong element choosen: " + item.getItemId()); - } - } else { - switch (item.getItemId()) { - case R.id.menu_category: - categorizeNotes(); - break; - case R.id.menu_tags: - tagNotes(); - break; - case R.id.menu_share: - share(); - break; - case R.id.menu_merge: - merge(); - break; - case R.id.menu_archive: - archiveNotes(true); - break; - case R.id.menu_unarchive: - archiveNotes(false); - break; - case R.id.menu_trash: - trashNotes(true); - break; - case R.id.menu_untrash: - trashNotes(false); - break; - case R.id.menu_delete: - deleteNotes(); - break; - case R.id.menu_select_all: - selectAllNotes(); - break; - case R.id.menu_add_reminder: - addReminders(); - break; + }); + } else { + performAction(item, null); + } + return super.onOptionsItemSelected(item); + } + + + /** + * Performs one of the ActionBar button's actions after checked notes protection + */ + public void performAction (MenuItem item, ActionMode actionMode) { + + if (isOptionsItemFastClick()) { + return; + } + + if (actionMode == null) { + switch (item.getItemId()) { + case android.R.id.home: + if (mainActivity.getDrawerLayout().isDrawerOpen(GravityCompat.START)) { + mainActivity.getDrawerLayout().closeDrawer(GravityCompat.START); + } else { + mainActivity.getDrawerLayout().openDrawer(GravityCompat.START); + } + break; + case R.id.menu_filter: + filterReminders(true); + break; + case R.id.menu_filter_remove: + filterReminders(false); + break; + case R.id.menu_filter_category: + filterCategoryArchived(true); + break; + case R.id.menu_filter_category_remove: + filterCategoryArchived(false); + break; + case R.id.menu_uncomplete_checklists: + filterByUncompleteChecklists(); + break; + case R.id.menu_tags: + filterByTags(); + break; + case R.id.menu_sort: + initSortingSubmenu(); + break; + case R.id.menu_expanded_view: + switchNotesView(); + break; + case R.id.menu_contracted_view: + switchNotesView(); + break; + case R.id.menu_empty_trash: + emptyTrash(); + break; + default: + LogDelegate.e("Wrong element choosen: " + item.getItemId()); + } + } else { + switch (item.getItemId()) { + case R.id.menu_category: + categorizeNotes(); + break; + case R.id.menu_tags: + tagNotes(); + break; + case R.id.menu_share: + share(); + break; + case R.id.menu_merge: + merge(); + break; + case R.id.menu_archive: + archiveNotes(true); + break; + case R.id.menu_unarchive: + archiveNotes(false); + break; + case R.id.menu_trash: + trashNotes(true); + break; + case R.id.menu_untrash: + trashNotes(false); + break; + case R.id.menu_delete: + deleteNotes(); + break; + case R.id.menu_select_all: + selectAllNotes(); + break; + case R.id.menu_add_reminder: + addReminders(); + break; // case R.id.menu_synchronize: // synchronizeSelectedNotes(); // break; - default: - LogDelegate.e("Wrong element choosen: " + item.getItemId()); - } - } - - checkSortActionPerformed(item); + default: + LogDelegate.e("Wrong element choosen: " + item.getItemId()); + } } - - private void addReminders() { - Intent intent = new Intent(OmniNotes.getAppContext(), SnoozeActivity.class); - intent.setAction(Constants.ACTION_POSTPONE); - intent.putExtra(Constants.INTENT_NOTE, selectedNotes.toArray(new Note[selectedNotes.size()])); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivityForResult(intent, REQUEST_CODE_ADD_ALARMS); - } + checkSortActionPerformed(item); + } - private void switchNotesView() { - boolean expandedView = prefs.getBoolean(Constants.PREF_EXPANDED_VIEW, true); - prefs.edit().putBoolean(Constants.PREF_EXPANDED_VIEW, !expandedView).commit(); - // Change list view - initNotesList(mainActivity.getIntent()); - // Called to switch menu voices - mainActivity.supportInvalidateOptionsMenu(); - } + private void addReminders () { + Intent intent = new Intent(OmniNotes.getAppContext(), SnoozeActivity.class); + intent.setAction(Constants.ACTION_POSTPONE); + intent.putExtra(Constants.INTENT_NOTE, selectedNotes.toArray(new Note[selectedNotes.size()])); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivityForResult(intent, REQUEST_CODE_ADD_ALARMS); + } - void editNote(final Note note, final View view) { - if (note.isLocked() && !prefs.getBoolean("settings_password_access", false)) { - PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { - note.setPasswordChecked(true); - AnimationsHelper.zoomListItem(mainActivity, view, getZoomListItemView(view, note), - listRoot, buildAnimatorListenerAdapter(note)); - } - }); - } else { - AnimationsHelper.zoomListItem(mainActivity, view, getZoomListItemView(view, note), - listRoot, buildAnimatorListenerAdapter(note)); - } - } + private void switchNotesView () { + boolean expandedView = prefs.getBoolean(Constants.PREF_EXPANDED_VIEW, true); + prefs.edit().putBoolean(Constants.PREF_EXPANDED_VIEW, !expandedView).commit(); + // Change list view + initNotesList(mainActivity.getIntent()); + // Called to switch menu voices + mainActivity.supportInvalidateOptionsMenu(); + } - void editNote2(Note note) { - if (note.get_id() == null) { - LogDelegate.d("Adding new note"); - // if navigation is a category it will be set into note - try { - if (Navigation.checkNavigation(Navigation.CATEGORY) || !TextUtils.isEmpty(mainActivity.navigationTmp)) { - String categoryId = (String) ObjectUtils.defaultIfNull(mainActivity.navigationTmp, - Navigation.getCategory().toString()); - note.setCategory(DbHelper.getInstance().getCategory(Long.parseLong(categoryId))); - } - } catch (NumberFormatException e) { - LogDelegate.v("Maybe was not a category!"); - } - } else { - LogDelegate.d("Editing note with id: " + note.get_id()); + void editNote (final Note note, final View view) { + if (note.isLocked() && !prefs.getBoolean("settings_password_access", false)) { + PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + note.setPasswordChecked(true); + AnimationsHelper.zoomListItem(mainActivity, view, getZoomListItemView(view, note), + listRoot, buildAnimatorListenerAdapter(note)); } - - // Current list scrolling position is saved to be restored later - refreshListScrollPosition(); - - // Fragments replacing - mainActivity.switchToDetail(note); - } - - - @Override - public// Used to show a Crouton dialog after saved (or tried to) a note - void onActivityResult(int requestCode, final int resultCode, Intent intent) { - super.onActivityResult(requestCode, resultCode, intent); - switch (requestCode) { - case REQUEST_CODE_CATEGORY: - // Dialog retarded to give time to activity's views of being completely initialized - // The dialog style is choosen depending on result code - switch (resultCode) { - case Activity.RESULT_OK: - mainActivity.showMessage(R.string.category_saved, ONStyle.CONFIRM); - EventBus.getDefault().post(new CategoriesUpdatedEvent()); - break; - case Activity.RESULT_FIRST_USER: - mainActivity.showMessage(R.string.category_deleted, ONStyle.ALERT); - break; - default: - break; - } - - break; - - case REQUEST_CODE_CATEGORY_NOTES: - if (intent != null) { - Category tag = intent.getParcelableExtra(Constants.INTENT_CATEGORY); - categorizeNotesExecute(tag); - } - break; - - case REQUEST_CODE_ADD_ALARMS: - list.clearChoices(); - selectedNotes.clear(); - finishActionMode(); - list.invalidateViews(); - break; - - default: - break; + }); + } else { + AnimationsHelper.zoomListItem(mainActivity, view, getZoomListItemView(view, note), + listRoot, buildAnimatorListenerAdapter(note)); + } + } + + + void editNote2 (Note note) { + if (note.get_id() == null) { + LogDelegate.d("Adding new note"); + // if navigation is a category it will be set into note + try { + if (Navigation.checkNavigation(Navigation.CATEGORY) || !TextUtils.isEmpty(mainActivity.navigationTmp)) { + String categoryId = (String) ObjectUtils.defaultIfNull(mainActivity.navigationTmp, + Navigation.getCategory().toString()); + note.setCategory(DbHelper.getInstance().getCategory(Long.parseLong(categoryId))); } - - } - - - private void checkSortActionPerformed(MenuItem item) { - if (item.getGroupId() == Constants.MENU_SORT_GROUP_ID) { - final String[] arrayDb = getResources().getStringArray(R.array.sortable_columns); - prefs.edit().putString(Constants.PREF_SORTING_COLUMN, arrayDb[item.getOrder()]).apply(); - initNotesList(mainActivity.getIntent()); - // Resets list scrolling position - listViewPositionOffset = 16; - listViewPosition = 0; - restoreListScrollPosition(); - toggleSearchLabel(false); - // Updates app widgets - mainActivity.updateWidgets(); - } else { - ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackActionFromResourceId(getActivity(), - item.getItemId()); - } - } - - - /** - * Empties trash deleting all the notes - */ - private void emptyTrash() { - new MaterialDialog.Builder(mainActivity) - .content(R.string.empty_trash_confirmation) - .positiveText(R.string.ok) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick( - @NonNull MaterialDialog dialog, @NonNull DialogAction which) { - boolean mustDeleteLockedNotes = false; - for (int i = 0; i < listAdapter.getCount(); i++) { - selectedNotes.add(listAdapter.getItem(i)); - mustDeleteLockedNotes = mustDeleteLockedNotes || listAdapter.getItem(i).isLocked(); - } - if (mustDeleteLockedNotes) { - mainActivity.requestPassword(mainActivity, getSelectedNotes(), - passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED) ) { - deleteNotesExecute(); - } - }); - } else { - deleteNotesExecute(); - } - } - }).build().show(); - } - - - /** - * Notes list adapter initialization and association to view - * @FIXME: This method is a divine opprobrium and MUST be refactored. I'm ashamed by myself. - */ - void initNotesList(Intent intent) { - LogDelegate.d("initNotesList intent: " + intent.getAction()); - - progress_wheel.setAlpha(1); - list.setAlpha(0); - - // Search for a tag - // A workaround to simplify it's to simulate normal search - if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getCategories() != null - && intent.getCategories().contains(Intent.CATEGORY_BROWSABLE)) { - searchTags = intent.getDataString().replace(UrlCompleter.HASHTAG_SCHEME, ""); - goBackOnToggleSearchLabel = true; + } catch (NumberFormatException e) { + LogDelegate.v("Maybe was not a category!"); + } + } else { + LogDelegate.d("Editing note with id: " + note.get_id()); + } + + // Current list scrolling position is saved to be restored later + refreshListScrollPosition(); + + // Fragments replacing + mainActivity.switchToDetail(note); + } + + + @Override + public// Used to show a Crouton dialog after saved (or tried to) a note + void onActivityResult (int requestCode, final int resultCode, Intent intent) { + super.onActivityResult(requestCode, resultCode, intent); + switch (requestCode) { + case REQUEST_CODE_CATEGORY: + // Dialog retarded to give time to activity's views of being completely initialized + // The dialog style is choosen depending on result code + switch (resultCode) { + case Activity.RESULT_OK: + mainActivity.showMessage(R.string.category_saved, ONStyle.CONFIRM); + EventBus.getDefault().post(new CategoriesUpdatedEvent()); + break; + case Activity.RESULT_FIRST_USER: + mainActivity.showMessage(R.string.category_deleted, ONStyle.ALERT); + break; + default: + break; } - if (Constants.ACTION_SHORTCUT_WIDGET.equals(intent.getAction())) { - return; - } - - // Searching - searchQuery = searchQueryInstant; - searchQueryInstant = null; - if (searchTags != null || searchQuery != null || searchUncompleteChecklists - || IntentChecker.checkAction(intent, Intent.ACTION_SEARCH, Constants.ACTION_SEARCH_UNCOMPLETE_CHECKLISTS)) { - - // Using tags - if (searchTags != null && intent.getStringExtra(SearchManager.QUERY) == null) { - searchQuery = searchTags; - NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByTag", - searchQuery); - } else if (searchUncompleteChecklists || Constants.ACTION_SEARCH_UNCOMPLETE_CHECKLISTS.equals(intent.getAction())) { - searchQuery = getContext().getResources().getString(R.string.uncompleted_checklists); - searchUncompleteChecklists = true; - NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByUncompleteChecklist"); - } else { - // Get the intent, verify the action and get the query - if (intent.getStringExtra(SearchManager.QUERY) != null) { - searchQuery = intent.getStringExtra(SearchManager.QUERY); - searchTags = null; - } - NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByPattern", - searchQuery); - } - - toggleSearchLabel(true); - - } else { - // Check if is launched from a widget with categories - if ((Constants.ACTION_WIDGET_SHOW_LIST.equals(intent.getAction()) && intent - .hasExtra(Constants.INTENT_WIDGET)) - || !TextUtils.isEmpty(mainActivity.navigationTmp)) { - String widgetId = intent.hasExtra(Constants.INTENT_WIDGET) ? intent.getExtras() - .get(Constants.INTENT_WIDGET).toString() : null; - if (widgetId != null) { - String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, ""); - String categoryId = TextHelper.checkIntentCategory(sqlCondition); - mainActivity.navigationTmp = !TextUtils.isEmpty(categoryId) ? categoryId : null; - } - intent.removeExtra(Constants.INTENT_WIDGET); - if (mainActivity.navigationTmp != null) { - Long categoryId = Long.parseLong(mainActivity.navigationTmp); - NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, - "getNotesByCategory", categoryId); - } else { - NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true); - } + break; - } else { - NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true); - } + case REQUEST_CODE_CATEGORY_NOTES: + if (intent != null) { + Category tag = intent.getParcelableExtra(Constants.INTENT_CATEGORY); + categorizeNotesExecute(tag); } - } - + break; - public void toggleSearchLabel(boolean activate) { - if (activate) { - searchQueryView.setText(Html.fromHtml(getString(R.string.search) + ": " + searchQuery + "")); - searchLayout.setVisibility(View.VISIBLE); - searchCancel.setOnClickListener(v -> toggleSearchLabel(false)); - searchLabelActive = true; - } else { - if (searchLabelActive) { - searchLabelActive = false; - AnimationsHelper.expandOrCollapse(searchLayout, false); - searchTags = null; - searchQuery = null; - searchUncompleteChecklists = false; - if (!goBackOnToggleSearchLabel) { - mainActivity.getIntent().setAction(Intent.ACTION_MAIN); - if (searchView != null) { - MenuItemCompat.collapseActionView(searchMenuItem); - } - initNotesList(mainActivity.getIntent()); - } else { - mainActivity.onBackPressed(); - } - goBackOnToggleSearchLabel = false; - if (Intent.ACTION_VIEW.equals(mainActivity.getIntent().getAction())) { - mainActivity.getIntent().setAction(null); - } + case REQUEST_CODE_ADD_ALARMS: + list.clearChoices(); + selectedNotes.clear(); + finishActionMode(); + list.invalidateViews(); + break; + + default: + break; + } + + } + + + private void checkSortActionPerformed (MenuItem item) { + if (item.getGroupId() == Constants.MENU_SORT_GROUP_ID) { + final String[] arrayDb = getResources().getStringArray(R.array.sortable_columns); + prefs.edit().putString(Constants.PREF_SORTING_COLUMN, arrayDb[item.getOrder()]).apply(); + initNotesList(mainActivity.getIntent()); + // Resets list scrolling position + listViewPositionOffset = 16; + listViewPosition = 0; + restoreListScrollPosition(); + toggleSearchLabel(false); + // Updates app widgets + mainActivity.updateWidgets(); + } else { + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackActionFromResourceId(getActivity(), + item.getItemId()); + } + } + + + /** + * Empties trash deleting all the notes + */ + private void emptyTrash () { + new MaterialDialog.Builder(mainActivity) + .content(R.string.empty_trash_confirmation) + .positiveText(R.string.ok) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick ( + @NonNull MaterialDialog dialog, @NonNull DialogAction which) { + boolean mustDeleteLockedNotes = false; + for (int i = 0; i < listAdapter.getCount(); i++) { + selectedNotes.add(listAdapter.getItem(i)); + mustDeleteLockedNotes = mustDeleteLockedNotes || listAdapter.getItem(i).isLocked(); } - } - } - - - public void onEvent(NavigationUpdatedNavDrawerClosedEvent navigationUpdatedNavDrawerClosedEvent) { - listViewPosition = 0; - listViewPositionOffset = 16; - initNotesList(mainActivity.getIntent()); - setActionItemsVisibility(menu, false); - } - - - public void onEvent(CategoriesUpdatedEvent categoriesUpdatedEvent) { - initNotesList(mainActivity.getIntent()); - } - - - public void onEvent(NotesLoadedEvent notesLoadedEvent) { - int layoutSelected = prefs.getBoolean(Constants.PREF_EXPANDED_VIEW, true) ? R.layout.note_layout_expanded - : R.layout.note_layout; - listAdapter = new NoteAdapter(mainActivity, layoutSelected, notesLoadedEvent.notes); - - View noteLayout = LayoutInflater.from(mainActivity).inflate(layoutSelected, null, false); - noteViewHolder = new NoteViewHolder(noteLayout); - - if (Navigation.getNavigation() != Navigation.UNCATEGORIZED && prefs.getBoolean(Constants.PREF_ENABLE_SWIPE, - true)) { - list.enableSwipeToDismiss((viewGroup, reverseSortedPositions) -> { - - // Avoids conflicts with action mode - finishActionMode(); - - for (int position : reverseSortedPositions) { - Note note; - try { - note = listAdapter.getItem(position); - } catch (IndexOutOfBoundsException e) { - LogDelegate.d("Please stop swiping in the zone beneath the last card"); - continue; + if (mustDeleteLockedNotes) { + mainActivity.requestPassword(mainActivity, getSelectedNotes(), + passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + deleteNotesExecute(); } - - if (note != null && note.isLocked()) { - PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { - if (!passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { - onUndo(null); - } - }); - } - - getSelectedNotes().add(note); - - // Depending on settings and note status this action will... - // ...restore - if (Navigation.checkNavigation(Navigation.TRASH)) { - trashNotes(false); - } - // ...removes category - else if (Navigation.checkNavigation(Navigation.CATEGORY)) { - categorizeNotesExecute(null); - } else { - // ...trash - if (prefs.getBoolean("settings_swipe_to_trash", false) - || Navigation.checkNavigation(Navigation.ARCHIVE)) { - trashNotes(true); - // ...archive - } else { - archiveNotes(true); - } - } - } - }); - } else { - list.disableSwipeToDismiss(); - } - list.setAdapter(listAdapter); - - // Replace listview with Mr. Jingles if it is empty - if (notesLoadedEvent.notes.size() == 0) list.setEmptyView(empyListItem); - - // Restores listview position when turning back to list or when navigating reminders - if (list != null && notesLoadedEvent.notes.size() > 0) { - if (Navigation.checkNavigation(Navigation.REMINDERS)) { - listViewPosition = listAdapter.getClosestNotePosition(); + }); + } else { + deleteNotesExecute(); } - restoreListScrollPosition(); + } + }).build().show(); + } + + + /** + * Notes list adapter initialization and association to view + * + * @FIXME: This method is a divine opprobrium and MUST be refactored. I'm ashamed by myself. + */ + void initNotesList (Intent intent) { + LogDelegate.d("initNotesList intent: " + intent.getAction()); + + progress_wheel.setAlpha(1); + list.setAlpha(0); + + // Search for a tag + // A workaround to simplify it's to simulate normal search + if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getCategories() != null + && intent.getCategories().contains(Intent.CATEGORY_BROWSABLE)) { + searchTags = intent.getDataString().replace(UrlCompleter.HASHTAG_SCHEME, ""); + goBackOnToggleSearchLabel = true; + } + + if (Constants.ACTION_SHORTCUT_WIDGET.equals(intent.getAction())) { + return; + } + + // Searching + searchQuery = searchQueryInstant; + searchQueryInstant = null; + if (searchTags != null || searchQuery != null || searchUncompleteChecklists + || IntentChecker.checkAction(intent, Intent.ACTION_SEARCH, Constants.ACTION_SEARCH_UNCOMPLETE_CHECKLISTS)) { + + // Using tags + if (searchTags != null && intent.getStringExtra(SearchManager.QUERY) == null) { + searchQuery = searchTags; + NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByTag", + searchQuery); + } else if (searchUncompleteChecklists || Constants.ACTION_SEARCH_UNCOMPLETE_CHECKLISTS.equals( + intent.getAction())) { + searchQuery = getContext().getResources().getString(R.string.uncompleted_checklists); + searchUncompleteChecklists = true; + NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByUncompleteChecklist"); + } else { + // Get the intent, verify the action and get the query + if (intent.getStringExtra(SearchManager.QUERY) != null) { + searchQuery = intent.getStringExtra(SearchManager.QUERY); + searchTags = null; } - - animateListView(); - - closeFab(); - } - - public void onEvent(PasswordRemovedEvent passwordRemovedEvent) { - initNotesList(mainActivity.getIntent()); - } - - private void animateListView() { - if (!OmniNotes.isDebugBuild()) { - animate(progress_wheel).setDuration(getResources().getInteger(R.integer.list_view_fade_anim)).alpha(0); - animate(list).setDuration(getResources().getInteger(R.integer.list_view_fade_anim)).alpha(1); - } else { - progress_wheel.setVisibility(View.INVISIBLE); - list.setAlpha(1); - } - } - - - private void restoreListScrollPosition() { - if (list.getCount() > listViewPosition) { - list.setSelectionFromTop(listViewPosition, listViewPositionOffset); - new Handler().postDelayed(fab::showFab, 150); - } else { - list.setSelectionFromTop(0, 0); + NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByPattern", + searchQuery); + } + + toggleSearchLabel(true); + + } else { + // Check if is launched from a widget with categories + if ((Constants.ACTION_WIDGET_SHOW_LIST.equals(intent.getAction()) && intent + .hasExtra(Constants.INTENT_WIDGET)) + || !TextUtils.isEmpty(mainActivity.navigationTmp)) { + String widgetId = intent.hasExtra(Constants.INTENT_WIDGET) ? intent.getExtras() + .get(Constants.INTENT_WIDGET).toString() + : null; + if (widgetId != null) { + String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, ""); + String categoryId = TextHelper.checkIntentCategory(sqlCondition); + mainActivity.navigationTmp = !TextUtils.isEmpty(categoryId) ? categoryId : null; } - } - - - /** - * Batch note trashing - */ - public void trashNotes(boolean trash) { - int selectedNotesSize = getSelectedNotes().size(); - - // Restore is performed immediately, otherwise undo bar is shown - if (trash) { - trackModifiedNotes(getSelectedNotes()); - for (Note note : getSelectedNotes()) { - listAdapter.remove(note); - ReminderHelper.removeReminder(OmniNotes.getAppContext(), note); - } + intent.removeExtra(Constants.INTENT_WIDGET); + if (mainActivity.navigationTmp != null) { + Long categoryId = Long.parseLong(mainActivity.navigationTmp); + NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, + "getNotesByCategory", categoryId); } else { - trashNote(getSelectedNotes(), false); + NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true); } - // If list is empty again Mr Jingles will appear again - if (listAdapter.getCount() == 0) - list.setEmptyView(empyListItem); - - finishActionMode(); - - // Advice to user - if (trash) { - mainActivity.showMessage(R.string.note_trashed, ONStyle.WARN); + } else { + NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true); + } + } + } + + + public void toggleSearchLabel (boolean activate) { + if (activate) { + searchQueryView.setText(Html.fromHtml(getString(R.string.search) + ": " + searchQuery + "")); + searchLayout.setVisibility(View.VISIBLE); + searchCancel.setOnClickListener(v -> toggleSearchLabel(false)); + searchLabelActive = true; + } else { + if (searchLabelActive) { + searchLabelActive = false; + AnimationsHelper.expandOrCollapse(searchLayout, false); + searchTags = null; + searchQuery = null; + searchUncompleteChecklists = false; + if (!goBackOnToggleSearchLabel) { + mainActivity.getIntent().setAction(Intent.ACTION_MAIN); + if (searchView != null) { + MenuItemCompat.collapseActionView(searchMenuItem); + } + initNotesList(mainActivity.getIntent()); } else { - mainActivity.showMessage(R.string.note_untrashed, ONStyle.INFO); + mainActivity.onBackPressed(); } - - // Creation of undo bar - if (trash) { - ubc.showUndoBar(false, selectedNotesSize + " " + getString(R.string.trashed), null); - fab.hideFab(); - undoTrash = true; - } else { - getSelectedNotes().clear(); + goBackOnToggleSearchLabel = false; + if (Intent.ACTION_VIEW.equals(mainActivity.getIntent().getAction())) { + mainActivity.getIntent().setAction(null); } + } } + } - private android.support.v7.view.ActionMode getActionMode() { - return actionMode; - } + public void onEvent (NavigationUpdatedNavDrawerClosedEvent navigationUpdatedNavDrawerClosedEvent) { + listViewPosition = 0; + listViewPositionOffset = 16; + initNotesList(mainActivity.getIntent()); + setActionItemsVisibility(menu, false); + } - private List getSelectedNotes() { - return selectedNotes; - } + public void onEvent (CategoriesUpdatedEvent categoriesUpdatedEvent) { + initNotesList(mainActivity.getIntent()); + } - /** - * Single note logical deletion - */ - @SuppressLint("NewApi") - protected void trashNote(List notes, boolean trash) { - listAdapter.remove(notes); - new NoteProcessorTrash(notes, trash).process(); - } + public void onEvent (NotesLoadedEvent notesLoadedEvent) { + int layoutSelected = prefs.getBoolean(Constants.PREF_EXPANDED_VIEW, true) ? R.layout.note_layout_expanded + : R.layout.note_layout; + listAdapter = new NoteAdapter(mainActivity, layoutSelected, notesLoadedEvent.notes); + View noteLayout = LayoutInflater.from(mainActivity).inflate(layoutSelected, null, false); + noteViewHolder = new NoteViewHolder(noteLayout); - /** - * Selects all notes in list - */ - private void selectAllNotes() { - for (int i = 0; i < list.getChildCount(); i++) { - LinearLayout v = (LinearLayout) list.getChildAt(i).findViewById(R.id.card_layout); - v.setBackgroundColor(getResources().getColor(R.color.list_bg_selected)); - } - selectedNotes.clear(); - for (int i = 0; i < listAdapter.getCount(); i++) { - selectedNotes.add(listAdapter.getItem(i)); - listAdapter.addSelectedItem(i); - } - prepareActionModeMenu(); - setCabTitle(); - } - - - /** - * Batch note permanent deletion - */ - private void deleteNotes() { - new MaterialDialog.Builder(mainActivity) - .content(R.string.delete_note_confirmation) - .positiveText(R.string.ok) - .onPositive((dialog, which) -> mainActivity.requestPassword(mainActivity, getSelectedNotes(), - passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED) ) { - deleteNotesExecute(); - } - })) - .build() - .show(); - } - - - /** - * Performs notes permanent deletion after confirmation by the user - */ - private void deleteNotesExecute() { - listAdapter.remove(getSelectedNotes()); - new NoteProcessorDelete(getSelectedNotes()).process(); - list.clearChoices(); - selectedNotes.clear(); - finishActionMode(); - // If list is empty again Mr Jingles will appear again - if (listAdapter.getCount() == 0) - list.setEmptyView(empyListItem); - mainActivity.showMessage(R.string.note_deleted, ONStyle.ALERT); - } - - - /** - * Batch note archiviation - */ - public void archiveNotes(boolean archive) { - int selectedNotesSize = getSelectedNotes().size(); - // Used in undo bar commit - sendToArchive = archive; + if (Navigation.getNavigation() != Navigation.UNCATEGORIZED && prefs.getBoolean(Constants.PREF_ENABLE_SWIPE, + true)) { + list.enableSwipeToDismiss((viewGroup, reverseSortedPositions) -> { - if (!archive) { - archiveNote(getSelectedNotes(), false); - } else { - trackModifiedNotes(getSelectedNotes()); - } + // Avoids conflicts with action mode + finishActionMode(); - for (Note note : getSelectedNotes()) { - // If is restore it will be done immediately, otherwise the undo bar will be shown - if (archive) { - // Saves archived state to eventually undo - undoArchivedMap.put(note, note.isArchived()); - } + for (int position : reverseSortedPositions) { + Note note; + try { + note = listAdapter.getItem(position); + } catch (IndexOutOfBoundsException e) { + LogDelegate.d("Please stop swiping in the zone beneath the last card"); + continue; + } - // If actual navigation is not "Notes" the item will not be removed but replaced to fit the new state - if (Navigation.checkNavigation(Navigation.NOTES) - || (Navigation.checkNavigation(Navigation.ARCHIVE) && !archive) - || (Navigation.checkNavigation(Navigation.CATEGORY) && prefs.getBoolean(Constants - .PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory(), false))) { - listAdapter.remove(note); + if (note != null && note.isLocked()) { + PasswordHelper.requestPassword(mainActivity, passwordConfirmed -> { + if (!passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + onUndo(null); + } + }); + } + + getSelectedNotes().add(note); + + // Depending on settings and note status this action will... + // ...restore + if (Navigation.checkNavigation(Navigation.TRASH)) { + trashNotes(false); + } + // ...removes category + else if (Navigation.checkNavigation(Navigation.CATEGORY)) { + categorizeNotesExecute(null); + } else { + // ...trash + if (prefs.getBoolean("settings_swipe_to_trash", false) + || Navigation.checkNavigation(Navigation.ARCHIVE)) { + trashNotes(true); + // ...archive } else { - note.setArchived(archive); - listAdapter.replace(note, listAdapter.getPosition(note)); + archiveNotes(true); } + } } - - listAdapter.notifyDataSetChanged(); - finishActionMode(); - - // If list is empty again Mr Jingles will appear again - if (listAdapter.getCount() == 0) list.setEmptyView(empyListItem); - - // Advice to user - int msg = archive ? R.string.note_archived : R.string.note_unarchived; - Style style = archive ? ONStyle.WARN : ONStyle.INFO; - mainActivity.showMessage(msg, style); - - // Creation of undo bar - if (archive) { - ubc.showUndoBar(false, selectedNotesSize + " " + getString(R.string.archived), null); - fab.hideFab(); - undoArchive = true; - } else { - getSelectedNotes().clear(); - } + }); + } else { + list.disableSwipeToDismiss(); } + list.setAdapter(listAdapter); - - /** - * Saves notes to be eventually restored at right position - */ - private void trackModifiedNotes(List modifiedNotesToTrack) { - for (Note note : modifiedNotesToTrack) { - undoNotesMap.put(listAdapter.getPosition(note), note); - } + // Replace listview with Mr. Jingles if it is empty + if (notesLoadedEvent.notes.size() == 0) { + list.setEmptyView(empyListItem); } - - private void archiveNote(List notes, boolean archive) { - new NoteProcessorArchive(notes, archive).process(); - if (!Navigation.checkNavigation(Navigation.CATEGORY)) { - listAdapter.remove(notes); - } - LogDelegate.d("Notes" + (archive ? "archived" : "restored from archive")); - } - - - /** - * Categories addition and editing - */ - void editCategory(Category category) { - Intent categoryIntent = new Intent(mainActivity, CategoryActivity.class); - categoryIntent.putExtra(Constants.INTENT_CATEGORY, category); - startActivityForResult(categoryIntent, REQUEST_CODE_CATEGORY); - } - - - /** - * Associates to or removes categories - */ - private void categorizeNotes() { - // Retrieves all available categories - final ArrayList categories = DbHelper.getInstance().getCategories(); - - final MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) - .title(R.string.categorize_as) - .adapter(new NavDrawerCategoryAdapter(mainActivity, categories), null) - .positiveText(R.string.add_category) - .positiveColorRes(R.color.colorPrimary) - .negativeText(R.string.remove_category) - .negativeColorRes(R.color.colorAccent) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick( - @NonNull MaterialDialog dialog, @NonNull DialogAction which) { - keepActionMode = true; - Intent intent = new Intent(mainActivity, CategoryActivity.class); - intent.putExtra("noHome", true); - startActivityForResult(intent, REQUEST_CODE_CATEGORY_NOTES); - } - }).onNegative(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - categorizeNotesExecute(null); - } - }).build(); - - ListView dialogList = dialog.getListView(); - assert dialogList != null; - dialogList.setOnItemClickListener((parent, view, position, id) -> { - dialog.dismiss(); - categorizeNotesExecute(categories.get(position)); - }); - - dialog.show(); + // Restores listview position when turning back to list or when navigating reminders + if (list != null && notesLoadedEvent.notes.size() > 0) { + if (Navigation.checkNavigation(Navigation.REMINDERS)) { + listViewPosition = listAdapter.getClosestNotePosition(); + } + restoreListScrollPosition(); } + animateListView(); - private void categorizeNotesExecute(Category category) { - if (category != null) { - categorizeNote(getSelectedNotes(), category); - } else { - trackModifiedNotes(getSelectedNotes()); - } - for (Note note : getSelectedNotes()) { - // If is restore it will be done immediately, otherwise the undo bar - // will be shown - if (category == null) { - // Saves categories associated to eventually undo - undoCategoryMap.put(note, note.getCategory()); - } - // Update adapter content if actual navigation is the category - // associated with actually cycled note - if ((Navigation.checkNavigation(Navigation.CATEGORY) && !Navigation.checkNavigationCategory(category)) || - Navigation.checkNavigation(Navigation.UNCATEGORIZED)) { - listAdapter.remove(note); - } else { - note.setCategory(category); - listAdapter.replace(note, listAdapter.getPosition(note)); - } - } + closeFab(); + } - finishActionMode(); - - // If list is empty again Mr Jingles will appear again - if (listAdapter.getCount() == 0) - list.setEmptyView(empyListItem); + public void onEvent (PasswordRemovedEvent passwordRemovedEvent) { + initNotesList(mainActivity.getIntent()); + } - // Advice to user - String msg; - if (category != null) { - msg = getResources().getText(R.string.notes_categorized_as) + " '" + category.getName() + "'"; - } else { - msg = getResources().getText(R.string.notes_category_removed).toString(); - } - mainActivity.showMessage(msg, ONStyle.INFO); - - // Creation of undo bar - if (category == null) { - ubc.showUndoBar(false, getString(R.string.notes_category_removed), null); - fab.hideFab(); - undoCategorize = true; - undoCategorizeCategory = null; - } else { - getSelectedNotes().clear(); - } + private void animateListView () { + if (!OmniNotes.isDebugBuild()) { + animate(progress_wheel).setDuration(getResources().getInteger(R.integer.list_view_fade_anim)).alpha(0); + animate(list).setDuration(getResources().getInteger(R.integer.list_view_fade_anim)).alpha(1); + } else { + progress_wheel.setVisibility(View.INVISIBLE); + list.setAlpha(1); } + } - private void categorizeNote(List notes, Category category) { - new NoteProcessorCategorize(notes, category).process(); + private void restoreListScrollPosition () { + if (list.getCount() > listViewPosition) { + list.setSelectionFromTop(listViewPosition, listViewPositionOffset); + new Handler().postDelayed(fab::showFab, 150); + } else { + list.setSelectionFromTop(0, 0); } + } - /** - * Bulk tag selected notes - */ - private void tagNotes() { + /** + * Batch note trashing + */ + public void trashNotes (boolean trash) { + int selectedNotesSize = getSelectedNotes().size(); - // Retrieves all available tags - final List tags = DbHelper.getInstance().getTags(); - - // If there is no tag a message will be shown - if (tags.size() == 0) { - finishActionMode(); - mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN); - return; - } - - final Integer[] preSelectedTags = TagsHelper.getPreselectedTagsArray(selectedNotes, tags); + // Restore is performed immediately, otherwise undo bar is shown + if (trash) { + trackModifiedNotes(getSelectedNotes()); + for (Note note : getSelectedNotes()) { + listAdapter.remove(note); + ReminderHelper.removeReminder(OmniNotes.getAppContext(), note); + } + } else { + trashNote(getSelectedNotes(), false); + } - new MaterialDialog.Builder(mainActivity) - .title(R.string.select_tags) - .items(TagsHelper.getTagsArray(tags)) - .positiveText(R.string.ok) - .itemsCallbackMultiChoice(preSelectedTags, (dialog, which, text) -> { - dialog.dismiss(); - tagNotesExecute(tags, which, preSelectedTags); - return false; - }).build().show(); + // If list is empty again Mr Jingles will appear again + if (listAdapter.getCount() == 0) { + list.setEmptyView(empyListItem); + } + + finishActionMode(); + + // Advice to user + if (trash) { + mainActivity.showMessage(R.string.note_trashed, ONStyle.WARN); + } else { + mainActivity.showMessage(R.string.note_untrashed, ONStyle.INFO); + } + + // Creation of undo bar + if (trash) { + ubc.showUndoBar(false, selectedNotesSize + " " + getString(R.string.trashed), null); + fab.hideFab(); + undoTrash = true; + } else { + getSelectedNotes().clear(); + } + } + + + private android.support.v7.view.ActionMode getActionMode () { + return actionMode; + } + + + private List getSelectedNotes () { + return selectedNotes; + } + + + /** + * Single note logical deletion + */ + @SuppressLint("NewApi") + protected void trashNote (List notes, boolean trash) { + listAdapter.remove(notes); + new NoteProcessorTrash(notes, trash).process(); + } + + + /** + * Selects all notes in list + */ + private void selectAllNotes () { + for (int i = 0; i < list.getChildCount(); i++) { + LinearLayout v = list.getChildAt(i).findViewById(R.id.card_layout); + v.setBackgroundColor(getResources().getColor(R.color.list_bg_selected)); + } + selectedNotes.clear(); + for (int i = 0; i < listAdapter.getCount(); i++) { + selectedNotes.add(listAdapter.getItem(i)); + listAdapter.addSelectedItem(i); + } + prepareActionModeMenu(); + setCabTitle(); + } + + + /** + * Batch note permanent deletion + */ + private void deleteNotes () { + new MaterialDialog.Builder(mainActivity) + .content(R.string.delete_note_confirmation) + .positiveText(R.string.ok) + .onPositive((dialog, which) -> mainActivity.requestPassword(mainActivity, getSelectedNotes(), + passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + deleteNotesExecute(); + } + })) + .build() + .show(); + } + + + /** + * Performs notes permanent deletion after confirmation by the user + */ + private void deleteNotesExecute () { + listAdapter.remove(getSelectedNotes()); + new NoteProcessorDelete(getSelectedNotes()).process(); + list.clearChoices(); + selectedNotes.clear(); + finishActionMode(); + // If list is empty again Mr Jingles will appear again + if (listAdapter.getCount() == 0) { + list.setEmptyView(empyListItem); + } + mainActivity.showMessage(R.string.note_deleted, ONStyle.ALERT); + } + + + /** + * Batch note archiviation + */ + public void archiveNotes (boolean archive) { + int selectedNotesSize = getSelectedNotes().size(); + // Used in undo bar commit + sendToArchive = archive; + + if (!archive) { + archiveNote(getSelectedNotes(), false); + } else { + trackModifiedNotes(getSelectedNotes()); + } + + for (Note note : getSelectedNotes()) { + // If is restore it will be done immediately, otherwise the undo bar will be shown + if (archive) { + // Saves archived state to eventually undo + undoArchivedMap.put(note, note.isArchived()); + } + + // If actual navigation is not "Notes" the item will not be removed but replaced to fit the new state + if (Navigation.checkNavigation(Navigation.NOTES) + || (Navigation.checkNavigation(Navigation.ARCHIVE) && !archive) + || (Navigation.checkNavigation(Navigation.CATEGORY) && prefs.getBoolean(Constants + .PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory(), false))) { + listAdapter.remove(note); + } else { + note.setArchived(archive); + listAdapter.replace(note, listAdapter.getPosition(note)); + } + } + + listAdapter.notifyDataSetChanged(); + finishActionMode(); + + // If list is empty again Mr Jingles will appear again + if (listAdapter.getCount() == 0) { + list.setEmptyView(empyListItem); + } + + // Advice to user + int msg = archive ? R.string.note_archived : R.string.note_unarchived; + Style style = archive ? ONStyle.WARN : ONStyle.INFO; + mainActivity.showMessage(msg, style); + + // Creation of undo bar + if (archive) { + ubc.showUndoBar(false, selectedNotesSize + " " + getString(R.string.archived), null); + fab.hideFab(); + undoArchive = true; + } else { + getSelectedNotes().clear(); + } + } + + + /** + * Saves notes to be eventually restored at right position + */ + private void trackModifiedNotes (List modifiedNotesToTrack) { + for (Note note : modifiedNotesToTrack) { + undoNotesMap.put(listAdapter.getPosition(note), note); + } + } + + + private void archiveNote (List notes, boolean archive) { + new NoteProcessorArchive(notes, archive).process(); + if (!Navigation.checkNavigation(Navigation.CATEGORY)) { + listAdapter.remove(notes); + } + LogDelegate.d("Notes" + (archive ? "archived" : "restored from archive")); + } + + + /** + * Categories addition and editing + */ + void editCategory (Category category) { + Intent categoryIntent = new Intent(mainActivity, CategoryActivity.class); + categoryIntent.putExtra(Constants.INTENT_CATEGORY, category); + startActivityForResult(categoryIntent, REQUEST_CODE_CATEGORY); + } + + + /** + * Associates to or removes categories + */ + private void categorizeNotes () { + // Retrieves all available categories + final ArrayList categories = DbHelper.getInstance().getCategories(); + + final MaterialDialog dialog = new MaterialDialog.Builder(mainActivity) + .title(R.string.categorize_as) + .adapter(new NavDrawerCategoryAdapter(mainActivity, categories), null) + .positiveText(R.string.add_category) + .positiveColorRes(R.color.colorPrimary) + .negativeText(R.string.remove_category) + .negativeColorRes(R.color.colorAccent) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick ( + @NonNull MaterialDialog dialog, @NonNull DialogAction which) { + keepActionMode = true; + Intent intent = new Intent(mainActivity, CategoryActivity.class); + intent.putExtra("noHome", true); + startActivityForResult(intent, REQUEST_CODE_CATEGORY_NOTES); + } + }).onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + categorizeNotesExecute(null); + } + }).build(); + + ListView dialogList = dialog.getListView(); + assert dialogList != null; + dialogList.setOnItemClickListener((parent, view, position, id) -> { + dialog.dismiss(); + categorizeNotesExecute(categories.get(position)); + }); + + dialog.show(); + } + + + private void categorizeNotesExecute (Category category) { + if (category != null) { + categorizeNote(getSelectedNotes(), category); + } else { + trackModifiedNotes(getSelectedNotes()); + } + for (Note note : getSelectedNotes()) { + // If is restore it will be done immediately, otherwise the undo bar + // will be shown + if (category == null) { + // Saves categories associated to eventually undo + undoCategoryMap.put(note, note.getCategory()); + } + // Update adapter content if actual navigation is the category + // associated with actually cycled note + if ((Navigation.checkNavigation(Navigation.CATEGORY) && !Navigation.checkNavigationCategory(category)) || + Navigation.checkNavigation(Navigation.UNCATEGORIZED)) { + listAdapter.remove(note); + } else { + note.setCategory(category); + listAdapter.replace(note, listAdapter.getPosition(note)); + } + } + + finishActionMode(); + + // If list is empty again Mr Jingles will appear again + if (listAdapter.getCount() == 0) { + list.setEmptyView(empyListItem); + } + + // Advice to user + String msg; + if (category != null) { + msg = getResources().getText(R.string.notes_categorized_as) + " '" + category.getName() + "'"; + } else { + msg = getResources().getText(R.string.notes_category_removed).toString(); + } + mainActivity.showMessage(msg, ONStyle.INFO); + + // Creation of undo bar + if (category == null) { + ubc.showUndoBar(false, getString(R.string.notes_category_removed), null); + fab.hideFab(); + undoCategorize = true; + undoCategorizeCategory = null; + } else { + getSelectedNotes().clear(); + } + } + + + private void categorizeNote (List notes, Category category) { + new NoteProcessorCategorize(notes, category).process(); + } + + + /** + * Bulk tag selected notes + */ + private void tagNotes () { + + // Retrieves all available tags + final List tags = DbHelper.getInstance().getTags(); + + // If there is no tag a message will be shown + if (tags.size() == 0) { + finishActionMode(); + mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN); + return; } + final Integer[] preSelectedTags = TagsHelper.getPreselectedTagsArray(selectedNotes, tags); - private void tagNotesExecute(List tags, Integer[] selectedTags, Integer[] preSelectedTags) { + new MaterialDialog.Builder(mainActivity) + .title(R.string.select_tags) + .items(TagsHelper.getTagsArray(tags)) + .positiveText(R.string.ok) + .itemsCallbackMultiChoice(preSelectedTags, (dialog, which, text) -> { + dialog.dismiss(); + tagNotesExecute(tags, which, preSelectedTags); + return false; + }).build().show(); + } - // Retrieves selected tags - for (Note note : getSelectedNotes()) { - tagNote(tags, selectedTags, note); - } - // Clears data structures - list.clearChoices(); + private void tagNotesExecute (List tags, Integer[] selectedTags, Integer[] preSelectedTags) { - // Refreshes list - list.invalidateViews(); + // Retrieves selected tags + for (Note note : getSelectedNotes()) { + tagNote(tags, selectedTags, note); + } - // If list is empty again Mr Jingles will appear again - if (listAdapter.getCount() == 0) - list.setEmptyView(empyListItem); + // Clears data structures + list.clearChoices(); - if (getActionMode() != null) { - getActionMode().finish(); - } + // Refreshes list + list.invalidateViews(); - mainActivity.showMessage(R.string.tags_added, ONStyle.INFO); + // If list is empty again Mr Jingles will appear again + if (listAdapter.getCount() == 0) { + list.setEmptyView(empyListItem); } + if (getActionMode() != null) { + getActionMode().finish(); + } - private void tagNote(List tags, Integer[] selectedTags, Note note) { + mainActivity.showMessage(R.string.tags_added, ONStyle.INFO); + } - Pair> taggingResult = TagsHelper.addTagToNote(tags, selectedTags, note); - if (note.isChecklist()) { - note.setTitle(note.getTitle() + System.getProperty("line.separator") + taggingResult.first); - } else { - StringBuilder sb = new StringBuilder(note.getContent()); - if (sb.length() > 0) { - sb.append(System.getProperty("line.separator")) - .append(System.getProperty("line.separator")); - } - sb.append(taggingResult.first); - note.setContent(sb.toString()); - } + private void tagNote (List tags, Integer[] selectedTags, Note note) { - // Removes unchecked tags - Pair titleAndContent = TagsHelper.removeTag(note.getTitle(), note.getContent(), - taggingResult.second); - note.setTitle(titleAndContent.first); - note.setContent(titleAndContent.second); + Pair> taggingResult = TagsHelper.addTagToNote(tags, selectedTags, note); - DbHelper.getInstance().updateNote(note, false); + if (note.isChecklist()) { + note.setTitle(note.getTitle() + System.getProperty("line.separator") + taggingResult.first); + } else { + StringBuilder sb = new StringBuilder(note.getContent()); + if (sb.length() > 0) { + sb.append(System.getProperty("line.separator")) + .append(System.getProperty("line.separator")); + } + sb.append(taggingResult.first); + note.setContent(sb.toString()); } + // Removes unchecked tags + Pair titleAndContent = TagsHelper.removeTag(note.getTitle(), note.getContent(), + taggingResult.second); + note.setTitle(titleAndContent.first); + note.setContent(titleAndContent.second); + + DbHelper.getInstance().updateNote(note, false); + } // private void synchronizeSelectedNotes() { // new DriveSyncTask(mainActivity).execute(new ArrayList(getSelectedNotes())); @@ -1613,241 +1638,242 @@ private void tagNote(List tags, Integer[] selectedTags, Note note) { // } - @Override - public void onUndo(Parcelable undoToken) { - // Cycles removed items to re-insert into adapter - for (Integer notePosition : undoNotesMap.keySet()) { - Note currentNote = undoNotesMap.get(notePosition); - // Manages uncategorize or archive undo - if ((undoCategorize && !Navigation.checkNavigationCategory(undoCategoryMap.get(currentNote))) - || undoArchive && !Navigation.checkNavigation(Navigation.NOTES)) { - if (undoCategorize) { - currentNote.setCategory(undoCategoryMap.get(currentNote)); - } else if (undoArchive) { - currentNote.setArchived(undoArchivedMap.get(currentNote)); - } - listAdapter.replace(currentNote, listAdapter.getPosition(currentNote)); - // Manages trash undo - } else { - list.insert(notePosition, currentNote); - } + @Override + public void onUndo (Parcelable undoToken) { + // Cycles removed items to re-insert into adapter + for (Integer notePosition : undoNotesMap.keySet()) { + Note currentNote = undoNotesMap.get(notePosition); + // Manages uncategorize or archive undo + if ((undoCategorize && !Navigation.checkNavigationCategory(undoCategoryMap.get(currentNote))) + || undoArchive && !Navigation.checkNavigation(Navigation.NOTES)) { + if (undoCategorize) { + currentNote.setCategory(undoCategoryMap.get(currentNote)); + } else if (undoArchive) { + currentNote.setArchived(undoArchivedMap.get(currentNote)); } - - listAdapter.notifyDataSetChanged(); - - selectedNotes.clear(); - undoNotesMap.clear(); - - undoTrash = false; - undoArchive = false; - undoCategorize = false; - undoNotesMap.clear(); - undoCategoryMap.clear(); - undoArchivedMap.clear(); - undoCategorizeCategory = null; - Crouton.cancelAllCroutons(); - - if (getActionMode() != null) { - getActionMode().finish(); + listAdapter.replace(currentNote, listAdapter.getPosition(currentNote)); + // Manages trash undo + } else { + list.insert(notePosition, currentNote); + } + } + + listAdapter.notifyDataSetChanged(); + + selectedNotes.clear(); + undoNotesMap.clear(); + + undoTrash = false; + undoArchive = false; + undoCategorize = false; + undoNotesMap.clear(); + undoCategoryMap.clear(); + undoArchivedMap.clear(); + undoCategorizeCategory = null; + Crouton.cancelAllCroutons(); + + if (getActionMode() != null) { + getActionMode().finish(); + } + ubc.hideUndoBar(false); + fab.showFab(); + } + + + void commitPending () { + if (undoTrash || undoArchive || undoCategorize) { + + List notesList = new ArrayList<>(undoNotesMap.values()); + if (undoTrash) { + trashNote(notesList, true); + } else if (undoArchive) { + archiveNote(notesList, sendToArchive); + } else if (undoCategorize) { + categorizeNote(notesList, undoCategorizeCategory); + } + + undoTrash = false; + undoArchive = false; + undoCategorize = false; + undoCategorizeCategory = null; + + // Clears data structures + selectedNotes.clear(); + undoNotesMap.clear(); + undoCategoryMap.clear(); + undoArchivedMap.clear(); + list.clearChoices(); + + ubc.hideUndoBar(false); + fab.showFab(); + + LogDelegate.d("Changes committed"); + } + mainActivity.updateWidgets(); + } + + + /** + * Shares the selected note from the list + */ + private void share () { + // Only one note should be selected to perform sharing but they'll be cycled anyhow + for (final Note note : getSelectedNotes()) { + mainActivity.shareNote(note); + } + + getSelectedNotes().clear(); + if (getActionMode() != null) { + getActionMode().finish(); + } + } + + + public void merge () { + new MaterialDialog.Builder(mainActivity) + .title(R.string.delete_merged) + .positiveText(R.string.ok) + .negativeText(R.string.no) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick ( + @NonNull MaterialDialog dialog, @NonNull DialogAction which) { + EventBus.getDefault().post(new NotesMergeEvent(false)); + } + }) + .onNegative(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + EventBus.getDefault().post(new NotesMergeEvent(true)); + } + }).build().show(); + } + + + /** + * Merges all the selected notes + */ + public void onEventAsync (NotesMergeEvent notesMergeEvent) { + + final Note finalMergedNote = NotesHelper.mergeNotes(getSelectedNotes(), notesMergeEvent.keepMergedNotes); + new Handler(Looper.getMainLooper()).post(() -> { + + if (!notesMergeEvent.keepMergedNotes) { + ArrayList notesIds = new ArrayList<>(); + for (Note selectedNote : getSelectedNotes()) { + notesIds.add(String.valueOf(selectedNote.get_id())); } - ubc.hideUndoBar(false); - fab.showFab(); - } - - - void commitPending() { - if (undoTrash || undoArchive || undoCategorize) { + mainActivity.getIntent().putExtra("merged_notes", notesIds); + } - List notesList = new ArrayList<>(undoNotesMap.values()); - if (undoTrash) - trashNote(notesList, true); - else if (undoArchive) - archiveNote(notesList, sendToArchive); - else if (undoCategorize) - categorizeNote(notesList, undoCategorizeCategory); - - undoTrash = false; - undoArchive = false; - undoCategorize = false; - undoCategorizeCategory = null; - - // Clears data structures - selectedNotes.clear(); - undoNotesMap.clear(); - undoCategoryMap.clear(); - undoArchivedMap.clear(); - list.clearChoices(); - - ubc.hideUndoBar(false); - fab.showFab(); - - LogDelegate.d("Changes committed"); - } - mainActivity.updateWidgets(); - } - - - /** - * Shares the selected note from the list - */ - private void share() { - // Only one note should be selected to perform sharing but they'll be cycled anyhow - for (final Note note : getSelectedNotes()) { - mainActivity.shareNote(note); - } - - getSelectedNotes().clear(); - if (getActionMode() != null) { - getActionMode().finish(); - } - } - - - public void merge() { - new MaterialDialog.Builder(mainActivity) - .title(R.string.delete_merged) - .positiveText(R.string.ok) - .negativeText(R.string.no) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick( - @NonNull MaterialDialog dialog, @NonNull DialogAction which) { - EventBus.getDefault().post(new NotesMergeEvent(false)); - } - }) - .onNegative(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - EventBus.getDefault().post(new NotesMergeEvent(true)); - } - }).build().show(); - } - - - /** - * Merges all the selected notes - */ - public void onEventAsync(NotesMergeEvent notesMergeEvent) { - - final Note finalMergedNote = NotesHelper.mergeNotes(getSelectedNotes(), notesMergeEvent.keepMergedNotes); - new Handler(Looper.getMainLooper()).post(() -> { - - if (!notesMergeEvent.keepMergedNotes) { - ArrayList notesIds = new ArrayList<>(); - for (Note selectedNote : getSelectedNotes()) { - notesIds.add(String.valueOf(selectedNote.get_id())); - } - mainActivity.getIntent().putExtra("merged_notes", notesIds); - } - - getSelectedNotes().clear(); - if (getActionMode() != null) { - getActionMode().finish(); - } - - mainActivity.getIntent().setAction(Constants.ACTION_MERGE); - mainActivity.switchToDetail(finalMergedNote); - }); - } - - - /** - * Excludes past reminders - */ - private void filterReminders(boolean filter) { - prefs.edit().putBoolean(Constants.PREF_FILTER_PAST_REMINDERS, filter).apply(); - // Change list view - initNotesList(mainActivity.getIntent()); - // Called to switch menu voices - mainActivity.supportInvalidateOptionsMenu(); - } - - - /** - * Excludes archived notes in categories navigation - */ - private void filterCategoryArchived(boolean filter) { - if (filter) { - prefs.edit().putBoolean(Constants.PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory(), true).apply(); - } else { - prefs.edit().remove(Constants.PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory()).apply(); - } - // Change list view - initNotesList(mainActivity.getIntent()); - // Called to switch menu voices - mainActivity.supportInvalidateOptionsMenu(); - } - - - private void filterByUncompleteChecklists() { - initNotesList(new Intent(Constants.ACTION_SEARCH_UNCOMPLETE_CHECKLISTS)); - } - - private void filterByTags() { - - // Retrieves all available categories - final List tags = TagsHelper.getAllTags(); - - // If there is no category a message will be shown - if (tags.size() == 0) { - mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN); - return; - } - - // Dialog and events creation - new MaterialDialog.Builder(mainActivity) - .title(R.string.select_tags) - .items(TagsHelper.getTagsArray(tags)) - .positiveText(R.string.ok) - .itemsCallbackMultiChoice(new Integer[]{}, (dialog, which, text) -> { - // Retrieves selected tags - List selectedTags = new ArrayList<>(); - for (Integer aWhich : which) { - selectedTags.add(tags.get(aWhich).getText()); - } - - // Saved here to allow persisting search - searchTags = selectedTags.toString().substring(1, selectedTags.toString().length() - 1) - .replace(" ", ""); - Intent intent = mainActivity.getIntent(); - - // Hides keyboard - searchView.clearFocus(); - KeyboardUtils.hideKeyboard(searchView); - - intent.removeExtra(SearchManager.QUERY); - initNotesList(intent); - return false; - }).build().show(); - } - - - public MenuItem getSearchMenuItem() { - return searchMenuItem; - } - - - private boolean isFabAllowed() { - return isFabAllowed(false); - } - - - private boolean isFabAllowed(boolean actionModeFinishing) { - - boolean isAllowed = true; - - // Actionmode check - isAllowed = isAllowed && (getActionMode() == null || actionModeFinishing); - // Navigation check - int navigation = Navigation.getNavigation(); - isAllowed = isAllowed && navigation != Navigation.ARCHIVE && navigation != Navigation.REMINDERS && navigation - != Navigation.TRASH; - // Navigation drawer check - isAllowed = isAllowed && mainActivity.getDrawerLayout() != null && !mainActivity.getDrawerLayout().isDrawerOpen - (GravityCompat.START); - - return isAllowed; - } + getSelectedNotes().clear(); + if (getActionMode() != null) { + getActionMode().finish(); + } + + mainActivity.getIntent().setAction(Constants.ACTION_MERGE); + mainActivity.switchToDetail(finalMergedNote); + }); + } + + + /** + * Excludes past reminders + */ + private void filterReminders (boolean filter) { + prefs.edit().putBoolean(Constants.PREF_FILTER_PAST_REMINDERS, filter).apply(); + // Change list view + initNotesList(mainActivity.getIntent()); + // Called to switch menu voices + mainActivity.supportInvalidateOptionsMenu(); + } + + + /** + * Excludes archived notes in categories navigation + */ + private void filterCategoryArchived (boolean filter) { + if (filter) { + prefs.edit().putBoolean(Constants.PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory(), true).apply(); + } else { + prefs.edit().remove(Constants.PREF_FILTER_ARCHIVED_IN_CATEGORIES + Navigation.getCategory()).apply(); + } + // Change list view + initNotesList(mainActivity.getIntent()); + // Called to switch menu voices + mainActivity.supportInvalidateOptionsMenu(); + } + + + private void filterByUncompleteChecklists () { + initNotesList(new Intent(Constants.ACTION_SEARCH_UNCOMPLETE_CHECKLISTS)); + } + + private void filterByTags () { + + // Retrieves all available categories + final List tags = TagsHelper.getAllTags(); + + // If there is no category a message will be shown + if (tags.size() == 0) { + mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN); + return; + } + + // Dialog and events creation + new MaterialDialog.Builder(mainActivity) + .title(R.string.select_tags) + .items(TagsHelper.getTagsArray(tags)) + .positiveText(R.string.ok) + .itemsCallbackMultiChoice(new Integer[]{}, (dialog, which, text) -> { + // Retrieves selected tags + List selectedTags = new ArrayList<>(); + for (Integer aWhich : which) { + selectedTags.add(tags.get(aWhich).getText()); + } + + // Saved here to allow persisting search + searchTags = selectedTags.toString().substring(1, selectedTags.toString().length() - 1) + .replace(" ", ""); + Intent intent = mainActivity.getIntent(); + + // Hides keyboard + searchView.clearFocus(); + KeyboardUtils.hideKeyboard(searchView); + + intent.removeExtra(SearchManager.QUERY); + initNotesList(intent); + return false; + }).build().show(); + } + + + public MenuItem getSearchMenuItem () { + return searchMenuItem; + } + + + private boolean isFabAllowed () { + return isFabAllowed(false); + } + + + private boolean isFabAllowed (boolean actionModeFinishing) { + + boolean isAllowed = true; + + // Actionmode check + isAllowed = isAllowed && (getActionMode() == null || actionModeFinishing); + // Navigation check + int navigation = Navigation.getNavigation(); + isAllowed = isAllowed && navigation != Navigation.ARCHIVE && navigation != Navigation.REMINDERS && navigation + != Navigation.TRASH; + // Navigation drawer check + isAllowed = isAllowed && mainActivity.getDrawerLayout() != null && !mainActivity.getDrawerLayout().isDrawerOpen + (GravityCompat.START); + + return isAllowed; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/MainActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/MainActivity.java index 2347102364..3f2922f55f 100755 --- a/omniNotes/src/main/java/it/feio/android/omninotes/MainActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/MainActivity.java @@ -38,12 +38,6 @@ import android.widget.DatePicker; import android.widget.TimePicker; import android.widget.Toast; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import butterknife.BindView; import butterknife.ButterKnife; import de.greenrobot.event.EventBus; @@ -59,7 +53,6 @@ import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.BackupHelper; import it.feio.android.omninotes.helpers.LogDelegate; -import it.feio.android.omninotes.helpers.BackupHelper; import it.feio.android.omninotes.helpers.NotesHelper; import it.feio.android.omninotes.intro.IntroActivity; import it.feio.android.omninotes.models.Attachment; @@ -71,525 +64,535 @@ import it.feio.android.omninotes.utils.PasswordHelper; import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.SystemHelper; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; -public class MainActivity extends BaseActivity implements OnDateSetListener, OnTimeSetListener, SharedPreferences.OnSharedPreferenceChangeListener { - - private static boolean isPasswordAccepted = false; - public final String FRAGMENT_DRAWER_TAG = "fragment_drawer"; - public final String FRAGMENT_LIST_TAG = "fragment_list"; - public final String FRAGMENT_DETAIL_TAG = "fragment_detail"; - public final String FRAGMENT_SKETCH_TAG = "fragment_sketch"; - public Uri sketchUri; - @BindView(R.id.crouton_handle) - ViewGroup croutonViewContainer; - @BindView(R.id.toolbar) - Toolbar toolbar; - @BindView(R.id.drawer_layout) - DrawerLayout drawerLayout; - boolean prefsChanged = false; - private FragmentManager mFragmentManager; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setTheme(R.style.OmniNotesTheme_ApiSpec); - setContentView(R.layout.activity_main); - ButterKnife.bind(this); - EventBus.getDefault().register(this); - prefs.registerOnSharedPreferenceChangeListener(this); - - initUI(); - - if (IntroActivity.mustRun()) { - startActivity(new Intent(getApplicationContext(), IntroActivity.class)); - } - -// new UpdaterTask(this).execute(); Removed due to missing backend - } - - @Override - protected void onResume() { - super.onResume(); - if (isPasswordAccepted) { - init(); - } else { - checkPassword(); - } - } - - - @Override - protected void onStop() { - super.onStop(); - EventBus.getDefault().unregister(this); - } - - - private void initUI() { - setSupportActionBar(toolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); - } - - - /** - * This method starts the bootstrap chain. - */ - private void checkPassword() { - if (prefs.getString(Constants.PREF_PASSWORD, null) != null - && prefs.getBoolean("settings_password_access", false)) { - PasswordHelper.requestPassword(this, passwordConfirmed -> { - switch (passwordConfirmed) { - case SUCCEED: - init(); - break; - case FAIL: - finish(); - break; - case RESTORE: - PasswordHelper.resetPassword(this); - } - }); - } else { - init(); - } - } - - - public void onEvent(PasswordRemovedEvent passwordRemovedEvent) { - showMessage(R.string.password_successfully_removed, ONStyle.ALERT); - init(); - } - - - private void init() { - isPasswordAccepted = true; - - getFragmentManagerInstance(); +public class MainActivity extends BaseActivity implements OnDateSetListener, OnTimeSetListener, + SharedPreferences.OnSharedPreferenceChangeListener { - NavigationDrawerFragment mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManagerInstance() - .findFragmentById(R.id.navigation_drawer); - if (mNavigationDrawerFragment == null) { - FragmentTransaction fragmentTransaction = getFragmentManagerInstance().beginTransaction(); - fragmentTransaction.replace(R.id.navigation_drawer, new NavigationDrawerFragment(), - FRAGMENT_DRAWER_TAG).commit(); - } + private static boolean isPasswordAccepted = false; + public final String FRAGMENT_DRAWER_TAG = "fragment_drawer"; + public final String FRAGMENT_LIST_TAG = "fragment_list"; + public final String FRAGMENT_DETAIL_TAG = "fragment_detail"; + public final String FRAGMENT_SKETCH_TAG = "fragment_sketch"; + public Uri sketchUri; + @BindView(R.id.crouton_handle) + ViewGroup croutonViewContainer; + @BindView(R.id.toolbar) + Toolbar toolbar; + @BindView(R.id.drawer_layout) + DrawerLayout drawerLayout; + boolean prefsChanged = false; + private FragmentManager mFragmentManager; - if (getFragmentManagerInstance().findFragmentByTag(FRAGMENT_LIST_TAG) == null) { - FragmentTransaction fragmentTransaction = getFragmentManagerInstance().beginTransaction(); - fragmentTransaction.add(R.id.fragment_container, new ListFragment(), FRAGMENT_LIST_TAG).commit(); - } + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setTheme(R.style.OmniNotesTheme_ApiSpec); + setContentView(R.layout.activity_main); + ButterKnife.bind(this); + EventBus.getDefault().register(this); + prefs.registerOnSharedPreferenceChangeListener(this); - handleIntents(); - } + initUI(); - private FragmentManager getFragmentManagerInstance() { - if (mFragmentManager == null) { - mFragmentManager = getSupportFragmentManager(); - } - return mFragmentManager; - } - - @Override - protected void onNewIntent(Intent intent) { - if (intent.getAction() == null) { - intent.setAction(Constants.ACTION_START_APP); - } - super.onNewIntent(intent); - setIntent(intent); - handleIntents(); - LogDelegate.d("onNewIntent"); + if (IntroActivity.mustRun()) { + startActivity(new Intent(getApplicationContext(), IntroActivity.class)); } - - public MenuItem getSearchMenuItem() { - Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); - if (f != null) { - return ((ListFragment) f).getSearchMenuItem(); - } else { - return null; +// new UpdaterTask(this).execute(); Removed due to missing backend + } + + @Override + protected void onResume () { + super.onResume(); + if (isPasswordAccepted) { + init(); + } else { + checkPassword(); + } + } + + + @Override + protected void onStop () { + super.onStop(); + EventBus.getDefault().unregister(this); + } + + + private void initUI () { + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setHomeButtonEnabled(true); + } + + + /** + * This method starts the bootstrap chain. + */ + private void checkPassword () { + if (prefs.getString(Constants.PREF_PASSWORD, null) != null + && prefs.getBoolean("settings_password_access", false)) { + PasswordHelper.requestPassword(this, passwordConfirmed -> { + switch (passwordConfirmed) { + case SUCCEED: + init(); + break; + case FAIL: + finish(); + break; + case RESTORE: + PasswordHelper.resetPassword(this); } + }); + } else { + init(); } + } - public void editTag(Category tag) { - Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); - if (f != null) { - ((ListFragment) f).editCategory(tag); - } - } + public void onEvent (PasswordRemovedEvent passwordRemovedEvent) { + showMessage(R.string.password_successfully_removed, ONStyle.ALERT); + init(); + } - public void initNotesList(Intent intent) { - Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); - if (f != null) { - new Handler(getMainLooper()).post(() -> { - ((ListFragment) f).toggleSearchLabel(false); - ((ListFragment) f).initNotesList(intent); - }); - } - } + private void init () { + isPasswordAccepted = true; + getFragmentManagerInstance(); - public void commitPending() { - Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); - if (f != null) { - ((ListFragment) f).commitPending(); - } + NavigationDrawerFragment mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManagerInstance() + .findFragmentById(R.id.navigation_drawer); + if (mNavigationDrawerFragment == null) { + FragmentTransaction fragmentTransaction = getFragmentManagerInstance().beginTransaction(); + fragmentTransaction.replace(R.id.navigation_drawer, new NavigationDrawerFragment(), + FRAGMENT_DRAWER_TAG).commit(); } - - /** - * Checks if allocated fragment is of the required type and then returns it or returns null - */ - private Fragment checkFragmentInstance(int id, Object instanceClass) { - Fragment result = null; - Fragment fragment = getFragmentManagerInstance().findFragmentById(id); - if (fragment!= null && instanceClass.equals(fragment.getClass())) { - result = fragment; - } - return result; + if (getFragmentManagerInstance().findFragmentByTag(FRAGMENT_LIST_TAG) == null) { + FragmentTransaction fragmentTransaction = getFragmentManagerInstance().beginTransaction(); + fragmentTransaction.add(R.id.fragment_container, new ListFragment(), FRAGMENT_LIST_TAG).commit(); } + handleIntents(); + } - public void onBackPressed() { - - // SketchFragment - Fragment f = checkFragmentInstance(R.id.fragment_container, SketchFragment.class); - if (f != null) { - ((SketchFragment) f).save(); - - // Removes forced portrait orientation for this fragment - setRequestedOrientation( - ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); - - getFragmentManagerInstance().popBackStack(); - return; - } - - // DetailFragment - f = checkFragmentInstance(R.id.fragment_container, DetailFragment.class); - if (f != null) { - ((DetailFragment) f).goBack = true; - ((DetailFragment) f).saveAndExit((DetailFragment) f); - return; - } - - // ListFragment - f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); - if (f != null) { - // Before exiting from app the navigation drawer is opened - if (prefs.getBoolean("settings_navdrawer_on_exit", false) && getDrawerLayout() != null && - !getDrawerLayout().isDrawerOpen(GravityCompat.START)) { - getDrawerLayout().openDrawer(GravityCompat.START); - } else if (!prefs.getBoolean("settings_navdrawer_on_exit", false) && getDrawerLayout() != null && - getDrawerLayout().isDrawerOpen(GravityCompat.START)) { - getDrawerLayout().closeDrawer(GravityCompat.START); - } else { - if (!((ListFragment)f).closeFab()) { - isPasswordAccepted = false; - super.onBackPressed(); - } - } - return; - } - super.onBackPressed(); + private FragmentManager getFragmentManagerInstance () { + if (mFragmentManager == null) { + mFragmentManager = getSupportFragmentManager(); } + return mFragmentManager; + } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putString("navigationTmp", navigationTmp); + @Override + protected void onNewIntent (Intent intent) { + if (intent.getAction() == null) { + intent.setAction(Constants.ACTION_START_APP); } + super.onNewIntent(intent); + setIntent(intent); + handleIntents(); + LogDelegate.d("onNewIntent"); + } - @Override - protected void onPause() { - super.onPause(); - Crouton.cancelAllCroutons(); + public MenuItem getSearchMenuItem () { + Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); + if (f != null) { + return ((ListFragment) f).getSearchMenuItem(); + } else { + return null; } + } - public DrawerLayout getDrawerLayout() { - return drawerLayout; + public void editTag (Category tag) { + Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); + if (f != null) { + ((ListFragment) f).editCategory(tag); } + } - public ActionBarDrawerToggle getDrawerToggle() { - if (getFragmentManagerInstance().findFragmentById(R.id.navigation_drawer) != null) { - return ((NavigationDrawerFragment) getFragmentManagerInstance().findFragmentById(R.id.navigation_drawer)).mDrawerToggle; - } else { - return null; - } + public void initNotesList (Intent intent) { + Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); + if (f != null) { + new Handler(getMainLooper()).post(() -> { + ((ListFragment) f).toggleSearchLabel(false); + ((ListFragment) f).initNotesList(intent); + }); } + } - /** - * Finishes multiselection mode started by ListFragment - */ - public void finishActionMode() { - ListFragment fragment = (ListFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_LIST_TAG); - if (fragment != null) { - fragment.finishActionMode(); - } + public void commitPending () { + Fragment f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); + if (f != null) { + ((ListFragment) f).commitPending(); } + } - Toolbar getToolbar() { - return toolbar; + /** + * Checks if allocated fragment is of the required type and then returns it or returns null + */ + private Fragment checkFragmentInstance (int id, Object instanceClass) { + Fragment result = null; + Fragment fragment = getFragmentManagerInstance().findFragmentById(id); + if (fragment != null && instanceClass.equals(fragment.getClass())) { + result = fragment; } + return result; + } - private void handleIntents() { - Intent i = getIntent(); - - if (i.getAction() == null) return; - - if (Constants.ACTION_RESTART_APP.equals(i.getAction())) { - SystemHelper.restartApp(getApplicationContext(), MainActivity.class); - } - - if (receivedIntent(i)) { - Note note = i.getParcelableExtra(Constants.INTENT_NOTE); - if (note == null) { - note = DbHelper.getInstance().getNote(i.getIntExtra(Constants.INTENT_KEY, 0)); - } - // Checks if the same note is already opened to avoid to open again - if (note != null && noteAlreadyOpened(note)) { - return; - } - // Empty note instantiation - if (note == null) { - note = new Note(); - } - switchToDetail(note); - return; - } - - if (Constants.ACTION_SEND_AND_EXIT.equals(i.getAction())) { - saveAndExit(i); - return; - } - - // Tag search - if (Intent.ACTION_VIEW.equals(i.getAction())) { - switchToList(); - return; - } - - // Home launcher shortcut widget - if (Constants.ACTION_SHORTCUT_WIDGET.equals(i.getAction())) { - switchToDetail(new Note()); - return; - } - } - + public void onBackPressed () { - /** - * Used to perform a quick text-only note saving (eg. Tasker+Pushbullet) - */ - private void saveAndExit(Intent i) { - Note note = new Note(); - note.setTitle(i.getStringExtra(Intent.EXTRA_SUBJECT)); - note.setContent(i.getStringExtra(Intent.EXTRA_TEXT)); - DbHelper.getInstance().updateNote(note, true); - showToast(getString(R.string.note_updated), Toast.LENGTH_SHORT); - finish(); - } + // SketchFragment + Fragment f = checkFragmentInstance(R.id.fragment_container, SketchFragment.class); + if (f != null) { + ((SketchFragment) f).save(); + // Removes forced portrait orientation for this fragment + setRequestedOrientation( + ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); - private boolean receivedIntent(Intent i) { - return Constants.ACTION_SHORTCUT.equals(i.getAction()) - || Constants.ACTION_NOTIFICATION_CLICK.equals(i.getAction()) - || Constants.ACTION_WIDGET.equals(i.getAction()) - || Constants.ACTION_WIDGET_TAKE_PHOTO.equals(i.getAction()) - || ((Intent.ACTION_SEND.equals(i.getAction()) - || Intent.ACTION_SEND_MULTIPLE.equals(i.getAction()) - || Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) - && i.getType() != null) - || i.getAction().contains(Constants.ACTION_NOTIFICATION_CLICK); + getFragmentManagerInstance().popBackStack(); + return; } - - private boolean noteAlreadyOpened(Note note) { - DetailFragment detailFragment = (DetailFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG); - return detailFragment != null && NotesHelper.haveSameId(note, detailFragment.getCurrentNote()); + // DetailFragment + f = checkFragmentInstance(R.id.fragment_container, DetailFragment.class); + if (f != null) { + ((DetailFragment) f).goBack = true; + ((DetailFragment) f).saveAndExit((DetailFragment) f); + return; } - - public void switchToList() { - FragmentTransaction transaction = getFragmentManagerInstance().beginTransaction(); - animateTransition(transaction, TRANSITION_HORIZONTAL); - ListFragment mListFragment = new ListFragment(); - transaction.replace(R.id.fragment_container, mListFragment, FRAGMENT_LIST_TAG).addToBackStack - (FRAGMENT_DETAIL_TAG).commitAllowingStateLoss(); - if (getDrawerToggle() != null) { - getDrawerToggle().setDrawerIndicatorEnabled(false); + // ListFragment + f = checkFragmentInstance(R.id.fragment_container, ListFragment.class); + if (f != null) { + // Before exiting from app the navigation drawer is opened + if (prefs.getBoolean("settings_navdrawer_on_exit", false) && getDrawerLayout() != null && + !getDrawerLayout().isDrawerOpen(GravityCompat.START)) { + getDrawerLayout().openDrawer(GravityCompat.START); + } else if (!prefs.getBoolean("settings_navdrawer_on_exit", false) && getDrawerLayout() != null && + getDrawerLayout().isDrawerOpen(GravityCompat.START)) { + getDrawerLayout().closeDrawer(GravityCompat.START); + } else { + if (!((ListFragment) f).closeFab()) { + isPasswordAccepted = false; + super.onBackPressed(); } - getFragmentManagerInstance().getFragments(); - EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.PARENT)); + } + return; } + super.onBackPressed(); + } - public void switchToDetail(Note note) { - FragmentTransaction transaction = getFragmentManagerInstance().beginTransaction(); - animateTransition(transaction, TRANSITION_HORIZONTAL); - DetailFragment mDetailFragment = new DetailFragment(); - Bundle b = new Bundle(); - b.putParcelable(Constants.INTENT_NOTE, note); - mDetailFragment.setArguments(b); - if (getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG) == null) { - transaction.replace(R.id.fragment_container, mDetailFragment, FRAGMENT_DETAIL_TAG) - .addToBackStack(FRAGMENT_LIST_TAG) - .commitAllowingStateLoss(); - } else { - getFragmentManagerInstance().popBackStackImmediate(); - transaction.replace(R.id.fragment_container, mDetailFragment, FRAGMENT_DETAIL_TAG) - .addToBackStack(FRAGMENT_DETAIL_TAG) - .commitAllowingStateLoss(); - } - } + @Override + public void onSaveInstanceState (Bundle outState) { + super.onSaveInstanceState(outState); + outState.putString("navigationTmp", navigationTmp); + } - /** - * Notes sharing - */ - public void shareNote(Note note) { - - String titleText = note.getTitle(); - - String contentText = titleText - + System.getProperty("line.separator") - + note.getContent(); - - - Intent shareIntent = new Intent(); - // Prepare sharing intent with only text - if (note.getAttachmentsList().size() == 0) { - shareIntent.setAction(Intent.ACTION_SEND); - shareIntent.setType("text/plain"); - - // Intent with single image attachment - } else if (note.getAttachmentsList().size() == 1) { - shareIntent.setAction(Intent.ACTION_SEND); - Attachment attachment = note.getAttachmentsList().get(0); - shareIntent.setType(attachment.getMime_type()); - shareIntent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment)); - - // Intent with multiple images - } else if (note.getAttachmentsList().size() > 1) { - shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); - ArrayList uris = new ArrayList<>(); - // A check to decide the mime type of attachments to share is done here - HashMap mimeTypes = new HashMap<>(); - for (Attachment attachment : note.getAttachmentsList()) { - uris.add(FileProviderHelper.getShareableUri(attachment)); - mimeTypes.put(attachment.getMime_type(), true); - } - // If many mime types are present a general type is assigned to intent - if (mimeTypes.size() > 1) { - shareIntent.setType("*/*"); - } else { - shareIntent.setType((String) mimeTypes.keySet().toArray()[0]); - } - - shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); - } - shareIntent.putExtra(Intent.EXTRA_SUBJECT, titleText); - shareIntent.putExtra(Intent.EXTRA_TEXT, contentText); + @Override + protected void onPause () { + super.onPause(); + Crouton.cancelAllCroutons(); + } - startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share_message_chooser))); - } + public DrawerLayout getDrawerLayout () { + return drawerLayout; + } - /** - * Single note permanent deletion - * - * @param note Note to be deleted - */ - public void deleteNote(Note note) { - new NoteProcessorDelete(Arrays.asList(new Note[]{note})).process(); - BaseActivity.notifyAppWidgets(this); - LogDelegate.d("Deleted permanently note with id '" + note.get_id() + "'"); - } - - public void updateWidgets() { - new UpdateWidgetsTask(getApplicationContext()) - .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + public ActionBarDrawerToggle getDrawerToggle () { + if (getFragmentManagerInstance().findFragmentById(R.id.navigation_drawer) != null) { + return ((NavigationDrawerFragment) getFragmentManagerInstance().findFragmentById( + R.id.navigation_drawer)).mDrawerToggle; + } else { + return null; } + } - public void showMessage(int messageId, Style style) { - showMessage(getString(messageId), style); + /** + * Finishes multiselection mode started by ListFragment + */ + public void finishActionMode () { + ListFragment fragment = (ListFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_LIST_TAG); + if (fragment != null) { + fragment.finishActionMode(); } + } - public void showMessage(String message, Style style) { - // ViewGroup used to show Crouton keeping compatibility with the new Toolbar - runOnUiThread(() -> Crouton.makeText(this, message, style, croutonViewContainer).show()); - } - + Toolbar getToolbar () { + return toolbar; + } - @Override - public void onTimeSet(TimePicker view, int hourOfDay, int minute) { - DetailFragment f = (DetailFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG); - if (f != null && f.isAdded()) { - f.onTimeSetListener.onTimeSet(view, hourOfDay, minute); - } - } + private void handleIntents () { + Intent i = getIntent(); - @Override - public void onDateSet(DatePicker view, int year, int monthOfYear, - int dayOfMonth) { - DetailFragment f = (DetailFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG); - if (f != null && f.isAdded() && f.onDateSetListener != null) { - f.onDateSetListener.onDateSet(view, year, monthOfYear, dayOfMonth); - } + if (i.getAction() == null) { + return; } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - prefsChanged = true; + if (Constants.ACTION_RESTART_APP.equals(i.getAction())) { + SystemHelper.restartApp(getApplicationContext(), MainActivity.class); } - /** - * Performs auto-backup into file of a modified note - * @param notesUpdatedEvent Event containing updated note - */ - public void onEventAsync(NotesUpdatedEvent notesUpdatedEvent) { - autobackupUpdate(notesUpdatedEvent.notes); + if (receivedIntent(i)) { + Note note = i.getParcelableExtra(Constants.INTENT_NOTE); + if (note == null) { + note = DbHelper.getInstance().getNote(i.getIntExtra(Constants.INTENT_KEY, 0)); + } + // Checks if the same note is already opened to avoid to open again + if (note != null && noteAlreadyOpened(note)) { + return; + } + // Empty note instantiation + if (note == null) { + note = new Note(); + } + switchToDetail(note); + return; } - private void autobackupUpdate(List updatedNotes) { - if (prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)) { - File autoBackupDir = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); - for (Note note : updatedNotes) { - BackupHelper.exportNote(autoBackupDir, note); - BackupHelper.exportAttachments(null, new File(autoBackupDir, StorageHelper.getAttachmentDir().getName()), - note.getAttachmentsList(), note.getAttachmentsListOld()); - } - } + if (Constants.ACTION_SEND_AND_EXIT.equals(i.getAction())) { + saveAndExit(i); + return; } - /** - * Performs deletion from auto-backup folder of a permanently deleted note - * @param notesDeletedEvent Event containing deleted note - */ - public void onEventAsync(NotesDeletedEvent notesDeletedEvent) { - autobackupDeletion(notesDeletedEvent.notes); + // Tag search + if (Intent.ACTION_VIEW.equals(i.getAction())) { + switchToList(); + return; } - private void autobackupDeletion(List deletedNotes) { - if (prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)) { - File autoBackupDir = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); - for (Note note : deletedNotes) { - BackupHelper.deleteNoteBackup(autoBackupDir, note); - } - } - } + // Home launcher shortcut widget + if (Constants.ACTION_SHORTCUT_WIDGET.equals(i.getAction())) { + switchToDetail(new Note()); + return; + } + } + + + /** + * Used to perform a quick text-only note saving (eg. Tasker+Pushbullet) + */ + private void saveAndExit (Intent i) { + Note note = new Note(); + note.setTitle(i.getStringExtra(Intent.EXTRA_SUBJECT)); + note.setContent(i.getStringExtra(Intent.EXTRA_TEXT)); + DbHelper.getInstance().updateNote(note, true); + showToast(getString(R.string.note_updated), Toast.LENGTH_SHORT); + finish(); + } + + + private boolean receivedIntent (Intent i) { + return Constants.ACTION_SHORTCUT.equals(i.getAction()) + || Constants.ACTION_NOTIFICATION_CLICK.equals(i.getAction()) + || Constants.ACTION_WIDGET.equals(i.getAction()) + || Constants.ACTION_WIDGET_TAKE_PHOTO.equals(i.getAction()) + || ((Intent.ACTION_SEND.equals(i.getAction()) + || Intent.ACTION_SEND_MULTIPLE.equals(i.getAction()) + || Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) + && i.getType() != null) + || i.getAction().contains(Constants.ACTION_NOTIFICATION_CLICK); + } + + + private boolean noteAlreadyOpened (Note note) { + DetailFragment detailFragment = (DetailFragment) getFragmentManagerInstance().findFragmentByTag( + FRAGMENT_DETAIL_TAG); + return detailFragment != null && NotesHelper.haveSameId(note, detailFragment.getCurrentNote()); + } + + + public void switchToList () { + FragmentTransaction transaction = getFragmentManagerInstance().beginTransaction(); + animateTransition(transaction, TRANSITION_HORIZONTAL); + ListFragment mListFragment = new ListFragment(); + transaction.replace(R.id.fragment_container, mListFragment, FRAGMENT_LIST_TAG).addToBackStack + (FRAGMENT_DETAIL_TAG).commitAllowingStateLoss(); + if (getDrawerToggle() != null) { + getDrawerToggle().setDrawerIndicatorEnabled(false); + } + getFragmentManagerInstance().getFragments(); + EventBus.getDefault().post(new SwitchFragmentEvent(SwitchFragmentEvent.Direction.PARENT)); + } + + + public void switchToDetail (Note note) { + FragmentTransaction transaction = getFragmentManagerInstance().beginTransaction(); + animateTransition(transaction, TRANSITION_HORIZONTAL); + DetailFragment mDetailFragment = new DetailFragment(); + Bundle b = new Bundle(); + b.putParcelable(Constants.INTENT_NOTE, note); + mDetailFragment.setArguments(b); + if (getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG) == null) { + transaction.replace(R.id.fragment_container, mDetailFragment, FRAGMENT_DETAIL_TAG) + .addToBackStack(FRAGMENT_LIST_TAG) + .commitAllowingStateLoss(); + } else { + getFragmentManagerInstance().popBackStackImmediate(); + transaction.replace(R.id.fragment_container, mDetailFragment, FRAGMENT_DETAIL_TAG) + .addToBackStack(FRAGMENT_DETAIL_TAG) + .commitAllowingStateLoss(); + } + } + + + /** + * Notes sharing + */ + public void shareNote (Note note) { + + String titleText = note.getTitle(); + + String contentText = titleText + + System.getProperty("line.separator") + + note.getContent(); + + Intent shareIntent = new Intent(); + // Prepare sharing intent with only text + if (note.getAttachmentsList().size() == 0) { + shareIntent.setAction(Intent.ACTION_SEND); + shareIntent.setType("text/plain"); + + // Intent with single image attachment + } else if (note.getAttachmentsList().size() == 1) { + shareIntent.setAction(Intent.ACTION_SEND); + Attachment attachment = note.getAttachmentsList().get(0); + shareIntent.setType(attachment.getMime_type()); + shareIntent.putExtra(Intent.EXTRA_STREAM, FileProviderHelper.getShareableUri(attachment)); + + // Intent with multiple images + } else if (note.getAttachmentsList().size() > 1) { + shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); + ArrayList uris = new ArrayList<>(); + // A check to decide the mime type of attachments to share is done here + HashMap mimeTypes = new HashMap<>(); + for (Attachment attachment : note.getAttachmentsList()) { + uris.add(FileProviderHelper.getShareableUri(attachment)); + mimeTypes.put(attachment.getMime_type(), true); + } + // If many mime types are present a general type is assigned to intent + if (mimeTypes.size() > 1) { + shareIntent.setType("*/*"); + } else { + shareIntent.setType((String) mimeTypes.keySet().toArray()[0]); + } + + shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); + } + shareIntent.putExtra(Intent.EXTRA_SUBJECT, titleText); + shareIntent.putExtra(Intent.EXTRA_TEXT, contentText); + + startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share_message_chooser))); + } + + + /** + * Single note permanent deletion + * + * @param note Note to be deleted + */ + public void deleteNote (Note note) { + new NoteProcessorDelete(Arrays.asList(new Note[]{note})).process(); + BaseActivity.notifyAppWidgets(this); + LogDelegate.d("Deleted permanently note with id '" + note.get_id() + "'"); + } + + + public void updateWidgets () { + new UpdateWidgetsTask(getApplicationContext()) + .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + + + public void showMessage (int messageId, Style style) { + showMessage(getString(messageId), style); + } + + + public void showMessage (String message, Style style) { + // ViewGroup used to show Crouton keeping compatibility with the new Toolbar + runOnUiThread(() -> Crouton.makeText(this, message, style, croutonViewContainer).show()); + } + + + @Override + public void onTimeSet (TimePicker view, int hourOfDay, int minute) { + DetailFragment f = (DetailFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG); + if (f != null && f.isAdded()) { + f.onTimeSetListener.onTimeSet(view, hourOfDay, minute); + } + } + + + @Override + public void onDateSet (DatePicker view, int year, int monthOfYear, + int dayOfMonth) { + DetailFragment f = (DetailFragment) getFragmentManagerInstance().findFragmentByTag(FRAGMENT_DETAIL_TAG); + if (f != null && f.isAdded() && f.onDateSetListener != null) { + f.onDateSetListener.onDateSet(view, year, monthOfYear, dayOfMonth); + } + } + + @Override + public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) { + prefsChanged = true; + } + + /** + * Performs auto-backup into file of a modified note + * + * @param notesUpdatedEvent Event containing updated note + */ + public void onEventAsync (NotesUpdatedEvent notesUpdatedEvent) { + autobackupUpdate(notesUpdatedEvent.notes); + } + + private void autobackupUpdate (List updatedNotes) { + if (prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)) { + File autoBackupDir = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); + for (Note note : updatedNotes) { + BackupHelper.exportNote(autoBackupDir, note); + BackupHelper.exportAttachments(null, new File(autoBackupDir, StorageHelper.getAttachmentDir().getName()), + note.getAttachmentsList(), note.getAttachmentsListOld()); + } + } + } + + /** + * Performs deletion from auto-backup folder of a permanently deleted note + * + * @param notesDeletedEvent Event containing deleted note + */ + public void onEventAsync (NotesDeletedEvent notesDeletedEvent) { + autobackupDeletion(notesDeletedEvent.notes); + } + + private void autobackupDeletion (List deletedNotes) { + if (prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)) { + File autoBackupDir = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); + for (Note note : deletedNotes) { + BackupHelper.deleteNoteBackup(autoBackupDir, note); + } + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/NavigationDrawerFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/NavigationDrawerFragment.java index ff7ed92a8c..672f044ecd 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/NavigationDrawerFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/NavigationDrawerFragment.java @@ -30,7 +30,6 @@ import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.CategoryMenuTask; import it.feio.android.omninotes.async.MainMenuTask; @@ -49,203 +48,204 @@ public class NavigationDrawerFragment extends Fragment { - static final int BURGER = 0; - static final int ARROW = 1; + static final int BURGER = 0; + static final int ARROW = 1; - ActionBarDrawerToggle mDrawerToggle; - DrawerLayout mDrawerLayout; - private MainActivity mActivity; - private boolean alreadyInitialized; + ActionBarDrawerToggle mDrawerToggle; + DrawerLayout mDrawerLayout; + private MainActivity mActivity; + private boolean alreadyInitialized; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setRetainInstance(true); - } + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setRetainInstance(true); + } - @Override - public void onStart() { - super.onStart(); - EventBus.getDefault().register(this); - } + @Override + public void onStart () { + super.onStart(); + EventBus.getDefault().register(this); + } - @Override - public void onStop() { - super.onStop(); - EventBus.getDefault().unregister(this); - } + @Override + public void onStop () { + super.onStop(); + EventBus.getDefault().unregister(this); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return inflater.inflate(R.layout.fragment_navigation_drawer, container, false); - } + @Override + public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_navigation_drawer, container, false); + } - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - mActivity = (MainActivity) getActivity(); - init(); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + mActivity = (MainActivity) getActivity(); + init(); + } - private MainActivity getMainActivity() { - return (MainActivity) getActivity(); - } + private MainActivity getMainActivity () { + return (MainActivity) getActivity(); + } - public void onEventMainThread(DynamicNavigationReadyEvent event) { - if (alreadyInitialized) { - alreadyInitialized = false; - } else { - refreshMenus(); - } + public void onEventMainThread (DynamicNavigationReadyEvent event) { + if (alreadyInitialized) { + alreadyInitialized = false; + } else { + refreshMenus(); } + } - public void onEvent(CategoriesUpdatedEvent event) { - refreshMenus(); - } + public void onEvent (CategoriesUpdatedEvent event) { + refreshMenus(); + } - public void onEventAsync(NotesUpdatedEvent event) { - alreadyInitialized = false; - } + public void onEventAsync (NotesUpdatedEvent event) { + alreadyInitialized = false; + } - public void onEvent(NotesLoadedEvent event) { - if (mDrawerLayout != null) { - if (!isDoublePanelActive()) { - mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); - } - } - if (getMainActivity().getSupportFragmentManager().getBackStackEntryCount() == 0) { - init(); - } - refreshMenus(); - alreadyInitialized = true; + public void onEvent (NotesLoadedEvent event) { + if (mDrawerLayout != null) { + if (!isDoublePanelActive()) { + mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); + } } + if (getMainActivity().getSupportFragmentManager().getBackStackEntryCount() == 0) { + init(); + } + refreshMenus(); + alreadyInitialized = true; + } - public void onEvent(SwitchFragmentEvent event) { - switch (event.direction) { - case CHILDREN: - animateBurger(ARROW); - break; - default: - animateBurger(BURGER); - } + public void onEvent (SwitchFragmentEvent event) { + switch (event.direction) { + case CHILDREN: + animateBurger(ARROW); + break; + default: + animateBurger(BURGER); } + } - public void onEvent(NavigationUpdatedEvent navigationUpdatedEvent) { - if (navigationUpdatedEvent.navigationItem.getClass().isAssignableFrom(NavigationItem.class)) { - mActivity.getSupportActionBar().setTitle(((NavigationItem) navigationUpdatedEvent.navigationItem).getText()); - } else { - mActivity.getSupportActionBar().setTitle(((Category) navigationUpdatedEvent.navigationItem).getName()); - } - if (mDrawerLayout != null) { - if (!isDoublePanelActive()) { - mDrawerLayout.closeDrawer(GravityCompat.START); - } - new Handler().postDelayed(() -> EventBus.getDefault().post(new NavigationUpdatedNavDrawerClosedEvent - (navigationUpdatedEvent.navigationItem)), 400); - } + public void onEvent (NavigationUpdatedEvent navigationUpdatedEvent) { + if (navigationUpdatedEvent.navigationItem.getClass().isAssignableFrom(NavigationItem.class)) { + mActivity.getSupportActionBar().setTitle(((NavigationItem) navigationUpdatedEvent.navigationItem).getText()); + } else { + mActivity.getSupportActionBar().setTitle(((Category) navigationUpdatedEvent.navigationItem).getName()); + } + if (mDrawerLayout != null) { + if (!isDoublePanelActive()) { + mDrawerLayout.closeDrawer(GravityCompat.START); + } + new Handler().postDelayed(() -> EventBus.getDefault().post(new NavigationUpdatedNavDrawerClosedEvent + (navigationUpdatedEvent.navigationItem)), 400); } + } - public void init() { - LogDelegate.v("Started navigation drawer initialization"); - - mDrawerLayout = mActivity.findViewById(R.id.drawer_layout); - mDrawerLayout.setFocusableInTouchMode(false); - - // Setting specific bottom margin for Kitkat with translucent nav bar - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - View leftDrawer = getView().findViewById(R.id.left_drawer); - int leftDrawerBottomPadding = Display.getNavigationBarHeightKitkat(getActivity()); - leftDrawer.setPadding(leftDrawer.getPaddingLeft(), leftDrawer.getPaddingTop(), - leftDrawer.getPaddingRight(), leftDrawerBottomPadding); - } - - // ActionBarDrawerToggle± ties together the the proper interactions - // between the sliding drawer and the action bar app icon - mDrawerToggle = new ActionBarDrawerToggle(mActivity, - mDrawerLayout, - getMainActivity().getToolbar(), - R.string.drawer_open, - R.string.drawer_close - ) { - public void onDrawerClosed(View view) { - mActivity.supportInvalidateOptionsMenu(); - } - - - public void onDrawerOpened(View drawerView) { - mActivity.commitPending(); - mActivity.finishActionMode(); - } - }; - - if (isDoublePanelActive()) { - mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN); - } - - // Styling options - mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); - mDrawerLayout.setDrawerListener(mDrawerToggle); - mDrawerToggle.setDrawerIndicatorEnabled(true); - - LogDelegate.v("Finished navigation drawer initialization"); - } + public void init () { + LogDelegate.v("Started navigation drawer initialization"); + mDrawerLayout = mActivity.findViewById(R.id.drawer_layout); + mDrawerLayout.setFocusableInTouchMode(false); - private void refreshMenus() { - buildMainMenu(); - LogDelegate.v("Finished main menu initialization"); - buildCategoriesMenu(); - LogDelegate.v("Finished categories menu initialization"); - mDrawerToggle.syncState(); + // Setting specific bottom margin for Kitkat with translucent nav bar + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + View leftDrawer = getView().findViewById(R.id.left_drawer); + int leftDrawerBottomPadding = Display.getNavigationBarHeightKitkat(getActivity()); + leftDrawer.setPadding(leftDrawer.getPaddingLeft(), leftDrawer.getPaddingTop(), + leftDrawer.getPaddingRight(), leftDrawerBottomPadding); } + // ActionBarDrawerToggle± ties together the the proper interactions + // between the sliding drawer and the action bar app icon + mDrawerToggle = new ActionBarDrawerToggle(mActivity, + mDrawerLayout, + getMainActivity().getToolbar(), + R.string.drawer_open, + R.string.drawer_close + ) { + public void onDrawerClosed (View view) { + mActivity.supportInvalidateOptionsMenu(); + } - private void buildCategoriesMenu() { - CategoryMenuTask task = new CategoryMenuTask(this); - task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + public void onDrawerOpened (View drawerView) { + mActivity.commitPending(); + mActivity.finishActionMode(); + } + }; - private void buildMainMenu() { - MainMenuTask task = new MainMenuTask(this); - task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + if (isDoublePanelActive()) { + mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN); } + // Styling options + mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + mDrawerLayout.setDrawerListener(mDrawerToggle); + mDrawerToggle.setDrawerIndicatorEnabled(true); + + LogDelegate.v("Finished navigation drawer initialization"); + } + + + private void refreshMenus () { + buildMainMenu(); + LogDelegate.v("Finished main menu initialization"); + buildCategoriesMenu(); + LogDelegate.v("Finished categories menu initialization"); + mDrawerToggle.syncState(); + } + + + private void buildCategoriesMenu () { + CategoryMenuTask task = new CategoryMenuTask(this); + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + + + private void buildMainMenu () { + MainMenuTask task = new MainMenuTask(this); + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + - void animateBurger(int targetShape) { - if (mDrawerToggle != null) { - if (targetShape != BURGER && targetShape != ARROW) - return; - ValueAnimator anim = ValueAnimator.ofFloat((targetShape + 1) % 2, targetShape); - anim.addUpdateListener(valueAnimator -> { - float slideOffset = (Float) valueAnimator.getAnimatedValue(); - mDrawerToggle.onDrawerSlide(mDrawerLayout, slideOffset); - }); - anim.setInterpolator(new DecelerateInterpolator()); - anim.setDuration(500); - anim.start(); - } + void animateBurger (int targetShape) { + if (mDrawerToggle != null) { + if (targetShape != BURGER && targetShape != ARROW) { + return; + } + ValueAnimator anim = ValueAnimator.ofFloat((targetShape + 1) % 2, targetShape); + anim.addUpdateListener(valueAnimator -> { + float slideOffset = (Float) valueAnimator.getAnimatedValue(); + mDrawerToggle.onDrawerSlide(mDrawerLayout, slideOffset); + }); + anim.setInterpolator(new DecelerateInterpolator()); + anim.setDuration(500); + anim.start(); } + } - public static boolean isDoublePanelActive() { + public static boolean isDoublePanelActive () { // Resources resources = OmniNotes.getAppContext().getResources(); // return resources.getDimension(R.dimen.navigation_drawer_width) == resources.getDimension(R.dimen // .navigation_drawer_reserved_space); - return false; - } + return false; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/NoteInfosActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/NoteInfosActivity.java index 691e75b751..c7a71521fd 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/NoteInfosActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/NoteInfosActivity.java @@ -21,79 +21,76 @@ import android.os.Bundle; import android.view.View; import android.widget.TextView; - -import org.apache.commons.lang.StringUtils; - -import java.util.Objects; - import butterknife.BindView; import butterknife.ButterKnife; import it.feio.android.omninotes.helpers.NotesHelper; import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.models.StatsSingleNote; import it.feio.android.omninotes.utils.Constants; +import java.util.Objects; +import org.apache.commons.lang.StringUtils; public class NoteInfosActivity extends Activity { - @BindView(R.id.note_infos_category) - TextView category; - @BindView(R.id.note_infos_tags) - TextView tags; - @BindView(R.id.note_infos_chars) - TextView chars; - @BindView(R.id.note_infos_words) - TextView words; - @BindView(R.id.note_infos_checklist_items) - TextView checklistItems; - @BindView(R.id.note_infos_completed_checklist_items) - TextView checklistCompletedItems; - @BindView(R.id.note_infos_images) - TextView images; - @BindView(R.id.note_infos_videos) - TextView videos; - @BindView(R.id.note_infos_audiorecordings) - TextView audioRecordings; - @BindView(R.id.note_infos_sketches) - TextView sketches; - @BindView(R.id.note_infos_files) - TextView files; + @BindView(R.id.note_infos_category) + TextView category; + @BindView(R.id.note_infos_tags) + TextView tags; + @BindView(R.id.note_infos_chars) + TextView chars; + @BindView(R.id.note_infos_words) + TextView words; + @BindView(R.id.note_infos_checklist_items) + TextView checklistItems; + @BindView(R.id.note_infos_completed_checklist_items) + TextView checklistCompletedItems; + @BindView(R.id.note_infos_images) + TextView images; + @BindView(R.id.note_infos_videos) + TextView videos; + @BindView(R.id.note_infos_audiorecordings) + TextView audioRecordings; + @BindView(R.id.note_infos_sketches) + TextView sketches; + @BindView(R.id.note_infos_files) + TextView files; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_note_infos); - ButterKnife.bind(this); - Note note = Objects.requireNonNull(getIntent().getExtras()).getParcelable(Constants.INTENT_NOTE); - populateViews(note); - } + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_note_infos); + ButterKnife.bind(this); + Note note = Objects.requireNonNull(getIntent().getExtras()).getParcelable(Constants.INTENT_NOTE); + populateViews(note); + } - private void populateViews(Note note) { - StatsSingleNote infos = NotesHelper.getNoteInfos(note); - populateView(category, infos.getCategoryName()); - populateView(tags, infos.getTags()); - populateView(chars, infos.getChars()); - populateView(words, infos.getWords()); - populateView(checklistItems, infos.getChecklistItemsNumber()); - populateView(checklistCompletedItems, infos.getChecklistCompletedItemsNumber()); - populateView(images, infos.getImages()); - populateView(videos, infos.getVideos()); - populateView(audioRecordings, infos.getAudioRecordings()); - populateView(sketches, infos.getSketches()); - populateView(files, infos.getFiles()); - } + private void populateViews (Note note) { + StatsSingleNote infos = NotesHelper.getNoteInfos(note); + populateView(category, infos.getCategoryName()); + populateView(tags, infos.getTags()); + populateView(chars, infos.getChars()); + populateView(words, infos.getWords()); + populateView(checklistItems, infos.getChecklistItemsNumber()); + populateView(checklistCompletedItems, infos.getChecklistCompletedItemsNumber()); + populateView(images, infos.getImages()); + populateView(videos, infos.getVideos()); + populateView(audioRecordings, infos.getAudioRecordings()); + populateView(sketches, infos.getSketches()); + populateView(files, infos.getFiles()); + } - private void populateView(TextView textView, int numberValue) { - String stringValue = numberValue > 0 ? String.valueOf(numberValue) : ""; - populateView(textView, stringValue); - } + private void populateView (TextView textView, int numberValue) { + String stringValue = numberValue > 0 ? String.valueOf(numberValue) : ""; + populateView(textView, stringValue); + } - private void populateView(TextView textView, String value) { - if (!StringUtils.isEmpty(value)) { - textView.setText(value); - } else { - ((View) textView.getParent()).setVisibility(View.GONE); - } - } + private void populateView (TextView textView, String value) { + if (!StringUtils.isEmpty(value)) { + textView.setText(value); + } else { + ((View) textView.getParent()).setVisibility(View.GONE); + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/OmniNotes.java b/omniNotes/src/main/java/it/feio/android/omninotes/OmniNotes.java index 618f6e4cd6..ef782b7044 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/OmniNotes.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/OmniNotes.java @@ -22,20 +22,7 @@ import android.content.res.Configuration; import android.os.StrictMode; import android.support.multidex.MultiDexApplication; - -import com.bosphere.filelogger.FL; -import com.bosphere.filelogger.FLConfig; -import com.bosphere.filelogger.FLConst; import com.squareup.leakcanary.LeakCanary; - -import org.acra.ACRA; -import org.acra.annotation.AcraCore; -import org.acra.annotation.AcraHttpSender; -import org.acra.annotation.AcraToast; -import org.acra.sender.HttpSender; - -import java.io.File; - import it.feio.android.analitica.AnalyticsHelper; import it.feio.android.analitica.AnalyticsHelperFactory; import it.feio.android.analitica.MockAnalyticsHelper; @@ -43,98 +30,99 @@ import it.feio.android.analitica.exceptions.InvalidIdentifierException; import it.feio.android.omninotes.helpers.LanguageHelper; import it.feio.android.omninotes.utils.Constants; -import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.notifications.NotificationsHelper; - -import static it.feio.android.omninotes.utils.ConstantsBase.PREF_ENABLE_FILE_LOGGING; +import org.acra.ACRA; +import org.acra.annotation.AcraCore; +import org.acra.annotation.AcraHttpSender; +import org.acra.annotation.AcraToast; +import org.acra.sender.HttpSender; @AcraCore(buildConfigClass = BuildConfig.class) @AcraHttpSender(uri = BuildConfig.CRASH_REPORTING_URL, - httpMethod = HttpSender.Method.POST) + httpMethod = HttpSender.Method.POST) @AcraToast(resText = R.string.crash_toast) public class OmniNotes extends MultiDexApplication { - static SharedPreferences prefs; - private static Context mContext; - private AnalyticsHelper analyticsHelper; - - public static boolean isDebugBuild() { - return BuildConfig.BUILD_TYPE.equals("debug"); - } - - public static Context getAppContext() { - return OmniNotes.mContext; - } - - /** - * Statically returns app's default SharedPreferences instance - * - * @return SharedPreferences object instance - */ - public static SharedPreferences getSharedPreferences() { - return getAppContext().getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); - } - - @Override - protected void attachBaseContext(Context base) { - super.attachBaseContext(base); - ACRA.init(this); - ACRA.getErrorReporter().putCustomData("TRACEPOT_DEVELOP_MODE", isDebugBuild() ? "1" : "0"); - } - - @Override - public void onCreate() { - super.onCreate(); - - if (initLeakCanary()) { - return; - } - - mContext = getApplicationContext(); - prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); - - enableStrictMode(); - - new NotificationsHelper(this).initNotificationChannels(); - } - - private void enableStrictMode() { - if (isDebugBuild()) { - StrictMode.enableDefaults(); - } - } - - /** - * Returns true if the process dedicated to LeakCanary for heap analysis is running - * and app's init must be skipped - */ - private boolean initLeakCanary() { - if (!LeakCanary.isInAnalyzerProcess(this)) { - LeakCanary.install(this); - return false; - } - return true; - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - String language = prefs.getString(Constants.PREF_LANG, ""); - LanguageHelper.updateLanguage(this, language); - } - - public AnalyticsHelper getAnalyticsHelper() { - if (analyticsHelper == null) { - boolean enableAnalytics = prefs.getBoolean(Constants.PREF_SEND_ANALYTICS, true); - try { - String[] analyticsParams = BuildConfig.ANALYTICS_PARAMS.split(Constants.PROPERTIES_PARAMS_SEPARATOR); - analyticsHelper = new AnalyticsHelperFactory().getAnalyticsHelper(this, enableAnalytics, - analyticsParams); - } catch (AnalyticsInstantiationException | InvalidIdentifierException e) { - analyticsHelper = new MockAnalyticsHelper(); - } - } - return analyticsHelper; - } + static SharedPreferences prefs; + private static Context mContext; + private AnalyticsHelper analyticsHelper; + + public static boolean isDebugBuild () { + return BuildConfig.BUILD_TYPE.equals("debug"); + } + + public static Context getAppContext () { + return OmniNotes.mContext; + } + + /** + * Statically returns app's default SharedPreferences instance + * + * @return SharedPreferences object instance + */ + public static SharedPreferences getSharedPreferences () { + return getAppContext().getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); + } + + @Override + protected void attachBaseContext (Context base) { + super.attachBaseContext(base); + ACRA.init(this); + ACRA.getErrorReporter().putCustomData("TRACEPOT_DEVELOP_MODE", isDebugBuild() ? "1" : "0"); + } + + @Override + public void onCreate () { + super.onCreate(); + + if (initLeakCanary()) { + return; + } + + mContext = getApplicationContext(); + prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); + + enableStrictMode(); + + new NotificationsHelper(this).initNotificationChannels(); + } + + private void enableStrictMode () { + if (isDebugBuild()) { + StrictMode.enableDefaults(); + } + } + + /** + * Returns true if the process dedicated to LeakCanary for heap analysis is running and app's init must be skipped + */ + private boolean initLeakCanary () { + if (!LeakCanary.isInAnalyzerProcess(this)) { + LeakCanary.install(this); + return false; + } + return true; + } + + @Override + public void onConfigurationChanged (Configuration newConfig) { + super.onConfigurationChanged(newConfig); + String language = prefs.getString(Constants.PREF_LANG, ""); + LanguageHelper.updateLanguage(this, language); + } + + public AnalyticsHelper getAnalyticsHelper () { + if (analyticsHelper == null) { + boolean enableAnalytics = prefs.getBoolean(Constants.PREF_SEND_ANALYTICS, true); + try { + String[] analyticsParams = BuildConfig.ANALYTICS_PARAMS.split(Constants.PROPERTIES_PARAMS_SEPARATOR); + analyticsHelper = new AnalyticsHelperFactory().getAnalyticsHelper(this, enableAnalytics, + analyticsParams); + } catch (AnalyticsInstantiationException | InvalidIdentifierException e) { + analyticsHelper = new MockAnalyticsHelper(); + } + } + return analyticsHelper; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/PasswordActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/PasswordActivity.java index 16c1d88d05..a5a53dd1b3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/PasswordActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/PasswordActivity.java @@ -23,10 +23,8 @@ import android.util.DisplayMetrics; import android.view.ViewGroup; import android.widget.EditText; - import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; - import de.greenrobot.event.EventBus; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.LifecycleCallback; @@ -44,213 +42,211 @@ public class PasswordActivity extends BaseActivity { - private ViewGroup crouton_handle; - private EditText passwordCheck; - private EditText password; - private EditText question; - private EditText answer; - private EditText answerCheck; - private PasswordActivity mActivity; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - DisplayMetrics metrics = getResources().getDisplayMetrics(); - int screenWidth = (int) (metrics.widthPixels * 0.80); - int screenHeight = (int) (metrics.heightPixels * 0.80); - setContentView(R.layout.activity_password); - getWindow().setLayout(screenWidth, screenHeight); - mActivity = this; - setActionBarTitle(getString(R.string.title_activity_password)); - initViews(); - } - - - @Override - protected void onStart() { - super.onStart(); - EventBus.getDefault().register(this, 1); - } - - - @Override - public void onStop() { - super.onStop(); - EventBus.getDefault().unregister(this); - } - - - private void initViews() { - crouton_handle = findViewById(R.id.crouton_handle); - password = findViewById(R.id.password); - passwordCheck = findViewById(R.id.password_check); - question = findViewById(R.id.question); - answer = findViewById(R.id.answer); - answerCheck = findViewById(R.id.answer_check); - - findViewById(R.id.password_remove).setOnClickListener(v -> { - if (prefs.getString(Constants.PREF_PASSWORD, null) != null) { - PasswordHelper.requestPassword(mActivity, passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { - updatePassword(null, null, null); - } - }); - } else { - Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN, crouton_handle).show(); - } - }); - - findViewById(R.id.password_confirm).setOnClickListener(v -> { - if (checkData()) { - final String passwordText = password.getText().toString(); - final String questionText = question.getText().toString(); - final String answerText = answer.getText().toString(); - if (prefs.getString(Constants.PREF_PASSWORD, null) != null) { - PasswordHelper.requestPassword(mActivity, passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { - updatePassword(passwordText, questionText, answerText); - } - }); - } else { - updatePassword(passwordText, questionText, answerText); - } - } - }); - - findViewById(R.id.password_forgotten).setOnClickListener(v -> { - if (prefs.getString(Constants.PREF_PASSWORD, "").length() == 0) { - Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN, crouton_handle).show(); - return; - } - PasswordHelper.resetPassword(this); - }); + private ViewGroup crouton_handle; + private EditText passwordCheck; + private EditText password; + private EditText question; + private EditText answer; + private EditText answerCheck; + private PasswordActivity mActivity; + + + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + DisplayMetrics metrics = getResources().getDisplayMetrics(); + int screenWidth = (int) (metrics.widthPixels * 0.80); + int screenHeight = (int) (metrics.heightPixels * 0.80); + setContentView(R.layout.activity_password); + getWindow().setLayout(screenWidth, screenHeight); + mActivity = this; + setActionBarTitle(getString(R.string.title_activity_password)); + initViews(); + } + + + @Override + protected void onStart () { + super.onStart(); + EventBus.getDefault().register(this, 1); + } + + + @Override + public void onStop () { + super.onStop(); + EventBus.getDefault().unregister(this); + } + + + private void initViews () { + crouton_handle = findViewById(R.id.crouton_handle); + password = findViewById(R.id.password); + passwordCheck = findViewById(R.id.password_check); + question = findViewById(R.id.question); + answer = findViewById(R.id.answer); + answerCheck = findViewById(R.id.answer_check); + + findViewById(R.id.password_remove).setOnClickListener(v -> { + if (prefs.getString(Constants.PREF_PASSWORD, null) != null) { + PasswordHelper.requestPassword(mActivity, passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + updatePassword(null, null, null); + } + }); + } else { + Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN, crouton_handle).show(); + } + }); + + findViewById(R.id.password_confirm).setOnClickListener(v -> { + if (checkData()) { + final String passwordText = password.getText().toString(); + final String questionText = question.getText().toString(); + final String answerText = answer.getText().toString(); + if (prefs.getString(Constants.PREF_PASSWORD, null) != null) { + PasswordHelper.requestPassword(mActivity, passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + updatePassword(passwordText, questionText, answerText); + } + }); + } else { + updatePassword(passwordText, questionText, answerText); + } + } + }); + + findViewById(R.id.password_forgotten).setOnClickListener(v -> { + if (prefs.getString(Constants.PREF_PASSWORD, "").length() == 0) { + Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN, crouton_handle).show(); + return; + } + PasswordHelper.resetPassword(this); + }); + } + + + public void onEvent (PasswordRemovedEvent passwordRemovedEvent) { + passwordCheck.setText(""); + password.setText(""); + question.setText(""); + answer.setText(""); + answerCheck.setText(""); + Crouton crouton = Crouton.makeText(mActivity, R.string.password_successfully_removed, + ONStyle.ALERT, crouton_handle); + crouton.setLifecycleCallback(new LifecycleCallback() { + @Override + public void onDisplayed () { + // Does nothing! + } + + + @Override + public void onRemoved () { + onBackPressed(); + } + }); + crouton.show(); + } + + + @SuppressLint("CommitPrefEdits") + private void updatePassword (String passwordText, String questionText, String answerText) { + if (passwordText == null) { + if (prefs.getString(Constants.PREF_PASSWORD, "").length() == 0) { + Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN, crouton_handle).show(); + return; + } + new MaterialDialog.Builder(mActivity) + .content(R.string.agree_unlocking_all_notes) + .positiveText(R.string.ok) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + PasswordHelper.removePassword(); + } + }).build().show(); + } else if (passwordText.length() == 0) { + Crouton.makeText(mActivity, R.string.empty_password, ONStyle.WARN, crouton_handle).show(); + } else { + Observable + .from(DbHelper.getInstance().getNotesWithLock(true)) + .subscribeOn(Schedulers.newThread()) + .observeOn(AndroidSchedulers.mainThread()) + .doOnSubscribe(() -> prefs.edit() + .putString(Constants.PREF_PASSWORD, Security.md5(passwordText)) + .putString(Constants.PREF_PASSWORD_QUESTION, questionText) + .putString(Constants.PREF_PASSWORD_ANSWER, Security.md5(answerText)) + .commit()) + .doOnNext(note -> DbHelper.getInstance().updateNote(note, false)) + .doOnCompleted(() -> { + Crouton crouton = Crouton.makeText(mActivity, R.string.password_successfully_changed, ONStyle + .CONFIRM, crouton_handle); + crouton.setLifecycleCallback(new LifecycleCallback() { + @Override + public void onDisplayed () { + // Does nothing! + } + + + @Override + public void onRemoved () { + onBackPressed(); + } + }); + crouton.show(); + }) + .subscribe(); } + } + /** + * Checks correctness of form data + */ + private boolean checkData () { + boolean res = true; - public void onEvent(PasswordRemovedEvent passwordRemovedEvent) { - passwordCheck.setText(""); - password.setText(""); - question.setText(""); - answer.setText(""); - answerCheck.setText(""); - Crouton crouton = Crouton.makeText(mActivity, R.string.password_successfully_removed, - ONStyle.ALERT, crouton_handle); - crouton.setLifecycleCallback(new LifecycleCallback() { - @Override - public void onDisplayed() { - // Does nothing! - } - - - @Override - public void onRemoved() { - onBackPressed(); - } - }); - crouton.show(); - } - - - @SuppressLint("CommitPrefEdits") - private void updatePassword(String passwordText, String questionText, String answerText) { - if (passwordText == null) { - if (prefs.getString(Constants.PREF_PASSWORD, "").length() == 0) { - Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN, crouton_handle).show(); - return; - } - new MaterialDialog.Builder(mActivity) - .content(R.string.agree_unlocking_all_notes) - .positiveText(R.string.ok) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - PasswordHelper.removePassword(); - } - }).build().show(); - } else if (passwordText.length() == 0) { - Crouton.makeText(mActivity, R.string.empty_password, ONStyle.WARN, crouton_handle).show(); - } else { - Observable - .from(DbHelper.getInstance().getNotesWithLock(true)) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .doOnSubscribe(() -> prefs.edit() - .putString(Constants.PREF_PASSWORD, Security.md5(passwordText)) - .putString(Constants.PREF_PASSWORD_QUESTION, questionText) - .putString(Constants.PREF_PASSWORD_ANSWER, Security.md5(answerText)) - .commit()) - .doOnNext(note -> DbHelper.getInstance().updateNote(note, false)) - .doOnCompleted(() -> { - Crouton crouton = Crouton.makeText(mActivity, R.string.password_successfully_changed, ONStyle - .CONFIRM, crouton_handle); - crouton.setLifecycleCallback(new LifecycleCallback() { - @Override - public void onDisplayed() { - // Does nothing! - } - - - @Override - public void onRemoved() { - onBackPressed(); - } - }); - crouton.show(); - }) - .subscribe(); - } - } - - - /** - * Checks correctness of form data - * - * @return - */ - private boolean checkData() { - boolean res = true; - - if (password.getText().length() == passwordCheck.getText().length() - && passwordCheck.getText().length() == 0) { - return true; - } + if (password.getText().length() == passwordCheck.getText().length() + && passwordCheck.getText().length() == 0) { + return true; + } - boolean passwordOk = password.getText().toString().length() > 0; - boolean passwordCheckOk = passwordCheck.getText().toString().length() > 0 && password.getText().toString() - .equals(passwordCheck.getText().toString()); - boolean questionOk = question.getText().toString().length() > 0; - boolean answerOk = answer.getText().toString().length() > 0; - boolean answerCheckOk = answerCheck.getText().toString().length() > 0 && answer.getText().toString().equals - (answerCheck.getText().toString()); - - if (!passwordOk || !passwordCheckOk || !questionOk || !answerOk || !answerCheckOk) { - res = false; - if (!passwordOk) { - password.setError(getString(R.string.settings_password_not_matching)); - } - if (!passwordCheckOk) { - passwordCheck.setError(getString(R.string.settings_password_not_matching)); - } - if (!questionOk) { - question.setError(getString(R.string.settings_password_question)); - } - if (!answerOk) { - answer.setError(getString(R.string.settings_answer_not_matching)); - } - if (!answerCheckOk) { - answerCheck.setError(getString(R.string.settings_answer_not_matching)); - } - } - return res; + boolean passwordOk = password.getText().toString().length() > 0; + boolean passwordCheckOk = passwordCheck.getText().toString().length() > 0 && password.getText().toString() + .equals( + passwordCheck.getText().toString()); + boolean questionOk = question.getText().toString().length() > 0; + boolean answerOk = answer.getText().toString().length() > 0; + boolean answerCheckOk = answerCheck.getText().toString().length() > 0 && answer.getText().toString().equals + (answerCheck.getText().toString()); + + if (!passwordOk || !passwordCheckOk || !questionOk || !answerOk || !answerCheckOk) { + res = false; + if (!passwordOk) { + password.setError(getString(R.string.settings_password_not_matching)); + } + if (!passwordCheckOk) { + passwordCheck.setError(getString(R.string.settings_password_not_matching)); + } + if (!questionOk) { + question.setError(getString(R.string.settings_password_question)); + } + if (!answerOk) { + answer.setError(getString(R.string.settings_answer_not_matching)); + } + if (!answerCheckOk) { + answerCheck.setError(getString(R.string.settings_answer_not_matching)); + } } + return res; + } - @Override - public void onBackPressed() { - setResult(RESULT_OK); - finish(); - } + @Override + public void onBackPressed () { + setResult(RESULT_OK); + finish(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/SettingsActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/SettingsActivity.java index 4b2232ad95..81da928327 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/SettingsActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/SettingsActivity.java @@ -24,99 +24,97 @@ import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.ViewGroup; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.afollestad.materialdialogs.folderselector.FolderChooserDialog; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - import butterknife.BindView; import butterknife.ButterKnife; +import com.afollestad.materialdialogs.MaterialDialog; +import com.afollestad.materialdialogs.folderselector.FolderChooserDialog; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import it.feio.android.analitica.AnalyticsHelper; import it.feio.android.omninotes.async.DataBackupIntentService; +import java.io.File; +import java.util.ArrayList; +import java.util.List; public class SettingsActivity extends AppCompatActivity implements FolderChooserDialog.FolderCallback { - @BindView(R.id.toolbar) - Toolbar toolbar; - @BindView(R.id.crouton_handle) ViewGroup croutonViewContainer; - - private List backStack = new ArrayList<>(); - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_settings); - ButterKnife.bind(this); - initUI(); - getFragmentManager().beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit(); - } - - - void initUI() { - setSupportActionBar(toolbar); - toolbar.setNavigationOnClickListener(v -> onBackPressed()); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); - } - - - void switchToScreen(String key) { - SettingsFragment sf = new SettingsFragment(); - Bundle b = new Bundle(); - b.putString(SettingsFragment.XML_NAME, key); - sf.setArguments(b); - backStack.add(getFragmentManager().findFragmentById(R.id.content_frame)); - replaceFragment(sf); - } - - - private void replaceFragment(Fragment sf) { - getFragmentManager().beginTransaction().setCustomAnimations(R.animator.fade_in, R.animator.fade_out, - R.animator.fade_in, R.animator.fade_out).replace(R.id.content_frame, sf).commit(); - } - - - @Override - public void onBackPressed() { - if (!backStack.isEmpty()) { - replaceFragment(backStack.remove(backStack.size() - 1)); - } else { - super.onBackPressed(); - } - } - - - public void showMessage(int messageId, Style style) { - showMessage(getString(messageId), style); - } - - - public void showMessage(String message, Style style) { - // ViewGroup used to show Crouton keeping compatibility with the new Toolbar - Crouton.makeText(this, message, style, croutonViewContainer).show(); - } - - - @Override - public void onFolderSelection(@NonNull FolderChooserDialog dialog, @NonNull File folder) { - new MaterialDialog.Builder(this) - .title(R.string.data_import_message_warning) - .content(folder.getName()) - .positiveText(R.string.confirm) - .onPositive((dialog1, which) -> { - ((OmniNotes)getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, - "settings_import_data"); - Intent service = new Intent(getApplicationContext(), DataBackupIntentService.class); - service.setAction(DataBackupIntentService.ACTION_DATA_IMPORT_LEGACY); - service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, folder.getAbsolutePath()); - startService(service); - }).build().show(); - } + @BindView(R.id.toolbar) + Toolbar toolbar; + @BindView(R.id.crouton_handle) + ViewGroup croutonViewContainer; + + private List backStack = new ArrayList<>(); + + + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + ButterKnife.bind(this); + initUI(); + getFragmentManager().beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit(); + } + + + void initUI () { + setSupportActionBar(toolbar); + toolbar.setNavigationOnClickListener(v -> onBackPressed()); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setHomeButtonEnabled(true); + } + + + void switchToScreen (String key) { + SettingsFragment sf = new SettingsFragment(); + Bundle b = new Bundle(); + b.putString(SettingsFragment.XML_NAME, key); + sf.setArguments(b); + backStack.add(getFragmentManager().findFragmentById(R.id.content_frame)); + replaceFragment(sf); + } + + + private void replaceFragment (Fragment sf) { + getFragmentManager().beginTransaction().setCustomAnimations(R.animator.fade_in, R.animator.fade_out, + R.animator.fade_in, R.animator.fade_out).replace(R.id.content_frame, sf).commit(); + } + + + @Override + public void onBackPressed () { + if (!backStack.isEmpty()) { + replaceFragment(backStack.remove(backStack.size() - 1)); + } else { + super.onBackPressed(); + } + } + + + public void showMessage (int messageId, Style style) { + showMessage(getString(messageId), style); + } + + + public void showMessage (String message, Style style) { + // ViewGroup used to show Crouton keeping compatibility with the new Toolbar + Crouton.makeText(this, message, style, croutonViewContainer).show(); + } + + + @Override + public void onFolderSelection (@NonNull FolderChooserDialog dialog, @NonNull File folder) { + new MaterialDialog.Builder(this) + .title(R.string.data_import_message_warning) + .content(folder.getName()) + .positiveText(R.string.confirm) + .onPositive((dialog1, which) -> { + ((OmniNotes) getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, + "settings_import_data"); + Intent service = new Intent(getApplicationContext(), DataBackupIntentService.class); + service.setAction(DataBackupIntentService.ACTION_DATA_IMPORT_LEGACY); + service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, folder.getAbsolutePath()); + startService(service); + }).build().show(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/SettingsFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/SettingsFragment.java index a9d52236c1..84dc9198b2 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/SettingsFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/SettingsFragment.java @@ -16,6 +16,9 @@ */ package it.feio.android.omninotes; +import static java.util.Arrays.asList; +import static java.util.Collections.reverse; + import android.Manifest; import android.app.Activity; import android.content.Context; @@ -44,19 +47,8 @@ import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; - import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.folderselector.FolderChooserDialog; - -import org.apache.commons.lang.StringUtils; -import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch; - -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.LinkedList; -import java.util.List; - import it.feio.android.analitica.AnalyticsHelper; import it.feio.android.omninotes.async.DataBackupIntentService; import it.feio.android.omninotes.helpers.AppVersionHelper; @@ -75,202 +67,207 @@ import it.feio.android.omninotes.utils.ResourcesUtils; import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.SystemHelper; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.LinkedList; +import java.util.List; +import org.apache.commons.lang.StringUtils; +import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch; import rx.Observable; -import static java.util.Arrays.asList; -import static java.util.Collections.reverse; - public class SettingsFragment extends PreferenceFragment { - private SharedPreferences prefs; - - private static final int SPRINGPAD_IMPORT = 0; - private static final int RINGTONE_REQUEST_CODE = 100; - public static final String XML_NAME = "xmlName"; - private Activity activity; - private SettingsFragment pf; - - - @Override - public void onCreate(Bundle savedInstanceState) { - pf = this; - super.onCreate(savedInstanceState); - int xmlId = R.xml.settings; - if (getArguments() != null && getArguments().containsKey(XML_NAME)) { - xmlId = ResourcesUtils.getXmlId(OmniNotes.getAppContext(), ResourcesUtils.ResourceIdentifiers.xml, String - .valueOf(getArguments().get(XML_NAME))); - } - addPreferencesFromResource(xmlId); - } - - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - this.activity = activity; - prefs = activity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - setTitle(); - } - - - private void setTitle() { - String title = getString(R.string.settings); - if (getArguments() != null && getArguments().containsKey(XML_NAME)) { - String xmlName = getArguments().getString(XML_NAME); - if (!TextUtils.isEmpty(xmlName)) { - int stringResourceId = getActivity().getResources().getIdentifier(xmlName.replace("settings_", - "settings_screen_"), "string", getActivity().getPackageName()); - title = stringResourceId != 0 ? getString(stringResourceId) : title; - } - } - Toolbar toolbar = getActivity().findViewById(R.id.toolbar); - if (toolbar != null) toolbar.setTitle(title); - } - - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - getActivity().onBackPressed(); - } else { - LogDelegate.e("Wrong element choosen: " + item.getItemId()); - } - return super.onOptionsItemSelected(item); - } - - - @Override - public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { - super.onPreferenceTreeClick(preferenceScreen, preference); - if (preference instanceof PreferenceScreen) { - ((SettingsActivity) getActivity()).switchToScreen(preference.getKey()); - } - return false; - } - - - @Override - public void onResume() { - super.onResume(); - - // Export notes - Preference export = findPreference("settings_export_data"); - if (export != null) { - export.setOnPreferenceClickListener(arg0 -> { - - // Inflate layout - LayoutInflater inflater = getActivity().getLayoutInflater(); - View v = inflater.inflate(R.layout.dialog_backup_layout, null); - - // Finds actually saved backups names - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, R - .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> export - (v)); - - return false; - }); - } - - // Import notes - Preference importData = findPreference("settings_import_data"); - if (importData != null) { - importData.setOnPreferenceClickListener(arg0 -> { - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, R - .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> importNotes()); - return false; - }); - } - - // Import legacy notes - Preference importLegacyData = findPreference("settings_import_data_legacy"); - if (importLegacyData != null) { - importLegacyData.setOnPreferenceClickListener(arg0 -> { - - // Finds actually saved backups names - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE, R - .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> new - FolderChooserDialog.Builder((SettingsActivity) getActivity()) - .chooseButton(R.string.md_choose_label) - .show()); - return false; - }); - } - - // Autobackup feature integrity check - Preference backupIntegrityCheck = findPreference("settings_backup_integrity_check"); - if (backupIntegrityCheck != null) { - backupIntegrityCheck.setOnPreferenceClickListener(arg0 -> { - List> errors = BackupHelper.integrityCheck(StorageHelper - .getBackupDir(ConstantsBase.AUTO_BACKUP_DIR)); - if (errors.isEmpty()) { - new MaterialDialog.Builder(activity) - .content("Everything is ok") - .positiveText(R.string.ok) - .build().show(); - } else { - DiffMatchPatch diffMatchPatch = new DiffMatchPatch(); - String content = Observable.from(errors).map(diffs -> diffMatchPatch.diffPrettyHtml(diffs) + - "
").toList().toBlocking().first().toString(); - View v = getActivity().getLayoutInflater().inflate(R.layout.webview, null); - ((WebView) v.findViewById(R.id.webview)).loadData(content, "text/html", null); - new MaterialDialog.Builder(activity) - .customView(v, true) - .positiveText(R.string.ok) - .negativeText("Copy to clipboard") - .onNegative((dialog, which) -> { - SystemHelper.copyToClipboard(activity, content); - Toast.makeText(activity, "Copied to clipboard", Toast.LENGTH_SHORT).show(); - }) - .build().show(); - } - return false; - }); - } - - // Autobackup - final SwitchPreference enableAutobackup = (SwitchPreference) findPreference("settings_enable_autobackup"); - if (enableAutobackup != null) { - enableAutobackup.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue) { - new MaterialDialog.Builder(activity) - .content(R.string.settings_enable_automatic_backup_dialog) - .positiveText(R.string.confirm) - .negativeText(R.string.cancel) - .onPositive((dialog, which) -> { - PermissionsHelper.requestPermission(getActivity(), Manifest.permission - .WRITE_EXTERNAL_STORAGE, R - .string.permission_external_storage, activity.findViewById(R.id - .crouton_handle), () -> { - BackupHelper.startBackupService(Constants.AUTO_BACKUP_DIR); - enableAutobackup.setChecked(true); - }); - }) - .build().show(); - } else { - enableAutobackup.setChecked(false); - } - return false; - }); - } - - Preference importFromSpringpad = findPreference("settings_import_from_springpad"); - if (importFromSpringpad != null) { - importFromSpringpad.setOnPreferenceClickListener(arg0 -> { - Intent intent; - intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.addCategory(Intent.CATEGORY_OPENABLE); - intent.setType("application/zip"); - if (!IntentChecker.isAvailable(getActivity(), intent, null)) { - Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, - Toast.LENGTH_SHORT).show(); - return false; - } - startActivityForResult(intent, SPRINGPAD_IMPORT); - return false; - }); - } - + private SharedPreferences prefs; + + private static final int SPRINGPAD_IMPORT = 0; + private static final int RINGTONE_REQUEST_CODE = 100; + public static final String XML_NAME = "xmlName"; + private Activity activity; + private SettingsFragment pf; + + + @Override + public void onCreate (Bundle savedInstanceState) { + pf = this; + super.onCreate(savedInstanceState); + int xmlId = R.xml.settings; + if (getArguments() != null && getArguments().containsKey(XML_NAME)) { + xmlId = ResourcesUtils.getXmlId(OmniNotes.getAppContext(), ResourcesUtils.ResourceIdentifiers.xml, String + .valueOf(getArguments().get(XML_NAME))); + } + addPreferencesFromResource(xmlId); + } + + + @Override + public void onAttach (Activity activity) { + super.onAttach(activity); + this.activity = activity; + prefs = activity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + setTitle(); + } + + + private void setTitle () { + String title = getString(R.string.settings); + if (getArguments() != null && getArguments().containsKey(XML_NAME)) { + String xmlName = getArguments().getString(XML_NAME); + if (!TextUtils.isEmpty(xmlName)) { + int stringResourceId = getActivity().getResources().getIdentifier(xmlName.replace("settings_", + "settings_screen_"), "string", getActivity().getPackageName()); + title = stringResourceId != 0 ? getString(stringResourceId) : title; + } + } + Toolbar toolbar = getActivity().findViewById(R.id.toolbar); + if (toolbar != null) { + toolbar.setTitle(title); + } + } + + + @Override + public boolean onOptionsItemSelected (MenuItem item) { + if (item.getItemId() == android.R.id.home) { + getActivity().onBackPressed(); + } else { + LogDelegate.e("Wrong element choosen: " + item.getItemId()); + } + return super.onOptionsItemSelected(item); + } + + + @Override + public boolean onPreferenceTreeClick (PreferenceScreen preferenceScreen, Preference preference) { + super.onPreferenceTreeClick(preferenceScreen, preference); + if (preference instanceof PreferenceScreen) { + ((SettingsActivity) getActivity()).switchToScreen(preference.getKey()); + } + return false; + } + + + @Override + public void onResume () { + super.onResume(); + + // Export notes + Preference export = findPreference("settings_export_data"); + if (export != null) { + export.setOnPreferenceClickListener(arg0 -> { + + // Inflate layout + LayoutInflater inflater = getActivity().getLayoutInflater(); + View v = inflater.inflate(R.layout.dialog_backup_layout, null); + + // Finds actually saved backups names + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, R + .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> export + (v)); + + return false; + }); + } + + // Import notes + Preference importData = findPreference("settings_import_data"); + if (importData != null) { + importData.setOnPreferenceClickListener(arg0 -> { + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, R + .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> importNotes()); + return false; + }); + } + + // Import legacy notes + Preference importLegacyData = findPreference("settings_import_data_legacy"); + if (importLegacyData != null) { + importLegacyData.setOnPreferenceClickListener(arg0 -> { + + // Finds actually saved backups names + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE, R + .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> new + FolderChooserDialog.Builder((SettingsActivity) getActivity()) + .chooseButton(R.string.md_choose_label) + .show()); + return false; + }); + } + + // Autobackup feature integrity check + Preference backupIntegrityCheck = findPreference("settings_backup_integrity_check"); + if (backupIntegrityCheck != null) { + backupIntegrityCheck.setOnPreferenceClickListener(arg0 -> { + List> errors = BackupHelper.integrityCheck(StorageHelper + .getBackupDir(ConstantsBase.AUTO_BACKUP_DIR)); + if (errors.isEmpty()) { + new MaterialDialog.Builder(activity) + .content("Everything is ok") + .positiveText(R.string.ok) + .build().show(); + } else { + DiffMatchPatch diffMatchPatch = new DiffMatchPatch(); + String content = Observable.from(errors).map(diffs -> diffMatchPatch.diffPrettyHtml(diffs) + + "
").toList().toBlocking().first().toString(); + View v = getActivity().getLayoutInflater().inflate(R.layout.webview, null); + ((WebView) v.findViewById(R.id.webview)).loadData(content, "text/html", null); + new MaterialDialog.Builder(activity) + .customView(v, true) + .positiveText(R.string.ok) + .negativeText("Copy to clipboard") + .onNegative((dialog, which) -> { + SystemHelper.copyToClipboard(activity, content); + Toast.makeText(activity, "Copied to clipboard", Toast.LENGTH_SHORT).show(); + }) + .build().show(); + } + return false; + }); + } + + // Autobackup + final SwitchPreference enableAutobackup = (SwitchPreference) findPreference("settings_enable_autobackup"); + if (enableAutobackup != null) { + enableAutobackup.setOnPreferenceChangeListener((preference, newValue) -> { + if ((Boolean) newValue) { + new MaterialDialog.Builder(activity) + .content(R.string.settings_enable_automatic_backup_dialog) + .positiveText(R.string.confirm) + .negativeText(R.string.cancel) + .onPositive((dialog, which) -> { + PermissionsHelper.requestPermission(getActivity(), Manifest.permission + .WRITE_EXTERNAL_STORAGE, R + .string.permission_external_storage, activity.findViewById(R.id + .crouton_handle), () -> { + BackupHelper.startBackupService(Constants.AUTO_BACKUP_DIR); + enableAutobackup.setChecked(true); + }); + }) + .build().show(); + } else { + enableAutobackup.setChecked(false); + } + return false; + }); + } + + Preference importFromSpringpad = findPreference("settings_import_from_springpad"); + if (importFromSpringpad != null) { + importFromSpringpad.setOnPreferenceClickListener(arg0 -> { + Intent intent; + intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("application/zip"); + if (!IntentChecker.isAvailable(getActivity(), intent, null)) { + Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, + Toast.LENGTH_SHORT).show(); + return false; + } + startActivityForResult(intent, SPRINGPAD_IMPORT); + return false; + }); + } // Preference syncWithDrive = findPreference("settings_backup_drive"); // importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() { @@ -290,273 +287,261 @@ public void onResume() { // } // }); - - // Swiping action - final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash"); - if (swipeToTrash != null) { - if (prefs.getBoolean("settings_swipe_to_trash", false)) { - swipeToTrash.setChecked(true); - swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2)); - } else { - swipeToTrash.setChecked(false); - swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1)); - } - swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue) { - swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2)); - } else { - swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1)); - } - return true; - }); - } - - - // Show uncategorized notes in menu - final SwitchPreference showUncategorized = (SwitchPreference) findPreference(Constants - .PREF_SHOW_UNCATEGORIZED); - if (showUncategorized != null) { - showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> true); - } - - - // Show Automatically adds location to new notes - final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION); - if (autoLocation != null) { - autoLocation.setOnPreferenceChangeListener((preference, newValue) -> true); - } - - - // Maximum video attachment size - final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size"); - if (maxVideoSize != null) { - maxVideoSize.setSummary(getString(R.string.settings_max_video_size_summary) + ": " - + prefs.getString("settings_max_video_size", getString(R.string.not_set))); - maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> { - maxVideoSize.setSummary(getString(R.string.settings_max_video_size_summary) + ": " + newValue); - prefs.edit().putString("settings_max_video_size", newValue.toString()).apply(); - return false; - }); - } - - - // Set notes' protection password - Preference password = findPreference("settings_password"); - if (password != null) { - password.setOnPreferenceClickListener(preference -> { - Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class); - startActivity(passwordIntent); - return false; - }); - } - - - // Use password to grant application access - final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access"); - if (passwordAccess != null) { - if (prefs.getString(Constants.PREF_PASSWORD, null) == null) { - passwordAccess.setEnabled(false); - passwordAccess.setChecked(false); - } else { - passwordAccess.setEnabled(true); - } - passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> { - PasswordHelper.requestPassword(getActivity(), passwordConfirmed -> { - if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { - passwordAccess.setChecked((Boolean) newValue); - } - }); - return true; - }); - } - - - // Languages - ListPreference lang = (ListPreference) findPreference("settings_language"); - if (lang != null) { - String languageName = getResources().getConfiguration().locale.getDisplayName(); - lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale) - + languageName.substring(1, languageName.length())); - lang.setOnPreferenceChangeListener((preference, value) -> { - LanguageHelper.updateLanguage(getActivity(), value.toString()); - SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class); - return false; - }); - } - - - // Text size - final ListPreference textSize = (ListPreference) findPreference("settings_text_size"); - if (textSize != null) { - int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default")); - String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex]; - textSize.setSummary(textSizeString); - textSize.setOnPreferenceChangeListener((preference, newValue) -> { - int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString()); - String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1]; - textSize.setSummary(checklistString); - prefs.edit().putString("settings_text_size", newValue.toString()).apply(); - textSize.setValueIndex(textSizeIndex1); - return false; - }); - } - - - // Application's colors - final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app"); - if (colorsApp != null) { - int colorsAppIndex = colorsApp.findIndexOfValue(prefs.getString("settings_colors_app", - Constants.PREF_COLORS_APP_DEFAULT)); - String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex]; - colorsApp.setSummary(colorsAppString); - colorsApp.setOnPreferenceChangeListener((preference, newValue) -> { - int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString()); - String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1]; - colorsApp.setSummary(colorsAppString1); - prefs.edit().putString("settings_colors_app", newValue.toString()).apply(); - colorsApp.setValueIndex(colorsAppIndex1); - return false; - }); - } - - - // Checklists - final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior"); - if (checklist != null) { - int checklistIndex = checklist.findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0")); - String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex]; - checklist.setSummary(checklistString); - checklist.setOnPreferenceChangeListener((preference, newValue) -> { - int checklistIndex1 = checklist.findIndexOfValue(newValue.toString()); - String checklistString1 = getResources().getStringArray(R.array.checked_items_behavior) - [checklistIndex1]; - checklist.setSummary(checklistString1); - prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).apply(); - checklist.setValueIndex(checklistIndex1); - return false; - }); - } - - - // Widget's colors - final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget"); - if (colorsWidget != null) { - int colorsWidgetIndex = colorsWidget.findIndexOfValue(prefs.getString("settings_colors_widget", - Constants.PREF_COLORS_APP_DEFAULT)); - String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex]; - colorsWidget.setSummary(colorsWidgetString); - colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> { - int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString()); - String colorsWidgetString1 = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex1]; - colorsWidget.setSummary(colorsWidgetString1); - prefs.edit().putString("settings_colors_widget", newValue.toString()).apply(); - colorsWidget.setValueIndex(colorsWidgetIndex1); - return false; - }); - } - - // Notification snooze delay - final EditTextPreference snoozeDelay = (EditTextPreference) findPreference - ("settings_notification_snooze_delay"); - if (snoozeDelay != null) { - String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT); - snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze; - snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes)); - snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> { - String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants - .PREF_SNOOZE_DEFAULT : String.valueOf(newValue); - snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes)); - prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply(); - return false; - }); - } - - - // NotificationServiceListener shortcut - final Preference norificationServiceListenerPreference = findPreference - ("settings_notification_service_listener"); - if (norificationServiceListenerPreference != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { - getPreferenceScreen().removePreference(norificationServiceListenerPreference); - } - - - // Changelog - Preference changelog = findPreference("settings_changelog"); - if (changelog != null) { - changelog.setOnPreferenceClickListener(arg0 -> { - - ((OmniNotes)getActivity().getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog"); - - new MaterialDialog.Builder(activity) - .customView(R.layout.activity_changelog, false) - .positiveText(R.string.ok) - .build().show(); - return false; - }); - try { - changelog.setSummary(AppVersionHelper.getCurrentAppVersionName(getActivity())); - } catch (NameNotFoundException e) { - LogDelegate.e("Error retrieving version", e); - } - } - - - // Settings reset - Preference resetData = findPreference("reset_all_data"); - if (resetData != null) { - resetData.setOnPreferenceClickListener(arg0 -> { - - new MaterialDialog.Builder(activity) - .content(R.string.reset_all_data_confirmation) - .positiveText(R.string.confirm) - .onPositive((dialog, which) -> { - prefs.edit().clear().apply(); - File db = getActivity().getDatabasePath(Constants.DATABASE_NAME); - StorageHelper.delete(getActivity(), db.getAbsolutePath()); - File attachmentsDir = StorageHelper.getAttachmentDir(); - StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath()); - File cacheDir = StorageHelper.getCacheDir(getActivity()); - StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath()); - SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class); - }).build().show(); - - return false; - }); - } - - // Logs on files activation - final SwitchPreference enableFileLogging = (SwitchPreference) findPreference(Constants - .PREF_ENABLE_FILE_LOGGING); - if (enableFileLogging != null) { - enableFileLogging.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue) { - PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, R - .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), () -> enableFileLogging.setChecked(true)); - } else { - enableFileLogging.setChecked(false); - } - return false; - }); - } - - // Instructions - Preference instructions = findPreference("settings_tour_show_again"); - if (instructions != null) { - instructions.setOnPreferenceClickListener(arg0 -> { - new MaterialDialog.Builder(getActivity()) - .content(getString(R.string.settings_tour_show_again_summary) + "?") - .positiveText(R.string.confirm) - .onPositive((dialog, which) -> { - ((OmniNotes)getActivity().getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_tour_show_again"); - prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).apply(); - SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class); - }).build().show(); - return false; - }); - } - - - // Donations + // Swiping action + final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash"); + if (swipeToTrash != null) { + if (prefs.getBoolean("settings_swipe_to_trash", false)) { + swipeToTrash.setChecked(true); + swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2)); + } else { + swipeToTrash.setChecked(false); + swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1)); + } + swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> { + if ((Boolean) newValue) { + swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2)); + } else { + swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1)); + } + return true; + }); + } + + // Show uncategorized notes in menu + final SwitchPreference showUncategorized = (SwitchPreference) findPreference(Constants + .PREF_SHOW_UNCATEGORIZED); + if (showUncategorized != null) { + showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> true); + } + + // Show Automatically adds location to new notes + final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION); + if (autoLocation != null) { + autoLocation.setOnPreferenceChangeListener((preference, newValue) -> true); + } + + // Maximum video attachment size + final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size"); + if (maxVideoSize != null) { + maxVideoSize.setSummary(getString(R.string.settings_max_video_size_summary) + ": " + + prefs.getString("settings_max_video_size", getString(R.string.not_set))); + maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> { + maxVideoSize.setSummary(getString(R.string.settings_max_video_size_summary) + ": " + newValue); + prefs.edit().putString("settings_max_video_size", newValue.toString()).apply(); + return false; + }); + } + + // Set notes' protection password + Preference password = findPreference("settings_password"); + if (password != null) { + password.setOnPreferenceClickListener(preference -> { + Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class); + startActivity(passwordIntent); + return false; + }); + } + + // Use password to grant application access + final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access"); + if (passwordAccess != null) { + if (prefs.getString(Constants.PREF_PASSWORD, null) == null) { + passwordAccess.setEnabled(false); + passwordAccess.setChecked(false); + } else { + passwordAccess.setEnabled(true); + } + passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> { + PasswordHelper.requestPassword(getActivity(), passwordConfirmed -> { + if (passwordConfirmed.equals(PasswordValidator.Result.SUCCEED)) { + passwordAccess.setChecked((Boolean) newValue); + } + }); + return true; + }); + } + + // Languages + ListPreference lang = (ListPreference) findPreference("settings_language"); + if (lang != null) { + String languageName = getResources().getConfiguration().locale.getDisplayName(); + lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale) + + languageName.substring(1)); + lang.setOnPreferenceChangeListener((preference, value) -> { + LanguageHelper.updateLanguage(getActivity(), value.toString()); + SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class); + return false; + }); + } + + // Text size + final ListPreference textSize = (ListPreference) findPreference("settings_text_size"); + if (textSize != null) { + int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default")); + String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex]; + textSize.setSummary(textSizeString); + textSize.setOnPreferenceChangeListener((preference, newValue) -> { + int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString()); + String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1]; + textSize.setSummary(checklistString); + prefs.edit().putString("settings_text_size", newValue.toString()).apply(); + textSize.setValueIndex(textSizeIndex1); + return false; + }); + } + + // Application's colors + final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app"); + if (colorsApp != null) { + int colorsAppIndex = colorsApp.findIndexOfValue(prefs.getString("settings_colors_app", + Constants.PREF_COLORS_APP_DEFAULT)); + String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex]; + colorsApp.setSummary(colorsAppString); + colorsApp.setOnPreferenceChangeListener((preference, newValue) -> { + int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString()); + String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1]; + colorsApp.setSummary(colorsAppString1); + prefs.edit().putString("settings_colors_app", newValue.toString()).apply(); + colorsApp.setValueIndex(colorsAppIndex1); + return false; + }); + } + + // Checklists + final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior"); + if (checklist != null) { + int checklistIndex = checklist.findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0")); + String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex]; + checklist.setSummary(checklistString); + checklist.setOnPreferenceChangeListener((preference, newValue) -> { + int checklistIndex1 = checklist.findIndexOfValue(newValue.toString()); + String checklistString1 = getResources().getStringArray(R.array.checked_items_behavior) + [checklistIndex1]; + checklist.setSummary(checklistString1); + prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).apply(); + checklist.setValueIndex(checklistIndex1); + return false; + }); + } + + // Widget's colors + final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget"); + if (colorsWidget != null) { + int colorsWidgetIndex = colorsWidget.findIndexOfValue(prefs.getString("settings_colors_widget", + Constants.PREF_COLORS_APP_DEFAULT)); + String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex]; + colorsWidget.setSummary(colorsWidgetString); + colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> { + int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString()); + String colorsWidgetString1 = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex1]; + colorsWidget.setSummary(colorsWidgetString1); + prefs.edit().putString("settings_colors_widget", newValue.toString()).apply(); + colorsWidget.setValueIndex(colorsWidgetIndex1); + return false; + }); + } + + // Notification snooze delay + final EditTextPreference snoozeDelay = (EditTextPreference) findPreference + ("settings_notification_snooze_delay"); + if (snoozeDelay != null) { + String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT); + snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze; + snoozeDelay.setSummary(snooze + " " + getString(R.string.minutes)); + snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> { + String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants + .PREF_SNOOZE_DEFAULT : String.valueOf(newValue); + snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes)); + prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply(); + return false; + }); + } + + // NotificationServiceListener shortcut + final Preference norificationServiceListenerPreference = findPreference + ("settings_notification_service_listener"); + if (norificationServiceListenerPreference != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { + getPreferenceScreen().removePreference(norificationServiceListenerPreference); + } + + // Changelog + Preference changelog = findPreference("settings_changelog"); + if (changelog != null) { + changelog.setOnPreferenceClickListener(arg0 -> { + + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, + "settings_changelog"); + + new MaterialDialog.Builder(activity) + .customView(R.layout.activity_changelog, false) + .positiveText(R.string.ok) + .build().show(); + return false; + }); + try { + changelog.setSummary(AppVersionHelper.getCurrentAppVersionName(getActivity())); + } catch (NameNotFoundException e) { + LogDelegate.e("Error retrieving version", e); + } + } + + // Settings reset + Preference resetData = findPreference("reset_all_data"); + if (resetData != null) { + resetData.setOnPreferenceClickListener(arg0 -> { + + new MaterialDialog.Builder(activity) + .content(R.string.reset_all_data_confirmation) + .positiveText(R.string.confirm) + .onPositive((dialog, which) -> { + prefs.edit().clear().apply(); + File db = getActivity().getDatabasePath(Constants.DATABASE_NAME); + StorageHelper.delete(getActivity(), db.getAbsolutePath()); + File attachmentsDir = StorageHelper.getAttachmentDir(); + StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath()); + File cacheDir = StorageHelper.getCacheDir(getActivity()); + StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath()); + SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class); + }).build().show(); + + return false; + }); + } + + // Logs on files activation + final SwitchPreference enableFileLogging = (SwitchPreference) findPreference(Constants + .PREF_ENABLE_FILE_LOGGING); + if (enableFileLogging != null) { + enableFileLogging.setOnPreferenceChangeListener((preference, newValue) -> { + if ((Boolean) newValue) { + PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE, R + .string.permission_external_storage, activity.findViewById(R.id.crouton_handle), + () -> enableFileLogging.setChecked(true)); + } else { + enableFileLogging.setChecked(false); + } + return false; + }); + } + + // Instructions + Preference instructions = findPreference("settings_tour_show_again"); + if (instructions != null) { + instructions.setOnPreferenceClickListener(arg0 -> { + new MaterialDialog.Builder(getActivity()) + .content(getString(R.string.settings_tour_show_again_summary) + "?") + .positiveText(R.string.confirm) + .onPositive((dialog, which) -> { + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackEvent( + AnalyticsHelper.CATEGORIES.SETTING, "settings_tour_show_again"); + prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).apply(); + SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class); + }).build().show(); + return false; + }); + } + + // Donations // Preference donation = findPreference("settings_donation"); // if (donation != null) { // donation.setOnPreferenceClickListener(new OnPreferenceClickListener() { @@ -597,174 +582,176 @@ public void onResume() { // } // }); // } - } - - - private void importNotes() { - final List backups = asList(StorageHelper.getExternalStoragePublicDir().list()); - reverse(backups); - - if (backups.isEmpty()) { - ((SettingsActivity)getActivity()).showMessage(R.string.no_backups_available, ONStyle.WARN); - } else { - - MaterialDialog importDialog = new MaterialDialog.Builder(getActivity()) - .title(R.string.data_import_message) - .items(backups) - .positiveText(R.string.confirm) - .onPositive((dialog, which) -> { - - }).build(); - - // OnShow is overridden to allow long-click on item so user can remove them - importDialog.setOnShowListener(dialog -> { - - ListView lv = importDialog.getListView(); - assert lv != null; - lv.setOnItemClickListener((parent, view, position, id) -> { - - // Retrieves backup size - File backupDir = StorageHelper.getBackupDir(backups.get(position)); - long size = StorageHelper.getSize(backupDir) / 1024; - String sizeString = size > 1024 ? size / 1024 + "Mb" : size + "Kb"; - - // Check preference presence - String prefName = StorageHelper.getSharedPreferencesFile(getActivity()).getName(); - boolean hasPreferences = (new File(backupDir, prefName)).exists(); - - String message = backups.get(position) - + " (" + sizeString - + (hasPreferences ? " " + getString(R.string.settings_included) : "") - + ")"; - - new MaterialDialog.Builder(getActivity()) - .title(R.string.confirm_restoring_backup) - .content(message) - .positiveText(R.string.confirm) - .onPositive((dialog1, which) -> { - ((OmniNotes)getActivity().getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, - "settings_import_data"); - - importDialog.dismiss(); - - // An IntentService will be launched to accomplish the import task - Intent service = new Intent(getActivity(), - DataBackupIntentService.class); - service.setAction(DataBackupIntentService.ACTION_DATA_IMPORT); - service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, - backups.get(position)); - getActivity().startService(service); - }).build().show(); - }); - - // Creation of backup removal dialog - lv.setOnItemLongClickListener((parent, view, position, id) -> { - - // Retrieves backup size - File backupDir = StorageHelper.getBackupDir(backups.get(position)); - long size = StorageHelper.getSize(backupDir) / 1024; - String sizeString = size > 1024 ? size / 1024 + "Mb" : size + "Kb"; - - new MaterialDialog.Builder(getActivity()) - .title(R.string.confirm_removing_backup) - .content(backups.get(position) + "" + " (" + sizeString + ")") - .positiveText(R.string.confirm) - .onPositive((dialog12, which) -> { - importDialog.dismiss(); - // An IntentService will be launched to accomplish the deletion task - Intent service = new Intent(getActivity(), - DataBackupIntentService.class); - service.setAction(DataBackupIntentService.ACTION_DATA_DELETE); - service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, - backups.get(position)); - getActivity().startService(service); - }).build().show(); - - return true; - }); - }); - - importDialog.show(); - } - } - - - private void export(View v) { - final List backups = asList(StorageHelper.getExternalStoragePublicDir().list()); - - // Sets default export file name - SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_EXPORT); - String fileName = sdf.format(Calendar.getInstance().getTime()); - final EditText fileNameEditText = v.findViewById(R.id.export_file_name); - final TextView backupExistingTextView = v.findViewById(R.id.backup_existing); - fileNameEditText.setHint(fileName); - fileNameEditText.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { - - } - - - @Override - public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { - - } - - - @Override - public void afterTextChanged(Editable arg0) { - - if (backups.contains(arg0.toString())) { - backupExistingTextView.setText(R.string.backup_existing); - } else { - backupExistingTextView.setText(""); - } - } - }); - - new MaterialDialog.Builder(getActivity()) - .title(R.string.data_export_message) - .customView(v, false) - .positiveText(R.string.confirm) - .onPositive((dialog, which) -> { - ((OmniNotes)getActivity().getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_export_data"); - String backupName = StringUtils.isEmpty(fileNameEditText.getText().toString()) ? - fileNameEditText.getHint().toString() : fileNameEditText.getText().toString(); - BackupHelper.startBackupService(backupName); - }).build().show(); - } - - - @Override - public void onStart() { - ((OmniNotes)getActivity().getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); - super.onStart(); - } - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) { - if (resultCode == Activity.RESULT_OK) { - switch (requestCode) { - case SPRINGPAD_IMPORT: - Uri filesUri = intent.getData(); - String path = FileHelper.getPath(getActivity(), filesUri); - // An IntentService will be launched to accomplish the import task - Intent service = new Intent(getActivity(), DataBackupIntentService.class); - service.setAction(SpringImportHelper.ACTION_DATA_IMPORT_SPRINGPAD); - service.putExtra(SpringImportHelper.EXTRA_SPRINGPAD_BACKUP, path); - getActivity().startService(service); - break; - - case RINGTONE_REQUEST_CODE: - Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); - String notificationSound = uri == null ? null : uri.toString(); - prefs.edit().putString("settings_notification_ringtone", notificationSound).apply(); - break; - - default: - LogDelegate.e("Wrong element choosen: " + requestCode); - } - } - } + } + + + private void importNotes () { + final List backups = asList(StorageHelper.getExternalStoragePublicDir().list()); + reverse(backups); + + if (backups.isEmpty()) { + ((SettingsActivity) getActivity()).showMessage(R.string.no_backups_available, ONStyle.WARN); + } else { + + MaterialDialog importDialog = new MaterialDialog.Builder(getActivity()) + .title(R.string.data_import_message) + .items(backups) + .positiveText(R.string.confirm) + .onPositive((dialog, which) -> { + + }).build(); + + // OnShow is overridden to allow long-click on item so user can remove them + importDialog.setOnShowListener(dialog -> { + + ListView lv = importDialog.getListView(); + assert lv != null; + lv.setOnItemClickListener((parent, view, position, id) -> { + + // Retrieves backup size + File backupDir = StorageHelper.getBackupDir(backups.get(position)); + long size = StorageHelper.getSize(backupDir) / 1024; + String sizeString = size > 1024 ? size / 1024 + "Mb" : size + "Kb"; + + // Check preference presence + String prefName = StorageHelper.getSharedPreferencesFile(getActivity()).getName(); + boolean hasPreferences = (new File(backupDir, prefName)).exists(); + + String message = backups.get(position) + + " (" + sizeString + + (hasPreferences ? " " + getString(R.string.settings_included) : "") + + ")"; + + new MaterialDialog.Builder(getActivity()) + .title(R.string.confirm_restoring_backup) + .content(message) + .positiveText(R.string.confirm) + .onPositive((dialog1, which) -> { + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackEvent( + AnalyticsHelper.CATEGORIES.SETTING, + "settings_import_data"); + + importDialog.dismiss(); + + // An IntentService will be launched to accomplish the import task + Intent service = new Intent(getActivity(), + DataBackupIntentService.class); + service.setAction(DataBackupIntentService.ACTION_DATA_IMPORT); + service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, + backups.get(position)); + getActivity().startService(service); + }).build().show(); + }); + + // Creation of backup removal dialog + lv.setOnItemLongClickListener((parent, view, position, id) -> { + + // Retrieves backup size + File backupDir = StorageHelper.getBackupDir(backups.get(position)); + long size = StorageHelper.getSize(backupDir) / 1024; + String sizeString = size > 1024 ? size / 1024 + "Mb" : size + "Kb"; + + new MaterialDialog.Builder(getActivity()) + .title(R.string.confirm_removing_backup) + .content(backups.get(position) + "" + " (" + sizeString + ")") + .positiveText(R.string.confirm) + .onPositive((dialog12, which) -> { + importDialog.dismiss(); + // An IntentService will be launched to accomplish the deletion task + Intent service = new Intent(getActivity(), + DataBackupIntentService.class); + service.setAction(DataBackupIntentService.ACTION_DATA_DELETE); + service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, + backups.get(position)); + getActivity().startService(service); + }).build().show(); + + return true; + }); + }); + + importDialog.show(); + } + } + + + private void export (View v) { + final List backups = asList(StorageHelper.getExternalStoragePublicDir().list()); + + // Sets default export file name + SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_EXPORT); + String fileName = sdf.format(Calendar.getInstance().getTime()); + final EditText fileNameEditText = v.findViewById(R.id.export_file_name); + final TextView backupExistingTextView = v.findViewById(R.id.backup_existing); + fileNameEditText.setHint(fileName); + fileNameEditText.addTextChangedListener(new TextWatcher() { + @Override + public void onTextChanged (CharSequence arg0, int arg1, int arg2, int arg3) { + + } + + + @Override + public void beforeTextChanged (CharSequence arg0, int arg1, int arg2, int arg3) { + + } + + + @Override + public void afterTextChanged (Editable arg0) { + + if (backups.contains(arg0.toString())) { + backupExistingTextView.setText(R.string.backup_existing); + } else { + backupExistingTextView.setText(""); + } + } + }); + + new MaterialDialog.Builder(getActivity()) + .title(R.string.data_export_message) + .customView(v, false) + .positiveText(R.string.confirm) + .onPositive((dialog, which) -> { + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackEvent( + AnalyticsHelper.CATEGORIES.SETTING, "settings_export_data"); + String backupName = StringUtils.isEmpty(fileNameEditText.getText().toString()) ? + fileNameEditText.getHint().toString() : fileNameEditText.getText().toString(); + BackupHelper.startBackupService(backupName); + }).build().show(); + } + + + @Override + public void onStart () { + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); + super.onStart(); + } + + + @Override + public void onActivityResult (int requestCode, int resultCode, Intent intent) { + if (resultCode == Activity.RESULT_OK) { + switch (requestCode) { + case SPRINGPAD_IMPORT: + Uri filesUri = intent.getData(); + String path = FileHelper.getPath(getActivity(), filesUri); + // An IntentService will be launched to accomplish the import task + Intent service = new Intent(getActivity(), DataBackupIntentService.class); + service.setAction(SpringImportHelper.ACTION_DATA_IMPORT_SPRINGPAD); + service.putExtra(SpringImportHelper.EXTRA_SPRINGPAD_BACKUP, path); + getActivity().startService(service); + break; + + case RINGTONE_REQUEST_CODE: + Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); + String notificationSound = uri == null ? null : uri.toString(); + prefs.edit().putString("settings_notification_ringtone", notificationSound).apply(); + break; + + default: + LogDelegate.e("Wrong element choosen: " + requestCode); + } + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/ShortcutActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/ShortcutActivity.java index 9a5f467d8e..cc55a58aaa 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/ShortcutActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/ShortcutActivity.java @@ -20,27 +20,26 @@ import android.app.Activity; import android.content.Intent; import android.os.Bundle; - import it.feio.android.omninotes.utils.Constants; public class ShortcutActivity extends Activity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - Intent shortcutIntent = new Intent(this, MainActivity.class); - shortcutIntent.setAction(Constants.ACTION_SHORTCUT_WIDGET); - Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable - .shortcut_icon); + Intent shortcutIntent = new Intent(this, MainActivity.class); + shortcutIntent.setAction(Constants.ACTION_SHORTCUT_WIDGET); + Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable + .shortcut_icon); - Intent intent = new Intent(); - intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); - intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.add_note)); - intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); - setResult(RESULT_OK, intent); + Intent intent = new Intent(); + intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.add_note)); + intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); + setResult(RESULT_OK, intent); - finish(); - } + finish(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/SketchFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/SketchFragment.java index ac58db9cf2..b0f27556a2 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/SketchFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/SketchFragment.java @@ -39,296 +39,303 @@ import android.widget.PopupWindow; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; - +import butterknife.BindView; +import butterknife.ButterKnife; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.larswerkman.holocolorpicker.ColorPicker; import com.larswerkman.holocolorpicker.OpacityBar; import com.larswerkman.holocolorpicker.SVBar; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; - -import butterknife.BindView; -import butterknife.ButterKnife; import it.feio.android.checklistview.utils.AlphaManager; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.ONStyle; import it.feio.android.omninotes.models.listeners.OnDrawChangedListener; import it.feio.android.omninotes.models.views.SketchView; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; public class SketchFragment extends Fragment implements OnDrawChangedListener { - @BindView(R.id.sketch_stroke) ImageView stroke; - @BindView(R.id.sketch_eraser) ImageView eraser; - @BindView(R.id.drawing) SketchView mSketchView; - @BindView(R.id.sketch_undo) ImageView undo; - @BindView(R.id.sketch_redo) ImageView redo; - @BindView(R.id.sketch_erase) ImageView erase; - private int seekBarStrokeProgress, seekBarEraserProgress; - private View popupLayout, popupEraserLayout; - private ImageView strokeImageView, eraserImageView; - private int size; - private ColorPicker mColorPicker; - private int oldColor; - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - setRetainInstance(false); - } - - - @Override - public void onStart() { - ((OmniNotes)getActivity().getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); - - super.onStart(); + @BindView(R.id.sketch_stroke) + ImageView stroke; + @BindView(R.id.sketch_eraser) + ImageView eraser; + @BindView(R.id.drawing) + SketchView mSketchView; + @BindView(R.id.sketch_undo) + ImageView undo; + @BindView(R.id.sketch_redo) + ImageView redo; + @BindView(R.id.sketch_erase) + ImageView erase; + private int seekBarStrokeProgress, seekBarEraserProgress; + private View popupLayout, popupEraserLayout; + private ImageView strokeImageView, eraserImageView; + private int size; + private ColorPicker mColorPicker; + private int oldColor; + + + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setHasOptionsMenu(true); + setRetainInstance(false); + } + + + @Override + public void onStart () { + ((OmniNotes) getActivity().getApplication()).getAnalyticsHelper().trackScreenView(getClass().getName()); + + super.onStart(); + } + + + @SuppressWarnings("unchecked") + @Override + public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_sketch, container, false); + ButterKnife.bind(this, view); + return view; + } + + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + getMainActivity().getToolbar().setNavigationOnClickListener(v -> getActivity().onBackPressed()); + + mSketchView.setOnDrawChangedListener(this); + + Uri baseUri = getArguments().getParcelable("base"); + if (baseUri != null) { + Bitmap bmp; + try { + bmp = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(baseUri)); + mSketchView.setBackgroundBitmap(getActivity(), bmp); + } catch (FileNotFoundException e) { + LogDelegate.e("Error replacing sketch bitmap background", e); + } } - - @SuppressWarnings("unchecked") - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_sketch, container, false); - ButterKnife.bind(this, view); - return view; + // Show the Up button in the action bar. + if (getMainActivity().getSupportActionBar() != null) { + getMainActivity().getSupportActionBar().setDisplayShowTitleEnabled(true); + getMainActivity().getSupportActionBar().setTitle(R.string.title_activity_sketch); + getMainActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true); } - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - getMainActivity().getToolbar().setNavigationOnClickListener(v -> getActivity().onBackPressed()); - - mSketchView.setOnDrawChangedListener(this); - - Uri baseUri = getArguments().getParcelable("base"); - if (baseUri != null) { - Bitmap bmp; - try { - bmp = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(baseUri)); - mSketchView.setBackgroundBitmap(getActivity(), bmp); - } catch (FileNotFoundException e) { - LogDelegate.e("Error replacing sketch bitmap background", e); - } - } - - // Show the Up button in the action bar. - if (getMainActivity().getSupportActionBar() != null) { - getMainActivity().getSupportActionBar().setDisplayShowTitleEnabled(true); - getMainActivity().getSupportActionBar().setTitle(R.string.title_activity_sketch); - getMainActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true); - } - - stroke.setOnClickListener(v -> { - if (mSketchView.getMode() == SketchView.STROKE) { - showPopup(v, SketchView.STROKE); - } else { - mSketchView.setMode(SketchView.STROKE); - AlphaManager.setAlpha(eraser, 0.4f); - AlphaManager.setAlpha(stroke, 1f); - } - }); - + stroke.setOnClickListener(v -> { + if (mSketchView.getMode() == SketchView.STROKE) { + showPopup(v, SketchView.STROKE); + } else { + mSketchView.setMode(SketchView.STROKE); AlphaManager.setAlpha(eraser, 0.4f); - eraser.setOnClickListener(v -> { - if (mSketchView.getMode() == SketchView.ERASER) { - showPopup(v, SketchView.ERASER); - } else { - mSketchView.setMode(SketchView.ERASER); - AlphaManager.setAlpha(stroke, 0.4f); - AlphaManager.setAlpha(eraser, 1f); - } - }); - - undo.setOnClickListener(v -> mSketchView.undo()); - - redo.setOnClickListener(v -> mSketchView.redo()); - - erase.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - askForErase(); - } - - private void askForErase() { - new MaterialDialog.Builder(getActivity()) - .content(R.string.erase_sketch) - .positiveText(R.string.confirm) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - mSketchView.erase(); - } - }).build().show(); - } - }); - - - // Inflate the popup_layout.xml - LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(AppCompatActivity.LAYOUT_INFLATER_SERVICE); - popupLayout = inflater.inflate(R.layout.popup_sketch_stroke, null); - // And the one for eraser - LayoutInflater inflaterEraser = (LayoutInflater) getActivity().getSystemService(AppCompatActivity.LAYOUT_INFLATER_SERVICE); - popupEraserLayout = inflaterEraser.inflate(R.layout.popup_sketch_eraser, null); - - // Actual stroke shape size is retrieved - strokeImageView = (ImageView) popupLayout.findViewById(R.id.stroke_circle); - final Drawable circleDrawable = getResources().getDrawable(R.drawable.circle); - size = circleDrawable.getIntrinsicWidth(); - // Actual eraser shape size is retrieved - eraserImageView = (ImageView) popupEraserLayout.findViewById(R.id.stroke_circle); - size = circleDrawable.getIntrinsicWidth(); - - setSeekbarProgress(SketchView.DEFAULT_STROKE_SIZE, SketchView.STROKE); - setSeekbarProgress(SketchView.DEFAULT_ERASER_SIZE, SketchView.ERASER); - - // Stroke color picker initialization and event managing - mColorPicker = (ColorPicker) popupLayout.findViewById(R.id.stroke_color_picker); - mColorPicker.addSVBar((SVBar) popupLayout.findViewById(R.id.svbar)); - mColorPicker.addOpacityBar((OpacityBar) popupLayout.findViewById(R.id.opacitybar)); - mColorPicker.setOnColorChangedListener(mSketchView::setStrokeColor); - mColorPicker.setColor(mSketchView.getStrokeColor()); - mColorPicker.setOldCenterColor(mSketchView.getStrokeColor()); + AlphaManager.setAlpha(stroke, 1f); + } + }); + + AlphaManager.setAlpha(eraser, 0.4f); + eraser.setOnClickListener(v -> { + if (mSketchView.getMode() == SketchView.ERASER) { + showPopup(v, SketchView.ERASER); + } else { + mSketchView.setMode(SketchView.ERASER); + AlphaManager.setAlpha(stroke, 0.4f); + AlphaManager.setAlpha(eraser, 1f); + } + }); + + undo.setOnClickListener(v -> mSketchView.undo()); + + redo.setOnClickListener(v -> mSketchView.redo()); + + erase.setOnClickListener(new OnClickListener() { + @Override + public void onClick (View v) { + askForErase(); + } + + private void askForErase () { + new MaterialDialog.Builder(getActivity()) + .content(R.string.erase_sketch) + .positiveText(R.string.confirm) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + mSketchView.erase(); + } + }).build().show(); + } + }); + + // Inflate the popup_layout.xml + LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService( + AppCompatActivity.LAYOUT_INFLATER_SERVICE); + popupLayout = inflater.inflate(R.layout.popup_sketch_stroke, null); + // And the one for eraser + LayoutInflater inflaterEraser = (LayoutInflater) getActivity().getSystemService( + AppCompatActivity.LAYOUT_INFLATER_SERVICE); + popupEraserLayout = inflaterEraser.inflate(R.layout.popup_sketch_eraser, null); + + // Actual stroke shape size is retrieved + strokeImageView = popupLayout.findViewById(R.id.stroke_circle); + final Drawable circleDrawable = getResources().getDrawable(R.drawable.circle); + size = circleDrawable.getIntrinsicWidth(); + // Actual eraser shape size is retrieved + eraserImageView = popupEraserLayout.findViewById(R.id.stroke_circle); + size = circleDrawable.getIntrinsicWidth(); + + setSeekbarProgress(SketchView.DEFAULT_STROKE_SIZE, SketchView.STROKE); + setSeekbarProgress(SketchView.DEFAULT_ERASER_SIZE, SketchView.ERASER); + + // Stroke color picker initialization and event managing + mColorPicker = popupLayout.findViewById(R.id.stroke_color_picker); + mColorPicker.addSVBar(popupLayout.findViewById(R.id.svbar)); + mColorPicker.addOpacityBar(popupLayout.findViewById(R.id.opacitybar)); + mColorPicker.setOnColorChangedListener(mSketchView::setStrokeColor); + mColorPicker.setColor(mSketchView.getStrokeColor()); + mColorPicker.setOldCenterColor(mSketchView.getStrokeColor()); + } + + @Override + public boolean onOptionsItemSelected (MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + getActivity().onBackPressed(); + break; + default: + LogDelegate.e("Wrong element choosen: " + item.getItemId()); } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - getActivity().onBackPressed(); - break; - default: - LogDelegate.e("Wrong element choosen: " + item.getItemId()); + return super.onOptionsItemSelected(item); + } + + + public void save () { + Bitmap bitmap = mSketchView.getBitmap(); + if (bitmap != null) { + + try { + Uri uri = getArguments().getParcelable(MediaStore.EXTRA_OUTPUT); + File bitmapFile = new File(uri.getPath()); + FileOutputStream out = new FileOutputStream(bitmapFile); + bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); + out.close(); + if (bitmapFile.exists()) { + getMainActivity().sketchUri = uri; + } else { + getMainActivity().showMessage(R.string.error, ONStyle.ALERT); } - return super.onOptionsItemSelected(item); - } - - public void save() { - Bitmap bitmap = mSketchView.getBitmap(); - if (bitmap != null) { - - try { - Uri uri = getArguments().getParcelable(MediaStore.EXTRA_OUTPUT); - File bitmapFile = new File(uri.getPath()); - FileOutputStream out = new FileOutputStream(bitmapFile); - bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); - out.close(); - if (bitmapFile.exists()) { - getMainActivity().sketchUri = uri; - } else { - getMainActivity().showMessage(R.string.error, ONStyle.ALERT); - } - - } catch (Exception e) { - LogDelegate.e("Error writing sketch image data", e); - } - } + } catch (Exception e) { + LogDelegate.e("Error writing sketch image data", e); + } } - - - // The method that displays the popup. - private void showPopup(View anchor, final int eraserOrStroke) { - - boolean isErasing = eraserOrStroke == SketchView.ERASER; - - oldColor = mColorPicker.getColor(); - - DisplayMetrics metrics = new DisplayMetrics(); - getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); - - // Creating the PopupWindow - PopupWindow popup = new PopupWindow(getActivity()); - popup.setContentView(isErasing ? popupEraserLayout : popupLayout); - popup.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); - popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); - popup.setFocusable(true); - popup.setOnDismissListener(() -> { - if (mColorPicker.getColor() != oldColor) - mColorPicker.setOldCenterColor(oldColor); - }); - - // Clear the default translucent background - popup.setBackgroundDrawable(new BitmapDrawable()); - - // Displaying the popup at the specified location, + offsets (transformed - // dp to pixel to support multiple screen sizes) - popup.showAsDropDown(anchor); - - // Stroke size seekbar initialization and event managing - SeekBar mSeekBar; - mSeekBar = (SeekBar) (isErasing ? popupEraserLayout - .findViewById(R.id.stroke_seekbar) : popupLayout - .findViewById(R.id.stroke_seekbar)); - mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } - - - @Override - public void onProgressChanged(SeekBar seekBar, int progress, - boolean fromUser) { - // When the seekbar is moved a new size is calculated and the new shape - // is positioned centrally into the ImageView - setSeekbarProgress(progress, eraserOrStroke); - } - }); - int progress = isErasing ? seekBarEraserProgress : seekBarStrokeProgress; - mSeekBar.setProgress(progress); + } + + + // The method that displays the popup. + private void showPopup (View anchor, final int eraserOrStroke) { + + boolean isErasing = eraserOrStroke == SketchView.ERASER; + + oldColor = mColorPicker.getColor(); + + DisplayMetrics metrics = new DisplayMetrics(); + getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); + + // Creating the PopupWindow + PopupWindow popup = new PopupWindow(getActivity()); + popup.setContentView(isErasing ? popupEraserLayout : popupLayout); + popup.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); + popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); + popup.setFocusable(true); + popup.setOnDismissListener(() -> { + if (mColorPicker.getColor() != oldColor) { + mColorPicker.setOldCenterColor(oldColor); + } + }); + + // Clear the default translucent background + popup.setBackgroundDrawable(new BitmapDrawable()); + + // Displaying the popup at the specified location, + offsets (transformed + // dp to pixel to support multiple screen sizes) + popup.showAsDropDown(anchor); + + // Stroke size seekbar initialization and event managing + SeekBar mSeekBar; + mSeekBar = (SeekBar) (isErasing ? popupEraserLayout + .findViewById(R.id.stroke_seekbar) : popupLayout + .findViewById(R.id.stroke_seekbar)); + mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { + @Override + public void onStopTrackingTouch (SeekBar seekBar) { + } + + + @Override + public void onStartTrackingTouch (SeekBar seekBar) { + } + + + @Override + public void onProgressChanged (SeekBar seekBar, int progress, + boolean fromUser) { + // When the seekbar is moved a new size is calculated and the new shape + // is positioned centrally into the ImageView + setSeekbarProgress(progress, eraserOrStroke); + } + }); + int progress = isErasing ? seekBarEraserProgress : seekBarStrokeProgress; + mSeekBar.setProgress(progress); + } + + + protected void setSeekbarProgress (int progress, int eraserOrStroke) { + int calcProgress = progress > 1 ? progress : 1; + + int newSize = Math.round((size / 100f) * calcProgress); + int offset = (size - newSize) / 2; + LogDelegate.v("Stroke size " + newSize + " (" + calcProgress + "%)"); + + LayoutParams lp = new LayoutParams(newSize, newSize); + lp.setMargins(offset, offset, offset, offset); + if (eraserOrStroke == SketchView.STROKE) { + strokeImageView.setLayoutParams(lp); + seekBarStrokeProgress = progress; + } else { + eraserImageView.setLayoutParams(lp); + seekBarEraserProgress = progress; } + mSketchView.setSize(newSize, eraserOrStroke); + } - protected void setSeekbarProgress(int progress, int eraserOrStroke) { - int calcProgress = progress > 1 ? progress : 1; - - int newSize = Math.round((size / 100f) * calcProgress); - int offset = (size - newSize) / 2; - LogDelegate.v("Stroke size " + newSize + " (" + calcProgress + "%)"); - - LayoutParams lp = new LayoutParams(newSize, newSize); - lp.setMargins(offset, offset, offset, offset); - if (eraserOrStroke == SketchView.STROKE) { - strokeImageView.setLayoutParams(lp); - seekBarStrokeProgress = progress; - } else { - eraserImageView.setLayoutParams(lp); - seekBarEraserProgress = progress; - } - mSketchView.setSize(newSize, eraserOrStroke); + @Override + public void onDrawChanged () { + // Undo + if (mSketchView.getPaths().size() > 0) { + AlphaManager.setAlpha(undo, 1f); + } else { + AlphaManager.setAlpha(undo, 0.4f); } - - - @Override - public void onDrawChanged() { - // Undo - if (mSketchView.getPaths().size() > 0) - AlphaManager.setAlpha(undo, 1f); - else - AlphaManager.setAlpha(undo, 0.4f); - // Redo - if (mSketchView.getUndoneCount() > 0) - AlphaManager.setAlpha(redo, 1f); - else - AlphaManager.setAlpha(redo, 0.4f); + // Redo + if (mSketchView.getUndoneCount() > 0) { + AlphaManager.setAlpha(redo, 1f); + } else { + AlphaManager.setAlpha(redo, 0.4f); } + } - private MainActivity getMainActivity() { - return (MainActivity) getActivity(); - } + private MainActivity getMainActivity () { + return (MainActivity) getActivity(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/SnoozeActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/SnoozeActivity.java index 129683dae4..d8205e0f87 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/SnoozeActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/SnoozeActivity.java @@ -29,10 +29,6 @@ import android.text.TextUtils; import android.widget.DatePicker; import android.widget.TimePicker; - -import java.util.Arrays; -import java.util.Calendar; - import it.feio.android.omninotes.async.notes.SaveNoteTask; import it.feio.android.omninotes.helpers.date.DateHelper; import it.feio.android.omninotes.models.Note; @@ -41,131 +37,134 @@ import it.feio.android.omninotes.utils.ReminderHelper; import it.feio.android.omninotes.utils.date.DateUtils; import it.feio.android.omninotes.utils.date.ReminderPickers; +import java.util.Arrays; +import java.util.Calendar; -public class SnoozeActivity extends AppCompatActivity implements OnReminderPickedListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { - - private Note note; - private Note[] notes; - private ReminderPickers onDateSetListener; - private ReminderPickers onTimeSetListener; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - if (getIntent().getParcelableExtra(Constants.INTENT_NOTE) != null) { - note = getIntent().getParcelableExtra(Constants.INTENT_NOTE); - manageNotification(getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS)); - } else { - Object[] notesObjs = (Object[]) getIntent().getExtras().get(Constants.INTENT_NOTE); - notes = Arrays.copyOf(notesObjs, notesObjs.length, Note[].class); - postpone(getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS), DateUtils.getNextMinute(), null); - } - } +public class SnoozeActivity extends AppCompatActivity implements OnReminderPickedListener, + DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { + private Note note; + private Note[] notes; + private ReminderPickers onDateSetListener; + private ReminderPickers onTimeSetListener; - private void manageNotification(SharedPreferences prefs) { - if (Constants.ACTION_DISMISS.equals(getIntent().getAction())) { - setNextRecurrentReminder(note); - finish(); - } else if (Constants.ACTION_SNOOZE.equals(getIntent().getAction())) { - String snoozeDelay = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT); - long newReminder = Calendar.getInstance().getTimeInMillis() + Integer.parseInt(snoozeDelay) * 60 * 1000; - updateNoteReminder(newReminder, note); - finish(); - } else if (Constants.ACTION_POSTPONE.equals(getIntent().getAction())) { - postpone(prefs, Long.parseLong(note.getAlarm()), note.getRecurrenceRule()); - } else { - Intent intent = new Intent(this, MainActivity.class); - intent.putExtra(Constants.INTENT_KEY, note.get_id()); - intent.setAction(Constants.ACTION_NOTIFICATION_CLICK); - startActivity(intent); - finish(); - } - removeNotification(note); - } + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - private void postpone(SharedPreferences prefs, Long alarm, String recurrenceRule) { - int pickerType = prefs.getBoolean("settings_simple_calendar", false) ? ReminderPickers.TYPE_AOSP : - ReminderPickers.TYPE_GOOGLE; - ReminderPickers reminderPicker = new ReminderPickers(this, this, pickerType); - reminderPicker.pick(alarm, recurrenceRule); - onDateSetListener = reminderPicker; - onTimeSetListener = reminderPicker; + if (getIntent().getParcelableExtra(Constants.INTENT_NOTE) != null) { + note = getIntent().getParcelableExtra(Constants.INTENT_NOTE); + manageNotification(getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS)); + } else { + Object[] notesObjs = (Object[]) getIntent().getExtras().get(Constants.INTENT_NOTE); + notes = Arrays.copyOf(notesObjs, notesObjs.length, Note[].class); + postpone(getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS), DateUtils.getNextMinute(), null); } - - - private void removeNotification(Note note) { - NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - manager.cancel(String.valueOf(note.get_id()), 0); + } + + + private void manageNotification (SharedPreferences prefs) { + if (Constants.ACTION_DISMISS.equals(getIntent().getAction())) { + setNextRecurrentReminder(note); + finish(); + } else if (Constants.ACTION_SNOOZE.equals(getIntent().getAction())) { + String snoozeDelay = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT); + long newReminder = Calendar.getInstance().getTimeInMillis() + Integer.parseInt(snoozeDelay) * 60 * 1000; + updateNoteReminder(newReminder, note); + finish(); + } else if (Constants.ACTION_POSTPONE.equals(getIntent().getAction())) { + postpone(prefs, Long.parseLong(note.getAlarm()), note.getRecurrenceRule()); + } else { + Intent intent = new Intent(this, MainActivity.class); + intent.putExtra(Constants.INTENT_KEY, note.get_id()); + intent.setAction(Constants.ACTION_NOTIFICATION_CLICK); + startActivity(intent); + finish(); } - - - @Override - public void onReminderPicked(long reminder) { - if (this.note != null) { - this.note.setAlarm(reminder); - } else { - for (Note note : this.notes) { - note.setAlarm(reminder); - } - } + removeNotification(note); + } + + + private void postpone (SharedPreferences prefs, Long alarm, String recurrenceRule) { + int pickerType = prefs.getBoolean("settings_simple_calendar", false) ? ReminderPickers.TYPE_AOSP : + ReminderPickers.TYPE_GOOGLE; + ReminderPickers reminderPicker = new ReminderPickers(this, this, pickerType); + reminderPicker.pick(alarm, recurrenceRule); + onDateSetListener = reminderPicker; + onTimeSetListener = reminderPicker; + } + + + private void removeNotification (Note note) { + NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + manager.cancel(String.valueOf(note.get_id()), 0); + } + + + @Override + public void onReminderPicked (long reminder) { + if (this.note != null) { + this.note.setAlarm(reminder); + } else { + for (Note note : this.notes) { + note.setAlarm(reminder); + } } - - @Override - public void onRecurrenceReminderPicked(String recurrenceRule) { - if (this.note != null) { - this.note.setRecurrenceRule(recurrenceRule); - setNextRecurrentReminder(this.note); - } else { - for (Note note : this.notes) { - note.setRecurrenceRule(recurrenceRule); - setNextRecurrentReminder(note); - } - setResult(RESULT_OK, getIntent()); - } - finish(); + } + + @Override + public void onRecurrenceReminderPicked (String recurrenceRule) { + if (this.note != null) { + this.note.setRecurrenceRule(recurrenceRule); + setNextRecurrentReminder(this.note); + } else { + for (Note note : this.notes) { + note.setRecurrenceRule(recurrenceRule); + setNextRecurrentReminder(note); + } + setResult(RESULT_OK, getIntent()); } - - - public static void setNextRecurrentReminder(Note note) { - if (!TextUtils.isEmpty(note.getRecurrenceRule())) { - long nextReminder = DateHelper.nextReminderFromRecurrenceRule(Long.parseLong(note.getAlarm()), note - .getRecurrenceRule()); - if (nextReminder > 0) { - updateNoteReminder(nextReminder, note, true); - } - } else { - new SaveNoteTask(false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, note); - } + finish(); + } + + + public static void setNextRecurrentReminder (Note note) { + if (!TextUtils.isEmpty(note.getRecurrenceRule())) { + long nextReminder = DateHelper.nextReminderFromRecurrenceRule(Long.parseLong(note.getAlarm()), note + .getRecurrenceRule()); + if (nextReminder > 0) { + updateNoteReminder(nextReminder, note, true); + } + } else { + new SaveNoteTask(false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, note); } + } - private static void updateNoteReminder(long reminder, Note note) { - updateNoteReminder(reminder, note, false); - } + private static void updateNoteReminder (long reminder, Note note) { + updateNoteReminder(reminder, note, false); + } - private static void updateNoteReminder(long reminder, Note noteToUpdate, boolean updateNote) { - if (updateNote) { - noteToUpdate.setAlarm(reminder); - new SaveNoteTask(false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, noteToUpdate); - } else { - ReminderHelper.addReminder(OmniNotes.getAppContext(), noteToUpdate, reminder); - ReminderHelper.showReminderMessage(String.valueOf(noteToUpdate.getAlarm())); - } + private static void updateNoteReminder (long reminder, Note noteToUpdate, boolean updateNote) { + if (updateNote) { + noteToUpdate.setAlarm(reminder); + new SaveNoteTask(false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, noteToUpdate); + } else { + ReminderHelper.addReminder(OmniNotes.getAppContext(), noteToUpdate, reminder); + ReminderHelper.showReminderMessage(String.valueOf(noteToUpdate.getAlarm())); } + } - @Override - public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { - onDateSetListener.onDateSet(view, year, monthOfYear, dayOfMonth); - } + @Override + public void onDateSet (DatePicker view, int year, int monthOfYear, int dayOfMonth) { + onDateSetListener.onDateSet(view, year, monthOfYear, dayOfMonth); + } - @Override - public void onTimeSet(TimePicker view, int hourOfDay, int minute) { - onTimeSetListener.onTimeSet(view, hourOfDay, minute); - } + @Override + public void onTimeSet (TimePicker view, int hourOfDay, int minute) { + onTimeSetListener.onTimeSet(view, hourOfDay, minute); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/StatsActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/StatsActivity.java index 1675756c23..6fdee473c3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/StatsActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/StatsActivity.java @@ -23,75 +23,74 @@ import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; - import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.models.Stats; public class StatsActivity extends Activity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_stats); - initData(); - } - + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_stats); + initData(); + } - @SuppressLint("NewApi") - private void initData() { - class StatsTask extends AsyncTask { - private Context mContext; + @SuppressLint("NewApi") + private void initData () { + class StatsTask extends AsyncTask { + private Context mContext; - public StatsTask(Context mContext) { - this.mContext = mContext; - } + public StatsTask (Context mContext) { + this.mContext = mContext; + } - @Override - protected Stats doInBackground(Void... params) { - return (DbHelper.getInstance()).getStats(); - } + @Override + protected Stats doInBackground (Void... params) { + return (DbHelper.getInstance()).getStats(); + } - @Override - protected void onPostExecute(Stats result) { - populateViews(result); - } - } - new StatsTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + @Override + protected void onPostExecute (Stats result) { + populateViews(result); + } } - - private void populateViews(Stats mStats) { - ((TextView) findViewById(R.id.stat_notes_total)).setText(String.valueOf(mStats.getNotesTotalNumber())); - ((TextView) findViewById(R.id.stat_notes_active)).setText(String.valueOf(mStats.getNotesActive())); - ((TextView) findViewById(R.id.stat_notes_archived)).setText(String.valueOf(mStats.getNotesArchived())); - ((TextView) findViewById(R.id.stat_notes_trashed)).setText(String.valueOf(mStats.getNotesTrashed())); - ((TextView) findViewById(R.id.stat_reminders)).setText(String.valueOf(mStats.getReminders())); - ((TextView) findViewById(R.id.stat_reminders_futures)).setText(String.valueOf(mStats.getRemindersFutures())); - ((TextView) findViewById(R.id.stat_checklists)).setText(String.valueOf(mStats.getNotesChecklist())); - ((TextView) findViewById(R.id.stat_masked)).setText(String.valueOf(mStats.getNotesMasked())); - ((TextView) findViewById(R.id.stat_categories)).setText(String.valueOf(mStats.getCategories())); - ((TextView) findViewById(R.id.stat_tags)).setText(String.valueOf(mStats.getTags())); - - ((TextView) findViewById(R.id.stat_attachments)).setText(String.valueOf(mStats.getAttachments())); - ((TextView) findViewById(R.id.stat_attachments_images)).setText(String.valueOf(mStats.getImages())); - ((TextView) findViewById(R.id.stat_attachments_videos)).setText(String.valueOf(mStats.getVideos())); - ((TextView) findViewById(R.id.stat_attachments_audiorecordings)).setText(String.valueOf(mStats - .getAudioRecordings())); - ((TextView) findViewById(R.id.stat_attachments_sketches)).setText(String.valueOf(mStats.getSketches())); - ((TextView) findViewById(R.id.stat_attachments_files)).setText(String.valueOf(mStats.getFiles())); - ((TextView) findViewById(R.id.stat_locations)).setText(String.valueOf(mStats.getLocation())); - - ((TextView) findViewById(R.id.stat_words)).setText(String.valueOf(mStats.getWords())); - ((TextView) findViewById(R.id.stat_words_max)).setText(String.valueOf(mStats.getWordsMax())); - ((TextView) findViewById(R.id.stat_words_avg)).setText(String.valueOf(mStats.getWordsAvg())); - ((TextView) findViewById(R.id.stat_chars)).setText(String.valueOf(mStats.getChars())); - ((TextView) findViewById(R.id.stat_chars_max)).setText(String.valueOf(mStats.getCharsMax())); - ((TextView) findViewById(R.id.stat_chars_avg)).setText(String.valueOf(mStats.getCharsAvg())); - } + new StatsTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + + + private void populateViews (Stats mStats) { + ((TextView) findViewById(R.id.stat_notes_total)).setText(String.valueOf(mStats.getNotesTotalNumber())); + ((TextView) findViewById(R.id.stat_notes_active)).setText(String.valueOf(mStats.getNotesActive())); + ((TextView) findViewById(R.id.stat_notes_archived)).setText(String.valueOf(mStats.getNotesArchived())); + ((TextView) findViewById(R.id.stat_notes_trashed)).setText(String.valueOf(mStats.getNotesTrashed())); + ((TextView) findViewById(R.id.stat_reminders)).setText(String.valueOf(mStats.getReminders())); + ((TextView) findViewById(R.id.stat_reminders_futures)).setText(String.valueOf(mStats.getRemindersFutures())); + ((TextView) findViewById(R.id.stat_checklists)).setText(String.valueOf(mStats.getNotesChecklist())); + ((TextView) findViewById(R.id.stat_masked)).setText(String.valueOf(mStats.getNotesMasked())); + ((TextView) findViewById(R.id.stat_categories)).setText(String.valueOf(mStats.getCategories())); + ((TextView) findViewById(R.id.stat_tags)).setText(String.valueOf(mStats.getTags())); + + ((TextView) findViewById(R.id.stat_attachments)).setText(String.valueOf(mStats.getAttachments())); + ((TextView) findViewById(R.id.stat_attachments_images)).setText(String.valueOf(mStats.getImages())); + ((TextView) findViewById(R.id.stat_attachments_videos)).setText(String.valueOf(mStats.getVideos())); + ((TextView) findViewById(R.id.stat_attachments_audiorecordings)).setText(String.valueOf(mStats + .getAudioRecordings())); + ((TextView) findViewById(R.id.stat_attachments_sketches)).setText(String.valueOf(mStats.getSketches())); + ((TextView) findViewById(R.id.stat_attachments_files)).setText(String.valueOf(mStats.getFiles())); + ((TextView) findViewById(R.id.stat_locations)).setText(String.valueOf(mStats.getLocation())); + + ((TextView) findViewById(R.id.stat_words)).setText(String.valueOf(mStats.getWords())); + ((TextView) findViewById(R.id.stat_words_max)).setText(String.valueOf(mStats.getWordsMax())); + ((TextView) findViewById(R.id.stat_words_avg)).setText(String.valueOf(mStats.getWordsAvg())); + ((TextView) findViewById(R.id.stat_chars)).setText(String.valueOf(mStats.getChars())); + ((TextView) findViewById(R.id.stat_chars_max)).setText(String.valueOf(mStats.getCharsMax())); + ((TextView) findViewById(R.id.stat_chars_avg)).setText(String.valueOf(mStats.getCharsAvg())); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/AlarmRestoreOnRebootService.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/AlarmRestoreOnRebootService.java index 2cda3833fd..3a02a862c3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/AlarmRestoreOnRebootService.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/AlarmRestoreOnRebootService.java @@ -21,37 +21,35 @@ import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.app.JobIntentService; - -import java.util.List; - import it.feio.android.omninotes.BaseActivity; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.utils.ReminderHelper; +import java.util.List; public class AlarmRestoreOnRebootService extends JobIntentService { - public static final int JOB_ID = 0x01; + public static final int JOB_ID = 0x01; - public static void enqueueWork(Context context, Intent work) { - enqueueWork(context, AlarmRestoreOnRebootService.class, JOB_ID, work); - } + public static void enqueueWork (Context context, Intent work) { + enqueueWork(context, AlarmRestoreOnRebootService.class, JOB_ID, work); + } - @Override - protected void onHandleWork(@NonNull Intent intent) { - LogDelegate.i("System rebooted: service refreshing reminders"); - Context mContext = getApplicationContext(); + @Override + protected void onHandleWork (@NonNull Intent intent) { + LogDelegate.i("System rebooted: service refreshing reminders"); + Context mContext = getApplicationContext(); - BaseActivity.notifyAppWidgets(mContext); + BaseActivity.notifyAppWidgets(mContext); - List notes = DbHelper.getInstance().getNotesWithReminderNotFired(); - LogDelegate.d("Found " + notes.size() + " reminders"); - for (Note note : notes) { - ReminderHelper.addReminder(OmniNotes.getAppContext(), note); - } - } + List notes = DbHelper.getInstance().getNotesWithReminderNotFired(); + LogDelegate.d("Found " + notes.size() + " reminders"); + for (Note note : notes) { + ReminderHelper.addReminder(OmniNotes.getAppContext(), note); + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/AttachmentTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/AttachmentTask.java index dd719e4234..4567d79007 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/AttachmentTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/AttachmentTask.java @@ -25,60 +25,59 @@ import it.feio.android.omninotes.models.Attachment; import it.feio.android.omninotes.models.listeners.OnAttachingFileListener; import it.feio.android.omninotes.utils.StorageHelper; - import java.lang.ref.WeakReference; public class AttachmentTask extends AsyncTask { - private final WeakReference mFragmentWeakReference; - private OnAttachingFileListener mOnAttachingFileListener; - private Uri uri; - private String fileName; + private final WeakReference mFragmentWeakReference; + private OnAttachingFileListener mOnAttachingFileListener; + private Uri uri; + private String fileName; - public AttachmentTask(Fragment mFragment, Uri uri, OnAttachingFileListener mOnAttachingFileListener) { - this(mFragment, uri, null, mOnAttachingFileListener); - } + public AttachmentTask (Fragment mFragment, Uri uri, OnAttachingFileListener mOnAttachingFileListener) { + this(mFragment, uri, null, mOnAttachingFileListener); + } - public AttachmentTask(Fragment mFragment, Uri uri, String fileName, - OnAttachingFileListener mOnAttachingFileListener) { - mFragmentWeakReference = new WeakReference<>(mFragment); - this.uri = uri; - this.fileName = TextUtils.isEmpty(fileName) ? "" : fileName; - this.mOnAttachingFileListener = mOnAttachingFileListener; - } + public AttachmentTask (Fragment mFragment, Uri uri, String fileName, + OnAttachingFileListener mOnAttachingFileListener) { + mFragmentWeakReference = new WeakReference<>(mFragment); + this.uri = uri; + this.fileName = TextUtils.isEmpty(fileName) ? "" : fileName; + this.mOnAttachingFileListener = mOnAttachingFileListener; + } - @Override - protected Attachment doInBackground(Void... params) { - return StorageHelper.createAttachmentFromUri(OmniNotes.getAppContext(), uri); - } + @Override + protected Attachment doInBackground (Void... params) { + return StorageHelper.createAttachmentFromUri(OmniNotes.getAppContext(), uri); + } - @Override - protected void onPostExecute(Attachment mAttachment) { - if (isAlive()) { - if (mAttachment != null) { - mOnAttachingFileListener.onAttachingFileFinished(mAttachment); - } else { - mOnAttachingFileListener.onAttachingFileErrorOccurred(null); - } - } else { - if (mAttachment != null) { - StorageHelper.delete(OmniNotes.getAppContext(), mAttachment.getUri().getPath()); - } - } + @Override + protected void onPostExecute (Attachment mAttachment) { + if (isAlive()) { + if (mAttachment != null) { + mOnAttachingFileListener.onAttachingFileFinished(mAttachment); + } else { + mOnAttachingFileListener.onAttachingFileErrorOccurred(null); + } + } else { + if (mAttachment != null) { + StorageHelper.delete(OmniNotes.getAppContext(), mAttachment.getUri().getPath()); + } } + } - private boolean isAlive() { - return mFragmentWeakReference != null - && mFragmentWeakReference.get() != null - && mFragmentWeakReference.get().isAdded() - && mFragmentWeakReference.get().getActivity() != null - && !mFragmentWeakReference.get().getActivity().isFinishing(); - } + private boolean isAlive () { + return mFragmentWeakReference != null + && mFragmentWeakReference.get() != null + && mFragmentWeakReference.get().isAdded() + && mFragmentWeakReference.get().getActivity() != null + && !mFragmentWeakReference.get().getActivity().isFinishing(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/CategoryMenuTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/CategoryMenuTask.java index e0d0935b1b..bf0dff58ce 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/CategoryMenuTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/CategoryMenuTask.java @@ -23,10 +23,6 @@ import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; - -import java.lang.ref.WeakReference; -import java.util.List; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.MainActivity; import it.feio.android.omninotes.R; @@ -37,134 +33,138 @@ import it.feio.android.omninotes.models.ONStyle; import it.feio.android.omninotes.models.adapters.NavDrawerCategoryAdapter; import it.feio.android.omninotes.models.views.NonScrollableListView; +import java.lang.ref.WeakReference; +import java.util.List; public class CategoryMenuTask extends AsyncTask> { - private final WeakReference mFragmentWeakReference; - private final MainActivity mainActivity; - private NonScrollableListView mDrawerCategoriesList; - private View settingsView; - private View settingsViewCat; - private NonScrollableListView mDrawerList; + private final WeakReference mFragmentWeakReference; + private final MainActivity mainActivity; + private NonScrollableListView mDrawerCategoriesList; + private View settingsView; + private View settingsViewCat; + private NonScrollableListView mDrawerList; - public CategoryMenuTask(Fragment mFragment) { - mFragmentWeakReference = new WeakReference<>(mFragment); - this.mainActivity = (MainActivity) mFragment.getActivity(); - } - + public CategoryMenuTask (Fragment mFragment) { + mFragmentWeakReference = new WeakReference<>(mFragment); + this.mainActivity = (MainActivity) mFragment.getActivity(); + } - @Override - protected void onPreExecute() { - super.onPreExecute(); - mDrawerList = (NonScrollableListView) mainActivity.findViewById(R.id.drawer_nav_list); - LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - settingsView = mainActivity.findViewById(R.id.settings_view); + @Override + protected void onPreExecute () { + super.onPreExecute(); + mDrawerList = mainActivity.findViewById(R.id.drawer_nav_list); + LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - // Settings view when categories are available - mDrawerCategoriesList = (NonScrollableListView) mainActivity.findViewById(R.id.drawer_tag_list); - if (mDrawerCategoriesList.getAdapter() == null && mDrawerCategoriesList.getFooterViewsCount() == 0) { - settingsViewCat = inflater.inflate(R.layout.drawer_category_list_footer, null); - mDrawerCategoriesList.addFooterView(settingsViewCat); - } else { - settingsViewCat = mDrawerCategoriesList.getChildAt(mDrawerCategoriesList.getChildCount() - 1); - } + settingsView = mainActivity.findViewById(R.id.settings_view); + // Settings view when categories are available + mDrawerCategoriesList = mainActivity.findViewById(R.id.drawer_tag_list); + if (mDrawerCategoriesList.getAdapter() == null && mDrawerCategoriesList.getFooterViewsCount() == 0) { + settingsViewCat = inflater.inflate(R.layout.drawer_category_list_footer, null); + mDrawerCategoriesList.addFooterView(settingsViewCat); + } else { + settingsViewCat = mDrawerCategoriesList.getChildAt(mDrawerCategoriesList.getChildCount() - 1); } - - @Override - protected List doInBackground(Void... params) { - if (isAlive()) { - return buildCategoryMenu(); - } else { - cancel(true); - return null; - } - } + } - @Override - protected void onPostExecute(final List categories) { - if (isAlive()) { - mDrawerCategoriesList.setAdapter(new NavDrawerCategoryAdapter(mainActivity, categories, - mainActivity.getNavigationTmp())); - if (categories.size() == 0) { - setWidgetVisibility(settingsViewCat, false); - setWidgetVisibility(settingsView, true); - } else { - setWidgetVisibility(settingsViewCat, true); - setWidgetVisibility(settingsView, false); - } - mDrawerCategoriesList.justifyListViewHeightBasedOnChildren(); - } + @Override + protected List doInBackground (Void... params) { + if (isAlive()) { + return buildCategoryMenu(); + } else { + cancel(true); + return null; } + } + + + @Override + protected void onPostExecute (final List categories) { + if (isAlive()) { + mDrawerCategoriesList.setAdapter(new NavDrawerCategoryAdapter(mainActivity, categories, + mainActivity.getNavigationTmp())); + if (categories.size() == 0) { + setWidgetVisibility(settingsViewCat, false); + setWidgetVisibility(settingsView, true); + } else { + setWidgetVisibility(settingsViewCat, true); + setWidgetVisibility(settingsView, false); + } + mDrawerCategoriesList.justifyListViewHeightBasedOnChildren(); + } + } - private void setWidgetVisibility(View view, boolean visible) { - if (view != null) { - view.setVisibility(visible ? View.VISIBLE : View.GONE); - } + private void setWidgetVisibility (View view, boolean visible) { + if (view != null) { + view.setVisibility(visible ? View.VISIBLE : View.GONE); } + } - private boolean isAlive() { - return mFragmentWeakReference.get() != null - && mFragmentWeakReference.get().isAdded() - && mFragmentWeakReference.get().getActivity() != null - && !mFragmentWeakReference.get().getActivity().isFinishing(); - } + private boolean isAlive () { + return mFragmentWeakReference.get() != null + && mFragmentWeakReference.get().isAdded() + && mFragmentWeakReference.get().getActivity() != null + && !mFragmentWeakReference.get().getActivity().isFinishing(); + } - private List buildCategoryMenu() { + private List buildCategoryMenu () { - List categories = DbHelper.getInstance().getCategories(); + List categories = DbHelper.getInstance().getCategories(); - View settings = categories.isEmpty() ? settingsView : settingsViewCat; - if (settings == null) return categories; + View settings = categories.isEmpty() ? settingsView : settingsViewCat; + if (settings == null) { + return categories; + } // Fonts.overrideTextSize(mainActivity, // mainActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS), // settings); - mainActivity.runOnUiThread(() -> { - settings.setOnClickListener(v -> { - Intent settingsIntent = new Intent(mainActivity, SettingsActivity.class); - mainActivity.startActivity(settingsIntent); - }); - - // Sets click events - mDrawerCategoriesList.setOnItemClickListener((arg0, arg1, position, arg3) -> { - - Object item = mDrawerCategoriesList.getAdapter().getItem(position); - if (mainActivity.updateNavigation(String.valueOf(((Category) item).getId()))) { - mDrawerCategoriesList.setItemChecked(position, true); - // Forces redraw - if (mDrawerList != null) { - mDrawerList.setItemChecked(0, false); - EventBus.getDefault().post(new NavigationUpdatedEvent(mDrawerCategoriesList.getItemAtPosition - (position))); - } - } - }); - - // Sets long click events - mDrawerCategoriesList.setOnItemLongClickListener((arg0, view, position, arg3) -> { - if (mDrawerCategoriesList.getAdapter() != null) { - Object item = mDrawerCategoriesList.getAdapter().getItem(position); - // Ensuring that clicked item is not the ListView header - if (item != null) { - mainActivity.editTag((Category) item); - } - } else { - mainActivity.showMessage(R.string.category_deleted, ONStyle.ALERT); - } - return true; - }); - }); - - return categories; - } + mainActivity.runOnUiThread(() -> { + settings.setOnClickListener(v -> { + Intent settingsIntent = new Intent(mainActivity, SettingsActivity.class); + mainActivity.startActivity(settingsIntent); + }); + + // Sets click events + mDrawerCategoriesList.setOnItemClickListener((arg0, arg1, position, arg3) -> { + + Object item = mDrawerCategoriesList.getAdapter().getItem(position); + if (mainActivity.updateNavigation(String.valueOf(((Category) item).getId()))) { + mDrawerCategoriesList.setItemChecked(position, true); + // Forces redraw + if (mDrawerList != null) { + mDrawerList.setItemChecked(0, false); + EventBus.getDefault().post(new NavigationUpdatedEvent(mDrawerCategoriesList.getItemAtPosition + (position))); + } + } + }); + + // Sets long click events + mDrawerCategoriesList.setOnItemLongClickListener((arg0, view, position, arg3) -> { + if (mDrawerCategoriesList.getAdapter() != null) { + Object item = mDrawerCategoriesList.getAdapter().getItem(position); + // Ensuring that clicked item is not the ListView header + if (item != null) { + mainActivity.editTag((Category) item); + } + } else { + mainActivity.showMessage(R.string.category_deleted, ONStyle.ALERT); + } + return true; + }); + }); + + return categories; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/DataBackupIntentService.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/DataBackupIntentService.java index 3f7d258ab6..a593d7b9ba 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/DataBackupIntentService.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/DataBackupIntentService.java @@ -22,9 +22,6 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; - -import java.io.File; - import it.feio.android.omninotes.MainActivity; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; @@ -40,18 +37,19 @@ import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.notifications.NotificationChannels; import it.feio.android.omninotes.utils.notifications.NotificationsHelper; +import java.io.File; public class DataBackupIntentService extends IntentService implements OnAttachingFileListener { - public final static String INTENT_BACKUP_NAME = "backup_name"; - public final static String INTENT_BACKUP_INCLUDE_SETTINGS = "backup_include_settings"; - public final static String ACTION_DATA_EXPORT = "action_data_export"; - public final static String ACTION_DATA_IMPORT = "action_data_import"; - public final static String ACTION_DATA_IMPORT_LEGACY = "action_data_import_legacy"; - public final static String ACTION_DATA_DELETE = "action_data_delete"; + public final static String INTENT_BACKUP_NAME = "backup_name"; + public final static String INTENT_BACKUP_INCLUDE_SETTINGS = "backup_include_settings"; + public final static String ACTION_DATA_EXPORT = "action_data_export"; + public final static String ACTION_DATA_IMPORT = "action_data_import"; + public final static String ACTION_DATA_IMPORT_LEGACY = "action_data_import_legacy"; + public final static String ACTION_DATA_DELETE = "action_data_delete"; - private SharedPreferences prefs; - private NotificationsHelper mNotificationsHelper; + private SharedPreferences prefs; + private NotificationsHelper mNotificationsHelper; // { // File autoBackupDir = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); @@ -60,168 +58,172 @@ public class DataBackupIntentService extends IntentService implements OnAttachin // } - public DataBackupIntentService() { - super("DataBackupIntentService"); - } + public DataBackupIntentService () { + super("DataBackupIntentService"); + } - @Override - protected void onHandleIntent(Intent intent) { - prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); + @Override + protected void onHandleIntent (Intent intent) { + prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); - // Creates an indeterminate processing notification until the work is complete + // Creates an indeterminate processing notification until the work is complete // mNotificationsHelper = new NotificationsHelper(this) // .createNotification(NotificationChannels.NotificationChannelNames.Backups, // R.drawable.ic_content_save_white_24dp, getString(R.string.working), // null) // .setIndeterminate().setOngoing(); - mNotificationsHelper = new NotificationsHelper(this).start(NotificationChannels.NotificationChannelNames.Backups, - R.drawable.ic_content_save_white_24dp, getString(R.string.working)); - - - // If an alarm has been fired a notification must be generated - if (ACTION_DATA_EXPORT.equals(intent.getAction())) { - exportData(intent); - } else if (ACTION_DATA_IMPORT.equals(intent.getAction()) || ACTION_DATA_IMPORT_LEGACY.equals(intent.getAction())) { - importData(intent); - } else if (SpringImportHelper.ACTION_DATA_IMPORT_SPRINGPAD.equals(intent.getAction())) { - importDataFromSpringpad(intent, mNotificationsHelper); - } else if (ACTION_DATA_DELETE.equals(intent.getAction())) { - deleteData(intent); - } + mNotificationsHelper = new NotificationsHelper(this).start(NotificationChannels.NotificationChannelNames.Backups, + R.drawable.ic_content_save_white_24dp, getString(R.string.working)); + + // If an alarm has been fired a notification must be generated + if (ACTION_DATA_EXPORT.equals(intent.getAction())) { + exportData(intent); + } else if (ACTION_DATA_IMPORT.equals(intent.getAction()) || ACTION_DATA_IMPORT_LEGACY.equals(intent.getAction())) { + importData(intent); + } else if (SpringImportHelper.ACTION_DATA_IMPORT_SPRINGPAD.equals(intent.getAction())) { + importDataFromSpringpad(intent, mNotificationsHelper); + } else if (ACTION_DATA_DELETE.equals(intent.getAction())) { + deleteData(intent); } + } - private void importDataFromSpringpad(Intent intent, NotificationsHelper mNotificationsHelper) { - new SpringImportHelper(OmniNotes.getAppContext()).importDataFromSpringpad(intent, mNotificationsHelper); - String title = getString(R.string.data_import_completed); - String text = getString(R.string.click_to_refresh_application); - createNotification(intent, this, title, text, null); - } - - synchronized private void exportData(Intent intent) { + private void importDataFromSpringpad (Intent intent, NotificationsHelper mNotificationsHelper) { + new SpringImportHelper(OmniNotes.getAppContext()).importDataFromSpringpad(intent, mNotificationsHelper); + String title = getString(R.string.data_import_completed); + String text = getString(R.string.click_to_refresh_application); + createNotification(intent, this, title, text, null); + } - boolean result = true; + synchronized private void exportData (Intent intent) { - // Gets backup folder - String backupName = intent.getStringExtra(INTENT_BACKUP_NAME); - File backupDir = StorageHelper.getBackupDir(backupName); + boolean result = true; - // Directory clean in case of previously used backup name - StorageHelper.delete(this, backupDir.getAbsolutePath()); + // Gets backup folder + String backupName = intent.getStringExtra(INTENT_BACKUP_NAME); + File backupDir = StorageHelper.getBackupDir(backupName); - // Directory is re-created in case of previously used backup name (removed above) - backupDir = StorageHelper.getBackupDir(backupName); + // Directory clean in case of previously used backup name + StorageHelper.delete(this, backupDir.getAbsolutePath()); - BackupHelper.exportNotes(backupDir); + // Directory is re-created in case of previously used backup name (removed above) + backupDir = StorageHelper.getBackupDir(backupName); - result = BackupHelper.exportAttachments(backupDir, mNotificationsHelper); + BackupHelper.exportNotes(backupDir); - if (intent.getBooleanExtra(INTENT_BACKUP_INCLUDE_SETTINGS, true)) { - BackupHelper.exportSettings(backupDir); - } + result = BackupHelper.exportAttachments(backupDir, mNotificationsHelper); - String notificationMessage = result ? getString(R.string.data_export_completed) : getString(R.string.data_export_failed); - mNotificationsHelper.finish(intent, notificationMessage); + if (intent.getBooleanExtra(INTENT_BACKUP_INCLUDE_SETTINGS, true)) { + BackupHelper.exportSettings(backupDir); } + String notificationMessage = + result ? getString(R.string.data_export_completed) : getString(R.string.data_export_failed); + mNotificationsHelper.finish(intent, notificationMessage); + } - synchronized private void importData(Intent intent) { - boolean importLegacy = ACTION_DATA_IMPORT_LEGACY.equals(intent.getAction()); + synchronized private void importData (Intent intent) { - // Gets backup folder - String backupName = intent.getStringExtra(INTENT_BACKUP_NAME); - File backupDir = importLegacy ? new File(backupName) : StorageHelper.getBackupDir(backupName); + boolean importLegacy = ACTION_DATA_IMPORT_LEGACY.equals(intent.getAction()); - BackupHelper.importSettings(backupDir); + // Gets backup folder + String backupName = intent.getStringExtra(INTENT_BACKUP_NAME); + File backupDir = importLegacy ? new File(backupName) : StorageHelper.getBackupDir(backupName); - if (importLegacy) { - BackupHelper.importDB(this, backupDir); - } else { - BackupHelper.importNotes(backupDir); - } + BackupHelper.importSettings(backupDir); - BackupHelper.importAttachments(backupDir, mNotificationsHelper); + if (importLegacy) { + BackupHelper.importDB(this, backupDir); + } else { + BackupHelper.importNotes(backupDir); + } + + BackupHelper.importAttachments(backupDir, mNotificationsHelper); - resetReminders(); + resetReminders(); - mNotificationsHelper.cancel(); + mNotificationsHelper.cancel(); - createNotification(intent, this, getString(R.string.data_import_completed), getString(R.string.click_to_refresh_application), backupDir); + createNotification(intent, this, getString(R.string.data_import_completed), + getString(R.string.click_to_refresh_application), backupDir); - // Performs auto-backup filling after backup restore + // Performs auto-backup filling after backup restore // if (prefs.getBoolean(Constants.PREF_ENABLE_AUTOBACKUP, false)) { // File autoBackupDir = StorageHelper.getBackupDir(Constants.AUTO_BACKUP_DIR); // BackupHelper.exportNotes(autoBackupDir); // BackupHelper.exportAttachments(autoBackupDir); // } - } + } - synchronized private void deleteData(Intent intent) { + synchronized private void deleteData (Intent intent) { - // Gets backup folder - String backupName = intent.getStringExtra(INTENT_BACKUP_NAME); - File backupDir = StorageHelper.getBackupDir(backupName); + // Gets backup folder + String backupName = intent.getStringExtra(INTENT_BACKUP_NAME); + File backupDir = StorageHelper.getBackupDir(backupName); - // Backups directory removal - StorageHelper.delete(this, backupDir.getAbsolutePath()); + // Backups directory removal + StorageHelper.delete(this, backupDir.getAbsolutePath()); + + String title = getString(R.string.data_deletion_completed); + String text = backupName + " " + getString(R.string.deleted); + createNotification(intent, this, title, text, backupDir); + } - String title = getString(R.string.data_deletion_completed); - String text = backupName + " " + getString(R.string.deleted); - createNotification(intent, this, title, text, backupDir); - } + /** + * Creation of notification on operations completed + */ + private void createNotification (Intent intent, Context mContext, String title, String message, File backupDir) { - /** - * Creation of notification on operations completed - */ - private void createNotification(Intent intent, Context mContext, String title, String message, File backupDir) { - - // The behavior differs depending on intent action - Intent intentLaunch; - if (DataBackupIntentService.ACTION_DATA_IMPORT.equals(intent.getAction()) - || SpringImportHelper.ACTION_DATA_IMPORT_SPRINGPAD.equals(intent.getAction())) { - intentLaunch = new Intent(mContext, MainActivity.class); - intentLaunch.setAction(Constants.ACTION_RESTART_APP); - } else { - intentLaunch = new Intent(); - } - // Add this bundle to the intent - intentLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - intentLaunch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - // Creates the PendingIntent - PendingIntent notifyIntent = PendingIntent.getActivity(mContext, 0, intentLaunch, - PendingIntent.FLAG_UPDATE_CURRENT); - - NotificationsHelper mNotificationsHelper = new NotificationsHelper(mContext); - mNotificationsHelper.createNotification(NotificationChannels.NotificationChannelNames.Backups, R.drawable.ic_content_save_white_24dp, title, notifyIntent) - .setMessage(message).setRingtone(prefs.getString("settings_notification_ringtone", null)) - .setLedActive(); - if (prefs.getBoolean("settings_notification_vibration", true)) mNotificationsHelper.setVibration(); - mNotificationsHelper.show(); + // The behavior differs depending on intent action + Intent intentLaunch; + if (DataBackupIntentService.ACTION_DATA_IMPORT.equals(intent.getAction()) + || SpringImportHelper.ACTION_DATA_IMPORT_SPRINGPAD.equals(intent.getAction())) { + intentLaunch = new Intent(mContext, MainActivity.class); + intentLaunch.setAction(Constants.ACTION_RESTART_APP); + } else { + intentLaunch = new Intent(); } + // Add this bundle to the intent + intentLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + intentLaunch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + // Creates the PendingIntent + PendingIntent notifyIntent = PendingIntent.getActivity(mContext, 0, intentLaunch, + PendingIntent.FLAG_UPDATE_CURRENT); + + NotificationsHelper mNotificationsHelper = new NotificationsHelper(mContext); + mNotificationsHelper.createNotification(NotificationChannels.NotificationChannelNames.Backups, + R.drawable.ic_content_save_white_24dp, title, notifyIntent) + .setMessage(message).setRingtone(prefs.getString("settings_notification_ringtone", null)) + .setLedActive(); + if (prefs.getBoolean("settings_notification_vibration", true)) { + mNotificationsHelper.setVibration(); + } + mNotificationsHelper.show(); + } - /** - * Schedules reminders - */ - private void resetReminders() { - LogDelegate.d("Resettings reminders"); - for (Note note : DbHelper.getInstance().getNotesWithReminderNotFired()) { - ReminderHelper.addReminder(OmniNotes.getAppContext(), note); - } - } + /** + * Schedules reminders + */ + private void resetReminders () { + LogDelegate.d("Resettings reminders"); + for (Note note : DbHelper.getInstance().getNotesWithReminderNotFired()) { + ReminderHelper.addReminder(OmniNotes.getAppContext(), note); + } + } - @Override - public void onAttachingFileErrorOccurred(Attachment mAttachment) { - // TODO Auto-generated method stub - } + @Override + public void onAttachingFileErrorOccurred (Attachment mAttachment) { + // TODO Auto-generated method stub + } - @Override - public void onAttachingFileFinished(Attachment mAttachment) { - // TODO Auto-generated method stub - } + @Override + public void onAttachingFileFinished (Attachment mAttachment) { + // TODO Auto-generated method stub + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/MainMenuTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/MainMenuTask.java index f81475077e..a5d4f56d16 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/MainMenuTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/MainMenuTask.java @@ -23,127 +23,131 @@ import android.content.res.TypedArray; import android.os.AsyncTask; import android.support.v4.app.Fragment; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.List; - import butterknife.BindView; import butterknife.ButterKnife; import de.greenrobot.event.EventBus; import it.feio.android.omninotes.MainActivity; import it.feio.android.omninotes.R; import it.feio.android.omninotes.async.bus.NavigationUpdatedEvent; -import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.NavigationItem; import it.feio.android.omninotes.models.adapters.NavDrawerAdapter; import it.feio.android.omninotes.models.misc.DynamicNavigationLookupTable; import it.feio.android.omninotes.models.views.NonScrollableListView; import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Navigation; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; public class MainMenuTask extends AsyncTask> { - private final WeakReference mFragmentWeakReference; - private final MainActivity mainActivity; - @BindView(R.id.drawer_nav_list) NonScrollableListView mDrawerList; - @BindView(R.id.drawer_tag_list) NonScrollableListView mDrawerCategoriesList; - - - public MainMenuTask(Fragment mFragment) { - mFragmentWeakReference = new WeakReference<>(mFragment); - this.mainActivity = (MainActivity) mFragment.getActivity(); - ButterKnife.bind(this, mFragment.getView()); + private final WeakReference mFragmentWeakReference; + private final MainActivity mainActivity; + @BindView(R.id.drawer_nav_list) + NonScrollableListView mDrawerList; + @BindView(R.id.drawer_tag_list) + NonScrollableListView mDrawerCategoriesList; + + + public MainMenuTask (Fragment mFragment) { + mFragmentWeakReference = new WeakReference<>(mFragment); + this.mainActivity = (MainActivity) mFragment.getActivity(); + ButterKnife.bind(this, mFragment.getView()); + } + + + @Override + protected List doInBackground (Void... params) { + return buildMainMenu(); + } + + + @Override + protected void onPostExecute (final List items) { + if (isAlive()) { + mDrawerList.setAdapter(new NavDrawerAdapter(mainActivity, items)); + mDrawerList.setOnItemClickListener((arg0, arg1, position, arg3) -> { + String navigation = mFragmentWeakReference.get().getResources().getStringArray(R.array + .navigation_list_codes)[items.get(position).getArrayIndex()]; + if (mainActivity.updateNavigation(navigation)) { + mDrawerList.setItemChecked(position, true); + if (mDrawerCategoriesList != null) { + mDrawerCategoriesList.setItemChecked(0, false); // Called to force redraw + } + mainActivity.getIntent().setAction(Intent.ACTION_MAIN); + EventBus.getDefault().post(new NavigationUpdatedEvent(mDrawerList.getItemAtPosition(position))); + } + }); + mDrawerList.justifyListViewHeightBasedOnChildren(); } + } - @Override - protected List doInBackground(Void... params) { - return buildMainMenu(); - } + private boolean isAlive () { + return mFragmentWeakReference.get() != null + && mFragmentWeakReference.get().isAdded() + && mFragmentWeakReference.get().getActivity() != null + && !mFragmentWeakReference.get().getActivity().isFinishing(); + } - @Override - protected void onPostExecute(final List items) { - if (isAlive()) { - mDrawerList.setAdapter(new NavDrawerAdapter(mainActivity, items)); - mDrawerList.setOnItemClickListener((arg0, arg1, position, arg3) -> { - String navigation = mFragmentWeakReference.get().getResources().getStringArray(R.array - .navigation_list_codes)[items.get(position).getArrayIndex()]; - if (mainActivity.updateNavigation(navigation)) { - mDrawerList.setItemChecked(position, true); - if (mDrawerCategoriesList != null) - mDrawerCategoriesList.setItemChecked(0, false); // Called to force redraw - mainActivity.getIntent().setAction(Intent.ACTION_MAIN); - EventBus.getDefault().post(new NavigationUpdatedEvent(mDrawerList.getItemAtPosition(position))); - } - }); - mDrawerList.justifyListViewHeightBasedOnChildren(); - } + private List buildMainMenu () { + if (!isAlive()) { + return new ArrayList<>(); } - - private boolean isAlive() { - return mFragmentWeakReference.get() != null - && mFragmentWeakReference.get().isAdded() - && mFragmentWeakReference.get().getActivity() != null - && !mFragmentWeakReference.get().getActivity().isFinishing(); + String[] mNavigationArray = mainActivity.getResources().getStringArray(R.array.navigation_list); + TypedArray mNavigationIconsArray = mainActivity.getResources().obtainTypedArray(R.array.navigation_list_icons); + TypedArray mNavigationIconsSelectedArray = mainActivity.getResources().obtainTypedArray(R.array + .navigation_list_icons_selected); + + final List items = new ArrayList<>(); + for (int i = 0; i < mNavigationArray.length; i++) { + if (!checkSkippableItem(i)) { + NavigationItem item = new NavigationItem(i, mNavigationArray[i], mNavigationIconsArray.getResourceId(i, + 0), mNavigationIconsSelectedArray.getResourceId(i, 0)); + items.add(item); + } } + return items; + } - private List buildMainMenu() { - if (!isAlive()) { - return new ArrayList<>(); + private boolean checkSkippableItem (int i) { + boolean skippable = false; + SharedPreferences prefs = mainActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + boolean dynamicMenu = prefs.getBoolean(Constants.PREF_DYNAMIC_MENU, true); + DynamicNavigationLookupTable dynamicNavigationLookupTable = null; + if (dynamicMenu) { + dynamicNavigationLookupTable = DynamicNavigationLookupTable.getInstance(); + } + switch (i) { + case Navigation.REMINDERS: + if (dynamicMenu && dynamicNavigationLookupTable.getReminders() == 0) { + skippable = true; } - - String[] mNavigationArray = mainActivity.getResources().getStringArray(R.array.navigation_list); - TypedArray mNavigationIconsArray = mainActivity.getResources().obtainTypedArray(R.array.navigation_list_icons); - TypedArray mNavigationIconsSelectedArray = mainActivity.getResources().obtainTypedArray(R.array - .navigation_list_icons_selected); - - final List items = new ArrayList<>(); - for (int i = 0; i < mNavigationArray.length; i++) { - if (!checkSkippableItem(i)) { - NavigationItem item = new NavigationItem(i, mNavigationArray[i], mNavigationIconsArray.getResourceId(i, - 0), mNavigationIconsSelectedArray.getResourceId(i, 0)); - items.add(item); - } + break; + case Navigation.UNCATEGORIZED: + boolean showUncategorized = prefs.getBoolean(Constants.PREF_SHOW_UNCATEGORIZED, false); + if (!showUncategorized || (dynamicMenu && dynamicNavigationLookupTable.getUncategorized() == 0)) { + skippable = true; } - return items; - } - - - private boolean checkSkippableItem(int i) { - boolean skippable = false; - SharedPreferences prefs = mainActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - boolean dynamicMenu = prefs.getBoolean(Constants.PREF_DYNAMIC_MENU, true); - DynamicNavigationLookupTable dynamicNavigationLookupTable = null; - if (dynamicMenu) { - dynamicNavigationLookupTable = DynamicNavigationLookupTable.getInstance(); + break; + case Navigation.ARCHIVE: + if (dynamicMenu && dynamicNavigationLookupTable.getArchived() == 0) { + skippable = true; } - switch (i) { - case Navigation.REMINDERS: - if (dynamicMenu && dynamicNavigationLookupTable.getReminders() == 0) - skippable = true; - break; - case Navigation.UNCATEGORIZED: - boolean showUncategorized = prefs.getBoolean(Constants.PREF_SHOW_UNCATEGORIZED, false); - if (!showUncategorized || (dynamicMenu && dynamicNavigationLookupTable.getUncategorized() == 0)) - skippable = true; - break; - case Navigation.ARCHIVE: - if (dynamicMenu && dynamicNavigationLookupTable.getArchived() == 0) - skippable = true; - break; - case Navigation.TRASH: - if (dynamicMenu && dynamicNavigationLookupTable.getTrashed() == 0) - skippable = true; - break; - default: - skippable = false; + break; + case Navigation.TRASH: + if (dynamicMenu && dynamicNavigationLookupTable.getTrashed() == 0) { + skippable = true; } - return skippable; + break; + default: + skippable = false; } + return skippable; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/TextWorkerTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/TextWorkerTask.java index 25c52d94c4..601d04dd91 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/TextWorkerTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/TextWorkerTask.java @@ -24,63 +24,61 @@ import android.widget.TextView; import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.utils.TextHelper; - import java.lang.ref.WeakReference; public class TextWorkerTask extends AsyncTask { - private final WeakReference mActivityWeakReference; - private Activity mActivity; - private TextView titleTextView; - private TextView contentTextView; - private boolean expandedView; - - - public TextWorkerTask(Activity activity, TextView titleTextView, - TextView contentTextView, boolean expandedView) { - mActivityWeakReference = new WeakReference<>(activity); - mActivity = activity; - this.titleTextView = titleTextView; - this.contentTextView = contentTextView; - this.expandedView = expandedView; - } - - - @Override - protected Spanned[] doInBackground(Note... params) { - return TextHelper.parseTitleAndContent(mActivity, params[0]); - } - - - @Override - protected void onPostExecute(Spanned[] titleAndContent) { - if (isAlive()) { - titleTextView.setText(titleAndContent[0]); - if (titleAndContent[1].length() > 0) { - contentTextView.setText(titleAndContent[1]); - contentTextView.setVisibility(View.VISIBLE); - } else { - if (expandedView) { - contentTextView.setVisibility(View.INVISIBLE); - } else { - contentTextView.setVisibility(View.GONE); - } - } + private final WeakReference mActivityWeakReference; + private Activity mActivity; + private TextView titleTextView; + private TextView contentTextView; + private boolean expandedView; + + + public TextWorkerTask (Activity activity, TextView titleTextView, + TextView contentTextView, boolean expandedView) { + mActivityWeakReference = new WeakReference<>(activity); + mActivity = activity; + this.titleTextView = titleTextView; + this.contentTextView = contentTextView; + this.expandedView = expandedView; + } + + + @Override + protected Spanned[] doInBackground (Note... params) { + return TextHelper.parseTitleAndContent(mActivity, params[0]); + } + + + @Override + protected void onPostExecute (Spanned[] titleAndContent) { + if (isAlive()) { + titleTextView.setText(titleAndContent[0]); + if (titleAndContent[1].length() > 0) { + contentTextView.setText(titleAndContent[1]); + contentTextView.setVisibility(View.VISIBLE); + } else { + if (expandedView) { + contentTextView.setVisibility(View.INVISIBLE); + } else { + contentTextView.setVisibility(View.GONE); } + } } + } - /** - * Cheks if activity is still alive and not finishing - * - * @param weakDetailFragmentReference - * @return True or false - */ - private boolean isAlive() { - return mActivityWeakReference != null - && mActivityWeakReference.get() != null; + /** + * Cheks if activity is still alive and not finishing + * + * @return True or false + */ + private boolean isAlive () { + return mActivityWeakReference != null + && mActivityWeakReference.get() != null; - } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdateWidgetsTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdateWidgetsTask.java index 9510544b7f..71629aaa2f 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdateWidgetsTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdateWidgetsTask.java @@ -19,34 +19,33 @@ import android.content.Context; import android.os.AsyncTask; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.BaseActivity; import it.feio.android.omninotes.async.bus.NotesUpdatedEvent; public class UpdateWidgetsTask extends AsyncTask { - private Context context; + private Context context; - public UpdateWidgetsTask(Context context) { - this.context = context; - } + public UpdateWidgetsTask (Context context) { + this.context = context; + } - @Override - protected Void doInBackground(Void... params) { - WidgetUpdateSubscriber widgetUpdateSubscriber = new WidgetUpdateSubscriber(); - return null; - } + @Override + protected Void doInBackground (Void... params) { + WidgetUpdateSubscriber widgetUpdateSubscriber = new WidgetUpdateSubscriber(); + return null; + } - class WidgetUpdateSubscriber { + class WidgetUpdateSubscriber { - WidgetUpdateSubscriber() { - EventBus.getDefault().register(this); - } + WidgetUpdateSubscriber () { + EventBus.getDefault().register(this); + } - public void onEvent(NotesUpdatedEvent event) { - BaseActivity.notifyAppWidgets(context); - EventBus.getDefault().unregister(this); - } + public void onEvent (NotesUpdatedEvent event) { + BaseActivity.notifyAppWidgets(context); + EventBus.getDefault().unregister(this); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdaterTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdaterTask.java index 789d93ff31..37447e39f4 100755 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdaterTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/UpdaterTask.java @@ -25,21 +25,9 @@ import android.net.Uri; import android.os.AsyncTask; import android.support.annotation.NonNull; - import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.google.gson.Gson; - -import org.json.JSONException; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.ref.WeakReference; -import java.net.URL; -import java.net.URLConnection; - import it.feio.android.analitica.AnalyticsHelper; import it.feio.android.omninotes.BuildConfig; import it.feio.android.omninotes.OmniNotes; @@ -51,171 +39,182 @@ import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.MiscUtils; import it.feio.android.omninotes.utils.SystemHelper; - +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.ref.WeakReference; +import java.net.URL; +import java.net.URLConnection; +import org.json.JSONException; public class UpdaterTask extends AsyncTask { - private static final String BETA = " Beta "; - private final WeakReference mActivityReference; - private final Activity mActivity; - private final SharedPreferences prefs; - private boolean promptUpdate = false; - private long now; - - - public UpdaterTask(Activity mActivity) { - this.mActivityReference = new WeakReference<>(mActivity); - this.mActivity = mActivity; - this.prefs = mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - } - - - @Override - protected void onPreExecute() { - now = System.currentTimeMillis(); - if (OmniNotes.isDebugBuild() || !ConnectionManager.internetAvailable(OmniNotes.getAppContext()) || now < prefs.getLong(Constants - .PREF_LAST_UPDATE_CHECK, 0) + Constants.UPDATE_MIN_FREQUENCY) { - cancel(true); - } - super.onPreExecute(); - } - - - @Override - protected Void doInBackground(String... params) { - if (!isCancelled()) { - try { - // Temporary disabled untill MetadataFetcher will work again - // promptUpdate = isVersionUpdated(getAppData()); - promptUpdate = false; - if (promptUpdate) { - prefs.edit().putLong(Constants.PREF_LAST_UPDATE_CHECK, now).apply(); - } - } catch (Exception e) { - LogDelegate.w("Error fetching app metadata", e); - } - } - return null; - } - - - private void promptUpdate() { - new MaterialDialog.Builder(mActivityReference.get()) - .title(R.string.app_name) - .content(R.string.new_update_available) - .positiveText(R.string.update) - .negativeText(R.string.not_now) - .negativeColorRes(R.color.colorPrimary) - .onPositive(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - if (MiscUtils.isGooglePlayAvailable(mActivity)) { - ((OmniNotes)mActivity.getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.UPDATE, "Play Store"); - mActivityReference.get().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse - ("market://details?id=" + mActivity.getPackageName()))); - } else { - ((OmniNotes)mActivity.getApplication()).getAnalyticsHelper().trackEvent(AnalyticsHelper.CATEGORIES.UPDATE, "Drive Repository"); - mActivityReference.get().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants - .DRIVE_FOLDER_LAST_BUILD))); - } - } - }).build().show(); - } - - - @Override - protected void onPostExecute(Void result) { - if (isAlive(mActivityReference)) { - if (promptUpdate) { - promptUpdate(); - } else { - try { - boolean appVersionUpdated = AppVersionHelper.isAppUpdated(mActivity); - if (appVersionUpdated) { - showChangelog(); - restoreReminders(); - AppVersionHelper.updateAppVersionInPreferences(mActivity); - } - } catch (NameNotFoundException e) { - LogDelegate.e("Error retrieving app version", e); - } - } - } - } - - private void restoreReminders() { - Intent service = new Intent(mActivity, AlarmRestoreOnRebootService.class); - mActivity.startService(service); - } - - private void showChangelog() { - new MaterialDialog.Builder(mActivity) - .customView(R.layout.activity_changelog, false) - .positiveText(R.string.ok) - .build().show(); - } - - - private boolean isAlive(WeakReference weakActivityReference) { - return !(weakActivityReference.get() == null || weakActivityReference.get().isFinishing()); - } - - - /** - * Fetches application data from internet - */ - private PlayStoreMetadataFetcherResult getAppData() throws IOException, JSONException { - InputStream is = null; - InputStreamReader inputStreamReader = null; - try { - StringBuilder sb = new StringBuilder(); - URLConnection conn = new URL(BuildConfig.VERSION_CHECK_URL).openConnection(); - is = conn.getInputStream(); - inputStreamReader = new InputStreamReader(is); - BufferedReader br = new BufferedReader(inputStreamReader); - - String inputLine; - while ((inputLine = br.readLine()) != null) { - sb.append(inputLine); - } - - return new Gson().fromJson(sb.toString(), PlayStoreMetadataFetcherResult.class); - } finally { - SystemHelper.closeCloseable(inputStreamReader, is); - } - } - - - /** - * Checks parsing "android:versionName" if app has been updated - */ - private boolean isVersionUpdated(PlayStoreMetadataFetcherResult playStoreMetadataFetcherResult) - throws NameNotFoundException { - - String playStoreVersion = playStoreMetadataFetcherResult.getSoftwareVersion(); - - // Retrieval of installed app version - PackageInfo pInfo = mActivity.getPackageManager().getPackageInfo( - mActivity.getPackageName(), 0); - String installedVersion = pInfo.versionName; - - // Parsing version string to obtain major.minor.point (excluding eventually beta) - String[] playStoreVersionArray = playStoreVersion.split(BETA)[0].split("\\."); - String[] installedVersionArray = installedVersion.split(BETA)[0].split("\\."); - - // Versions strings are converted into integer - String playStoreVersionString = playStoreVersionArray[0]; - String installedVersionString = installedVersionArray[0]; - for (int i = 1; i < playStoreVersionArray.length; i++) { - playStoreVersionString += String.format("%02d", Integer.parseInt(playStoreVersionArray[i])); - installedVersionString += String.format("%02d", Integer.parseInt(installedVersionArray[i])); - } - - boolean playStoreHasMoreRecentVersion = Integer.parseInt(playStoreVersionString) > Integer.parseInt(installedVersionString); - boolean outOfBeta = Integer.parseInt(playStoreVersionString) == Integer.parseInt(installedVersionString) - && playStoreVersion.split("b").length == 1 && installedVersion.split("b").length == 2; - - return playStoreHasMoreRecentVersion || outOfBeta; - } + private static final String BETA = " Beta "; + private final WeakReference mActivityReference; + private final Activity mActivity; + private final SharedPreferences prefs; + private boolean promptUpdate = false; + private long now; + + + public UpdaterTask (Activity mActivity) { + this.mActivityReference = new WeakReference<>(mActivity); + this.mActivity = mActivity; + this.prefs = mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + } + + + @Override + protected void onPreExecute () { + now = System.currentTimeMillis(); + if (OmniNotes.isDebugBuild() || !ConnectionManager.internetAvailable(OmniNotes.getAppContext()) + || now < prefs.getLong(Constants + .PREF_LAST_UPDATE_CHECK, 0) + Constants.UPDATE_MIN_FREQUENCY) { + cancel(true); + } + super.onPreExecute(); + } + + + @Override + protected Void doInBackground (String... params) { + if (!isCancelled()) { + try { + // Temporary disabled untill MetadataFetcher will work again + // promptUpdate = isVersionUpdated(getAppData()); + promptUpdate = false; + if (promptUpdate) { + prefs.edit().putLong(Constants.PREF_LAST_UPDATE_CHECK, now).apply(); + } + } catch (Exception e) { + LogDelegate.w("Error fetching app metadata", e); + } + } + return null; + } + + + private void promptUpdate () { + new MaterialDialog.Builder(mActivityReference.get()) + .title(R.string.app_name) + .content(R.string.new_update_available) + .positiveText(R.string.update) + .negativeText(R.string.not_now) + .negativeColorRes(R.color.colorPrimary) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick (@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + if (MiscUtils.isGooglePlayAvailable(mActivity)) { + ((OmniNotes) mActivity.getApplication()).getAnalyticsHelper().trackEvent( + AnalyticsHelper.CATEGORIES.UPDATE, "Play Store"); + mActivityReference.get().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse + ("market://details?id=" + mActivity.getPackageName()))); + } else { + ((OmniNotes) mActivity.getApplication()).getAnalyticsHelper().trackEvent( + AnalyticsHelper.CATEGORIES.UPDATE, "Drive Repository"); + mActivityReference.get().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants + .DRIVE_FOLDER_LAST_BUILD))); + } + } + }).build().show(); + } + + + @Override + protected void onPostExecute (Void result) { + if (isAlive(mActivityReference)) { + if (promptUpdate) { + promptUpdate(); + } else { + try { + boolean appVersionUpdated = AppVersionHelper.isAppUpdated(mActivity); + if (appVersionUpdated) { + showChangelog(); + restoreReminders(); + AppVersionHelper.updateAppVersionInPreferences(mActivity); + } + } catch (NameNotFoundException e) { + LogDelegate.e("Error retrieving app version", e); + } + } + } + } + + private void restoreReminders () { + Intent service = new Intent(mActivity, AlarmRestoreOnRebootService.class); + mActivity.startService(service); + } + + private void showChangelog () { + new MaterialDialog.Builder(mActivity) + .customView(R.layout.activity_changelog, false) + .positiveText(R.string.ok) + .build().show(); + } + + + private boolean isAlive (WeakReference weakActivityReference) { + return !(weakActivityReference.get() == null || weakActivityReference.get().isFinishing()); + } + + + /** + * Fetches application data from internet + */ + private PlayStoreMetadataFetcherResult getAppData () throws IOException, JSONException { + InputStream is = null; + InputStreamReader inputStreamReader = null; + try { + StringBuilder sb = new StringBuilder(); + URLConnection conn = new URL(BuildConfig.VERSION_CHECK_URL).openConnection(); + is = conn.getInputStream(); + inputStreamReader = new InputStreamReader(is); + BufferedReader br = new BufferedReader(inputStreamReader); + + String inputLine; + while ((inputLine = br.readLine()) != null) { + sb.append(inputLine); + } + + return new Gson().fromJson(sb.toString(), PlayStoreMetadataFetcherResult.class); + } finally { + SystemHelper.closeCloseable(inputStreamReader, is); + } + } + + + /** + * Checks parsing "android:versionName" if app has been updated + */ + private boolean isVersionUpdated (PlayStoreMetadataFetcherResult playStoreMetadataFetcherResult) + throws NameNotFoundException { + + String playStoreVersion = playStoreMetadataFetcherResult.getSoftwareVersion(); + + // Retrieval of installed app version + PackageInfo pInfo = mActivity.getPackageManager().getPackageInfo( + mActivity.getPackageName(), 0); + String installedVersion = pInfo.versionName; + + // Parsing version string to obtain major.minor.point (excluding eventually beta) + String[] playStoreVersionArray = playStoreVersion.split(BETA)[0].split("\\."); + String[] installedVersionArray = installedVersion.split(BETA)[0].split("\\."); + + // Versions strings are converted into integer + String playStoreVersionString = playStoreVersionArray[0]; + String installedVersionString = installedVersionArray[0]; + for (int i = 1; i < playStoreVersionArray.length; i++) { + playStoreVersionString += String.format("%02d", Integer.parseInt(playStoreVersionArray[i])); + installedVersionString += String.format("%02d", Integer.parseInt(installedVersionArray[i])); + } + + boolean playStoreHasMoreRecentVersion = + Integer.parseInt(playStoreVersionString) > Integer.parseInt(installedVersionString); + boolean outOfBeta = Integer.parseInt(playStoreVersionString) == Integer.parseInt(installedVersionString) + && playStoreVersion.split("b").length == 1 && installedVersion.split("b").length == 2; + + return playStoreHasMoreRecentVersion || outOfBeta; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedEvent.java index 713c0f5eb5..173316d002 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedEvent.java @@ -24,11 +24,11 @@ */ public class NavigationUpdatedEvent { - public final Object navigationItem; + public final Object navigationItem; - public NavigationUpdatedEvent(Object navigationItem) { - LogDelegate.d(this.getClass().getName()); - this.navigationItem = navigationItem; - } + public NavigationUpdatedEvent (Object navigationItem) { + LogDelegate.d(this.getClass().getName()); + this.navigationItem = navigationItem; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedNavDrawerClosedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedNavDrawerClosedEvent.java index a99723a46b..1ab52d4fe1 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedNavDrawerClosedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NavigationUpdatedNavDrawerClosedEvent.java @@ -21,11 +21,11 @@ public class NavigationUpdatedNavDrawerClosedEvent { - public final Object navigationItem; + public final Object navigationItem; - public NavigationUpdatedNavDrawerClosedEvent(Object navigationItem) { - LogDelegate.d(this.getClass().getName()); - this.navigationItem = navigationItem; - } + public NavigationUpdatedNavDrawerClosedEvent (Object navigationItem) { + LogDelegate.d(this.getClass().getName()); + this.navigationItem = navigationItem; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesDeletedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesDeletedEvent.java index d74ca2fb52..03abc53de2 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesDeletedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesDeletedEvent.java @@ -17,19 +17,18 @@ package it.feio.android.omninotes.async.bus; -import java.util.List; - import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Note; +import java.util.List; public class NotesDeletedEvent { - public List notes; + public List notes; - public NotesDeletedEvent(List notes) { - LogDelegate.d(this.getClass().getName()); - this.notes = notes; - } + public NotesDeletedEvent (List notes) { + LogDelegate.d(this.getClass().getName()); + this.notes = notes; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesLoadedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesLoadedEvent.java index b72351e59f..f9ee164b03 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesLoadedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesLoadedEvent.java @@ -17,19 +17,18 @@ package it.feio.android.omninotes.async.bus; -import java.util.ArrayList; - import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Note; +import java.util.ArrayList; public class NotesLoadedEvent { - public ArrayList notes; + public ArrayList notes; - public NotesLoadedEvent(ArrayList notes) { - LogDelegate.d(this.getClass().getName()); - this.notes = notes; - } + public NotesLoadedEvent (ArrayList notes) { + LogDelegate.d(this.getClass().getName()); + this.notes = notes; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesMergeEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesMergeEvent.java index 02481ad6b1..af75c1adcb 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesMergeEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesMergeEvent.java @@ -21,11 +21,11 @@ public class NotesMergeEvent { - public final boolean keepMergedNotes; + public final boolean keepMergedNotes; - public NotesMergeEvent(boolean keepMergedNotes) { - LogDelegate.d(this.getClass().getName()); - this.keepMergedNotes = keepMergedNotes; - } + public NotesMergeEvent (boolean keepMergedNotes) { + LogDelegate.d(this.getClass().getName()); + this.keepMergedNotes = keepMergedNotes; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesUpdatedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesUpdatedEvent.java index e3c234a0b6..72124a2063 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesUpdatedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotesUpdatedEvent.java @@ -17,19 +17,18 @@ package it.feio.android.omninotes.async.bus; -import java.util.List; - import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Note; +import java.util.List; public class NotesUpdatedEvent { - public List notes; + public List notes; - public NotesUpdatedEvent(List notes) { - LogDelegate.d(this.getClass().getName()); - this.notes = notes; - } + public NotesUpdatedEvent (List notes) { + LogDelegate.d(this.getClass().getName()); + this.notes = notes; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotificationRemovedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotificationRemovedEvent.java index 9f8879c64a..2a704b426c 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotificationRemovedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/NotificationRemovedEvent.java @@ -18,17 +18,16 @@ package it.feio.android.omninotes.async.bus; import android.service.notification.StatusBarNotification; - import it.feio.android.omninotes.helpers.LogDelegate; public class NotificationRemovedEvent { - public StatusBarNotification statusBarNotification; + public StatusBarNotification statusBarNotification; - public NotificationRemovedEvent(StatusBarNotification statusBarNotification) { - LogDelegate.d(this.getClass().getName()); - this.statusBarNotification = statusBarNotification; - } + public NotificationRemovedEvent (StatusBarNotification statusBarNotification) { + LogDelegate.d(this.getClass().getName()); + this.statusBarNotification = statusBarNotification; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PasswordRemovedEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PasswordRemovedEvent.java index 34b7636ff8..233890627e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PasswordRemovedEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PasswordRemovedEvent.java @@ -21,7 +21,7 @@ public class PasswordRemovedEvent { - public PasswordRemovedEvent() { - LogDelegate.d(this.getClass().getName()); - } + public PasswordRemovedEvent () { + LogDelegate.d(this.getClass().getName()); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PushbulletReplyEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PushbulletReplyEvent.java index 259a27f00d..4b7819eb86 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PushbulletReplyEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/PushbulletReplyEvent.java @@ -22,10 +22,10 @@ public class PushbulletReplyEvent { - public String message; + public String message; - public PushbulletReplyEvent(String message) { - LogDelegate.d(this.getClass().getName()); - this.message = message; - } + public PushbulletReplyEvent (String message) { + LogDelegate.d(this.getClass().getName()); + this.message = message; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/SwitchFragmentEvent.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/SwitchFragmentEvent.java index 59f9eb01ab..c10d9e1099 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/SwitchFragmentEvent.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/bus/SwitchFragmentEvent.java @@ -21,16 +21,16 @@ public class SwitchFragmentEvent { - public enum Direction { - CHILDREN, PARENT - } + public enum Direction { + CHILDREN, PARENT + } - public Direction direction; + public Direction direction; - public SwitchFragmentEvent(Direction direction) { - LogDelegate.d(this.getClass().getName()); - this.direction = direction; - } + public SwitchFragmentEvent (Direction direction) { + LogDelegate.d(this.getClass().getName()); + this.direction = direction; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteLoaderTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteLoaderTask.java index 0b43f25a6f..ad846496e5 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteLoaderTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteLoaderTask.java @@ -17,14 +17,11 @@ package it.feio.android.omninotes.async.notes; import android.os.AsyncTask; -import android.util.Log; import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.bus.NotesLoadedEvent; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.exceptions.NotesLoadingException; import it.feio.android.omninotes.models.Note; -import it.feio.android.omninotes.utils.Constants; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; @@ -32,63 +29,63 @@ public class NoteLoaderTask extends AsyncTask> { - private static NoteLoaderTask instance; - - private NoteLoaderTask() {} - - - public static NoteLoaderTask getInstance() { - - if (instance != null) { - if (instance.getStatus() == Status.RUNNING && !instance.isCancelled()) { - instance.cancel(true); - } else if (instance.getStatus() == Status.PENDING) { - return instance; - } - } - - instance = new NoteLoaderTask(); - return instance; - } - - - @Override - protected ArrayList doInBackground(Object... params) { - - ArrayList notes = new ArrayList<>(); - String methodName = params[0].toString(); - DbHelper db = DbHelper.getInstance(); - - if (params.length < 2 || params[1] == null) { - try { - Method method = db.getClass().getDeclaredMethod(methodName); - notes = (ArrayList)method.invoke(db); - } catch (NoSuchMethodException e) { - return notes; - } catch (IllegalAccessException e) { - throw new NotesLoadingException("Error retrieving notes", e); - } catch (InvocationTargetException e) { - throw new NotesLoadingException("Error retrieving notes", e); - } - } else { - Object methodArgs = params[1]; - Class[] paramClass = new Class[]{methodArgs.getClass()}; - try { - Method method = db.getClass().getDeclaredMethod(methodName, paramClass); - notes = (ArrayList) method.invoke(db, paramClass[0].cast(methodArgs)); - } catch (Exception e) { - throw new NotesLoadingException("Error retrieving notes", e); - } - } - - return notes; - } - - - @Override - protected void onPostExecute(ArrayList notes) { - - super.onPostExecute(notes); - EventBus.getDefault().post(new NotesLoadedEvent(notes)); - } + private static NoteLoaderTask instance; + + private NoteLoaderTask () {} + + + public static NoteLoaderTask getInstance () { + + if (instance != null) { + if (instance.getStatus() == Status.RUNNING && !instance.isCancelled()) { + instance.cancel(true); + } else if (instance.getStatus() == Status.PENDING) { + return instance; + } + } + + instance = new NoteLoaderTask(); + return instance; + } + + + @Override + protected ArrayList doInBackground (Object... params) { + + ArrayList notes = new ArrayList<>(); + String methodName = params[0].toString(); + DbHelper db = DbHelper.getInstance(); + + if (params.length < 2 || params[1] == null) { + try { + Method method = db.getClass().getDeclaredMethod(methodName); + notes = (ArrayList) method.invoke(db); + } catch (NoSuchMethodException e) { + return notes; + } catch (IllegalAccessException e) { + throw new NotesLoadingException("Error retrieving notes", e); + } catch (InvocationTargetException e) { + throw new NotesLoadingException("Error retrieving notes", e); + } + } else { + Object methodArgs = params[1]; + Class[] paramClass = new Class[]{methodArgs.getClass()}; + try { + Method method = db.getClass().getDeclaredMethod(methodName, paramClass); + notes = (ArrayList) method.invoke(db, paramClass[0].cast(methodArgs)); + } catch (Exception e) { + throw new NotesLoadingException("Error retrieving notes", e); + } + } + + return notes; + } + + + @Override + protected void onPostExecute (ArrayList notes) { + + super.onPostExecute(notes); + EventBus.getDefault().post(new NotesLoadedEvent(notes)); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessor.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessor.java index b3a52a9082..de15ea9b9c 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessor.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessor.java @@ -21,50 +21,49 @@ import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.bus.NotesUpdatedEvent; import it.feio.android.omninotes.models.Note; - import java.util.ArrayList; import java.util.List; public abstract class NoteProcessor { - List notes; + List notes; - protected NoteProcessor(List notes) { - this.notes = new ArrayList<>(notes); - } + protected NoteProcessor (List notes) { + this.notes = new ArrayList<>(notes); + } - public void process() { - NotesProcessorTask task = new NotesProcessorTask(); - task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notes); - } + public void process () { + NotesProcessorTask task = new NotesProcessorTask(); + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notes); + } - protected abstract void processNote(Note note); + protected abstract void processNote (Note note); - class NotesProcessorTask extends AsyncTask, Void, List> { + class NotesProcessorTask extends AsyncTask, Void, List> { - @Override - protected List doInBackground(List... params) { - List notes = params[0]; - for (Note note : notes) { - processNote(note); - } - return notes; - } + @Override + protected List doInBackground (List... params) { + List notes = params[0]; + for (Note note : notes) { + processNote(note); + } + return notes; + } - @Override - protected void onPostExecute(List notes) { - afterProcess(notes); - } - } + @Override + protected void onPostExecute (List notes) { + afterProcess(notes); + } + } - protected void afterProcess(List notes) { - EventBus.getDefault().post(new NotesUpdatedEvent(notes)); - } + protected void afterProcess (List notes) { + EventBus.getDefault().post(new NotesUpdatedEvent(notes)); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorArchive.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorArchive.java index 5fb3e4e7a1..bb0ab6ea53 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorArchive.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorArchive.java @@ -17,25 +17,24 @@ package it.feio.android.omninotes.async.notes; -import java.util.List; - import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.models.Note; +import java.util.List; public class NoteProcessorArchive extends NoteProcessor { - boolean archive; + boolean archive; - public NoteProcessorArchive(List notes, boolean archive) { - super(notes); - this.archive = archive; - } + public NoteProcessorArchive (List notes, boolean archive) { + super(notes); + this.archive = archive; + } - @Override - protected void processNote(Note note) { - DbHelper.getInstance().archiveNote(note, archive); - } + @Override + protected void processNote (Note note) { + DbHelper.getInstance().archiveNote(note, archive); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorCategorize.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorCategorize.java index 834822c6d2..253bf1df63 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorCategorize.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorCategorize.java @@ -17,27 +17,26 @@ package it.feio.android.omninotes.async.notes; -import java.util.List; - import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.models.Category; import it.feio.android.omninotes.models.Note; +import java.util.List; public class NoteProcessorCategorize extends NoteProcessor { - Category category; + Category category; - public NoteProcessorCategorize(List notes, Category category) { - super(notes); - this.category = category; - } + public NoteProcessorCategorize (List notes, Category category) { + super(notes); + this.category = category; + } - @Override - protected void processNote(Note note) { - note.setCategory(category); - DbHelper.getInstance().updateNote(note, false); - } + @Override + protected void processNote (Note note) { + note.setCategory(category); + DbHelper.getInstance().updateNote(note, false); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorDelete.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorDelete.java index d0e5078884..664e82be9e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorDelete.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorDelete.java @@ -24,42 +24,41 @@ import it.feio.android.omninotes.models.Attachment; import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.utils.StorageHelper; - import java.util.List; public class NoteProcessorDelete extends NoteProcessor { - private final boolean keepAttachments; + private final boolean keepAttachments; - public NoteProcessorDelete(List notes) { - this(notes, false); - } + public NoteProcessorDelete (List notes) { + this(notes, false); + } - public NoteProcessorDelete(List notes, boolean keepAttachments) { - super(notes); - this.keepAttachments = keepAttachments; - } + public NoteProcessorDelete (List notes, boolean keepAttachments) { + super(notes); + this.keepAttachments = keepAttachments; + } - @Override - protected void processNote(Note note) { - DbHelper db = DbHelper.getInstance(); - if (db.deleteNote(note) && !keepAttachments) { - for (Attachment mAttachment : note.getAttachmentsList()) { - StorageHelper.deleteExternalStoragePrivateFile(OmniNotes.getAppContext(), mAttachment.getUri() - .getLastPathSegment()); - } - } - } + @Override + protected void processNote (Note note) { + DbHelper db = DbHelper.getInstance(); + if (db.deleteNote(note) && !keepAttachments) { + for (Attachment mAttachment : note.getAttachmentsList()) { + StorageHelper.deleteExternalStoragePrivateFile(OmniNotes.getAppContext(), mAttachment.getUri() + .getLastPathSegment()); + } + } + } - @Override - protected void afterProcess(List notes) { - EventBus.getDefault().post(new NotesDeletedEvent(notes)); - } + @Override + protected void afterProcess (List notes) { + EventBus.getDefault().post(new NotesDeletedEvent(notes)); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorTrash.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorTrash.java index 613bd305f2..5427a1cbb6 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorTrash.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/NoteProcessorTrash.java @@ -17,34 +17,33 @@ package it.feio.android.omninotes.async.notes; -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.utils.ReminderHelper; import it.feio.android.omninotes.utils.ShortcutHelper; +import java.util.List; public class NoteProcessorTrash extends NoteProcessor { - boolean trash; + boolean trash; - public NoteProcessorTrash(List notes, boolean trash) { - super(notes); - this.trash = trash; - } + public NoteProcessorTrash (List notes, boolean trash) { + super(notes); + this.trash = trash; + } - @Override - protected void processNote(Note note) { - if (trash) { - ShortcutHelper.removeshortCut(OmniNotes.getAppContext(), note); - ReminderHelper.removeReminder(OmniNotes.getAppContext(), note); - } else { - ReminderHelper.addReminder(OmniNotes.getAppContext(), note); - } - DbHelper.getInstance().trashNote(note, trash); + @Override + protected void processNote (Note note) { + if (trash) { + ShortcutHelper.removeshortCut(OmniNotes.getAppContext(), note); + ReminderHelper.removeReminder(OmniNotes.getAppContext(), note); + } else { + ReminderHelper.addReminder(OmniNotes.getAppContext(), note); } + DbHelper.getInstance().trashNote(note, trash); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/SaveNoteTask.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/SaveNoteTask.java index fdaa9f53fa..b727aa5c8e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/SaveNoteTask.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/notes/SaveNoteTask.java @@ -19,9 +19,6 @@ import android.content.Context; import android.os.AsyncTask; - -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.LogDelegate; @@ -31,78 +28,79 @@ import it.feio.android.omninotes.utils.ReminderHelper; import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.date.DateUtils; +import java.util.List; public class SaveNoteTask extends AsyncTask { - private Context context; - private boolean updateLastModification = true; - private OnNoteSaved mOnNoteSaved; - - - public SaveNoteTask(boolean updateLastModification) { - this(null, updateLastModification); - } - - - public SaveNoteTask(OnNoteSaved mOnNoteSaved, boolean updateLastModification) { - super(); - this.context = OmniNotes.getAppContext(); - this.mOnNoteSaved = mOnNoteSaved; - this.updateLastModification = updateLastModification; - } - - - @Override - protected Note doInBackground(Note... params) { - Note note = params[0]; - purgeRemovedAttachments(note); - boolean reminderMustBeSet = DateUtils.isFuture(note.getAlarm()); - if (reminderMustBeSet) { - note.setReminderFired(false); - } - note = DbHelper.getInstance().updateNote(note, updateLastModification); - if (reminderMustBeSet) { - ReminderHelper.addReminder(context, note); - } - return note; - } - - - private void purgeRemovedAttachments(Note note) { - List deletedAttachments = note.getAttachmentsListOld(); - for (Attachment attachment : note.getAttachmentsList()) { - if (attachment.getId() != null) { - // Workaround to prevent deleting attachments if instance is changed (app restart) - if (deletedAttachments.indexOf(attachment) == -1) { - attachment = getFixedAttachmentInstance(deletedAttachments, attachment); - } - deletedAttachments.remove(attachment); - } - } - // Remove from database deleted attachments - for (Attachment deletedAttachment : deletedAttachments) { - StorageHelper.delete(context, deletedAttachment.getUri().getPath()); - LogDelegate.d("Removed attachment " + deletedAttachment.getUri()); - } - } - - - private Attachment getFixedAttachmentInstance(List deletedAttachments, Attachment attachment) { - for (Attachment deletedAttachment : deletedAttachments) { - if (deletedAttachment.getId().equals(attachment.getId())) { - return deletedAttachment; - } - } - return attachment; + private Context context; + private boolean updateLastModification = true; + private OnNoteSaved mOnNoteSaved; + + + public SaveNoteTask (boolean updateLastModification) { + this(null, updateLastModification); + } + + + public SaveNoteTask (OnNoteSaved mOnNoteSaved, boolean updateLastModification) { + super(); + this.context = OmniNotes.getAppContext(); + this.mOnNoteSaved = mOnNoteSaved; + this.updateLastModification = updateLastModification; + } + + + @Override + protected Note doInBackground (Note... params) { + Note note = params[0]; + purgeRemovedAttachments(note); + boolean reminderMustBeSet = DateUtils.isFuture(note.getAlarm()); + if (reminderMustBeSet) { + note.setReminderFired(false); + } + note = DbHelper.getInstance().updateNote(note, updateLastModification); + if (reminderMustBeSet) { + ReminderHelper.addReminder(context, note); } + return note; + } - @Override - protected void onPostExecute(Note note) { - super.onPostExecute(note); - if (this.mOnNoteSaved != null) { - mOnNoteSaved.onNoteSaved(note); + private void purgeRemovedAttachments (Note note) { + List deletedAttachments = note.getAttachmentsListOld(); + for (Attachment attachment : note.getAttachmentsList()) { + if (attachment.getId() != null) { + // Workaround to prevent deleting attachments if instance is changed (app restart) + if (deletedAttachments.indexOf(attachment) == -1) { + attachment = getFixedAttachmentInstance(deletedAttachments, attachment); } - } + deletedAttachments.remove(attachment); + } + } + // Remove from database deleted attachments + for (Attachment deletedAttachment : deletedAttachments) { + StorageHelper.delete(context, deletedAttachment.getUri().getPath()); + LogDelegate.d("Removed attachment " + deletedAttachment.getUri()); + } + } + + + private Attachment getFixedAttachmentInstance (List deletedAttachments, Attachment attachment) { + for (Attachment deletedAttachment : deletedAttachments) { + if (deletedAttachment.getId().equals(attachment.getId())) { + return deletedAttachment; + } + } + return attachment; + } + + + @Override + protected void onPostExecute (Note note) { + super.onPostExecute(note); + if (this.mOnNoteSaved != null) { + mOnNoteSaved.onNoteSaved(note); + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/async/upgrade/UpgradeProcessor.java b/omniNotes/src/main/java/it/feio/android/omninotes/async/upgrade/UpgradeProcessor.java index 13056dd431..7abf8ede57 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/async/upgrade/UpgradeProcessor.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/async/upgrade/UpgradeProcessor.java @@ -20,15 +20,6 @@ import android.content.ContentValues; import android.net.Uri; import android.text.TextUtils; - -import org.apache.commons.io.FilenameUtils; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.LogDelegate; @@ -37,146 +28,152 @@ import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.ReminderHelper; import it.feio.android.omninotes.utils.StorageHelper; +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.io.FilenameUtils; /** - * Processor used to perform asynchronous tasks on database upgrade. - * It's not intended to be used to perform actions strictly related to DB (for this - * {@link it.feio.android.omninotes.db.DbHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)} - * DbHelper.onUpgrade()} is used + * Processor used to perform asynchronous tasks on database upgrade. It's not intended to be used to perform actions + * strictly related to DB (for this {@link it.feio.android.omninotes.db.DbHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, + * int, int)} DbHelper.onUpgrade()} is used */ public class UpgradeProcessor { - private final static String METHODS_PREFIX = "onUpgradeTo"; + private final static String METHODS_PREFIX = "onUpgradeTo"; - private static UpgradeProcessor instance; + private static UpgradeProcessor instance; - private UpgradeProcessor() { - } + private UpgradeProcessor () { + } - private static UpgradeProcessor getInstance() { - if (instance == null) { - instance = new UpgradeProcessor(); - } - return instance; + private static UpgradeProcessor getInstance () { + if (instance == null) { + instance = new UpgradeProcessor(); + } + return instance; + } + + + public static void process (int dbOldVersion, int dbNewVersion) + throws InvocationTargetException, IllegalAccessException { + try { + List methodsToLaunch = getInstance().getMethodsToLaunch(dbOldVersion, dbNewVersion); + for (Method methodToLaunch : methodsToLaunch) { + LogDelegate.d("Running upgrade processing method: " + methodToLaunch.getName()); + methodToLaunch.invoke(getInstance()); + } + } catch (SecurityException | IllegalAccessException | InvocationTargetException e) { + LogDelegate.e("Explosion processing upgrade!", e); + throw e; } + } - public static void process(int dbOldVersion, int dbNewVersion) throws InvocationTargetException, IllegalAccessException { - try { - List methodsToLaunch = getInstance().getMethodsToLaunch(dbOldVersion, dbNewVersion); - for (Method methodToLaunch : methodsToLaunch) { - LogDelegate.d("Running upgrade processing method: " + methodToLaunch.getName()); - methodToLaunch.invoke(getInstance()); - } - } catch (SecurityException | IllegalAccessException | InvocationTargetException e) { - LogDelegate.e("Explosion processing upgrade!", e); - throw e; + private List getMethodsToLaunch (int dbOldVersion, int dbNewVersion) { + List methodsToLaunch = new ArrayList<>(); + Method[] declaredMethods = getInstance().getClass().getDeclaredMethods(); + for (Method declaredMethod : declaredMethods) { + if (declaredMethod.getName().contains(METHODS_PREFIX)) { + int methodVersionPostfix = Integer.parseInt(declaredMethod.getName().replace(METHODS_PREFIX, "")); + if (dbOldVersion <= methodVersionPostfix && methodVersionPostfix <= dbNewVersion) { + methodsToLaunch.add(declaredMethod); } + } } - - - private List getMethodsToLaunch(int dbOldVersion, int dbNewVersion) { - List methodsToLaunch = new ArrayList<>(); - Method[] declaredMethods = getInstance().getClass().getDeclaredMethods(); - for (Method declaredMethod : declaredMethods) { - if (declaredMethod.getName().contains(METHODS_PREFIX)) { - int methodVersionPostfix = Integer.parseInt(declaredMethod.getName().replace(METHODS_PREFIX, "")); - if (dbOldVersion <= methodVersionPostfix && methodVersionPostfix <= dbNewVersion) { - methodsToLaunch.add(declaredMethod); - } - } + return methodsToLaunch; + } + + + /** + * Adjustment of all the old attachments without mimetype field set into DB + */ + private void onUpgradeTo476 () { + final DbHelper dbHelper = DbHelper.getInstance(); + for (Attachment attachment : dbHelper.getAllAttachments()) { + if (attachment.getMime_type() == null) { + String mimeType = StorageHelper.getMimeType(attachment.getUri().toString()); + if (!TextUtils.isEmpty(mimeType)) { + String type = mimeType.replaceFirst("/.*", ""); + switch (type) { + case "image": + attachment.setMime_type(Constants.MIME_TYPE_IMAGE); + break; + case "video": + attachment.setMime_type(Constants.MIME_TYPE_VIDEO); + break; + case "audio": + attachment.setMime_type(Constants.MIME_TYPE_AUDIO); + break; + default: + attachment.setMime_type(Constants.MIME_TYPE_FILES); + break; + } + dbHelper.updateAttachment(attachment); + } else { + attachment.setMime_type(Constants.MIME_TYPE_FILES); } - return methodsToLaunch; + } } - - - /** - * Adjustment of all the old attachments without mimetype field set into DB - */ - private void onUpgradeTo476() { - final DbHelper dbHelper = DbHelper.getInstance(); - for (Attachment attachment : dbHelper.getAllAttachments()) { - if (attachment.getMime_type() == null) { - String mimeType = StorageHelper.getMimeType(attachment.getUri().toString()); - if (!TextUtils.isEmpty(mimeType)) { - String type = mimeType.replaceFirst("/.*", ""); - switch (type) { - case "image": - attachment.setMime_type(Constants.MIME_TYPE_IMAGE); - break; - case "video": - attachment.setMime_type(Constants.MIME_TYPE_VIDEO); - break; - case "audio": - attachment.setMime_type(Constants.MIME_TYPE_AUDIO); - break; - default: - attachment.setMime_type(Constants.MIME_TYPE_FILES); - break; - } - dbHelper.updateAttachment(attachment); - } else { - attachment.setMime_type(Constants.MIME_TYPE_FILES); - } - } - } + } + + + /** + * Upgrades all the old audio attachments to the new format 3gpp to avoid to exchange them for videos + */ + private void onUpgradeTo480 () { + final DbHelper dbHelper = DbHelper.getInstance(); + for (Attachment attachment : dbHelper.getAllAttachments()) { + if ("audio/3gp".equals(attachment.getMime_type()) || "audio/3gpp".equals(attachment.getMime_type + ())) { + + // File renaming + File from = new File(attachment.getUriPath()); + FilenameUtils.getExtension(from.getName()); + File to = new File(from.getParent(), from.getName().replace(FilenameUtils.getExtension(from + .getName()), Constants.MIME_TYPE_AUDIO_EXT)); + from.renameTo(to); + + // Note's attachment update + attachment.setUri(Uri.fromFile(to)); + attachment.setMime_type(Constants.MIME_TYPE_AUDIO); + dbHelper.updateAttachment(attachment); + } } + } - /** - * Upgrades all the old audio attachments to the new format 3gpp to avoid to exchange them for videos - */ - private void onUpgradeTo480() { - final DbHelper dbHelper = DbHelper.getInstance(); - for (Attachment attachment : dbHelper.getAllAttachments()) { - if ("audio/3gp".equals(attachment.getMime_type()) || "audio/3gpp".equals(attachment.getMime_type - ())) { - - // File renaming - File from = new File(attachment.getUriPath()); - FilenameUtils.getExtension(from.getName()); - File to = new File(from.getParent(), from.getName().replace(FilenameUtils.getExtension(from - .getName()), Constants.MIME_TYPE_AUDIO_EXT)); - from.renameTo(to); - - // Note's attachment update - attachment.setUri(Uri.fromFile(to)); - attachment.setMime_type(Constants.MIME_TYPE_AUDIO); - dbHelper.updateAttachment(attachment); - } - } - } - - - /** - * Reschedule reminders after upgrade - */ - private void onUpgradeTo482() { - for (Note note : DbHelper.getInstance().getNotesWithReminderNotFired()) { - ReminderHelper.addReminder(OmniNotes.getAppContext(), note); - } - } - - - /** - * Ensures that no duplicates will be found during the creation-to-id transition - */ - private void onUpgradeTo501() { - List creations = new ArrayList<>(); - for (Note note : DbHelper.getInstance().getAllNotes(false)) { - if (creations.contains(note.getCreation())) { - - ContentValues values = new ContentValues(); - values.put(DbHelper.KEY_CREATION, note.getCreation() + (long) (Math.random() * 999)); - DbHelper.getInstance().getDatabase().update(DbHelper.TABLE_NOTES, values, DbHelper.KEY_TITLE + - " = ? AND " + DbHelper.KEY_CREATION + " = ? AND " + DbHelper.KEY_CONTENT + " = ?", new String[]{note - .getTitle(), String.valueOf(note.getCreation()), note.getContent()}); - } - creations.add(note.getCreation()); - } - } + /** + * Reschedule reminders after upgrade + */ + private void onUpgradeTo482 () { + for (Note note : DbHelper.getInstance().getNotesWithReminderNotFired()) { + ReminderHelper.addReminder(OmniNotes.getAppContext(), note); + } + } + + + /** + * Ensures that no duplicates will be found during the creation-to-id transition + */ + private void onUpgradeTo501 () { + List creations = new ArrayList<>(); + for (Note note : DbHelper.getInstance().getAllNotes(false)) { + if (creations.contains(note.getCreation())) { + + ContentValues values = new ContentValues(); + values.put(DbHelper.KEY_CREATION, note.getCreation() + (long) (Math.random() * 999)); + DbHelper.getInstance().getDatabase().update(DbHelper.TABLE_NOTES, values, DbHelper.KEY_TITLE + + " = ? AND " + DbHelper.KEY_CREATION + " = ? AND " + DbHelper.KEY_CONTENT + " = ?", new String[]{note + .getTitle(), String.valueOf(note.getCreation()), note.getContent()}); + } + creations.add(note.getCreation()); + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/db/DbHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/db/DbHelper.java index eee5357edd..898c0ab778 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/db/DbHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/db/DbHelper.java @@ -24,18 +24,6 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; - -import org.apache.commons.lang.StringEscapeUtils; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.regex.Pattern; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.async.upgrade.UpgradeProcessor; import it.feio.android.omninotes.helpers.LogDelegate; @@ -50,1001 +38,1019 @@ import it.feio.android.omninotes.utils.Navigation; import it.feio.android.omninotes.utils.Security; import it.feio.android.omninotes.utils.TagsHelper; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.regex.Pattern; +import org.apache.commons.lang.StringEscapeUtils; public class DbHelper extends SQLiteOpenHelper { - // Database name - private static final String DATABASE_NAME = Constants.DATABASE_NAME; - // Database version aligned if possible to software version - private static final int DATABASE_VERSION = 560; - // Sql query file directory - private static final String SQL_DIR = "sql"; - - // Notes table name - public static final String TABLE_NOTES = "notes"; - // Notes table columns - public static final String KEY_ID = "creation"; - public static final String KEY_CREATION = "creation"; - public static final String KEY_LAST_MODIFICATION = "last_modification"; - public static final String KEY_TITLE = "title"; - public static final String KEY_CONTENT = "content"; - public static final String KEY_ARCHIVED = "archived"; - public static final String KEY_TRASHED = "trashed"; - public static final String KEY_REMINDER = "alarm"; - public static final String KEY_REMINDER_FIRED = "reminder_fired"; - public static final String KEY_RECURRENCE_RULE = "recurrence_rule"; - public static final String KEY_LATITUDE = "latitude"; - public static final String KEY_LONGITUDE = "longitude"; - public static final String KEY_ADDRESS = "address"; - public static final String KEY_CATEGORY = "category_id"; - public static final String KEY_LOCKED = "locked"; - public static final String KEY_CHECKLIST = "checklist"; - - // Attachments table name - public static final String TABLE_ATTACHMENTS = "attachments"; - // Attachments table columns - public static final String KEY_ATTACHMENT_ID = "attachment_id"; - public static final String KEY_ATTACHMENT_URI = "uri"; - public static final String KEY_ATTACHMENT_NAME = "name"; - public static final String KEY_ATTACHMENT_SIZE = "size"; - public static final String KEY_ATTACHMENT_LENGTH = "length"; - public static final String KEY_ATTACHMENT_MIME_TYPE = "mime_type"; - public static final String KEY_ATTACHMENT_NOTE_ID = "note_id"; - - // Categories table name - public static final String TABLE_CATEGORY = "categories"; - // Categories table columns - public static final String KEY_CATEGORY_ID = "category_id"; - public static final String KEY_CATEGORY_NAME = "name"; - public static final String KEY_CATEGORY_DESCRIPTION = "description"; - public static final String KEY_CATEGORY_COLOR = "color"; - - // Queries - private static final String CREATE_QUERY = "create.sql"; - private static final String UPGRADE_QUERY_PREFIX = "upgrade-"; - private static final String UPGRADE_QUERY_SUFFIX = ".sql"; - - - private final Context mContext; - private final SharedPreferences prefs; - - private static DbHelper instance = null; - private SQLiteDatabase db; - - - public static synchronized DbHelper getInstance() { - return getInstance(OmniNotes.getAppContext()); - } - - - public static synchronized DbHelper getInstance(Context context) { - if (instance == null) { - instance = new DbHelper(context); - } - return instance; + // Database name + private static final String DATABASE_NAME = Constants.DATABASE_NAME; + // Database version aligned if possible to software version + private static final int DATABASE_VERSION = 560; + // Sql query file directory + private static final String SQL_DIR = "sql"; + + // Notes table name + public static final String TABLE_NOTES = "notes"; + // Notes table columns + public static final String KEY_ID = "creation"; + public static final String KEY_CREATION = "creation"; + public static final String KEY_LAST_MODIFICATION = "last_modification"; + public static final String KEY_TITLE = "title"; + public static final String KEY_CONTENT = "content"; + public static final String KEY_ARCHIVED = "archived"; + public static final String KEY_TRASHED = "trashed"; + public static final String KEY_REMINDER = "alarm"; + public static final String KEY_REMINDER_FIRED = "reminder_fired"; + public static final String KEY_RECURRENCE_RULE = "recurrence_rule"; + public static final String KEY_LATITUDE = "latitude"; + public static final String KEY_LONGITUDE = "longitude"; + public static final String KEY_ADDRESS = "address"; + public static final String KEY_CATEGORY = "category_id"; + public static final String KEY_LOCKED = "locked"; + public static final String KEY_CHECKLIST = "checklist"; + + // Attachments table name + public static final String TABLE_ATTACHMENTS = "attachments"; + // Attachments table columns + public static final String KEY_ATTACHMENT_ID = "attachment_id"; + public static final String KEY_ATTACHMENT_URI = "uri"; + public static final String KEY_ATTACHMENT_NAME = "name"; + public static final String KEY_ATTACHMENT_SIZE = "size"; + public static final String KEY_ATTACHMENT_LENGTH = "length"; + public static final String KEY_ATTACHMENT_MIME_TYPE = "mime_type"; + public static final String KEY_ATTACHMENT_NOTE_ID = "note_id"; + + // Categories table name + public static final String TABLE_CATEGORY = "categories"; + // Categories table columns + public static final String KEY_CATEGORY_ID = "category_id"; + public static final String KEY_CATEGORY_NAME = "name"; + public static final String KEY_CATEGORY_DESCRIPTION = "description"; + public static final String KEY_CATEGORY_COLOR = "color"; + + // Queries + private static final String CREATE_QUERY = "create.sql"; + private static final String UPGRADE_QUERY_PREFIX = "upgrade-"; + private static final String UPGRADE_QUERY_SUFFIX = ".sql"; + + + private final Context mContext; + private final SharedPreferences prefs; + + private static DbHelper instance = null; + private SQLiteDatabase db; + + + public static synchronized DbHelper getInstance () { + return getInstance(OmniNotes.getAppContext()); + } + + + public static synchronized DbHelper getInstance (Context context) { + if (instance == null) { + instance = new DbHelper(context); } + return instance; + } - public static synchronized DbHelper getInstance(boolean forcedNewInstance) { - if (instance == null || forcedNewInstance) { - Context context = instance.mContext == null ? OmniNotes.getAppContext() : instance.mContext; - instance = new DbHelper(context); - } - return instance; - } - - - private DbHelper(Context mContext) { - super(mContext, DATABASE_NAME, null, DATABASE_VERSION); - this.mContext = mContext; - this.prefs = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + public static synchronized DbHelper getInstance (boolean forcedNewInstance) { + if (instance == null || forcedNewInstance) { + Context context = instance.mContext == null ? OmniNotes.getAppContext() : instance.mContext; + instance = new DbHelper(context); } + return instance; + } - public String getDatabaseName() { - return DATABASE_NAME; - } + private DbHelper (Context mContext) { + super(mContext, DATABASE_NAME, null, DATABASE_VERSION); + this.mContext = mContext; + this.prefs = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + } - public SQLiteDatabase getDatabase() { - return getDatabase(false); - } + public String getDatabaseName () { + return DATABASE_NAME; + } - public SQLiteDatabase getDatabase(boolean forceWritable) { - try { - return forceWritable ? getWritableDatabase() : getReadableDatabase(); - } catch (IllegalStateException e) { - return this.db; - } - } + public SQLiteDatabase getDatabase () { + return getDatabase(false); + } - @Override - public void onCreate(SQLiteDatabase db) { - try { - LogDelegate.i("Database creation"); - execSqlFile(CREATE_QUERY, db); - } catch (IOException exception) { - throw new RuntimeException("Database creation failed", exception); - } + public SQLiteDatabase getDatabase (boolean forceWritable) { + try { + return forceWritable ? getWritableDatabase() : getReadableDatabase(); + } catch (IllegalStateException e) { + return this.db; } + } - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - this.db = db; - LogDelegate.i("Upgrading database version from " + oldVersion + " to " + newVersion); - - try { - - UpgradeProcessor.process(oldVersion, newVersion); - - for (String sqlFile : AssetUtils.list(SQL_DIR, mContext.getAssets())) { - if (sqlFile.startsWith(UPGRADE_QUERY_PREFIX)) { - int fileVersion = Integer.parseInt(sqlFile.substring(UPGRADE_QUERY_PREFIX.length(), - sqlFile.length() - UPGRADE_QUERY_SUFFIX.length())); - if (fileVersion > oldVersion && fileVersion <= newVersion) { - execSqlFile(sqlFile, db); - } - } - } - LogDelegate.i("Database upgrade successful"); - - } catch (IOException |InvocationTargetException | IllegalAccessException e) { - throw new RuntimeException("Database upgrade failed", e); - } + @Override + public void onCreate (SQLiteDatabase db) { + try { + LogDelegate.i("Database creation"); + execSqlFile(CREATE_QUERY, db); + } catch (IOException exception) { + throw new RuntimeException("Database creation failed", exception); } + } - public Note updateNote(Note note, boolean updateLastModification) { - db = getDatabase(true); - - String content = note.isLocked() - ? Security.encrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, "")) - : note.getContent(); - - // To ensure note and attachments insertions are atomic and boost performances transaction are used - db.beginTransaction(); - - ContentValues values = new ContentValues(); - values.put(KEY_TITLE, note.getTitle()); - values.put(KEY_CONTENT, content); - values.put(KEY_CREATION, note.getCreation() != null ? note.getCreation() : Calendar.getInstance().getTimeInMillis()); - long lastModification = note.getLastModification() != null && !updateLastModification - ? note.getLastModification() - : Calendar.getInstance().getTimeInMillis(); - values.put(KEY_LAST_MODIFICATION, lastModification); - values.put(KEY_ARCHIVED, note.isArchived()); - values.put(KEY_TRASHED, note.isTrashed()); - values.put(KEY_REMINDER, note.getAlarm()); - values.put(KEY_REMINDER_FIRED, note.isReminderFired()); - values.put(KEY_RECURRENCE_RULE, note.getRecurrenceRule()); - values.put(KEY_LATITUDE, note.getLatitude()); - values.put(KEY_LONGITUDE, note.getLongitude()); - values.put(KEY_ADDRESS, note.getAddress()); - values.put(KEY_CATEGORY, note.getCategory() != null ? note.getCategory().getId() : null); - values.put(KEY_LOCKED, note.isLocked() != null && note.isLocked()); - values.put(KEY_CHECKLIST, note.isChecklist() != null && note.isChecklist()); - - db.insertWithOnConflict(TABLE_NOTES, KEY_ID, values, SQLiteDatabase.CONFLICT_REPLACE); - LogDelegate.d("Updated note titled '" + note.getTitle() + "'"); - - // Updating attachments - List deletedAttachments = note.getAttachmentsListOld(); - for (Attachment attachment : note.getAttachmentsList()) { - updateAttachment(note.get_id() != null ? note.get_id() : values.getAsLong(KEY_CREATION), attachment, db); - deletedAttachments.remove(attachment); - } - // Remove from database deleted attachments - for (Attachment attachmentDeleted : deletedAttachments) { - db.delete(TABLE_ATTACHMENTS, KEY_ATTACHMENT_ID + " = ?", - new String[]{String.valueOf(attachmentDeleted.getId())}); - } - - db.setTransactionSuccessful(); - db.endTransaction(); - - // Fill the note with correct data before returning it - note.setCreation(note.getCreation() != null ? note.getCreation() : values.getAsLong(KEY_CREATION)); - note.setLastModification(values.getAsLong(KEY_LAST_MODIFICATION)); + @Override + public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) { + this.db = db; + LogDelegate.i("Upgrading database version from " + oldVersion + " to " + newVersion); - return note; - } + try { + UpgradeProcessor.process(oldVersion, newVersion); - protected void execSqlFile(String sqlFile, SQLiteDatabase db) throws SQLException, IOException { - LogDelegate.i(" exec sql file: {}" + sqlFile); - for (String sqlInstruction : SqlParser.parseSqlFile(SQL_DIR + "/" + sqlFile, mContext.getAssets())) { - LogDelegate.v(" sql: {}" + sqlInstruction); - try { - db.execSQL(sqlInstruction); - } catch (Exception e) { - LogDelegate.e("Error executing command: " + sqlInstruction, e); - } + for (String sqlFile : AssetUtils.list(SQL_DIR, mContext.getAssets())) { + if (sqlFile.startsWith(UPGRADE_QUERY_PREFIX)) { + int fileVersion = Integer.parseInt(sqlFile.substring(UPGRADE_QUERY_PREFIX.length(), + sqlFile.length() - UPGRADE_QUERY_SUFFIX.length())); + if (fileVersion > oldVersion && fileVersion <= newVersion) { + execSqlFile(sqlFile, db); + } } - } - - - /** - * Attachments update - * */ - public Attachment updateAttachment(Attachment attachment) { - return updateAttachment(-1, attachment, getDatabase(true)); - } - - - /** - * New attachment insertion - * */ - public Attachment updateAttachment(long noteId, Attachment attachment, SQLiteDatabase db) { - ContentValues valuesAttachments = new ContentValues(); - valuesAttachments.put(KEY_ATTACHMENT_ID, attachment.getId() != null ? attachment.getId() : Calendar - .getInstance().getTimeInMillis()); - valuesAttachments.put(KEY_ATTACHMENT_NOTE_ID, noteId); - valuesAttachments.put(KEY_ATTACHMENT_URI, attachment.getUri().toString()); - valuesAttachments.put(KEY_ATTACHMENT_MIME_TYPE, attachment.getMime_type()); - valuesAttachments.put(KEY_ATTACHMENT_NAME, attachment.getName()); - valuesAttachments.put(KEY_ATTACHMENT_SIZE, attachment.getSize()); - valuesAttachments.put(KEY_ATTACHMENT_LENGTH, attachment.getLength()); - db.insertWithOnConflict(TABLE_ATTACHMENTS, KEY_ATTACHMENT_ID, valuesAttachments, SQLiteDatabase.CONFLICT_REPLACE); - return attachment; - } - - - /** - * Getting single note - */ - public Note getNote(long id) { - List notes = getNotes(" WHERE " + KEY_ID + " = " + id, true); - return notes.isEmpty() ? null : notes.get(0); - } - - - /** - * Getting All notes - * - * @param checkNavigation Tells if navigation status (notes, archived) must be kept in - * consideration or if all notes have to be retrieved - * @return Notes list - */ - public List getAllNotes(Boolean checkNavigation) { - String whereCondition = ""; - if (checkNavigation) { - int navigation = Navigation.getNavigation(); - switch (navigation) { - case Navigation.NOTES: - return getNotesActive(); - case Navigation.ARCHIVE: - return getNotesArchived(); - case Navigation.REMINDERS: - return getNotesWithReminder(prefs.getBoolean(Constants.PREF_FILTER_PAST_REMINDERS, false)); - case Navigation.TRASH: - return getNotesTrashed(); - case Navigation.UNCATEGORIZED: - return getNotesUncategorized(); - case Navigation.CATEGORY: - return getNotesByCategory(Navigation.getCategory()); - default: - return getNotes(whereCondition, true); - } - } else { - return getNotes(whereCondition, true); - } - - } - - - public List getNotesActive() { - String whereCondition = " WHERE " + KEY_ARCHIVED + " IS NOT 1 AND " + KEY_TRASHED + " IS NOT 1 "; - return getNotes(whereCondition, true); - } - - - public List getNotesArchived() { - String whereCondition = " WHERE " + KEY_ARCHIVED + " = 1 AND " + KEY_TRASHED + " IS NOT 1 "; - return getNotes(whereCondition, true); - } - + } + LogDelegate.i("Database upgrade successful"); - public List getNotesTrashed() { - String whereCondition = " WHERE " + KEY_TRASHED + " = 1 "; - return getNotes(whereCondition, true); + } catch (IOException | InvocationTargetException | IllegalAccessException e) { + throw new RuntimeException("Database upgrade failed", e); } - - - public List getNotesUncategorized() { - String whereCondition = " WHERE " - + "(" + KEY_CATEGORY_ID + " IS NULL OR " + KEY_CATEGORY_ID + " == 0) " - + "AND " + KEY_TRASHED + " IS NOT 1"; - return getNotes(whereCondition, true); + } + + + public Note updateNote (Note note, boolean updateLastModification) { + db = getDatabase(true); + + String content = note.isLocked() + ? Security.encrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, "")) + : note.getContent(); + + // To ensure note and attachments insertions are atomic and boost performances transaction are used + db.beginTransaction(); + + ContentValues values = new ContentValues(); + values.put(KEY_TITLE, note.getTitle()); + values.put(KEY_CONTENT, content); + values.put(KEY_CREATION, + note.getCreation() != null ? note.getCreation() : Calendar.getInstance().getTimeInMillis()); + long lastModification = note.getLastModification() != null && !updateLastModification + ? note.getLastModification() + : Calendar.getInstance().getTimeInMillis(); + values.put(KEY_LAST_MODIFICATION, lastModification); + values.put(KEY_ARCHIVED, note.isArchived()); + values.put(KEY_TRASHED, note.isTrashed()); + values.put(KEY_REMINDER, note.getAlarm()); + values.put(KEY_REMINDER_FIRED, note.isReminderFired()); + values.put(KEY_RECURRENCE_RULE, note.getRecurrenceRule()); + values.put(KEY_LATITUDE, note.getLatitude()); + values.put(KEY_LONGITUDE, note.getLongitude()); + values.put(KEY_ADDRESS, note.getAddress()); + values.put(KEY_CATEGORY, note.getCategory() != null ? note.getCategory().getId() : null); + values.put(KEY_LOCKED, note.isLocked() != null && note.isLocked()); + values.put(KEY_CHECKLIST, note.isChecklist() != null && note.isChecklist()); + + db.insertWithOnConflict(TABLE_NOTES, KEY_ID, values, SQLiteDatabase.CONFLICT_REPLACE); + LogDelegate.d("Updated note titled '" + note.getTitle() + "'"); + + // Updating attachments + List deletedAttachments = note.getAttachmentsListOld(); + for (Attachment attachment : note.getAttachmentsList()) { + updateAttachment(note.get_id() != null ? note.get_id() : values.getAsLong(KEY_CREATION), attachment, db); + deletedAttachments.remove(attachment); } - - - public List getNotesWithLocation() { - String whereCondition = " WHERE " + KEY_LONGITUDE + " IS NOT NULL " - + "AND " + KEY_LONGITUDE + " != 0 "; - return getNotes(whereCondition, true); + // Remove from database deleted attachments + for (Attachment attachmentDeleted : deletedAttachments) { + db.delete(TABLE_ATTACHMENTS, KEY_ATTACHMENT_ID + " = ?", + new String[]{String.valueOf(attachmentDeleted.getId())}); } + db.setTransactionSuccessful(); + db.endTransaction(); - /** - * Common method for notes retrieval. It accepts a query to perform and returns matching records. - */ - public List getNotes(String whereCondition, boolean order) { - List noteList = new ArrayList<>(); + // Fill the note with correct data before returning it + note.setCreation(note.getCreation() != null ? note.getCreation() : values.getAsLong(KEY_CREATION)); + note.setLastModification(values.getAsLong(KEY_LAST_MODIFICATION)); - String sort_column, sort_order = ""; + return note; + } - // Getting sorting criteria from preferences. Reminder screen forces sorting. - if (Navigation.checkNavigation(Navigation.REMINDERS)) { - sort_column = KEY_REMINDER; - } else { - sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, KEY_TITLE); - } - if (order) { - sort_order = KEY_TITLE.equals(sort_column) || KEY_REMINDER.equals(sort_column) ? " ASC " : " DESC "; - } - // In case of title sorting criteria it must be handled empty title by concatenating content - sort_column = KEY_TITLE.equals(sort_column) ? KEY_TITLE + "||" + KEY_CONTENT : sort_column; - - // In case of reminder sorting criteria the empty reminder notes must be moved on bottom of results - sort_column = KEY_REMINDER.equals(sort_column) ? "IFNULL(" + KEY_REMINDER + ", " + - "" + Constants.TIMESTAMP_UNIX_EPOCH + ")" : sort_column; - - // Generic query to be specialized with conditions passed as parameter - String query = "SELECT " - + KEY_CREATION + "," - + KEY_LAST_MODIFICATION + "," - + KEY_TITLE + "," - + KEY_CONTENT + "," - + KEY_ARCHIVED + "," - + KEY_TRASHED + "," - + KEY_REMINDER + "," - + KEY_REMINDER_FIRED + "," - + KEY_RECURRENCE_RULE + "," - + KEY_LATITUDE + "," - + KEY_LONGITUDE + "," - + KEY_ADDRESS + "," - + KEY_LOCKED + "," - + KEY_CHECKLIST + "," - + KEY_CATEGORY + "," - + KEY_CATEGORY_NAME + "," - + KEY_CATEGORY_DESCRIPTION + "," - + KEY_CATEGORY_COLOR - + " FROM " + TABLE_NOTES - + " LEFT JOIN " + TABLE_CATEGORY + " USING( " + KEY_CATEGORY + ") " - + whereCondition - + (order ? " ORDER BY " + sort_column + " COLLATE NOCASE " + sort_order : ""); - - LogDelegate.v("Query: " + query); - - Cursor cursor = null; - try { - cursor = getDatabase().rawQuery(query, null); - - // Looping through all rows and adding to list - if (cursor.moveToFirst()) { - do { - int i = 0; - Note note = new Note(); - note.setCreation(cursor.getLong(i++)); - note.setLastModification(cursor.getLong(i++)); - note.setTitle(cursor.getString(i++)); - note.setContent(cursor.getString(i++)); - note.setArchived("1".equals(cursor.getString(i++))); - note.setTrashed("1".equals(cursor.getString(i++))); - note.setAlarm(cursor.getString(i++)); - note.setReminderFired(cursor.getInt(i++)); - note.setRecurrenceRule(cursor.getString(i++)); - note.setLatitude(cursor.getString(i++)); - note.setLongitude(cursor.getString(i++)); - note.setAddress(cursor.getString(i++)); - note.setLocked("1".equals(cursor.getString(i++))); - note.setChecklist("1".equals(cursor.getString(i++))); - - // Eventual decryption of content - if (note.isLocked()) { - note.setContent(Security.decrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, - ""))); - } - - // Set category - long categoryId = cursor.getLong(i++); - if (categoryId != 0) { - Category category = new Category(categoryId, cursor.getString(i++), - cursor.getString(i++), cursor.getString(i++)); - note.setCategory(category); - } - - // Add eventual attachments uri - note.setAttachmentsList(getNoteAttachments(note)); - - // Adding note to list - noteList.add(note); - - } while (cursor.moveToNext()); - } - - } finally { - if (cursor != null) - cursor.close(); - } - - LogDelegate.v("Query: Retrieval finished!"); - return noteList; + protected void execSqlFile (String sqlFile, SQLiteDatabase db) throws SQLException, IOException { + LogDelegate.i(" exec sql file: {}" + sqlFile); + for (String sqlInstruction : SqlParser.parseSqlFile(SQL_DIR + "/" + sqlFile, mContext.getAssets())) { + LogDelegate.v(" sql: {}" + sqlInstruction); + try { + db.execSQL(sqlInstruction); + } catch (Exception e) { + LogDelegate.e("Error executing command: " + sqlInstruction, e); + } } - - - /** - * Archives/restore single note - */ - public void archiveNote(Note note, boolean archive) { - note.setArchived(archive); - updateNote(note, false); + } + + + /** + * Attachments update + */ + public Attachment updateAttachment (Attachment attachment) { + return updateAttachment(-1, attachment, getDatabase(true)); + } + + + /** + * New attachment insertion + */ + public Attachment updateAttachment (long noteId, Attachment attachment, SQLiteDatabase db) { + ContentValues valuesAttachments = new ContentValues(); + valuesAttachments.put(KEY_ATTACHMENT_ID, attachment.getId() != null ? attachment.getId() : Calendar + .getInstance().getTimeInMillis()); + valuesAttachments.put(KEY_ATTACHMENT_NOTE_ID, noteId); + valuesAttachments.put(KEY_ATTACHMENT_URI, attachment.getUri().toString()); + valuesAttachments.put(KEY_ATTACHMENT_MIME_TYPE, attachment.getMime_type()); + valuesAttachments.put(KEY_ATTACHMENT_NAME, attachment.getName()); + valuesAttachments.put(KEY_ATTACHMENT_SIZE, attachment.getSize()); + valuesAttachments.put(KEY_ATTACHMENT_LENGTH, attachment.getLength()); + db.insertWithOnConflict(TABLE_ATTACHMENTS, KEY_ATTACHMENT_ID, valuesAttachments, SQLiteDatabase.CONFLICT_REPLACE); + return attachment; + } + + + /** + * Getting single note + */ + public Note getNote (long id) { + List notes = getNotes(" WHERE " + KEY_ID + " = " + id, true); + return notes.isEmpty() ? null : notes.get(0); + } + + + /** + * Getting All notes + * + * @param checkNavigation Tells if navigation status (notes, archived) must be kept in consideration or if all notes + * have to be retrieved + * @return Notes list + */ + public List getAllNotes (Boolean checkNavigation) { + String whereCondition = ""; + if (checkNavigation) { + int navigation = Navigation.getNavigation(); + switch (navigation) { + case Navigation.NOTES: + return getNotesActive(); + case Navigation.ARCHIVE: + return getNotesArchived(); + case Navigation.REMINDERS: + return getNotesWithReminder(prefs.getBoolean(Constants.PREF_FILTER_PAST_REMINDERS, false)); + case Navigation.TRASH: + return getNotesTrashed(); + case Navigation.UNCATEGORIZED: + return getNotesUncategorized(); + case Navigation.CATEGORY: + return getNotesByCategory(Navigation.getCategory()); + default: + return getNotes(whereCondition, true); + } + } else { + return getNotes(whereCondition, true); } + } - /** - * Trashes/restore single note - */ - public void trashNote(Note note, boolean trash) { - note.setTrashed(trash); - updateNote(note, false); - } + public List getNotesActive () { + String whereCondition = " WHERE " + KEY_ARCHIVED + " IS NOT 1 AND " + KEY_TRASHED + " IS NOT 1 "; + return getNotes(whereCondition, true); + } - /** - * Deleting single note - */ - public boolean deleteNote(Note note) { - return deleteNote(note, false); - } + public List getNotesArchived () { + String whereCondition = " WHERE " + KEY_ARCHIVED + " = 1 AND " + KEY_TRASHED + " IS NOT 1 "; + return getNotes(whereCondition, true); + } - /** - * Deleting single note, eventually keeping attachments - */ - public boolean deleteNote(Note note, boolean keepAttachments) { - return deleteNote(note.get_id(), keepAttachments); - } - - - /** - * Deleting single note by its id - */ - public boolean deleteNote(long noteId, boolean keepAttachments) { - SQLiteDatabase db = getDatabase(true); - db.delete(TABLE_NOTES, KEY_ID + " = ?", new String[]{String.valueOf(noteId)}); - if (!keepAttachments) { - db.delete(TABLE_ATTACHMENTS, KEY_ATTACHMENT_NOTE_ID + " = ?", new String[]{String.valueOf(noteId)}); - } - return true; - } - - - /** - * Empties trash deleting all trashed notes - */ - public void emptyTrash() { - for (Note note : getNotesTrashed()) { - deleteNote(note); - } - } + public List getNotesTrashed () { + String whereCondition = " WHERE " + KEY_TRASHED + " = 1 "; + return getNotes(whereCondition, true); + } - /** - * Gets notes matching pattern with title or content text - * - * @param pattern String to match with - * @return Notes list - */ - public List getNotesByPattern(String pattern) { - String escapedPattern = escapeSql(pattern); - int navigation = Navigation.getNavigation(); - String whereCondition = " WHERE " - + KEY_TRASHED + (navigation == Navigation.TRASH ? " IS 1" : " IS NOT 1") - + (navigation == Navigation.ARCHIVE ? " AND " + KEY_ARCHIVED + " IS 1" : "") - + (navigation == Navigation.CATEGORY ? " AND " + KEY_CATEGORY + " = " + Navigation.getCategory() : "") - + (navigation == Navigation.UNCATEGORIZED ? " AND (" + KEY_CATEGORY + " IS NULL OR " + KEY_CATEGORY_ID - + " == 0) " : "") - + (Navigation.checkNavigation(Navigation.REMINDERS) ? " AND " + KEY_REMINDER + " IS NOT NULL" : "") - + " AND (" - + " ( " + KEY_LOCKED + " IS NOT 1 AND (" + KEY_TITLE + " LIKE '%" + escapedPattern + "%' ESCAPE '\\' " + " OR " + - KEY_CONTENT + " LIKE '%" + escapedPattern + "%' ESCAPE '\\' ))" - + " OR ( " + KEY_LOCKED + " = 1 AND " + KEY_TITLE + " LIKE '%" + escapedPattern + "%' ESCAPE '\\' )" - + ")"; - return getNotes(whereCondition, true); - } - static String escapeSql(String pattern) { - return StringEscapeUtils.escapeSql(pattern).replace("%", "\\%").replace("_", "\\_"); - } + public List getNotesUncategorized () { + String whereCondition = " WHERE " + + "(" + KEY_CATEGORY_ID + " IS NULL OR " + KEY_CATEGORY_ID + " == 0) " + + "AND " + KEY_TRASHED + " IS NOT 1"; + return getNotes(whereCondition, true); + } - /** - * Search for notes with reminder - * - * @param filterPastReminders Excludes past reminders - * @return Notes list - */ - public List getNotesWithReminder(boolean filterPastReminders) { - String whereCondition = " WHERE " + KEY_REMINDER - + (filterPastReminders ? " >= " + Calendar.getInstance().getTimeInMillis() : " IS NOT NULL") - + " AND " + KEY_ARCHIVED + " IS NOT 1" - + " AND " + KEY_TRASHED + " IS NOT 1"; - return getNotes(whereCondition, true); - } + public List getNotesWithLocation () { + String whereCondition = " WHERE " + KEY_LONGITUDE + " IS NOT NULL " + + "AND " + KEY_LONGITUDE + " != 0 "; + return getNotes(whereCondition, true); + } - /** - * Returns all notes that have a reminder that has not been alredy fired - * - * @return Notes list - */ - public List getNotesWithReminderNotFired () { - String whereCondition = " WHERE " + KEY_REMINDER + " IS NOT NULL" - + " AND " + KEY_REMINDER_FIRED + " IS NOT 1" - + " AND " + KEY_ARCHIVED + " IS NOT 1" - + " AND " + KEY_TRASHED + " IS NOT 1"; - return getNotes(whereCondition, true); - } + /** + * Common method for notes retrieval. It accepts a query to perform and returns matching records. + */ + public List getNotes (String whereCondition, boolean order) { + List noteList = new ArrayList<>(); + String sort_column, sort_order = ""; - /** - * Retrieves locked or unlocked notes - */ - public List getNotesWithLock(boolean locked) { - String whereCondition = " WHERE " + KEY_LOCKED + (locked ? " = 1 " : " IS NOT 1 "); - return getNotes(whereCondition, true); + // Getting sorting criteria from preferences. Reminder screen forces sorting. + if (Navigation.checkNavigation(Navigation.REMINDERS)) { + sort_column = KEY_REMINDER; + } else { + sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, KEY_TITLE); } - - - /** - * Search for notes with reminder expiring the current day - * - * @return Notes list - */ - public List getTodayReminders() { - String whereCondition = " WHERE DATE(" + KEY_REMINDER + "/1000, 'unixepoch') = DATE('now') AND " + - KEY_TRASHED + " IS NOT 1"; - return getNotes(whereCondition, false); + if (order) { + sort_order = KEY_TITLE.equals(sort_column) || KEY_REMINDER.equals(sort_column) ? " ASC " : " DESC "; } - - /** - * Retrieves all attachments related to specific note - */ - public ArrayList getNoteAttachments(Note note) { - String whereCondition = " WHERE " + KEY_ATTACHMENT_NOTE_ID + " = " + note.get_id(); - return getAttachments(whereCondition); + // In case of title sorting criteria it must be handled empty title by concatenating content + sort_column = KEY_TITLE.equals(sort_column) ? KEY_TITLE + "||" + KEY_CONTENT : sort_column; + + // In case of reminder sorting criteria the empty reminder notes must be moved on bottom of results + sort_column = KEY_REMINDER.equals(sort_column) ? "IFNULL(" + KEY_REMINDER + ", " + + "" + Constants.TIMESTAMP_UNIX_EPOCH + ")" : sort_column; + + // Generic query to be specialized with conditions passed as parameter + String query = "SELECT " + + KEY_CREATION + "," + + KEY_LAST_MODIFICATION + "," + + KEY_TITLE + "," + + KEY_CONTENT + "," + + KEY_ARCHIVED + "," + + KEY_TRASHED + "," + + KEY_REMINDER + "," + + KEY_REMINDER_FIRED + "," + + KEY_RECURRENCE_RULE + "," + + KEY_LATITUDE + "," + + KEY_LONGITUDE + "," + + KEY_ADDRESS + "," + + KEY_LOCKED + "," + + KEY_CHECKLIST + "," + + KEY_CATEGORY + "," + + KEY_CATEGORY_NAME + "," + + KEY_CATEGORY_DESCRIPTION + "," + + KEY_CATEGORY_COLOR + + " FROM " + TABLE_NOTES + + " LEFT JOIN " + TABLE_CATEGORY + " USING( " + KEY_CATEGORY + ") " + + whereCondition + + (order ? " ORDER BY " + sort_column + " COLLATE NOCASE " + sort_order : ""); + + LogDelegate.v("Query: " + query); + + Cursor cursor = null; + try { + cursor = getDatabase().rawQuery(query, null); + + // Looping through all rows and adding to list + if (cursor.moveToFirst()) { + do { + int i = 0; + Note note = new Note(); + note.setCreation(cursor.getLong(i++)); + note.setLastModification(cursor.getLong(i++)); + note.setTitle(cursor.getString(i++)); + note.setContent(cursor.getString(i++)); + note.setArchived("1".equals(cursor.getString(i++))); + note.setTrashed("1".equals(cursor.getString(i++))); + note.setAlarm(cursor.getString(i++)); + note.setReminderFired(cursor.getInt(i++)); + note.setRecurrenceRule(cursor.getString(i++)); + note.setLatitude(cursor.getString(i++)); + note.setLongitude(cursor.getString(i++)); + note.setAddress(cursor.getString(i++)); + note.setLocked("1".equals(cursor.getString(i++))); + note.setChecklist("1".equals(cursor.getString(i++))); + + // Eventual decryption of content + if (note.isLocked()) { + note.setContent(Security.decrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, + ""))); + } + + // Set category + long categoryId = cursor.getLong(i++); + if (categoryId != 0) { + Category category = new Category(categoryId, cursor.getString(i++), + cursor.getString(i++), cursor.getString(i++)); + note.setCategory(category); + } + + // Add eventual attachments uri + note.setAttachmentsList(getNoteAttachments(note)); + + // Adding note to list + noteList.add(note); + + } while (cursor.moveToNext()); + } + + } finally { + if (cursor != null) { + cursor.close(); + } } - - public List getChecklists() { - String whereCondition = " WHERE " + KEY_CHECKLIST + " = 1"; - return getNotes(whereCondition, false); + LogDelegate.v("Query: Retrieval finished!"); + return noteList; + } + + + /** + * Archives/restore single note + */ + public void archiveNote (Note note, boolean archive) { + note.setArchived(archive); + updateNote(note, false); + } + + + /** + * Trashes/restore single note + */ + public void trashNote (Note note, boolean trash) { + note.setTrashed(trash); + updateNote(note, false); + } + + + /** + * Deleting single note + */ + public boolean deleteNote (Note note) { + return deleteNote(note, false); + } + + + /** + * Deleting single note, eventually keeping attachments + */ + public boolean deleteNote (Note note, boolean keepAttachments) { + return deleteNote(note.get_id(), keepAttachments); + } + + + /** + * Deleting single note by its id + */ + public boolean deleteNote (long noteId, boolean keepAttachments) { + SQLiteDatabase db = getDatabase(true); + db.delete(TABLE_NOTES, KEY_ID + " = ?", new String[]{String.valueOf(noteId)}); + if (!keepAttachments) { + db.delete(TABLE_ATTACHMENTS, KEY_ATTACHMENT_NOTE_ID + " = ?", new String[]{String.valueOf(noteId)}); } + return true; + } - public List getMasked() { - String whereCondition = " WHERE " + KEY_LOCKED + " = 1"; - return getNotes(whereCondition, false); + /** + * Empties trash deleting all trashed notes + */ + public void emptyTrash () { + for (Note note : getNotesTrashed()) { + deleteNote(note); } - - - /** - * Retrieves all notes related to Category it passed as parameter - * - * @param categoryId Category integer identifier - * @return List of notes with requested category - */ - public List getNotesByCategory(Long categoryId) { - List notes; - boolean filterArchived = prefs.getBoolean(Constants.PREF_FILTER_ARCHIVED_IN_CATEGORIES + categoryId, false); - try { - String whereCondition = " WHERE " - + KEY_CATEGORY_ID + " = " + categoryId - + " AND " + KEY_TRASHED + " IS NOT 1" - + (filterArchived ? " AND " + KEY_ARCHIVED + " IS NOT 1" : ""); - notes = getNotes(whereCondition, true); - } catch (NumberFormatException e) { - notes = getAllNotes(true); - } - return notes; + } + + + /** + * Gets notes matching pattern with title or content text + * + * @param pattern String to match with + * @return Notes list + */ + public List getNotesByPattern (String pattern) { + String escapedPattern = escapeSql(pattern); + int navigation = Navigation.getNavigation(); + String whereCondition = " WHERE " + + KEY_TRASHED + (navigation == Navigation.TRASH ? " IS 1" : " IS NOT 1") + + (navigation == Navigation.ARCHIVE ? " AND " + KEY_ARCHIVED + " IS 1" : "") + + (navigation == Navigation.CATEGORY ? " AND " + KEY_CATEGORY + " = " + Navigation.getCategory() : "") + + (navigation == Navigation.UNCATEGORIZED ? " AND (" + KEY_CATEGORY + " IS NULL OR " + KEY_CATEGORY_ID + + " == 0) " : "") + + (Navigation.checkNavigation(Navigation.REMINDERS) ? " AND " + KEY_REMINDER + " IS NOT NULL" : "") + + " AND (" + + " ( " + KEY_LOCKED + " IS NOT 1 AND (" + KEY_TITLE + " LIKE '%" + escapedPattern + "%' ESCAPE '\\' " + " OR " + + + KEY_CONTENT + " LIKE '%" + escapedPattern + "%' ESCAPE '\\' ))" + + " OR ( " + KEY_LOCKED + " = 1 AND " + KEY_TITLE + " LIKE '%" + escapedPattern + "%' ESCAPE '\\' )" + + ")"; + return getNotes(whereCondition, true); + } + + static String escapeSql (String pattern) { + return StringEscapeUtils.escapeSql(pattern).replace("%", "\\%").replace("_", "\\_"); + } + + + /** + * Search for notes with reminder + * + * @param filterPastReminders Excludes past reminders + * @return Notes list + */ + public List getNotesWithReminder (boolean filterPastReminders) { + String whereCondition = " WHERE " + KEY_REMINDER + + (filterPastReminders ? " >= " + Calendar.getInstance().getTimeInMillis() : " IS NOT NULL") + + " AND " + KEY_ARCHIVED + " IS NOT 1" + + " AND " + KEY_TRASHED + " IS NOT 1"; + return getNotes(whereCondition, true); + } + + + /** + * Returns all notes that have a reminder that has not been alredy fired + * + * @return Notes list + */ + public List getNotesWithReminderNotFired () { + String whereCondition = " WHERE " + KEY_REMINDER + " IS NOT NULL" + + " AND " + KEY_REMINDER_FIRED + " IS NOT 1" + + " AND " + KEY_ARCHIVED + " IS NOT 1" + + " AND " + KEY_TRASHED + " IS NOT 1"; + return getNotes(whereCondition, true); + } + + + /** + * Retrieves locked or unlocked notes + */ + public List getNotesWithLock (boolean locked) { + String whereCondition = " WHERE " + KEY_LOCKED + (locked ? " = 1 " : " IS NOT 1 "); + return getNotes(whereCondition, true); + } + + + /** + * Search for notes with reminder expiring the current day + * + * @return Notes list + */ + public List getTodayReminders () { + String whereCondition = " WHERE DATE(" + KEY_REMINDER + "/1000, 'unixepoch') = DATE('now') AND " + + KEY_TRASHED + " IS NOT 1"; + return getNotes(whereCondition, false); + } + + + /** + * Retrieves all attachments related to specific note + */ + public ArrayList getNoteAttachments (Note note) { + String whereCondition = " WHERE " + KEY_ATTACHMENT_NOTE_ID + " = " + note.get_id(); + return getAttachments(whereCondition); + } + + + public List getChecklists () { + String whereCondition = " WHERE " + KEY_CHECKLIST + " = 1"; + return getNotes(whereCondition, false); + } + + + public List getMasked () { + String whereCondition = " WHERE " + KEY_LOCKED + " = 1"; + return getNotes(whereCondition, false); + } + + + /** + * Retrieves all notes related to Category it passed as parameter + * + * @param categoryId Category integer identifier + * @return List of notes with requested category + */ + public List getNotesByCategory (Long categoryId) { + List notes; + boolean filterArchived = prefs.getBoolean(Constants.PREF_FILTER_ARCHIVED_IN_CATEGORIES + categoryId, false); + try { + String whereCondition = " WHERE " + + KEY_CATEGORY_ID + " = " + categoryId + + " AND " + KEY_TRASHED + " IS NOT 1" + + (filterArchived ? " AND " + KEY_ARCHIVED + " IS NOT 1" : ""); + notes = getNotes(whereCondition, true); + } catch (NumberFormatException e) { + notes = getAllNotes(true); } - - - /** - * Retrieves all tags - */ - public List getTags() { - return getTags(null); + return notes; + } + + + /** + * Retrieves all tags + */ + public List getTags () { + return getTags(null); + } + + + /** + * Retrieves all tags of a specified note + */ + public List getTags (Note note) { + List tags = new ArrayList<>(); + HashMap tagsMap = new HashMap<>(); + + String whereCondition = " WHERE " + + (note != null ? KEY_ID + " = " + note.get_id() + " AND " : "") + + "(" + KEY_CONTENT + " LIKE '%#%' OR " + KEY_TITLE + " LIKE '%#%' " + ")" + + " AND " + KEY_TRASHED + " IS " + (Navigation.checkNavigation(Navigation.TRASH) ? "" : " NOT ") + " 1"; + List notesRetrieved = getNotes(whereCondition, true); + + for (Note noteRetrieved : notesRetrieved) { + HashMap tagsRetrieved = TagsHelper.retrieveTags(noteRetrieved); + for (String s : tagsRetrieved.keySet()) { + int count = tagsMap.get(s) == null ? 0 : tagsMap.get(s); + tagsMap.put(s, ++count); + } } - - /** - * Retrieves all tags of a specified note - */ - public List getTags(Note note) { - List tags = new ArrayList<>(); - HashMap tagsMap = new HashMap<>(); - - String whereCondition = " WHERE " - + (note != null ? KEY_ID + " = " + note.get_id() + " AND " : "") - + "(" + KEY_CONTENT + " LIKE '%#%' OR " + KEY_TITLE + " LIKE '%#%' " + ")" - + " AND " + KEY_TRASHED + " IS " + (Navigation.checkNavigation(Navigation.TRASH) ? "" : " NOT ") + " 1"; - List notesRetrieved = getNotes(whereCondition, true); - - for (Note noteRetrieved : notesRetrieved) { - HashMap tagsRetrieved = TagsHelper.retrieveTags(noteRetrieved); - for (String s : tagsRetrieved.keySet()) { - int count = tagsMap.get(s) == null ? 0 : tagsMap.get(s); - tagsMap.put(s, ++count); - } - } - - for (String s : tagsMap.keySet()) { - Tag tag = new Tag(s, tagsMap.get(s)); - tags.add(tag); - } - - Collections.sort(tags, (tag1, tag2) -> tag1.getText().compareToIgnoreCase(tag2.getText())); - return tags; + for (String s : tagsMap.keySet()) { + Tag tag = new Tag(s, tagsMap.get(s)); + tags.add(tag); } - - /** - * Retrieves all notes related to category it passed as parameter - */ - public List getNotesByTag(String tag) { - if (tag.contains(",")) { - return getNotesByTag(tag.split(",")); - } else { - return getNotesByTag(new String[]{tag}); - } - } + Collections.sort(tags, (tag1, tag2) -> tag1.getText().compareToIgnoreCase(tag2.getText())); + return tags; + } - /** - * Retrieves all notes with specified tags - */ - public List getNotesByTag(String[] tags) { - StringBuilder whereCondition = new StringBuilder(); - whereCondition.append(" WHERE "); - for (int i = 0; i < tags.length; i++) { - if (i != 0) { - whereCondition.append(" AND "); - } - whereCondition.append("(" + KEY_CONTENT + " LIKE '%").append(tags[i]).append("%' OR ").append(KEY_TITLE) - .append(" LIKE '%").append(tags[i]).append("%')"); - } - // Trashed notes must be included in search results only if search if performed from trash - whereCondition.append(" AND " + KEY_TRASHED + " IS ").append(Navigation.checkNavigation(Navigation.TRASH) ? - "" : "" + - " NOT ").append(" 1"); - - return rx.Observable.from(getNotes(whereCondition.toString(), true)) - .map(note -> { - boolean matches = rx.Observable.from(tags) - .all(tag -> { - Pattern p = Pattern.compile(".*(\\s|^)" + tag + "(\\s|$).*", Pattern.MULTILINE); - return p.matcher((note.getTitle() + " " + note.getContent())).find(); - }).toBlocking().single(); - return matches ? note : null; - }) - .filter(note -> note != null) - .toList().toBlocking().single(); - } - - /** - * Retrieves all uncompleted checklists - */ - public List getNotesByUncompleteChecklist() { - String whereCondition = " WHERE " + KEY_CHECKLIST + " = 1 AND " + KEY_CONTENT + " LIKE '%" + it.feio.android - .checklistview.interfaces.Constants.UNCHECKED_SYM + "%'"; - return getNotes(whereCondition, true); - } - - - /** - * Retrieves all attachments - */ - public ArrayList getAllAttachments() { - return getAttachments(""); + /** + * Retrieves all notes related to category it passed as parameter + */ + public List getNotesByTag (String tag) { + if (tag.contains(",")) { + return getNotesByTag(tag.split(",")); + } else { + return getNotesByTag(new String[]{tag}); } - - - /** - * Retrieves attachments using a condition passed as parameter - * - * @return List of attachments - */ - public ArrayList getAttachments(String whereCondition) { - - ArrayList attachmentsList = new ArrayList<>(); - String sql = "SELECT " - + KEY_ATTACHMENT_ID + "," - + KEY_ATTACHMENT_URI + "," - + KEY_ATTACHMENT_NAME + "," - + KEY_ATTACHMENT_SIZE + "," - + KEY_ATTACHMENT_LENGTH + "," - + KEY_ATTACHMENT_MIME_TYPE - + " FROM " + TABLE_ATTACHMENTS - + whereCondition; - SQLiteDatabase db; - Cursor cursor = null; - - try { - - cursor = getDatabase().rawQuery(sql, null); - - // Looping through all rows and adding to list - if (cursor.moveToFirst()) { - Attachment mAttachment; - do { - mAttachment = new Attachment(cursor.getLong(0), - Uri.parse(cursor.getString(1)), cursor.getString(2), cursor.getInt(3), - (long) cursor.getInt(4), cursor.getString(5)); - attachmentsList.add(mAttachment); - } while (cursor.moveToNext()); - } - - } finally { - if (cursor != null) - cursor.close(); - } - return attachmentsList; + } + + + /** + * Retrieves all notes with specified tags + */ + public List getNotesByTag (String[] tags) { + StringBuilder whereCondition = new StringBuilder(); + whereCondition.append(" WHERE "); + for (int i = 0; i < tags.length; i++) { + if (i != 0) { + whereCondition.append(" AND "); + } + whereCondition.append("(" + KEY_CONTENT + " LIKE '%").append(tags[i]).append("%' OR ").append(KEY_TITLE) + .append(" LIKE '%").append(tags[i]).append("%')"); } - - - /** - * Retrieves categories list from database - * - * @return List of categories - */ - public ArrayList getCategories() { - ArrayList categoriesList = new ArrayList<>(); - String sql = "SELECT " - + KEY_CATEGORY_ID + "," - + KEY_CATEGORY_NAME + "," - + KEY_CATEGORY_DESCRIPTION + "," - + KEY_CATEGORY_COLOR + "," - + " COUNT(" + KEY_ID + ") count" - + " FROM " + TABLE_CATEGORY - + " LEFT JOIN (" - + " SELECT " + KEY_ID + ", " + KEY_CATEGORY - + " FROM " + TABLE_NOTES - + " WHERE " + KEY_TRASHED + " IS NOT 1" - + ") USING( " + KEY_CATEGORY + ") " - + " GROUP BY " - + KEY_CATEGORY_ID + "," - + KEY_CATEGORY_NAME + "," - + KEY_CATEGORY_DESCRIPTION + "," - + KEY_CATEGORY_COLOR - + " ORDER BY IFNULL(NULLIF(" + KEY_CATEGORY_NAME + ", ''),'zzzzzzzz') "; - - Cursor cursor = null; - try { - cursor = getDatabase().rawQuery(sql, null); - // Looping through all rows and adding to list - if (cursor.moveToFirst()) { - do { - categoriesList.add(new Category(cursor.getLong(0), - cursor.getString(1), cursor.getString(2), cursor - .getString(3), cursor.getInt(4))); - } while (cursor.moveToNext()); - } - - } finally { - if (cursor != null) - cursor.close(); - } - return categoriesList; + // Trashed notes must be included in search results only if search if performed from trash + whereCondition.append(" AND " + KEY_TRASHED + " IS ").append(Navigation.checkNavigation(Navigation.TRASH) ? + "" : "" + + " NOT ").append(" 1"); + + return rx.Observable.from(getNotes(whereCondition.toString(), true)) + .map(note -> { + boolean matches = rx.Observable.from(tags) + .all(tag -> { + Pattern p = Pattern.compile(".*(\\s|^)" + tag + "(\\s|$).*", + Pattern.MULTILINE); + return p.matcher( + (note.getTitle() + " " + note.getContent())).find(); + }).toBlocking().single(); + return matches ? note : null; + }) + .filter(note -> note != null) + .toList().toBlocking().single(); + } + + /** + * Retrieves all uncompleted checklists + */ + public List getNotesByUncompleteChecklist () { + String whereCondition = " WHERE " + KEY_CHECKLIST + " = 1 AND " + KEY_CONTENT + " LIKE '%" + it.feio.android + .checklistview.interfaces.Constants.UNCHECKED_SYM + "%'"; + return getNotes(whereCondition, true); + } + + + /** + * Retrieves all attachments + */ + public ArrayList getAllAttachments () { + return getAttachments(""); + } + + + /** + * Retrieves attachments using a condition passed as parameter + * + * @return List of attachments + */ + public ArrayList getAttachments (String whereCondition) { + + ArrayList attachmentsList = new ArrayList<>(); + String sql = "SELECT " + + KEY_ATTACHMENT_ID + "," + + KEY_ATTACHMENT_URI + "," + + KEY_ATTACHMENT_NAME + "," + + KEY_ATTACHMENT_SIZE + "," + + KEY_ATTACHMENT_LENGTH + "," + + KEY_ATTACHMENT_MIME_TYPE + + " FROM " + TABLE_ATTACHMENTS + + whereCondition; + SQLiteDatabase db; + Cursor cursor = null; + + try { + + cursor = getDatabase().rawQuery(sql, null); + + // Looping through all rows and adding to list + if (cursor.moveToFirst()) { + Attachment mAttachment; + do { + mAttachment = new Attachment(cursor.getLong(0), + Uri.parse(cursor.getString(1)), cursor.getString(2), cursor.getInt(3), + (long) cursor.getInt(4), cursor.getString(5)); + attachmentsList.add(mAttachment); + } while (cursor.moveToNext()); + } + + } finally { + if (cursor != null) { + cursor.close(); + } } - - - /** - * Updates or insert a new a category - * - * @param category Category to be updated or inserted - * @return Rows affected or new inserted category id - */ - public Category updateCategory(Category category) { - ContentValues values = new ContentValues(); - values.put(KEY_CATEGORY_ID, category.getId() != null ? category.getId() : Calendar.getInstance() - .getTimeInMillis()); - values.put(KEY_CATEGORY_NAME, category.getName()); - values.put(KEY_CATEGORY_DESCRIPTION, category.getDescription()); - values.put(KEY_CATEGORY_COLOR, category.getColor()); - getDatabase(true).insertWithOnConflict(TABLE_CATEGORY, KEY_CATEGORY_ID, values, SQLiteDatabase - .CONFLICT_REPLACE); - return category; - } - - - /** - * Deletion of a category - * - * @param category Category to be deleted - * @return Number 1 if category's record has been deleted, 0 otherwise - */ - public long deleteCategory(Category category) { - long deleted; - - SQLiteDatabase db = getDatabase(true); - // Un-categorize notes associated with this category - ContentValues values = new ContentValues(); - values.put(KEY_CATEGORY, ""); - - // Updating row - db.update(TABLE_NOTES, values, KEY_CATEGORY + " = ?", - new String[]{String.valueOf(category.getId())}); - - // Delete category - deleted = db.delete(TABLE_CATEGORY, KEY_CATEGORY_ID + " = ?", - new String[]{String.valueOf(category.getId())}); - return deleted; + return attachmentsList; + } + + + /** + * Retrieves categories list from database + * + * @return List of categories + */ + public ArrayList getCategories () { + ArrayList categoriesList = new ArrayList<>(); + String sql = "SELECT " + + KEY_CATEGORY_ID + "," + + KEY_CATEGORY_NAME + "," + + KEY_CATEGORY_DESCRIPTION + "," + + KEY_CATEGORY_COLOR + "," + + " COUNT(" + KEY_ID + ") count" + + " FROM " + TABLE_CATEGORY + + " LEFT JOIN (" + + " SELECT " + KEY_ID + ", " + KEY_CATEGORY + + " FROM " + TABLE_NOTES + + " WHERE " + KEY_TRASHED + " IS NOT 1" + + ") USING( " + KEY_CATEGORY + ") " + + " GROUP BY " + + KEY_CATEGORY_ID + "," + + KEY_CATEGORY_NAME + "," + + KEY_CATEGORY_DESCRIPTION + "," + + KEY_CATEGORY_COLOR + + " ORDER BY IFNULL(NULLIF(" + KEY_CATEGORY_NAME + ", ''),'zzzzzzzz') "; + + Cursor cursor = null; + try { + cursor = getDatabase().rawQuery(sql, null); + // Looping through all rows and adding to list + if (cursor.moveToFirst()) { + do { + categoriesList.add(new Category(cursor.getLong(0), + cursor.getString(1), cursor.getString(2), cursor + .getString(3), cursor.getInt(4))); + } while (cursor.moveToNext()); + } + + } finally { + if (cursor != null) { + cursor.close(); + } } - - - /** - * Get note Category - */ - public Category getCategory(Long id) { - Category category = null; - String sql = "SELECT " - + KEY_CATEGORY_ID + "," - + KEY_CATEGORY_NAME + "," - + KEY_CATEGORY_DESCRIPTION + "," - + KEY_CATEGORY_COLOR - + " FROM " + TABLE_CATEGORY - + " WHERE " + KEY_CATEGORY_ID + " = " + id; - - Cursor cursor = null; - try { - cursor = getDatabase().rawQuery(sql, null); - - // Looping through all rows and adding to list - if (cursor.moveToFirst()) { - category = new Category(cursor.getLong(0), cursor.getString(1), - cursor.getString(2), cursor.getString(3)); - } - - } finally { - if (cursor != null) - cursor.close(); - } - return category; + return categoriesList; + } + + + /** + * Updates or insert a new a category + * + * @param category Category to be updated or inserted + * @return Rows affected or new inserted category id + */ + public Category updateCategory (Category category) { + ContentValues values = new ContentValues(); + values.put(KEY_CATEGORY_ID, category.getId() != null ? category.getId() : Calendar.getInstance() + .getTimeInMillis()); + values.put(KEY_CATEGORY_NAME, category.getName()); + values.put(KEY_CATEGORY_DESCRIPTION, category.getDescription()); + values.put(KEY_CATEGORY_COLOR, category.getColor()); + getDatabase(true).insertWithOnConflict(TABLE_CATEGORY, KEY_CATEGORY_ID, values, SQLiteDatabase + .CONFLICT_REPLACE); + return category; + } + + + /** + * Deletion of a category + * + * @param category Category to be deleted + * @return Number 1 if category's record has been deleted, 0 otherwise + */ + public long deleteCategory (Category category) { + long deleted; + + SQLiteDatabase db = getDatabase(true); + // Un-categorize notes associated with this category + ContentValues values = new ContentValues(); + values.put(KEY_CATEGORY, ""); + + // Updating row + db.update(TABLE_NOTES, values, KEY_CATEGORY + " = ?", + new String[]{String.valueOf(category.getId())}); + + // Delete category + deleted = db.delete(TABLE_CATEGORY, KEY_CATEGORY_ID + " = ?", + new String[]{String.valueOf(category.getId())}); + return deleted; + } + + + /** + * Get note Category + */ + public Category getCategory (Long id) { + Category category = null; + String sql = "SELECT " + + KEY_CATEGORY_ID + "," + + KEY_CATEGORY_NAME + "," + + KEY_CATEGORY_DESCRIPTION + "," + + KEY_CATEGORY_COLOR + + " FROM " + TABLE_CATEGORY + + " WHERE " + KEY_CATEGORY_ID + " = " + id; + + Cursor cursor = null; + try { + cursor = getDatabase().rawQuery(sql, null); + + // Looping through all rows and adding to list + if (cursor.moveToFirst()) { + category = new Category(cursor.getLong(0), cursor.getString(1), + cursor.getString(2), cursor.getString(3)); + } + + } finally { + if (cursor != null) { + cursor.close(); + } } + return category; + } - public int getCategorizedCount(Category category) { - int count = 0; - String sql = "SELECT COUNT(*)" - + " FROM " + TABLE_NOTES - + " WHERE " + KEY_CATEGORY + " = " + category.getId(); + public int getCategorizedCount (Category category) { + int count = 0; + String sql = "SELECT COUNT(*)" + + " FROM " + TABLE_NOTES + + " WHERE " + KEY_CATEGORY + " = " + category.getId(); - Cursor cursor = null; - try { - cursor = getDatabase().rawQuery(sql, null); + Cursor cursor = null; + try { + cursor = getDatabase().rawQuery(sql, null); - // Looping through all rows and adding to list - if (cursor.moveToFirst()) { - count = cursor.getInt(0); - } + // Looping through all rows and adding to list + if (cursor.moveToFirst()) { + count = cursor.getInt(0); + } - } finally { - if (cursor != null) - cursor.close(); - } - return count; + } finally { + if (cursor != null) { + cursor.close(); + } } - - - /** - * Retrieves statistics data based on app usage - */ - public Stats getStats() { - Stats mStats = new Stats(); - - // Categories - mStats.setCategories(getCategories().size()); - - // Everything about notes and their text stats - int notesActive = 0, notesArchived = 0, notesTrashed = 0, reminders = 0, remindersFuture = 0, checklists = 0, - notesMasked = 0, tags = 0, locations = 0; - int totalWords = 0, totalChars = 0, maxWords = 0, maxChars = 0, avgWords = 0, avgChars = 0; - int words, chars; - List notes = getAllNotes(false); - for (Note note : notes) { - if (note.isTrashed()) { - notesTrashed++; - } else if (note.isArchived()) { - notesArchived++; - } else { - notesActive++; - } - if (note.getAlarm() != null && Long.parseLong(note.getAlarm()) > 0) { - if (Long.parseLong(note.getAlarm()) > Calendar.getInstance().getTimeInMillis()) { - remindersFuture++; - } else { - reminders++; - } - } - if (note.isChecklist()) { - checklists++; - } - if (note.isLocked()) { - notesMasked++; - } - tags += TagsHelper.retrieveTags(note).size(); - if (note.getLongitude() != null && note.getLongitude() != 0) { - locations++; - } - words = NotesHelper.getWords(note); - chars = NotesHelper.getChars(note); - if (words > maxWords) { - maxWords = words; - } - if (chars > maxChars) { - maxChars = chars; - } - totalWords += words; - totalChars += chars; - } - mStats.setNotesActive(notesActive); - mStats.setNotesArchived(notesArchived); - mStats.setNotesTrashed(notesTrashed); - mStats.setReminders(reminders); - mStats.setRemindersFutures(remindersFuture); - mStats.setNotesChecklist(checklists); - mStats.setNotesMasked(notesMasked); - mStats.setTags(tags); - mStats.setLocation(locations); - avgWords = totalWords / (notes.size() != 0 ? notes.size() : 1); - avgChars = totalChars / (notes.size() != 0 ? notes.size() : 1); - - mStats.setWords(totalWords); - mStats.setWordsMax(maxWords); - mStats.setWordsAvg(avgWords); - mStats.setChars(totalChars); - mStats.setCharsMax(maxChars); - mStats.setCharsAvg(avgChars); - - // Everything about attachments - int attachmentsAll = 0, images = 0, videos = 0, audioRecordings = 0, sketches = 0, files = 0; - List attachments = getAllAttachments(); - for (Attachment attachment : attachments) { - if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())) { - images++; - } else if (Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) { - videos++; - } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) { - audioRecordings++; - } else if (Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())) { - sketches++; - } else if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) { - files++; - } + return count; + } + + + /** + * Retrieves statistics data based on app usage + */ + public Stats getStats () { + Stats mStats = new Stats(); + + // Categories + mStats.setCategories(getCategories().size()); + + // Everything about notes and their text stats + int notesActive = 0, notesArchived = 0, notesTrashed = 0, reminders = 0, remindersFuture = 0, checklists = 0, + notesMasked = 0, tags = 0, locations = 0; + int totalWords = 0, totalChars = 0, maxWords = 0, maxChars = 0, avgWords = 0, avgChars = 0; + int words, chars; + List notes = getAllNotes(false); + for (Note note : notes) { + if (note.isTrashed()) { + notesTrashed++; + } else if (note.isArchived()) { + notesArchived++; + } else { + notesActive++; + } + if (note.getAlarm() != null && Long.parseLong(note.getAlarm()) > 0) { + if (Long.parseLong(note.getAlarm()) > Calendar.getInstance().getTimeInMillis()) { + remindersFuture++; + } else { + reminders++; } - mStats.setAttachments(attachmentsAll); - mStats.setImages(images); - mStats.setVideos(videos); - mStats.setAudioRecordings(audioRecordings); - mStats.setSketches(sketches); - mStats.setFiles(files); - - return mStats; + } + if (note.isChecklist()) { + checklists++; + } + if (note.isLocked()) { + notesMasked++; + } + tags += TagsHelper.retrieveTags(note).size(); + if (note.getLongitude() != null && note.getLongitude() != 0) { + locations++; + } + words = NotesHelper.getWords(note); + chars = NotesHelper.getChars(note); + if (words > maxWords) { + maxWords = words; + } + if (chars > maxChars) { + maxChars = chars; + } + totalWords += words; + totalChars += chars; } - - - public void setReminderFired(long noteId, boolean fired) { - ContentValues values = new ContentValues(); - values.put(KEY_REMINDER_FIRED, fired); - getDatabase(true).update(TABLE_NOTES, values, KEY_ID + " = ?", new String[]{String.valueOf(noteId)}); + mStats.setNotesActive(notesActive); + mStats.setNotesArchived(notesArchived); + mStats.setNotesTrashed(notesTrashed); + mStats.setReminders(reminders); + mStats.setRemindersFutures(remindersFuture); + mStats.setNotesChecklist(checklists); + mStats.setNotesMasked(notesMasked); + mStats.setTags(tags); + mStats.setLocation(locations); + avgWords = totalWords / (notes.size() != 0 ? notes.size() : 1); + avgChars = totalChars / (notes.size() != 0 ? notes.size() : 1); + + mStats.setWords(totalWords); + mStats.setWordsMax(maxWords); + mStats.setWordsAvg(avgWords); + mStats.setChars(totalChars); + mStats.setCharsMax(maxChars); + mStats.setCharsAvg(avgChars); + + // Everything about attachments + int attachmentsAll = 0, images = 0, videos = 0, audioRecordings = 0, sketches = 0, files = 0; + List attachments = getAllAttachments(); + for (Attachment attachment : attachments) { + if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())) { + images++; + } else if (Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) { + videos++; + } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) { + audioRecordings++; + } else if (Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())) { + sketches++; + } else if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) { + files++; + } } + mStats.setAttachments(attachmentsAll); + mStats.setImages(images); + mStats.setVideos(videos); + mStats.setAudioRecordings(audioRecordings); + mStats.setSketches(sketches); + mStats.setFiles(files); + + return mStats; + } + + + public void setReminderFired (long noteId, boolean fired) { + ContentValues values = new ContentValues(); + values.put(KEY_REMINDER_FIRED, fired); + getDatabase(true).update(TABLE_NOTES, values, KEY_ID + " = ?", new String[]{String.valueOf(noteId)}); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/db/SqlParser.java b/omniNotes/src/main/java/it/feio/android/omninotes/db/SqlParser.java index 465eb725ed..a306e7cf09 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/db/SqlParser.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/db/SqlParser.java @@ -17,7 +17,6 @@ package it.feio.android.omninotes.db; import android.content.res.AssetManager; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -28,95 +27,95 @@ public class SqlParser { - public static List parseSqlFile(String sqlFile, - AssetManager assetManager) throws IOException { - List sqlIns = null; - InputStream is = assetManager.open(sqlFile); - try { - sqlIns = parseSqlFile(is); - } finally { - is.close(); - } - return sqlIns; + public static List parseSqlFile (String sqlFile, + AssetManager assetManager) throws IOException { + List sqlIns = null; + InputStream is = assetManager.open(sqlFile); + try { + sqlIns = parseSqlFile(is); + } finally { + is.close(); } - - - public static List parseSqlFile(InputStream is) throws IOException { - String script = removeComments(is); - return splitSqlScript(script, ';'); - } - - - private static String removeComments(InputStream is) throws IOException { - - StringBuilder sql = new StringBuilder(); - - InputStreamReader isReader = new InputStreamReader(is); - try { - BufferedReader buffReader = new BufferedReader(isReader); - try { - String line; - String multiLineComment = null; - while ((line = buffReader.readLine()) != null) { - line = line.trim(); - - if (multiLineComment == null) { - if (line.startsWith("/*")) { - if (!line.endsWith("}")) { - multiLineComment = "/*"; - } - } else if (line.startsWith("{")) { - if (!line.endsWith("}")) { - multiLineComment = "{"; - } - } else if (!line.startsWith("--") && !line.equals("")) { - sql.append(" ").append(line); - } - } else if (multiLineComment.equals("/*")) { - if (line.endsWith("*/")) { - multiLineComment = null; - } - } else if (multiLineComment.equals("{")) { - if (line.endsWith("}")) { - multiLineComment = null; - } - } - - } - } finally { - buffReader.close(); + return sqlIns; + } + + + public static List parseSqlFile (InputStream is) throws IOException { + String script = removeComments(is); + return splitSqlScript(script, ';'); + } + + + private static String removeComments (InputStream is) throws IOException { + + StringBuilder sql = new StringBuilder(); + + InputStreamReader isReader = new InputStreamReader(is); + try { + BufferedReader buffReader = new BufferedReader(isReader); + try { + String line; + String multiLineComment = null; + while ((line = buffReader.readLine()) != null) { + line = line.trim(); + + if (multiLineComment == null) { + if (line.startsWith("/*")) { + if (!line.endsWith("}")) { + multiLineComment = "/*"; + } + } else if (line.startsWith("{")) { + if (!line.endsWith("}")) { + multiLineComment = "{"; + } + } else if (!line.startsWith("--") && !line.equals("")) { + sql.append(" ").append(line); } + } else if (multiLineComment.equals("/*")) { + if (line.endsWith("*/")) { + multiLineComment = null; + } + } else if (multiLineComment.equals("{")) { + if (line.endsWith("}")) { + multiLineComment = null; + } + } - } finally { - isReader.close(); } + } finally { + buffReader.close(); + } - return sql.toString(); + } finally { + isReader.close(); } + return sql.toString(); + } - private static List splitSqlScript(String script, char delim) { - List statements = new ArrayList<>(); - StringBuilder sb = new StringBuilder(); - boolean inLiteral = false; - char[] content = script.toCharArray(); - for (int i = 0; i < script.length(); i++) { - if (content[i] == '\'') { - inLiteral = !inLiteral; - } - if (content[i] == delim && !inLiteral) { - if (sb.length() > 0) { - statements.add(sb.toString().trim()); - sb = new StringBuilder(); - } - } else { - sb.append(content[i]); - } - } + + private static List splitSqlScript (String script, char delim) { + List statements = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + boolean inLiteral = false; + char[] content = script.toCharArray(); + for (int i = 0; i < script.length(); i++) { + if (content[i] == '\'') { + inLiteral = !inLiteral; + } + if (content[i] == delim && !inLiteral) { if (sb.length() > 0) { - statements.add(sb.toString().trim()); + statements.add(sb.toString().trim()); + sb = new StringBuilder(); } - return statements; + } else { + sb.append(content[i]); + } + } + if (sb.length() > 0) { + statements.add(sb.toString().trim()); } + return statements; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/BackupException.java b/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/BackupException.java index a368114ff3..9646cf66aa 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/BackupException.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/BackupException.java @@ -19,10 +19,10 @@ public class BackupException extends RuntimeException { - private static final long serialVersionUID = 7892197590810157669L; + private static final long serialVersionUID = 7892197590810157669L; - public BackupException(String message, Exception e) { - super(message, e); - } + public BackupException (String message, Exception e) { + super(message, e); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/GenericException.java b/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/GenericException.java index bf0da5066a..53ae4eecc9 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/GenericException.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/GenericException.java @@ -19,8 +19,8 @@ public class GenericException extends RuntimeException { - public GenericException(String message) { - super(message); - } + public GenericException (String message) { + super(message); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/NotesLoadingException.java b/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/NotesLoadingException.java index 6b722c0ec3..a889328d6a 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/NotesLoadingException.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/exceptions/NotesLoadingException.java @@ -19,10 +19,10 @@ public class NotesLoadingException extends RuntimeException { - private static final long serialVersionUID = 1288015037660807104L; + private static final long serialVersionUID = 1288015037660807104L; - public NotesLoadingException(String message, Exception e) { - super(message, e); - } + public NotesLoadingException (String message, Exception e) { + super(message, e); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/extensions/ONDashClockExtension.java b/omniNotes/src/main/java/it/feio/android/omninotes/extensions/ONDashClockExtension.java index 839bdc57ac..f09a95e463 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/extensions/ONDashClockExtension.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/extensions/ONDashClockExtension.java @@ -32,112 +32,118 @@ import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.TextHelper; import it.feio.android.omninotes.utils.date.DateUtils; - -import java.util.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ONDashClockExtension extends DashClockExtension { - private enum Counters {ACTIVE, REMINDERS, TODAY, TOMORROW} + private enum Counters {ACTIVE, REMINDERS, TODAY, TOMORROW} - private DashClockUpdateReceiver mDashClockReceiver; + private DashClockUpdateReceiver mDashClockReceiver; - @Override - protected void onInitialize(boolean isReconnect) { - super.onInitialize(isReconnect); - LocalBroadcastManager broadcastMgr = LocalBroadcastManager.getInstance(this); - if (mDashClockReceiver != null) { - broadcastMgr.unregisterReceiver(mDashClockReceiver); - } - mDashClockReceiver = new DashClockUpdateReceiver(); - broadcastMgr.registerReceiver(mDashClockReceiver, new IntentFilter(Constants.INTENT_UPDATE_DASHCLOCK)); + @Override + protected void onInitialize (boolean isReconnect) { + super.onInitialize(isReconnect); + LocalBroadcastManager broadcastMgr = LocalBroadcastManager.getInstance(this); + if (mDashClockReceiver != null) { + broadcastMgr.unregisterReceiver(mDashClockReceiver); } + mDashClockReceiver = new DashClockUpdateReceiver(); + broadcastMgr.registerReceiver(mDashClockReceiver, new IntentFilter(Constants.INTENT_UPDATE_DASHCLOCK)); + } - @SuppressLint("DefaultLocale") - @Override - protected void onUpdateData(int reason) { + @SuppressLint("DefaultLocale") + @Override + protected void onUpdateData (int reason) { - Map> notesCounters = getNotesCounters(); - int reminders = notesCounters.get(Counters.REMINDERS).size(); + Map> notesCounters = getNotesCounters(); + int reminders = notesCounters.get(Counters.REMINDERS).size(); - StringBuilder expandedTitle = new StringBuilder(); - expandedTitle.append(notesCounters.get(Counters.ACTIVE).size()).append(" ").append(getString(R.string.notes).toLowerCase()); - if (reminders > 0) { - expandedTitle.append(", ").append(reminders).append(" ").append(getString(R.string.reminders)); - } + StringBuilder expandedTitle = new StringBuilder(); + expandedTitle.append(notesCounters.get(Counters.ACTIVE).size()).append(" ").append( + getString(R.string.notes).toLowerCase()); + if (reminders > 0) { + expandedTitle.append(", ").append(reminders).append(" ").append(getString(R.string.reminders)); + } - StringBuilder expandedBody = new StringBuilder(); - - if (notesCounters.get(Counters.TODAY).size() > 0) { - expandedBody.append(notesCounters.get(Counters.TODAY).size()).append(" ").append(getString(R.string.today)).append(":"); - for (Note todayReminder : notesCounters.get(Counters.TODAY)) { - expandedBody.append(System.getProperty("line.separator")).append(("☆ ")).append(getNoteTitle(this, - todayReminder)); - } - expandedBody.append("\n"); - } - - if (notesCounters.get(Counters.TOMORROW).size() > 0) { - expandedBody.append(notesCounters.get(Counters.TOMORROW).size()).append(" ").append(getString(R.string.tomorrow)).append(":"); - for (Note tomorrowReminder : notesCounters.get(Counters.TOMORROW)) { - expandedBody.append(System.getProperty("line.separator")).append(("☆ ")).append(getNoteTitle(this, - tomorrowReminder)); - } - } - - // Publish the extension data update. - Intent launchIntent = new Intent(this, MainActivity.class); - launchIntent.setAction(Intent.ACTION_MAIN); - publishUpdate(new ExtensionData() - .visible(true) - .icon(R.drawable.ic_stat_literal_icon) - .status(String.valueOf(notesCounters.get(Counters.ACTIVE).size())) - .expandedTitle(expandedTitle.toString()) - .expandedBody(expandedBody.toString()) - .clickIntent(launchIntent)); + StringBuilder expandedBody = new StringBuilder(); + + if (notesCounters.get(Counters.TODAY).size() > 0) { + expandedBody.append(notesCounters.get(Counters.TODAY).size()).append(" ").append( + getString(R.string.today)).append(":"); + for (Note todayReminder : notesCounters.get(Counters.TODAY)) { + expandedBody.append(System.getProperty("line.separator")).append(("☆ ")).append(getNoteTitle(this, + todayReminder)); + } + expandedBody.append("\n"); } + if (notesCounters.get(Counters.TOMORROW).size() > 0) { + expandedBody.append(notesCounters.get(Counters.TOMORROW).size()).append(" ").append( + getString(R.string.tomorrow)).append(":"); + for (Note tomorrowReminder : notesCounters.get(Counters.TOMORROW)) { + expandedBody.append(System.getProperty("line.separator")).append(("☆ ")).append(getNoteTitle(this, + tomorrowReminder)); + } + } - private String getNoteTitle(Context context, Note note) { - return TextHelper.getAlternativeTitle(context, note, TextHelper.parseTitleAndContent(context, note)[0]); - } - - - private Map> getNotesCounters() { - Map noteCounters = new HashMap<>(); - List activeNotes = new ArrayList<>(); - List reminders = new ArrayList<>(); - List today = new ArrayList<>(); - List tomorrow = new ArrayList<>(); - for (Note note : DbHelper.getInstance().getNotesActive()) { - activeNotes.add(note); - if (note.getAlarm() != null && !note.isReminderFired()) { - reminders.add(note); - if (DateUtils.isSameDay(Long.valueOf(note.getAlarm()), Calendar.getInstance().getTimeInMillis())) { - today.add(note); - } else if ((Long.valueOf(note.getAlarm()) - Calendar.getInstance().getTimeInMillis()) / (1000 * 60 * - 60) < 24) { - tomorrow.add(note); - } - } + // Publish the extension data update. + Intent launchIntent = new Intent(this, MainActivity.class); + launchIntent.setAction(Intent.ACTION_MAIN); + publishUpdate(new ExtensionData() + .visible(true) + .icon(R.drawable.ic_stat_literal_icon) + .status(String.valueOf(notesCounters.get(Counters.ACTIVE).size())) + .expandedTitle(expandedTitle.toString()) + .expandedBody(expandedBody.toString()) + .clickIntent(launchIntent)); + } + + + private String getNoteTitle (Context context, Note note) { + return TextHelper.getAlternativeTitle(context, note, TextHelper.parseTitleAndContent(context, note)[0]); + } + + + private Map> getNotesCounters () { + Map noteCounters = new HashMap<>(); + List activeNotes = new ArrayList<>(); + List reminders = new ArrayList<>(); + List today = new ArrayList<>(); + List tomorrow = new ArrayList<>(); + for (Note note : DbHelper.getInstance().getNotesActive()) { + activeNotes.add(note); + if (note.getAlarm() != null && !note.isReminderFired()) { + reminders.add(note); + if (DateUtils.isSameDay(Long.valueOf(note.getAlarm()), Calendar.getInstance().getTimeInMillis())) { + today.add(note); + } else if ((Long.valueOf(note.getAlarm()) - Calendar.getInstance().getTimeInMillis()) / (1000 * 60 * + 60) < 24) { + tomorrow.add(note); } - noteCounters.put(Counters.ACTIVE, activeNotes); - noteCounters.put(Counters.REMINDERS, reminders); - noteCounters.put(Counters.TODAY, today); - noteCounters.put(Counters.TOMORROW, tomorrow); - return noteCounters; + } } + noteCounters.put(Counters.ACTIVE, activeNotes); + noteCounters.put(Counters.REMINDERS, reminders); + noteCounters.put(Counters.TODAY, today); + noteCounters.put(Counters.TOMORROW, tomorrow); + return noteCounters; + } - public class DashClockUpdateReceiver extends BroadcastReceiver { - - @Override - public void onReceive(Context context, Intent intent) { - onUpdateData(UPDATE_REASON_MANUAL); - } + public class DashClockUpdateReceiver extends BroadcastReceiver { + @Override + public void onReceive (Context context, Intent intent) { + onUpdateData(UPDATE_REASON_MANUAL); } + + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/extensions/PushBulletExtension.java b/omniNotes/src/main/java/it/feio/android/omninotes/extensions/PushBulletExtension.java index dd08b06a0e..eecb71c7e7 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/extensions/PushBulletExtension.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/extensions/PushBulletExtension.java @@ -18,7 +18,6 @@ package it.feio.android.omninotes.extensions; import com.pushbullet.android.extension.MessagingExtension; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.bus.PushbulletReplyEvent; import it.feio.android.omninotes.helpers.LogDelegate; @@ -26,23 +25,23 @@ public class PushBulletExtension extends MessagingExtension { - private static final String TAG = "PushBulletExtension"; + private static final String TAG = "PushBulletExtension"; - @Override - protected void onMessageReceived(final String conversationIden, final String message) { - LogDelegate.i("Pushbullet MessagingExtension: onMessageReceived(" + conversationIden + ", " + message - + ")"); - EventBus.getDefault().post(new PushbulletReplyEvent(message)); + @Override + protected void onMessageReceived (final String conversationIden, final String message) { + LogDelegate.i("Pushbullet MessagingExtension: onMessageReceived(" + conversationIden + ", " + message + + ")"); + EventBus.getDefault().post(new PushbulletReplyEvent(message)); // MainActivity runningMainActivity = MainActivity.getInstance(); // if (runningMainActivity != null && !runningMainActivity.isFinishing()) { // runningMainActivity.onPushBulletReply(message); // } - } + } - @Override - protected void onConversationDismissed(final String conversationIden) { - LogDelegate.i("Pushbullet MessagingExtension: onConversationDismissed(" + conversationIden + ")"); - } + @Override + protected void onConversationDismissed (final String conversationIden) { + LogDelegate.i("Pushbullet MessagingExtension: onConversationDismissed(" + conversationIden + ")"); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/factory/MediaStoreFactory.java b/omniNotes/src/main/java/it/feio/android/omninotes/factory/MediaStoreFactory.java index 51ef91277b..a410a6e2dc 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/factory/MediaStoreFactory.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/factory/MediaStoreFactory.java @@ -17,23 +17,23 @@ package it.feio.android.omninotes.factory; -import android.provider.MediaStore; - import android.net.Uri; +import android.provider.MediaStore; /** * Created by Relf on 11/24/2015. */ public class MediaStoreFactory { - public Uri createURI(String type){ - switch (type) { - case "image": - return MediaStore.Images.Media.EXTERNAL_CONTENT_URI; - case "video": - return MediaStore.Video.Media.EXTERNAL_CONTENT_URI; - case "audio": - return MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; - } - return null; + + public Uri createURI (String type) { + switch (type) { + case "image": + return MediaStore.Images.Media.EXTERNAL_CONTENT_URI; + case "video": + return MediaStore.Video.Media.EXTERNAL_CONTENT_URI; + case "audio": + return MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } + return null; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AppVersionHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AppVersionHelper.java index b9f36e8a60..7c40785a03 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AppVersionHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AppVersionHelper.java @@ -20,8 +20,6 @@ import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; - -import it.feio.android.omninotes.R; import it.feio.android.omninotes.utils.Constants; @@ -30,34 +28,34 @@ */ public class AppVersionHelper { - public static boolean isAppUpdated(Context context) throws PackageManager.NameNotFoundException { - int currentAppVersion = getCurrentAppVersion(context); - int savedAppVersion = getAppVersionFromPreferences(context); - return currentAppVersion > savedAppVersion; - } - - public static int getAppVersionFromPreferences(Context context) throws PackageManager.NameNotFoundException { - try { - return context.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS).getInt(Constants.PREF_CURRENT_APP_VERSION, 1); - } catch (ClassCastException e) { - return getCurrentAppVersion(context) - 1; - } - } - - public static void updateAppVersionInPreferences(Context context) throws PackageManager.NameNotFoundException { - context.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS).edit().putInt(Constants.PREF_CURRENT_APP_VERSION, - getCurrentAppVersion(context)).apply(); - } - - public static int getCurrentAppVersion(Context context) throws PackageManager.NameNotFoundException { - return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; - } - - public static String getCurrentAppVersionName(Context context) throws PackageManager.NameNotFoundException { - PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - return pInfo.versionName; + public static boolean isAppUpdated (Context context) throws PackageManager.NameNotFoundException { + int currentAppVersion = getCurrentAppVersion(context); + int savedAppVersion = getAppVersionFromPreferences(context); + return currentAppVersion > savedAppVersion; + } + + public static int getAppVersionFromPreferences (Context context) throws PackageManager.NameNotFoundException { + try { + return context.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS).getInt(Constants.PREF_CURRENT_APP_VERSION, 1); + } catch (ClassCastException e) { + return getCurrentAppVersion(context) - 1; } + } + + public static void updateAppVersionInPreferences (Context context) throws PackageManager.NameNotFoundException { + context.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS).edit().putInt(Constants.PREF_CURRENT_APP_VERSION, + getCurrentAppVersion(context)).apply(); + } + + public static int getCurrentAppVersion (Context context) throws PackageManager.NameNotFoundException { + return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; + } + + public static String getCurrentAppVersionName (Context context) throws PackageManager.NameNotFoundException { + PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + return pInfo.versionName; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AttachmentsHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AttachmentsHelper.java index 2c47af1229..14e8e4af7c 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AttachmentsHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/AttachmentsHelper.java @@ -18,39 +18,36 @@ package it.feio.android.omninotes.helpers; -import org.apache.commons.io.FileUtils; - -import java.io.File; - import it.feio.android.omninotes.models.Attachment; +import java.io.File; +import org.apache.commons.io.FileUtils; public class AttachmentsHelper { - /** - * Retrieves attachment file size - * - * @param attachment Attachment to evaluate - * @return Human readable file size string - */ - public static String getSize(Attachment attachment) { - long sizeInKb = attachment.getSize(); - if (attachment.getSize() == 0) { - sizeInKb = new File(attachment.getUri().getPath()).length(); - } - return FileUtils.byteCountToDisplaySize(sizeInKb); - } - - /** - * Checks type of attachment - * - * @param attachment - * @return - */ - public static boolean typeOf(Attachment attachment, String... mimeTypes) { - for (String mimeType : mimeTypes) { - if (mimeType.equals(attachment.getMime_type())) return true; - } - return false; - } + /** + * Retrieves attachment file size + * + * @param attachment Attachment to evaluate + * @return Human readable file size string + */ + public static String getSize (Attachment attachment) { + long sizeInKb = attachment.getSize(); + if (attachment.getSize() == 0) { + sizeInKb = new File(attachment.getUri().getPath()).length(); + } + return FileUtils.byteCountToDisplaySize(sizeInKb); + } + + /** + * Checks type of attachment + */ + public static boolean typeOf (Attachment attachment, String... mimeTypes) { + for (String mimeType : mimeTypes) { + if (mimeType.equals(attachment.getMime_type())) { + return true; + } + } + return false; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/BackupHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/BackupHelper.java index cb9348b0d8..43b02c6bb5 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/BackupHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/BackupHelper.java @@ -22,24 +22,6 @@ import android.content.Intent; import android.support.annotation.NonNull; import android.text.TextUtils; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.filefilter.FileFilterUtils; -import org.apache.commons.io.filefilter.RegexFileFilter; -import org.apache.commons.io.filefilter.TrueFileFilter; -import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; import it.feio.android.omninotes.async.DataBackupIntentService; @@ -50,302 +32,320 @@ import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.TextHelper; import it.feio.android.omninotes.utils.notifications.NotificationsHelper; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.FileFilterUtils; +import org.apache.commons.io.filefilter.RegexFileFilter; +import org.apache.commons.io.filefilter.TrueFileFilter; +import org.bitbucket.cowwoc.diffmatchpatch.DiffMatchPatch; import rx.Observable; public class BackupHelper { - private static String TAG = BackupHelper.class.getSimpleName(); - - - public static void exportNotes(File backupDir) { - for (Note note : DbHelper.getInstance(true).getAllNotes(false)) { - exportNote(backupDir, note); - } - } - - - public static void exportNote(File backupDir, Note note) { - File noteFile = getBackupNoteFile(backupDir, note); - try { - FileUtils.write(noteFile, note.toJSON()); - } catch (IOException e) { - LogDelegate.e("Error backupping note: " + note.get_id()); - } - } - - @NonNull - public static File getBackupNoteFile(File backupDir, Note note) { - return new File(backupDir, String.valueOf(note.get_id()) + ".json"); - } - - - /** - * Export attachments to backup folder - * - * @return True if success, false otherwise - */ - public static boolean exportAttachments(File backupDir) { - return exportAttachments(backupDir, null); - } - - - /** - * Export attachments to backup folder notifying for each attachment copied - * - * @return True if success, false otherwise - */ - public static boolean exportAttachments(File backupDir, NotificationsHelper notificationsHelper) { - File destinationattachmentsDir = new File(backupDir, StorageHelper.getAttachmentDir().getName()); - ArrayList list = DbHelper.getInstance().getAllAttachments(); - exportAttachments(notificationsHelper, destinationattachmentsDir, list, null); - return true; - } - - - public static boolean exportAttachments(NotificationsHelper notificationsHelper, File destinationattachmentsDir, - List list, List listOld) { - - boolean result = true; - - listOld = listOld == null ? Collections.EMPTY_LIST : listOld; - int exported = 0; - int failed = 0; - for (Attachment attachment : list) { - try { - StorageHelper.copyToBackupDir(destinationattachmentsDir, FilenameUtils.getName(attachment.getUriPath()), OmniNotes.getAppContext().getContentResolver().openInputStream(attachment.getUri())); - ++exported; - } catch (FileNotFoundException e) { - LogDelegate.w("Attachment not found during backup: " + attachment.getUriPath()); - ++failed; - result = false; - } - - String failedString = failed > 0 ? " (" + failed + " " + OmniNotes.getAppContext().getString(R.string.failed) + ")" : ""; - if (notificationsHelper != null) { - notificationsHelper.updateMessage( - TextHelper.capitalize(OmniNotes.getAppContext().getString(R.string.attachment)) - + " " + exported + "/" + list.size() + failedString - ); - } - } - - Observable.from(listOld) - .filter(attachment -> !list.contains(attachment)) - .forEach(attachment -> StorageHelper.delete(OmniNotes.getAppContext(), new File - (destinationattachmentsDir.getAbsolutePath(), - attachment.getUri().getLastPathSegment()).getAbsolutePath())); - - return result; - } - - - /** - * Imports backuped notes - * - * @param backupDir - */ - public static List importNotes(File backupDir) { - List notes = new ArrayList<>(); - for (File file : FileUtils.listFiles(backupDir, new RegexFileFilter("\\d{13}.json"), TrueFileFilter.INSTANCE)) { - notes.add(importNote(file)); - } - return notes; - } - - - /** - * Imports single note from its file - */ - public static Note importNote(File file) { - Note note = getImportNote(file); - if (note.getCategory() != null) { - DbHelper.getInstance().updateCategory(note.getCategory()); - } - note.setAttachmentsListOld(DbHelper.getInstance().getNoteAttachments(note)); - DbHelper.getInstance().updateNote(note, false); - return note; - } - - - /** - * Retrieves single note from its file - */ - public static Note getImportNote(File file) { - try { - Note note = new Note(); - String jsonString = FileUtils.readFileToString(file); - if (!TextUtils.isEmpty(jsonString)) { - note.buildFromJson(jsonString); - note.setAttachmentsListOld(DbHelper.getInstance().getNoteAttachments(note)); - } - return note; - } catch (IOException e) { - LogDelegate.e("Error parsing note json"); - return new Note(); - } - } - - - /** - * Import attachments from backup folder - */ - public static boolean importAttachments(File backupDir) { - return importAttachments(backupDir, null); - } - - - /** - * Import attachments from backup folder notifying for each imported item - */ - public static boolean importAttachments(File backupDir, NotificationsHelper notificationsHelper) { - File attachmentsDir = StorageHelper.getAttachmentDir(); - File backupAttachmentsDir = new File(backupDir, attachmentsDir.getName()); - if (!backupAttachmentsDir.exists()) return true; - boolean result = true; - Collection list = FileUtils.listFiles(backupAttachmentsDir, FileFilterUtils.trueFileFilter(), - TrueFileFilter.INSTANCE); - Iterator i = list.iterator(); - int imported = 0; - File file = null; - while (i.hasNext()) { - try { - file = (File) i.next(); - FileUtils.copyFileToDirectory(file, attachmentsDir, true); - if (notificationsHelper != null) { - notificationsHelper.updateMessage( - TextHelper.capitalize(OmniNotes.getAppContext().getString(R.string.attachment)) - + " " + imported++ + "/" + list.size() - ); - } - } catch (IOException e) { - result = false; - LogDelegate.e("Error importing the attachment " + file.getName()); - } - } - return result; - } - - - /** - * Import attachments of a specific note from backup folder - */ - public static void importAttachments(Note note, File backupDir) throws IOException { - - File backupAttachmentsDir = new File(backupDir, StorageHelper.getAttachmentDir().getName()); - - for (Attachment attachment : note.getAttachmentsList()) { - String attachmentFileName = FilenameUtils.getName(attachment.getUriPath()); - File attachmentFile = new File(backupAttachmentsDir, attachmentFileName); - if (attachmentFile.exists()) { - FileUtils.copyFileToDirectory(attachmentFile, StorageHelper.getAttachmentDir(), true); - } else { - LogDelegate.e("Attachment file not found: " + attachmentFileName); - } - } - } - - - /** - * Starts backup service - * @param backupFolderName subfolder of the app's external sd folder where notes will be stored - */ - public static void startBackupService(String backupFolderName) { - Intent service = new Intent(OmniNotes.getAppContext(), DataBackupIntentService.class); - service.setAction(DataBackupIntentService.ACTION_DATA_EXPORT); - service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, backupFolderName); - OmniNotes.getAppContext().startService(service); - } - - - /** - * Exports settings if required - */ - public static boolean exportSettings(File backupDir) { - File preferences = StorageHelper.getSharedPreferencesFile(OmniNotes.getAppContext()); - return (StorageHelper.copyFile(preferences, new File(backupDir, preferences.getName()))); - } - - - /** - * Imports settings - */ - public static boolean importSettings(File backupDir) { - File preferences = StorageHelper.getSharedPreferencesFile(OmniNotes.getAppContext()); - File preferenceBackup = new File(backupDir, preferences.getName()); - return (StorageHelper.copyFile(preferenceBackup, preferences)); - } - - - public static boolean deleteNoteBackup(File backupDir, Note note) { - File noteFile = getBackupNoteFile(backupDir, note); - boolean result = noteFile.delete(); - File attachmentBackup = new File(backupDir, StorageHelper.getAttachmentDir().getName()); - for (Attachment attachment : note.getAttachmentsList()) { - result = result && new File(attachmentBackup, FilenameUtils.getName(attachment.getUri().getPath())) - .delete(); - } - return result; - } - - - public static void deleteNote(File file) { - try { - Note note = new Note(); - note.buildFromJson(FileUtils.readFileToString(file)); - DbHelper.getInstance().deleteNote(note); - } catch (IOException e) { - LogDelegate.e("Error parsing note json"); - } - } - - - /** - * Import database from backup folder. Used ONLY to restore legacy backup - * - * @deprecated {@link BackupHelper#importNotes(File)} - */ - @Deprecated - public static boolean importDB(Context context, File backupDir) { - File database = context.getDatabasePath(Constants.DATABASE_NAME); - if (database.exists()) { - database.delete(); - } - return (StorageHelper.copyFile(new File(backupDir, Constants.DATABASE_NAME), database)); - } - - - public static List> integrityCheck(File backupDir) { - List> errors = new ArrayList<>(); - for (Note note : DbHelper.getInstance(true).getAllNotes(false)) { - File noteFile = getBackupNoteFile(backupDir, note); - try { - String noteString = note.toJSON(); - String noteFileString = FileUtils.readFileToString(noteFile); - if (noteString.equals(noteFileString)) { - File backupAttachmentsDir = new File(backupDir, StorageHelper.getAttachmentDir().getName()); - for (Attachment attachment : note.getAttachmentsList()) { - if (!new File(backupAttachmentsDir, FilenameUtils.getName(attachment.getUriPath())).exists()) { - addIntegrityCheckError(errors, new FileNotFoundException("Attachment " + attachment - .getUriPath() + " missing")); - } - } - } else { - errors.add(new DiffMatchPatch().diffMain(noteString, noteFileString)); - } - } catch (IOException e) { - LogDelegate.e(e.getMessage(), e); - addIntegrityCheckError(errors, e); - } - } - return errors; - } - - - private static void addIntegrityCheckError(List> errors, IOException e) { - LinkedList l = new LinkedList(); - l.add(new DiffMatchPatch.Diff(DiffMatchPatch.Operation.DELETE, e.getMessage())); - errors.add(l); - } + private static String TAG = BackupHelper.class.getSimpleName(); + + + public static void exportNotes (File backupDir) { + for (Note note : DbHelper.getInstance(true).getAllNotes(false)) { + exportNote(backupDir, note); + } + } + + + public static void exportNote (File backupDir, Note note) { + File noteFile = getBackupNoteFile(backupDir, note); + try { + FileUtils.write(noteFile, note.toJSON()); + } catch (IOException e) { + LogDelegate.e("Error backupping note: " + note.get_id()); + } + } + + @NonNull + public static File getBackupNoteFile (File backupDir, Note note) { + return new File(backupDir, note.get_id() + ".json"); + } + + + /** + * Export attachments to backup folder + * + * @return True if success, false otherwise + */ + public static boolean exportAttachments (File backupDir) { + return exportAttachments(backupDir, null); + } + + + /** + * Export attachments to backup folder notifying for each attachment copied + * + * @return True if success, false otherwise + */ + public static boolean exportAttachments (File backupDir, NotificationsHelper notificationsHelper) { + File destinationattachmentsDir = new File(backupDir, StorageHelper.getAttachmentDir().getName()); + ArrayList list = DbHelper.getInstance().getAllAttachments(); + exportAttachments(notificationsHelper, destinationattachmentsDir, list, null); + return true; + } + + + public static boolean exportAttachments (NotificationsHelper notificationsHelper, File destinationattachmentsDir, + List list, List listOld) { + + boolean result = true; + + listOld = listOld == null ? Collections.EMPTY_LIST : listOld; + int exported = 0; + int failed = 0; + for (Attachment attachment : list) { + try { + StorageHelper.copyToBackupDir(destinationattachmentsDir, FilenameUtils.getName(attachment.getUriPath()), + OmniNotes.getAppContext().getContentResolver().openInputStream(attachment.getUri())); + ++exported; + } catch (FileNotFoundException e) { + LogDelegate.w("Attachment not found during backup: " + attachment.getUriPath()); + ++failed; + result = false; + } + + String failedString = + failed > 0 ? " (" + failed + " " + OmniNotes.getAppContext().getString(R.string.failed) + ")" : ""; + if (notificationsHelper != null) { + notificationsHelper.updateMessage( + TextHelper.capitalize(OmniNotes.getAppContext().getString(R.string.attachment)) + + " " + exported + "/" + list.size() + failedString + ); + } + } + + Observable.from(listOld) + .filter(attachment -> !list.contains(attachment)) + .forEach(attachment -> StorageHelper.delete(OmniNotes.getAppContext(), new File + (destinationattachmentsDir.getAbsolutePath(), + attachment.getUri().getLastPathSegment()).getAbsolutePath())); + + return result; + } + + + /** + * Imports backuped notes + */ + public static List importNotes (File backupDir) { + List notes = new ArrayList<>(); + for (File file : FileUtils.listFiles(backupDir, new RegexFileFilter("\\d{13}.json"), TrueFileFilter.INSTANCE)) { + notes.add(importNote(file)); + } + return notes; + } + + + /** + * Imports single note from its file + */ + public static Note importNote (File file) { + Note note = getImportNote(file); + if (note.getCategory() != null) { + DbHelper.getInstance().updateCategory(note.getCategory()); + } + note.setAttachmentsListOld(DbHelper.getInstance().getNoteAttachments(note)); + DbHelper.getInstance().updateNote(note, false); + return note; + } + + + /** + * Retrieves single note from its file + */ + public static Note getImportNote (File file) { + try { + Note note = new Note(); + String jsonString = FileUtils.readFileToString(file); + if (!TextUtils.isEmpty(jsonString)) { + note.buildFromJson(jsonString); + note.setAttachmentsListOld(DbHelper.getInstance().getNoteAttachments(note)); + } + return note; + } catch (IOException e) { + LogDelegate.e("Error parsing note json"); + return new Note(); + } + } + + + /** + * Import attachments from backup folder + */ + public static boolean importAttachments (File backupDir) { + return importAttachments(backupDir, null); + } + + + /** + * Import attachments from backup folder notifying for each imported item + */ + public static boolean importAttachments (File backupDir, NotificationsHelper notificationsHelper) { + File attachmentsDir = StorageHelper.getAttachmentDir(); + File backupAttachmentsDir = new File(backupDir, attachmentsDir.getName()); + if (!backupAttachmentsDir.exists()) { + return true; + } + boolean result = true; + Collection list = FileUtils.listFiles(backupAttachmentsDir, FileFilterUtils.trueFileFilter(), + TrueFileFilter.INSTANCE); + Iterator i = list.iterator(); + int imported = 0; + File file = null; + while (i.hasNext()) { + try { + file = (File) i.next(); + FileUtils.copyFileToDirectory(file, attachmentsDir, true); + if (notificationsHelper != null) { + notificationsHelper.updateMessage( + TextHelper.capitalize(OmniNotes.getAppContext().getString(R.string.attachment)) + + " " + imported++ + "/" + list.size() + ); + } + } catch (IOException e) { + result = false; + LogDelegate.e("Error importing the attachment " + file.getName()); + } + } + return result; + } + + + /** + * Import attachments of a specific note from backup folder + */ + public static void importAttachments (Note note, File backupDir) throws IOException { + + File backupAttachmentsDir = new File(backupDir, StorageHelper.getAttachmentDir().getName()); + + for (Attachment attachment : note.getAttachmentsList()) { + String attachmentFileName = FilenameUtils.getName(attachment.getUriPath()); + File attachmentFile = new File(backupAttachmentsDir, attachmentFileName); + if (attachmentFile.exists()) { + FileUtils.copyFileToDirectory(attachmentFile, StorageHelper.getAttachmentDir(), true); + } else { + LogDelegate.e("Attachment file not found: " + attachmentFileName); + } + } + } + + + /** + * Starts backup service + * + * @param backupFolderName subfolder of the app's external sd folder where notes will be stored + */ + public static void startBackupService (String backupFolderName) { + Intent service = new Intent(OmniNotes.getAppContext(), DataBackupIntentService.class); + service.setAction(DataBackupIntentService.ACTION_DATA_EXPORT); + service.putExtra(DataBackupIntentService.INTENT_BACKUP_NAME, backupFolderName); + OmniNotes.getAppContext().startService(service); + } + + + /** + * Exports settings if required + */ + public static boolean exportSettings (File backupDir) { + File preferences = StorageHelper.getSharedPreferencesFile(OmniNotes.getAppContext()); + return (StorageHelper.copyFile(preferences, new File(backupDir, preferences.getName()))); + } + + + /** + * Imports settings + */ + public static boolean importSettings (File backupDir) { + File preferences = StorageHelper.getSharedPreferencesFile(OmniNotes.getAppContext()); + File preferenceBackup = new File(backupDir, preferences.getName()); + return (StorageHelper.copyFile(preferenceBackup, preferences)); + } + + + public static boolean deleteNoteBackup (File backupDir, Note note) { + File noteFile = getBackupNoteFile(backupDir, note); + boolean result = noteFile.delete(); + File attachmentBackup = new File(backupDir, StorageHelper.getAttachmentDir().getName()); + for (Attachment attachment : note.getAttachmentsList()) { + result = result && new File(attachmentBackup, FilenameUtils.getName(attachment.getUri().getPath())) + .delete(); + } + return result; + } + + + public static void deleteNote (File file) { + try { + Note note = new Note(); + note.buildFromJson(FileUtils.readFileToString(file)); + DbHelper.getInstance().deleteNote(note); + } catch (IOException e) { + LogDelegate.e("Error parsing note json"); + } + } + + + /** + * Import database from backup folder. Used ONLY to restore legacy backup + * + * @deprecated {@link BackupHelper#importNotes(File)} + */ + @Deprecated + public static boolean importDB (Context context, File backupDir) { + File database = context.getDatabasePath(Constants.DATABASE_NAME); + if (database.exists()) { + database.delete(); + } + return (StorageHelper.copyFile(new File(backupDir, Constants.DATABASE_NAME), database)); + } + + + public static List> integrityCheck (File backupDir) { + List> errors = new ArrayList<>(); + for (Note note : DbHelper.getInstance(true).getAllNotes(false)) { + File noteFile = getBackupNoteFile(backupDir, note); + try { + String noteString = note.toJSON(); + String noteFileString = FileUtils.readFileToString(noteFile); + if (noteString.equals(noteFileString)) { + File backupAttachmentsDir = new File(backupDir, StorageHelper.getAttachmentDir().getName()); + for (Attachment attachment : note.getAttachmentsList()) { + if (!new File(backupAttachmentsDir, FilenameUtils.getName(attachment.getUriPath())).exists()) { + addIntegrityCheckError(errors, new FileNotFoundException("Attachment " + attachment + .getUriPath() + " missing")); + } + } + } else { + errors.add(new DiffMatchPatch().diffMain(noteString, noteFileString)); + } + } catch (IOException e) { + LogDelegate.e(e.getMessage(), e); + addIntegrityCheckError(errors, e); + } + } + return errors; + } + + + private static void addIntegrityCheckError (List> errors, IOException e) { + LinkedList l = new LinkedList(); + l.add(new DiffMatchPatch.Diff(DiffMatchPatch.Operation.DELETE, e.getMessage())); + errors.add(l); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LanguageHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LanguageHelper.java index 9fb3f89630..2a98842002 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LanguageHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LanguageHelper.java @@ -17,6 +17,8 @@ package it.feio.android.omninotes.helpers; +import static android.content.Context.MODE_MULTI_PROCESS; + import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; @@ -26,73 +28,70 @@ import android.support.annotation.NonNull; import android.text.TextUtils; import it.feio.android.omninotes.utils.Constants; - import java.util.Locale; -import static android.content.Context.MODE_MULTI_PROCESS; - public class LanguageHelper { - /** - * Updates default language with forced one - */ - @SuppressLint("ApplySharedPref") - public static Context updateLanguage(Context ctx, String lang) { - SharedPreferences prefs = ctx.getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); - String language = prefs.getString(Constants.PREF_LANG, ""); + /** + * Updates default language with forced one + */ + @SuppressLint("ApplySharedPref") + public static Context updateLanguage (Context ctx, String lang) { + SharedPreferences prefs = ctx.getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS); + String language = prefs.getString(Constants.PREF_LANG, ""); - Locale locale = null; - if (TextUtils.isEmpty(language) && lang == null) { - locale = Locale.getDefault(); - prefs.edit().putString(Constants.PREF_LANG, locale.toString()).commit(); - } else if (lang != null) { - locale = getLocale(lang); - prefs.edit().putString(Constants.PREF_LANG, lang).commit(); - } else if (!TextUtils.isEmpty(language)) { - locale = getLocale(language); - } + Locale locale = null; + if (TextUtils.isEmpty(language) && lang == null) { + locale = Locale.getDefault(); + prefs.edit().putString(Constants.PREF_LANG, locale.toString()).commit(); + } else if (lang != null) { + locale = getLocale(lang); + prefs.edit().putString(Constants.PREF_LANG, lang).commit(); + } else if (!TextUtils.isEmpty(language)) { + locale = getLocale(language); + } - return setLocale(ctx, locale); - } + return setLocale(ctx, locale); + } - private static Context setLocale(Context context, Locale locale) { - Configuration configuration = context.getResources().getConfiguration(); - configuration.locale = locale; - context.getResources().updateConfiguration(configuration, null); - return context; - } + private static Context setLocale (Context context, Locale locale) { + Configuration configuration = context.getResources().getConfiguration(); + configuration.locale = locale; + context.getResources().updateConfiguration(configuration, null); + return context; + } - /** - * Checks country AND region - */ - private static Locale getLocale(String lang) { - if (lang.contains("_")) { - return new Locale(lang.split("_")[0], lang.split("_")[1]); - } else { - return new Locale(lang); - } - } + /** + * Checks country AND region + */ + private static Locale getLocale (String lang) { + if (lang.contains("_")) { + return new Locale(lang.split("_")[0], lang.split("_")[1]); + } else { + return new Locale(lang); + } + } - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - @NonNull - static String getLocalizedString(Context context, String desiredLocale, int resourceId) { - if (desiredLocale.equals(getCurrentLocale(context))) { - return context.getResources().getString(resourceId); - } - Configuration conf = context.getResources().getConfiguration(); - conf = new Configuration(conf); - conf.setLocale(getLocale(desiredLocale)); - Context localizedContext = context.createConfigurationContext(conf); - return localizedContext.getResources().getString(resourceId); - } + @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) + @NonNull + static String getLocalizedString (Context context, String desiredLocale, int resourceId) { + if (desiredLocale.equals(getCurrentLocale(context))) { + return context.getResources().getString(resourceId); + } + Configuration conf = context.getResources().getConfiguration(); + conf = new Configuration(conf); + conf.setLocale(getLocale(desiredLocale)); + Context localizedContext = context.createConfigurationContext(conf); + return localizedContext.getResources().getString(resourceId); + } - public static String getCurrentLocale(Context context) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - return context.getResources().getConfiguration().getLocales().get(0).toString(); - } else { - return context.getResources().getConfiguration().locale.toString(); - } - } + public static String getCurrentLocale (Context context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + return context.getResources().getConfiguration().getLocales().get(0).toString(); + } else { + return context.getResources().getConfiguration().locale.toString(); + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LogDelegate.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LogDelegate.java index e5bc660c05..9d177c0029 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LogDelegate.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/LogDelegate.java @@ -17,94 +17,91 @@ package it.feio.android.omninotes.helpers; -import android.util.Log; +import static it.feio.android.checklistview.interfaces.Constants.TAG; +import static it.feio.android.omninotes.utils.ConstantsBase.PREF_ENABLE_FILE_LOGGING; +import android.util.Log; import com.bosphere.filelogger.FL; import com.bosphere.filelogger.FLConfig; import com.bosphere.filelogger.FLConst; - -import java.io.File; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.exceptions.GenericException; import it.feio.android.omninotes.utils.StorageHelper; - -import static it.feio.android.checklistview.interfaces.Constants.TAG; -import static it.feio.android.omninotes.utils.ConstantsBase.PREF_ENABLE_FILE_LOGGING; +import java.io.File; public class LogDelegate { - private static Boolean fileLoggingEnabled; + private static Boolean fileLoggingEnabled; - private LogDelegate() { - // Public constructor hiding - } + private LogDelegate () { + // Public constructor hiding + } - public static void v(String message) { - if (isFileLoggingEnabled()) { - FL.v(message); - } else { - Log.v(TAG, message); - } + public static void v (String message) { + if (isFileLoggingEnabled()) { + FL.v(message); + } else { + Log.v(TAG, message); } + } - public static void d(String message) { - if (isFileLoggingEnabled()) { - FL.d(message); - } else { - Log.d(TAG, message); - } + public static void d (String message) { + if (isFileLoggingEnabled()) { + FL.d(message); + } else { + Log.d(TAG, message); } + } - public static void i(String message) { - if (isFileLoggingEnabled()) { - FL.i(message); - } else { - Log.i(TAG, message); - } + public static void i (String message) { + if (isFileLoggingEnabled()) { + FL.i(message); + } else { + Log.i(TAG, message); } + } - public static void w(String message, Throwable e) { - if (isFileLoggingEnabled()) { - FL.w(message, e); - } else { - Log.w(TAG, message, e); - } + public static void w (String message, Throwable e) { + if (isFileLoggingEnabled()) { + FL.w(message, e); + } else { + Log.w(TAG, message, e); } + } - public static void w(String message) { - if (isFileLoggingEnabled()) { - FL.w(message); - } else { - Log.w(TAG, message); - } + public static void w (String message) { + if (isFileLoggingEnabled()) { + FL.w(message); + } else { + Log.w(TAG, message); } + } - public static void e(String message, Throwable e) { - if (isFileLoggingEnabled()) { - FL.e(message, e); - } else { - Log.e(TAG, message, e); - } + public static void e (String message, Throwable e) { + if (isFileLoggingEnabled()) { + FL.e(message, e); + } else { + Log.e(TAG, message, e); } - - public static void e(String message) { - e(message, new GenericException(message)); - } - - private static boolean isFileLoggingEnabled() { - if (fileLoggingEnabled == null) { - fileLoggingEnabled = OmniNotes.getSharedPreferences().getBoolean(PREF_ENABLE_FILE_LOGGING, false); - if (fileLoggingEnabled) { - FL.init(new FLConfig.Builder(OmniNotes.getAppContext()) - .minLevel(FLConst.Level.V) - .logToFile(true) - .dir(new File(StorageHelper.getExternalStoragePublicDir(), "logs")) - .retentionPolicy(FLConst.RetentionPolicy.FILE_COUNT) - .build()); - FL.setEnabled(true); - } - } - return fileLoggingEnabled; + } + + public static void e (String message) { + e(message, new GenericException(message)); + } + + private static boolean isFileLoggingEnabled () { + if (fileLoggingEnabled == null) { + fileLoggingEnabled = OmniNotes.getSharedPreferences().getBoolean(PREF_ENABLE_FILE_LOGGING, false); + if (fileLoggingEnabled) { + FL.init(new FLConfig.Builder(OmniNotes.getAppContext()) + .minLevel(FLConst.Level.V) + .logToFile(true) + .dir(new File(StorageHelper.getExternalStoragePublicDir(), "logs")) + .retentionPolicy(FLConst.RetentionPolicy.FILE_COUNT) + .build()); + FL.setEnabled(true); + } } + return fileLoggingEnabled; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/NotesHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/NotesHelper.java index 62f58f13a3..620460c55e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/NotesHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/NotesHelper.java @@ -17,12 +17,6 @@ package it.feio.android.omninotes.helpers; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.StringUtils; - -import java.util.ArrayList; -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.helpers.count.CountFactory; import it.feio.android.omninotes.models.Attachment; @@ -31,147 +25,152 @@ import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.StorageHelper; import it.feio.android.omninotes.utils.TagsHelper; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.StringUtils; public class NotesHelper { - public static boolean haveSameId(Note note, Note currentNote) { - return currentNote != null - && currentNote.get_id() != null - && currentNote.get_id().equals(note.get_id()); + public static boolean haveSameId (Note note, Note currentNote) { + return currentNote != null + && currentNote.get_id() != null + && currentNote.get_id().equals(note.get_id()); - } + } - public static StringBuilder appendContent(Note note, StringBuilder content, boolean includeTitle) { - if (content.length() > 0 - && (!StringUtils.isEmpty(note.getTitle()) || !StringUtils.isEmpty(note.getContent()))) { - content.append(System.getProperty("line.separator")).append(System.getProperty("line.separator")) - .append(Constants.MERGED_NOTES_SEPARATOR).append(System.getProperty("line.separator")) - .append(System.getProperty("line.separator")); - } - if (includeTitle && !StringUtils.isEmpty(note.getTitle())) { - content.append(note.getTitle()); - } - if (!StringUtils.isEmpty(note.getTitle()) && !StringUtils.isEmpty(note.getContent())) { - content.append(System.getProperty("line.separator")).append(System.getProperty("line.separator")); - } - if (!StringUtils.isEmpty(note.getContent())) { - content.append(note.getContent()); - } - return content; + public static StringBuilder appendContent (Note note, StringBuilder content, boolean includeTitle) { + if (content.length() > 0 + && (!StringUtils.isEmpty(note.getTitle()) || !StringUtils.isEmpty(note.getContent()))) { + content.append(System.getProperty("line.separator")).append(System.getProperty("line.separator")) + .append(Constants.MERGED_NOTES_SEPARATOR).append(System.getProperty("line.separator")) + .append(System.getProperty("line.separator")); + } + if (includeTitle && !StringUtils.isEmpty(note.getTitle())) { + content.append(note.getTitle()); + } + if (!StringUtils.isEmpty(note.getTitle()) && !StringUtils.isEmpty(note.getContent())) { + content.append(System.getProperty("line.separator")).append(System.getProperty("line.separator")); + } + if (!StringUtils.isEmpty(note.getContent())) { + content.append(note.getContent()); + } + return content; + } + + public static void addAttachments (boolean keepMergedNotes, Note note, ArrayList attachments) { + if (keepMergedNotes) { + for (Attachment attachment : note.getAttachmentsList()) { + attachments.add(StorageHelper.createAttachmentFromUri(OmniNotes.getAppContext(), attachment.getUri + ())); + } + } else { + attachments.addAll(note.getAttachmentsList()); + } + } + + public static Note mergeNotes (List notes, boolean keepMergedNotes) { + boolean locked = false; + ArrayList attachments = new ArrayList<>(); + String reminder = null; + String reminderRecurrenceRule = null; + Double latitude = null; + Double longitude = null; + + Note mergedNote = new Note(); + mergedNote.setTitle(notes.get(0).getTitle()); + mergedNote.setArchived(notes.get(0).isArchived()); + mergedNote.setCategory(notes.get(0).getCategory()); + StringBuilder content = new StringBuilder(); + // Just first note title must not be included into the content + boolean includeTitle = false; + + for (Note note : notes) { + appendContent(note, content, includeTitle); + locked = locked || note.isLocked(); + String currentReminder = note.getAlarm(); + if (!StringUtils.isEmpty(currentReminder) && reminder == null) { + reminder = currentReminder; + reminderRecurrenceRule = note.getRecurrenceRule(); + } + latitude = (Double) ObjectUtils.defaultIfNull(latitude, note.getLatitude()); + longitude = (Double) ObjectUtils.defaultIfNull(longitude, note.getLongitude()); + addAttachments(keepMergedNotes, note, attachments); + includeTitle = true; } - public static void addAttachments(boolean keepMergedNotes, Note note, ArrayList attachments) { - if (keepMergedNotes) { - for (Attachment attachment : note.getAttachmentsList()) { - attachments.add(StorageHelper.createAttachmentFromUri(OmniNotes.getAppContext(), attachment.getUri - ())); - } - } else { - attachments.addAll(note.getAttachmentsList()); - } + mergedNote.setContent(content.toString()); + mergedNote.setLocked(locked); + mergedNote.setAlarm(reminder); + mergedNote.setRecurrenceRule(reminderRecurrenceRule); + mergedNote.setLatitude(latitude); + mergedNote.setLongitude(longitude); + mergedNote.setAttachmentsList(attachments); + + return mergedNote; + } + + /** + * Retrieves statistics data for a single note + */ + public static StatsSingleNote getNoteInfos (Note note) { + StatsSingleNote infos = new StatsSingleNote(); + + int words, chars; + if (note.isChecklist()) { + infos.setChecklistCompletedItemsNumber(StringUtils.countMatches(note.getContent(), it.feio.android.checklistview + .interfaces.Constants.CHECKED_SYM)); + infos.setChecklistItemsNumber(infos.getChecklistCompletedItemsNumber() + + StringUtils.countMatches(note.getContent(), + it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM)); + } + infos.setTags(TagsHelper.retrieveTags(note).size()); + words = getWords(note); + chars = getChars(note); + infos.setWords(words); + infos.setChars(chars); + + int attachmentsAll = 0, images = 0, videos = 0, audioRecordings = 0, sketches = 0, files = 0; + for (Attachment attachment : note.getAttachmentsList()) { + if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())) { + images++; + } else if (Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) { + videos++; + } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) { + audioRecordings++; + } else if (Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())) { + sketches++; + } else if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) { + files++; + } + } + infos.setAttachments(attachmentsAll); + infos.setImages(images); + infos.setVideos(videos); + infos.setAudioRecordings(audioRecordings); + infos.setSketches(sketches); + infos.setFiles(files); + + if (note.getCategory() != null) { + infos.setCategoryName(note.getCategory().getName()); } - public static Note mergeNotes(List notes, boolean keepMergedNotes) { - boolean locked = false; - ArrayList attachments = new ArrayList<>(); - String reminder = null; - String reminderRecurrenceRule = null; - Double latitude = null; - Double longitude = null; - - Note mergedNote = new Note(); - mergedNote.setTitle(notes.get(0).getTitle()); - mergedNote.setArchived(notes.get(0).isArchived()); - mergedNote.setCategory(notes.get(0).getCategory()); - StringBuilder content = new StringBuilder(); - // Just first note title must not be included into the content - boolean includeTitle = false; - - for (Note note : notes) { - appendContent(note, content, includeTitle); - locked = locked || note.isLocked(); - String currentReminder = note.getAlarm(); - if (!StringUtils.isEmpty(currentReminder) && reminder == null) { - reminder = currentReminder; - reminderRecurrenceRule = note.getRecurrenceRule(); - } - latitude = (Double) ObjectUtils.defaultIfNull(latitude, note.getLatitude()); - longitude = (Double) ObjectUtils.defaultIfNull(longitude, note.getLongitude()); - addAttachments(keepMergedNotes, note, attachments); - includeTitle = true; - } - - mergedNote.setContent(content.toString()); - mergedNote.setLocked(locked); - mergedNote.setAlarm(reminder); - mergedNote.setRecurrenceRule(reminderRecurrenceRule); - mergedNote.setLatitude(latitude); - mergedNote.setLongitude(longitude); - mergedNote.setAttachmentsList(attachments); - - return mergedNote; - } - - /** - * Retrieves statistics data for a single note - */ - public static StatsSingleNote getNoteInfos(Note note) { - StatsSingleNote infos = new StatsSingleNote(); - - int words, chars; - if (note.isChecklist()) { - infos.setChecklistCompletedItemsNumber(StringUtils.countMatches(note.getContent(), it.feio.android.checklistview - .interfaces.Constants.CHECKED_SYM)); - infos.setChecklistItemsNumber(infos.getChecklistCompletedItemsNumber() + - StringUtils.countMatches(note.getContent(), it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM)); - } - infos.setTags(TagsHelper.retrieveTags(note).size()); - words = getWords(note); - chars = getChars(note); - infos.setWords(words); - infos.setChars(chars); - - int attachmentsAll = 0, images = 0, videos = 0, audioRecordings = 0, sketches = 0, files = 0; - for (Attachment attachment : note.getAttachmentsList()) { - if (Constants.MIME_TYPE_IMAGE.equals(attachment.getMime_type())) { - images++; - } else if (Constants.MIME_TYPE_VIDEO.equals(attachment.getMime_type())) { - videos++; - } else if (Constants.MIME_TYPE_AUDIO.equals(attachment.getMime_type())) { - audioRecordings++; - } else if (Constants.MIME_TYPE_SKETCH.equals(attachment.getMime_type())) { - sketches++; - } else if (Constants.MIME_TYPE_FILES.equals(attachment.getMime_type())) { - files++; - } - } - infos.setAttachments(attachmentsAll); - infos.setImages(images); - infos.setVideos(videos); - infos.setAudioRecordings(audioRecordings); - infos.setSketches(sketches); - infos.setFiles(files); - - if (note.getCategory() != null) { - infos.setCategoryName(note.getCategory().getName()); - } - - return infos; - } - - /** - * Counts words in a note - */ - public static int getWords(Note note) { - return CountFactory.getWordCounter().countWords(note); - } - - /** - * Counts chars in a note - */ - public static int getChars(Note note) { - return CountFactory.getWordCounter().countChars(note); - } + return infos; + } + + /** + * Counts words in a note + */ + public static int getWords (Note note) { + return CountFactory.getWordCounter().countWords(note); + } + + /** + * Counts chars in a note + */ + public static int getChars (Note note) { + return CountFactory.getWordCounter().countChars(note); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/PermissionsHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/PermissionsHelper.java index c215fa7c95..7a0f66dc44 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/PermissionsHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/PermissionsHelper.java @@ -31,41 +31,41 @@ public class PermissionsHelper { - public static void requestPermission(Activity activity, String permission, int rationaleDescription, View - messageView, OnPermissionRequestedListener onPermissionRequestedListener) { + public static void requestPermission (Activity activity, String permission, int rationaleDescription, View + messageView, OnPermissionRequestedListener onPermissionRequestedListener) { - if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { + if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { - if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { - Snackbar.make(messageView, rationaleDescription, Snackbar.LENGTH_INDEFINITE) - .setAction(R.string.ok, view -> { - requestPermissionExecute(activity, permission, onPermissionRequestedListener, messageView); - }) - .show(); - } else { - requestPermissionExecute(activity, permission, onPermissionRequestedListener, messageView); - } - } else { - if (onPermissionRequestedListener != null) { - onPermissionRequestedListener.onPermissionGranted(); - } - } - } + if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { + Snackbar.make(messageView, rationaleDescription, Snackbar.LENGTH_INDEFINITE) + .setAction(R.string.ok, view -> { + requestPermissionExecute(activity, permission, onPermissionRequestedListener, messageView); + }) + .show(); + } else { + requestPermissionExecute(activity, permission, onPermissionRequestedListener, messageView); + } + } else { + if (onPermissionRequestedListener != null) { + onPermissionRequestedListener.onPermissionGranted(); + } + } + } - private static void requestPermissionExecute(Activity activity, String permission, OnPermissionRequestedListener - onPermissionRequestedListener, View messageView) { - RxPermissions.getInstance(activity) - .request(permission) - .subscribe(granted -> { - if (granted) { - if (onPermissionRequestedListener != null) { - onPermissionRequestedListener.onPermissionGranted(); - } - } else { - String msg = activity.getString(R.string.permission_not_granted) + ": " + permission; - Snackbar.make(messageView, msg, Snackbar.LENGTH_LONG).show(); - } - }); - } + private static void requestPermissionExecute (Activity activity, String permission, OnPermissionRequestedListener + onPermissionRequestedListener, View messageView) { + RxPermissions.getInstance(activity) + .request(permission) + .subscribe(granted -> { + if (granted) { + if (onPermissionRequestedListener != null) { + onPermissionRequestedListener.onPermissionGranted(); + } + } else { + String msg = activity.getString(R.string.permission_not_granted) + ": " + permission; + Snackbar.make(messageView, msg, Snackbar.LENGTH_LONG).show(); + } + }); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/SpringImportHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/SpringImportHelper.java index e2a9a4d428..d8b3da934d 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/SpringImportHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/SpringImportHelper.java @@ -24,13 +24,6 @@ import android.text.Html; import android.text.TextUtils; import android.widget.Toast; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.HashMap; -import java.util.List; - import exceptions.ImportException; import it.feio.android.omninotes.R; import it.feio.android.omninotes.db.DbHelper; @@ -47,274 +40,278 @@ import it.feio.android.springpadimporter.models.SpringpadComment; import it.feio.android.springpadimporter.models.SpringpadElement; import it.feio.android.springpadimporter.models.SpringpadItem; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.List; public class SpringImportHelper { - public final static String ACTION_DATA_IMPORT_SPRINGPAD = "action_data_import_springpad"; - public final static String EXTRA_SPRINGPAD_BACKUP = "extra_springpad_backup"; - private final Context context; - - - private int importedSpringpadNotes, importedSpringpadNotebooks; - - public SpringImportHelper(Context context) { - this.context = context; - } - - - /** - * Imports notes and notebooks from Springpad exported archive - * - * @param intent - * @param mNotificationsHelper - */ - public synchronized void importDataFromSpringpad(Intent intent, NotificationsHelper mNotificationsHelper) { - String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP); - Importer importer = new Importer(); - try { - importer.setZipProgressesListener(percentage -> mNotificationsHelper.setMessage(context - .getString(R.string.extracted) + " " + percentage + "%").show()); - importer.doImport(backupPath); - // Updating notification - updateImportNotification(importer, mNotificationsHelper); - } catch (ImportException e) { - new NotificationsHelper(context) - .createNotification(NotificationChannels.NotificationChannelNames.Backups, - R.drawable.ic_emoticon_sad_white_24dp, - context.getString(R.string.import_fail) + ": " + e.getMessage(), null).setLedActive().show(); - return; - } - List elements = importer.getSpringpadNotes(); - - // If nothing is retrieved it will exit - if (elements == null || elements.size() == 0) { - return; - } - - // These maps are used to associate with post processing notes to categories (notebooks) - HashMap categoriesWithUuid = new HashMap<>(); - - // Adds all the notebooks (categories) - for (SpringpadElement springpadElement : importer.getNotebooks()) { - Category cat = new Category(); - cat.setName(springpadElement.getName()); - cat.setColor(String.valueOf(Color.parseColor("#F9EA1B"))); - DbHelper.getInstance().updateCategory(cat); - categoriesWithUuid.put(springpadElement.getUuid(), cat); - - // Updating notification - importedSpringpadNotebooks++; - updateImportNotification(importer, mNotificationsHelper); - } - // And creates a default one for notes without notebook - Category defaulCategory = new Category(); - defaulCategory.setName("Springpad"); - defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B"))); - DbHelper.getInstance().updateCategory(defaulCategory); - - // And then notes are created - Note note; - Attachment mAttachment = null; - Uri uri; - for (SpringpadElement springpadElement : importer.getNotes()) { - note = new Note(); - - // Title - note.setTitle(springpadElement.getName()); - - // Content dependent from type of Springpad note - StringBuilder content = new StringBuilder(); - content.append(TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement - .getText())); - content.append(TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement - .getDescription()); - - // Some notes could have been exported wrongly - if (springpadElement.getType() == null) { - Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show(); - continue; - } - - if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) { - try { - content.append(System.getProperty("line.separator")).append(springpadElement.getVideos().get(0)); - } catch (IndexOutOfBoundsException e) { - content.append(System.getProperty("line.separator")).append(springpadElement.getUrl()); - } - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) { - content.append(System.getProperty("line.separator")).append( - TextUtils.join(", ", springpadElement.getCast())); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) { - content.append(System.getProperty("line.separator")).append("Author: ") - .append(springpadElement.getAuthor()).append(System.getProperty("line.separator")) - .append("Publication date: ").append(springpadElement.getPublicationDate()); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) { - content.append(System.getProperty("line.separator")).append("Ingredients: ") - .append(springpadElement.getIngredients()).append(System.getProperty("line.separator")) - .append("Directions: ").append(springpadElement.getDirections()); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) { - content.append(System.getProperty("line.separator")).append(springpadElement.getUrl()); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS) - && springpadElement.getPhoneNumbers() != null) { - content.append(System.getProperty("line.separator")).append("Phone number: ") - .append(springpadElement.getPhoneNumbers().getPhone()); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) { - content.append(System.getProperty("line.separator")).append("Category: ") - .append(springpadElement.getCategory()).append(System.getProperty("line.separator")) - .append("Manufacturer: ").append(springpadElement.getManufacturer()) - .append(System.getProperty("line.separator")).append("Price: ") - .append(springpadElement.getPrice()); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) { - content.append(System.getProperty("line.separator")).append("Wine type: ") - .append(springpadElement.getWine_type()).append(System.getProperty("line.separator")) - .append("Varietal: ").append(springpadElement.getVarietal()) - .append(System.getProperty("line.separator")).append("Price: ") - .append(springpadElement.getPrice()); - } - if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) { - content.append(System.getProperty("line.separator")).append("Artist: ") - .append(springpadElement.getArtist()); - } - for (SpringpadComment springpadComment : springpadElement.getComments()) { - content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter()) - .append(" commented at 0").append(springpadComment.getDate()).append(": ") - .append(springpadElement.getArtist()); - } - - note.setContent(content.toString()); - - // Checklists - if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) { - StringBuilder sb = new StringBuilder(); - String checkmark; - for (SpringpadItem mSpringpadItem : springpadElement.getItems()) { - checkmark = mSpringpadItem.getComplete() ? it.feio.android.checklistview.interfaces.Constants - .CHECKED_SYM - : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM; - sb.append(checkmark).append(mSpringpadItem.getName()).append(System.getProperty("line.separator")); - } - note.setContent(sb.toString()); - note.setChecklist(true); - } - - // Tags - String tags = springpadElement.getTags().size() > 0 ? "#" - + TextUtils.join(" #", springpadElement.getTags()) : ""; - if (note.isChecklist()) { - note.setTitle(note.getTitle() + tags); - } else { - note.setContent(note.getContent() + System.getProperty("line.separator") + tags); - } - - // Address - String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress() - : ""; - if (!TextUtils.isEmpty(address)) { - try { - double[] coords = GeocodeHelper.getCoordinatesFromAddress(context, address); - note.setLatitude(coords[0]); - note.setLongitude(coords[1]); - } catch (IOException e) { - LogDelegate.e("An error occurred trying to resolve address to coords during Springpad " + - "import"); - } - note.setAddress(address); - } - - // Reminder - if (springpadElement.getDate() != null) { - note.setAlarm(springpadElement.getDate().getTime()); - } - - // Creation, modification, category - note.setCreation(springpadElement.getCreated().getTime()); - note.setLastModification(springpadElement.getModified().getTime()); - - // Image - String image = springpadElement.getImage(); - if (!TextUtils.isEmpty(image)) { - try { - File file = StorageHelper.createNewAttachmentFileFromHttp(context, image); - uri = Uri.fromFile(file); - String mimeType = StorageHelper.getMimeType(uri.getPath()); - mAttachment = new Attachment(uri, mimeType); - } catch (MalformedURLException e) { - uri = Uri.parse(importer.getWorkingPath() + image); - mAttachment = StorageHelper.createAttachmentFromUri(context, uri, true); - } catch (IOException e) { - LogDelegate.e("Error retrieving Springpad online image"); - } - if (mAttachment != null) { - note.addAttachment(mAttachment); - } - mAttachment = null; - } - - // Other attachments - for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) { - // The attachment could be the image itself so it's jumped - if (image != null && image.equals(springpadAttachment.getUrl())) continue; - - if (TextUtils.isEmpty(springpadAttachment.getUrl())) { - continue; - } - - // Tries first with online images - try { - File file = StorageHelper.createNewAttachmentFileFromHttp(context, springpadAttachment.getUrl()); - uri = Uri.fromFile(file); - String mimeType = StorageHelper.getMimeType(uri.getPath()); - mAttachment = new Attachment(uri, mimeType); - } catch (MalformedURLException e) { - uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl()); - mAttachment = StorageHelper.createAttachmentFromUri(context, uri, true); - } catch (IOException e) { - LogDelegate.e("Error retrieving Springpad online image"); - } - if (mAttachment != null) { - note.addAttachment(mAttachment); - } - mAttachment = null; - } - - // If the note has a category is added to the map to be post-processed - if (springpadElement.getNotebooks().size() > 0) { - note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0))); - } else { - note.setCategory(defaulCategory); - } - - // The note is saved - DbHelper.getInstance().updateNote(note, false); - ReminderHelper.addReminder(context, note); - - // Updating notification - importedSpringpadNotes++; - updateImportNotification(importer, mNotificationsHelper); - } - - // Delete temp data - try { - importer.clean(); - } catch (IOException e) { - LogDelegate.w("Springpad import temp files not deleted"); - } - } - - - private void updateImportNotification(Importer importer, NotificationsHelper mNotificationsHelper) { - mNotificationsHelper.setMessage( - importer.getNotebooksCount() + " " + context.getString(R.string.categories) + " (" - + importedSpringpadNotebooks + " " + context.getString(R.string.imported) + "), " - + +importer.getNotesCount() + " " + context.getString(R.string.notes) + " (" - + importedSpringpadNotes + " " + context.getString(R.string.imported) + ")").show(); - } + public final static String ACTION_DATA_IMPORT_SPRINGPAD = "action_data_import_springpad"; + public final static String EXTRA_SPRINGPAD_BACKUP = "extra_springpad_backup"; + private final Context context; + + + private int importedSpringpadNotes, importedSpringpadNotebooks; + + public SpringImportHelper (Context context) { + this.context = context; + } + + + /** + * Imports notes and notebooks from Springpad exported archive + */ + public synchronized void importDataFromSpringpad (Intent intent, NotificationsHelper mNotificationsHelper) { + String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP); + Importer importer = new Importer(); + try { + importer.setZipProgressesListener(percentage -> mNotificationsHelper.setMessage(context + .getString(R.string.extracted) + " " + percentage + "%").show()); + importer.doImport(backupPath); + // Updating notification + updateImportNotification(importer, mNotificationsHelper); + } catch (ImportException e) { + new NotificationsHelper(context) + .createNotification(NotificationChannels.NotificationChannelNames.Backups, + R.drawable.ic_emoticon_sad_white_24dp, + context.getString(R.string.import_fail) + ": " + e.getMessage(), null).setLedActive().show(); + return; + } + List elements = importer.getSpringpadNotes(); + + // If nothing is retrieved it will exit + if (elements == null || elements.size() == 0) { + return; + } + + // These maps are used to associate with post processing notes to categories (notebooks) + HashMap categoriesWithUuid = new HashMap<>(); + + // Adds all the notebooks (categories) + for (SpringpadElement springpadElement : importer.getNotebooks()) { + Category cat = new Category(); + cat.setName(springpadElement.getName()); + cat.setColor(String.valueOf(Color.parseColor("#F9EA1B"))); + DbHelper.getInstance().updateCategory(cat); + categoriesWithUuid.put(springpadElement.getUuid(), cat); + + // Updating notification + importedSpringpadNotebooks++; + updateImportNotification(importer, mNotificationsHelper); + } + // And creates a default one for notes without notebook + Category defaulCategory = new Category(); + defaulCategory.setName("Springpad"); + defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B"))); + DbHelper.getInstance().updateCategory(defaulCategory); + + // And then notes are created + Note note; + Attachment mAttachment = null; + Uri uri; + for (SpringpadElement springpadElement : importer.getNotes()) { + note = new Note(); + + // Title + note.setTitle(springpadElement.getName()); + + // Content dependent from type of Springpad note + StringBuilder content = new StringBuilder(); + content.append(TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement + .getText())); + content.append(TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement + .getDescription()); + + // Some notes could have been exported wrongly + if (springpadElement.getType() == null) { + Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show(); + continue; + } + + if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) { + try { + content.append(System.getProperty("line.separator")).append(springpadElement.getVideos().get(0)); + } catch (IndexOutOfBoundsException e) { + content.append(System.getProperty("line.separator")).append(springpadElement.getUrl()); + } + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) { + content.append(System.getProperty("line.separator")).append( + TextUtils.join(", ", springpadElement.getCast())); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) { + content.append(System.getProperty("line.separator")).append("Author: ") + .append(springpadElement.getAuthor()).append(System.getProperty("line.separator")) + .append("Publication date: ").append(springpadElement.getPublicationDate()); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) { + content.append(System.getProperty("line.separator")).append("Ingredients: ") + .append(springpadElement.getIngredients()).append(System.getProperty("line.separator")) + .append("Directions: ").append(springpadElement.getDirections()); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) { + content.append(System.getProperty("line.separator")).append(springpadElement.getUrl()); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS) + && springpadElement.getPhoneNumbers() != null) { + content.append(System.getProperty("line.separator")).append("Phone number: ") + .append(springpadElement.getPhoneNumbers().getPhone()); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) { + content.append(System.getProperty("line.separator")).append("Category: ") + .append(springpadElement.getCategory()).append(System.getProperty("line.separator")) + .append("Manufacturer: ").append(springpadElement.getManufacturer()) + .append(System.getProperty("line.separator")).append("Price: ") + .append(springpadElement.getPrice()); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) { + content.append(System.getProperty("line.separator")).append("Wine type: ") + .append(springpadElement.getWine_type()).append(System.getProperty("line.separator")) + .append("Varietal: ").append(springpadElement.getVarietal()) + .append(System.getProperty("line.separator")).append("Price: ") + .append(springpadElement.getPrice()); + } + if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) { + content.append(System.getProperty("line.separator")).append("Artist: ") + .append(springpadElement.getArtist()); + } + for (SpringpadComment springpadComment : springpadElement.getComments()) { + content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter()) + .append(" commented at 0").append(springpadComment.getDate()).append(": ") + .append(springpadElement.getArtist()); + } + + note.setContent(content.toString()); + + // Checklists + if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) { + StringBuilder sb = new StringBuilder(); + String checkmark; + for (SpringpadItem mSpringpadItem : springpadElement.getItems()) { + checkmark = mSpringpadItem.getComplete() ? it.feio.android.checklistview.interfaces.Constants + .CHECKED_SYM + : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM; + sb.append(checkmark).append(mSpringpadItem.getName()).append(System.getProperty("line.separator")); + } + note.setContent(sb.toString()); + note.setChecklist(true); + } + + // Tags + String tags = springpadElement.getTags().size() > 0 ? "#" + + TextUtils.join(" #", springpadElement.getTags()) : ""; + if (note.isChecklist()) { + note.setTitle(note.getTitle() + tags); + } else { + note.setContent(note.getContent() + System.getProperty("line.separator") + tags); + } + + // Address + String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress() + : ""; + if (!TextUtils.isEmpty(address)) { + try { + double[] coords = GeocodeHelper.getCoordinatesFromAddress(context, address); + note.setLatitude(coords[0]); + note.setLongitude(coords[1]); + } catch (IOException e) { + LogDelegate.e("An error occurred trying to resolve address to coords during Springpad " + + "import"); + } + note.setAddress(address); + } + + // Reminder + if (springpadElement.getDate() != null) { + note.setAlarm(springpadElement.getDate().getTime()); + } + + // Creation, modification, category + note.setCreation(springpadElement.getCreated().getTime()); + note.setLastModification(springpadElement.getModified().getTime()); + + // Image + String image = springpadElement.getImage(); + if (!TextUtils.isEmpty(image)) { + try { + File file = StorageHelper.createNewAttachmentFileFromHttp(context, image); + uri = Uri.fromFile(file); + String mimeType = StorageHelper.getMimeType(uri.getPath()); + mAttachment = new Attachment(uri, mimeType); + } catch (MalformedURLException e) { + uri = Uri.parse(importer.getWorkingPath() + image); + mAttachment = StorageHelper.createAttachmentFromUri(context, uri, true); + } catch (IOException e) { + LogDelegate.e("Error retrieving Springpad online image"); + } + if (mAttachment != null) { + note.addAttachment(mAttachment); + } + mAttachment = null; + } + + // Other attachments + for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) { + // The attachment could be the image itself so it's jumped + if (image != null && image.equals(springpadAttachment.getUrl())) { + continue; + } + + if (TextUtils.isEmpty(springpadAttachment.getUrl())) { + continue; + } + + // Tries first with online images + try { + File file = StorageHelper.createNewAttachmentFileFromHttp(context, springpadAttachment.getUrl()); + uri = Uri.fromFile(file); + String mimeType = StorageHelper.getMimeType(uri.getPath()); + mAttachment = new Attachment(uri, mimeType); + } catch (MalformedURLException e) { + uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl()); + mAttachment = StorageHelper.createAttachmentFromUri(context, uri, true); + } catch (IOException e) { + LogDelegate.e("Error retrieving Springpad online image"); + } + if (mAttachment != null) { + note.addAttachment(mAttachment); + } + mAttachment = null; + } + + // If the note has a category is added to the map to be post-processed + if (springpadElement.getNotebooks().size() > 0) { + note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0))); + } else { + note.setCategory(defaulCategory); + } + + // The note is saved + DbHelper.getInstance().updateNote(note, false); + ReminderHelper.addReminder(context, note); + + // Updating notification + importedSpringpadNotes++; + updateImportNotification(importer, mNotificationsHelper); + } + + // Delete temp data + try { + importer.clean(); + } catch (IOException e) { + LogDelegate.w("Springpad import temp files not deleted"); + } + } + + + private void updateImportNotification (Importer importer, NotificationsHelper mNotificationsHelper) { + mNotificationsHelper.setMessage( + importer.getNotebooksCount() + " " + context.getString(R.string.categories) + " (" + + importedSpringpadNotebooks + " " + context.getString(R.string.imported) + "), " + + +importer.getNotesCount() + " " + context.getString(R.string.notes) + " (" + + importedSpringpadNotes + " " + context.getString(R.string.imported) + ")").show(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/CountFactory.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/CountFactory.java index 17eeeaabb9..ba3ccef0c5 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/CountFactory.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/CountFactory.java @@ -22,24 +22,24 @@ public class CountFactory { - private CountFactory() { - } + private CountFactory () { + } - public static WordCounter getWordCounter() { - String locale = LanguageHelper.getCurrentLocale(OmniNotes.getAppContext()); - return getCounterInstanceByLocale(locale); - } + public static WordCounter getWordCounter () { + String locale = LanguageHelper.getCurrentLocale(OmniNotes.getAppContext()); + return getCounterInstanceByLocale(locale); + } - static WordCounter getCounterInstanceByLocale(String locale) { - switch (locale) { - case "ja_JP": - return new IdeogramsWordCounter(); - case "zh_CN": - return new IdeogramsWordCounter(); - case "zh_TW": - return new IdeogramsWordCounter(); - default: - return new DefaultWordCounter(); - } + static WordCounter getCounterInstanceByLocale (String locale) { + switch (locale) { + case "ja_JP": + return new IdeogramsWordCounter(); + case "zh_CN": + return new IdeogramsWordCounter(); + case "zh_TW": + return new IdeogramsWordCounter(); + default: + return new DefaultWordCounter(); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/DefaultWordCounter.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/DefaultWordCounter.java index a62a7dd684..d8cf71fa8a 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/DefaultWordCounter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/DefaultWordCounter.java @@ -22,38 +22,38 @@ public class DefaultWordCounter implements WordCounter { - @Override - public int countWords(Note note) { - int count = 0; - String[] fields = {note.getTitle(), note.getContent()}; - for (String field : fields) { - field = sanitizeTextForWordsAndCharsCount(note, field); - boolean word = false; - int endOfLine = field.length() - 1; - for (int i = 0; i < field.length(); i++) { - // if the char is a letter, word = true. - if (Character.isLetter(field.charAt(i)) && i != endOfLine) { - word = true; - // if char isn't a letter and there have been letters before, counter goes up. - } else if (!Character.isLetter(field.charAt(i)) && word) { - count++; - word = false; - // last word of String; if it doesn't end with a non letter, it wouldn't count without this. - } else if (Character.isLetter(field.charAt(i)) && i == endOfLine) { - count++; - } - } + @Override + public int countWords (Note note) { + int count = 0; + String[] fields = {note.getTitle(), note.getContent()}; + for (String field : fields) { + field = sanitizeTextForWordsAndCharsCount(note, field); + boolean word = false; + int endOfLine = field.length() - 1; + for (int i = 0; i < field.length(); i++) { + // if the char is a letter, word = true. + if (Character.isLetter(field.charAt(i)) && i != endOfLine) { + word = true; + // if char isn't a letter and there have been letters before, counter goes up. + } else if (!Character.isLetter(field.charAt(i)) && word) { + count++; + word = false; + // last word of String; if it doesn't end with a non letter, it wouldn't count without this. + } else if (Character.isLetter(field.charAt(i)) && i == endOfLine) { + count++; } - return count; + } } + return count; + } - @Override - public int countChars(Note note) { - String titleAndContent = note.getTitle() + "\n" + note.getContent(); - return Observable - .from(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split("")) - .filter(s -> !s.matches("\\s")) - .count().toBlocking().single(); - } + @Override + public int countChars (Note note) { + String titleAndContent = note.getTitle() + "\n" + note.getContent(); + return Observable + .from(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split("")) + .filter(s -> !s.matches("\\s")) + .count().toBlocking().single(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounter.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounter.java index 7bb07efbc8..dc377b9dd3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounter.java @@ -22,17 +22,17 @@ public class IdeogramsWordCounter implements WordCounter { - @Override - public int countWords(Note note) { - return countChars(note); - } + @Override + public int countWords (Note note) { + return countChars(note); + } - @Override - public int countChars(Note note) { - String titleAndContent = note.getTitle() + "\n" + note.getContent(); - return Observable - .from(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split("")) - .filter(s -> !s.matches("\\s")) - .count().toBlocking().single(); - } + @Override + public int countChars (Note note) { + String titleAndContent = note.getTitle() + "\n" + note.getContent(); + return Observable + .from(sanitizeTextForWordsAndCharsCount(note, titleAndContent).split("")) + .filter(s -> !s.matches("\\s")) + .count().toBlocking().single(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/WordCounter.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/WordCounter.java index 8894aab73b..f9d7fcc051 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/WordCounter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/count/WordCounter.java @@ -17,22 +17,21 @@ package it.feio.android.omninotes.helpers.count; -import java.util.regex.Pattern; - import it.feio.android.omninotes.models.Note; +import java.util.regex.Pattern; public interface WordCounter { - int countWords(Note note); + int countWords (Note note); - int countChars(Note note); + int countChars (Note note); - default String sanitizeTextForWordsAndCharsCount(Note note, String field) { - if (note.isChecklist()) { - String regex = "(" + Pattern.quote(it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM) + "|" - + Pattern.quote(it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM) + ")"; - field = field.replaceAll(regex, ""); - } - return field; + default String sanitizeTextForWordsAndCharsCount (Note note, String field) { + if (note.isChecklist()) { + String regex = "(" + Pattern.quote(it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM) + "|" + + Pattern.quote(it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM) + ")"; + field = field.replaceAll(regex, ""); } + return field; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/date/DateHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/date/DateHelper.java index bd83a14833..bb1946fb50 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/helpers/date/DateHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/helpers/date/DateHelper.java @@ -20,20 +20,17 @@ import android.text.TextUtils; import android.text.format.DateUtils; import android.text.format.Time; - -import net.fortuna.ical4j.model.property.RRule; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - import be.billington.calendar.recurrencepicker.EventRecurrence; import be.billington.calendar.recurrencepicker.EventRecurrenceFormatter; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.utils.Constants; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import net.fortuna.ical4j.model.property.RRule; /** @@ -43,159 +40,139 @@ */ public class DateHelper { - public static String getSortableDate() { - String result; - SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SORTABLE); - Date now = Calendar.getInstance().getTime(); - result = sdf.format(now); - return result; - } - - - /** - * Build a formatted date string starting from values obtained by a DatePicker - * - * @param year - * @param month - * @param day - * @param format - * @return - */ - public static String onDateSet(int year, int month, int day, String format) { - SimpleDateFormat sdf = new SimpleDateFormat(format); - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.YEAR, year); - cal.set(Calendar.MONTH, month); - cal.set(Calendar.DAY_OF_MONTH, day); - return sdf.format(cal.getTime()); - } - - - /** - * Build a formatted time string starting from values obtained by a TimePicker - * - * @param hour - * @param minute - * @param format - * @return - */ - public static String onTimeSet(int hour, int minute, String format) { - SimpleDateFormat sdf = new SimpleDateFormat(format); - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.HOUR_OF_DAY, hour); - cal.set(Calendar.MINUTE, minute); - return sdf.format(cal.getTime()); + public static String getSortableDate () { + String result; + SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SORTABLE); + Date now = Calendar.getInstance().getTime(); + result = sdf.format(now); + return result; + } + + + /** + * Build a formatted date string starting from values obtained by a DatePicker + */ + public static String onDateSet (int year, int month, int day, String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, year); + cal.set(Calendar.MONTH, month); + cal.set(Calendar.DAY_OF_MONTH, day); + return sdf.format(cal.getTime()); + } + + + /** + * Build a formatted time string starting from values obtained by a TimePicker + */ + public static String onTimeSet (int hour, int minute, String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.HOUR_OF_DAY, hour); + cal.set(Calendar.MINUTE, minute); + return sdf.format(cal.getTime()); + } + + /** + * + */ + public static String getDateTimeShort (Context mContext, Long date) { + int flags = DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_SHOW_WEEKDAY + | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE; + return (date == null) ? "" : DateUtils.formatDateTime(mContext, date, flags) + + " " + DateUtils.formatDateTime(mContext, date, DateUtils.FORMAT_SHOW_TIME); + } + + + /** + * + */ + public static String getTimeShort (Context mContext, Long time) { + if (time == null) { + return ""; } - - /** - * @param mContext - * @param date - * @return - */ - public static String getDateTimeShort(Context mContext, Long date) { - int flags = DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_SHOW_WEEKDAY - | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE; - return (date == null) ? "" : DateUtils.formatDateTime(mContext, date, flags) - + " " + DateUtils.formatDateTime(mContext, date, DateUtils.FORMAT_SHOW_TIME); + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(time); + return DateUtils.formatDateTime(mContext, time, DateUtils.FORMAT_SHOW_TIME); + } + + + /** + * + */ + public static String getTimeShort (Context mContext, int hourOfDay, int minute) { + Calendar c = Calendar.getInstance(); + c.set(Calendar.HOUR_OF_DAY, hourOfDay); + c.set(Calendar.MINUTE, minute); + return DateUtils.formatDateTime(mContext, c.getTimeInMillis(), DateUtils.FORMAT_SHOW_TIME); + } + + + /** + * Formats a short time period (minutes) + */ + public static String formatShortTime (Context mContext, long time) { + String m = String.valueOf(time / 1000 / 60); + String s = String.format("%02d", (time / 1000) % 60); + return m + ":" + s; + } + + + public static String formatRecurrence (Context mContext, String recurrenceRule) { + if (!TextUtils.isEmpty(recurrenceRule)) { + EventRecurrence recurrenceEvent = new EventRecurrence(); + recurrenceEvent.setStartDate(new Time("" + new Date().getTime())); + recurrenceEvent.parse(recurrenceRule); + return EventRecurrenceFormatter.getRepeatString(mContext.getApplicationContext(), + mContext.getResources(), recurrenceEvent, true); + } else { + return ""; } - - - /** - * @param mContext - * @param date - * @return - */ - public static String getTimeShort(Context mContext, Long time) { - if (time == null) - return ""; - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(time); - return DateUtils.formatDateTime(mContext, time, DateUtils.FORMAT_SHOW_TIME); - } - - - /** - * @param mContext - * @param hourOfDay - * @param minute - * @return - */ - public static String getTimeShort(Context mContext, int hourOfDay, int minute) { - Calendar c = Calendar.getInstance(); - c.set(Calendar.HOUR_OF_DAY, hourOfDay); - c.set(Calendar.MINUTE, minute); - return DateUtils.formatDateTime(mContext, c.getTimeInMillis(), DateUtils.FORMAT_SHOW_TIME); + } + + + public static Long nextReminderFromRecurrenceRule (long reminder, String recurrenceRule) { + return nextReminderFromRecurrenceRule(reminder, Calendar.getInstance().getTimeInMillis(), recurrenceRule); + } + + + public static Long nextReminderFromRecurrenceRule (long reminder, long currentTime, String recurrenceRule) { + RRule rule = new RRule(); + try { + rule.setValue(recurrenceRule); + net.fortuna.ical4j.model.DateTime seed = new net.fortuna.ical4j.model.DateTime(reminder); + long startTimestamp = reminder + 60 * 1000; + if (startTimestamp < currentTime) { + startTimestamp = currentTime; + } + net.fortuna.ical4j.model.DateTime start = new net.fortuna.ical4j.model.DateTime(startTimestamp); + Date nextDate = rule.getRecur().getNextDate(seed, start); + return nextDate == null ? 0L : nextDate.getTime(); + } catch (ParseException e) { + LogDelegate.e("Error parsing rrule"); } + return 0L; + } - /** - * Formats a short time period (minutes) - * - * @param time - * @return - */ - public static String formatShortTime(Context mContext, long time) { - String m = String.valueOf(time / 1000 / 60); - String s = String.format("%02d", (time / 1000) % 60); - return m + ":" + s; - } + public static String getNoteReminderText (long reminder) { + return OmniNotes.getAppContext().getString(R.string.alarm_set_on) + " " + getDateTimeShort(OmniNotes + .getAppContext(), reminder); + } - public static String formatRecurrence(Context mContext, String recurrenceRule) { - if (!TextUtils.isEmpty(recurrenceRule)) { - EventRecurrence recurrenceEvent = new EventRecurrence(); - recurrenceEvent.setStartDate(new Time("" + new Date().getTime())); - recurrenceEvent.parse(recurrenceRule); - return EventRecurrenceFormatter.getRepeatString(mContext.getApplicationContext(), - mContext.getResources(), recurrenceEvent, true); - } else { - return ""; - } - } + public static String getNoteRecurrentReminderText (long reminder, String rrule) { + return DateHelper.formatRecurrence(OmniNotes.getAppContext(), rrule) + " " + OmniNotes.getAppContext().getString + (R.string.starting_from) + " " + DateHelper.getDateTimeShort(OmniNotes.getAppContext(), reminder); + } - public static Long nextReminderFromRecurrenceRule(long reminder, String recurrenceRule) { - return nextReminderFromRecurrenceRule(reminder, Calendar.getInstance().getTimeInMillis(), recurrenceRule); + public static String getFormattedDate (Long timestamp, boolean prettified) { + if (prettified) { + return it.feio.android.omninotes.utils.date.DateUtils.prettyTime(timestamp); + } else { + return DateHelper.getDateTimeShort(OmniNotes.getAppContext(), timestamp); } - - - public static Long nextReminderFromRecurrenceRule(long reminder, long currentTime, String recurrenceRule) { - RRule rule = new RRule(); - try { - rule.setValue(recurrenceRule); - net.fortuna.ical4j.model.DateTime seed = new net.fortuna.ical4j.model.DateTime(reminder); - long startTimestamp = reminder + 60 * 1000; - if (startTimestamp < currentTime) { - startTimestamp = currentTime; - } - net.fortuna.ical4j.model.DateTime start = new net.fortuna.ical4j.model.DateTime(startTimestamp); - Date nextDate = rule.getRecur().getNextDate(seed, start); - return nextDate == null ? 0L : nextDate.getTime(); - } catch (ParseException e) { - LogDelegate.e("Error parsing rrule"); - } - return 0L; - } - - - public static String getNoteReminderText(long reminder) { - return OmniNotes.getAppContext().getString(R.string.alarm_set_on) + " " + getDateTimeShort(OmniNotes - .getAppContext(), reminder); - } - - - public static String getNoteRecurrentReminderText(long reminder, String rrule) { - return DateHelper.formatRecurrence(OmniNotes.getAppContext(), rrule) + " " + OmniNotes.getAppContext().getString - (R.string.starting_from) + " " + DateHelper.getDateTimeShort(OmniNotes.getAppContext(), reminder); - } - - - public static String getFormattedDate(Long timestamp, boolean prettified) { - if(prettified) { - return it.feio.android.omninotes.utils.date.DateUtils.prettyTime(timestamp); - } else { - return DateHelper.getDateTimeShort(OmniNotes.getAppContext(), timestamp); - } - } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroActivity.java index dd516f439c..7e1101a39d 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroActivity.java @@ -26,33 +26,33 @@ public class IntroActivity extends AppIntro2 { - @Override - public void init(Bundle savedInstanceState) { - addSlide(new IntroSlide1(), getApplicationContext()); - addSlide(new IntroSlide2(), getApplicationContext()); - addSlide(new IntroSlide3(), getApplicationContext()); - addSlide(new IntroSlide4(), getApplicationContext()); - addSlide(new IntroSlide5(), getApplicationContext()); - addSlide(new IntroSlide6(), getApplicationContext()); - } - - - @Override - public void onDonePressed() { - OmniNotes.getAppContext().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).edit() - .putBoolean(Constants.PREF_TOUR_COMPLETE, true).apply(); - finish(); - } - - - public static boolean mustRun() { - return !OmniNotes.isDebugBuild() && !OmniNotes.getAppContext().getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS).getBoolean(Constants.PREF_TOUR_COMPLETE, false); - } - - - @Override - public void onBackPressed() { - // Does nothing, you HAVE TO SEE THE INTRO! - } + @Override + public void init (Bundle savedInstanceState) { + addSlide(new IntroSlide1(), getApplicationContext()); + addSlide(new IntroSlide2(), getApplicationContext()); + addSlide(new IntroSlide3(), getApplicationContext()); + addSlide(new IntroSlide4(), getApplicationContext()); + addSlide(new IntroSlide5(), getApplicationContext()); + addSlide(new IntroSlide6(), getApplicationContext()); + } + + + @Override + public void onDonePressed () { + OmniNotes.getAppContext().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).edit() + .putBoolean(Constants.PREF_TOUR_COMPLETE, true).apply(); + finish(); + } + + + public static boolean mustRun () { + return !OmniNotes.isDebugBuild() && !OmniNotes.getAppContext().getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS).getBoolean(Constants.PREF_TOUR_COMPLETE, false); + } + + + @Override + public void onBackPressed () { + // Does nothing, you HAVE TO SEE THE INTRO! + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroFragment.java index 5891ca779f..4ce2f852e3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroFragment.java @@ -24,7 +24,6 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; - import butterknife.BindView; import butterknife.ButterKnife; import it.feio.android.omninotes.R; @@ -32,26 +31,26 @@ public class IntroFragment extends Fragment { - @BindView(R.id.intro_background) - View background; + @BindView(R.id.intro_background) + View background; - @BindView(R.id.intro_title) - TextView title; + @BindView(R.id.intro_title) + TextView title; - @BindView(R.id.intro_image) - ImageView image; + @BindView(R.id.intro_image) + ImageView image; - @BindView(R.id.intro_image_small) - ImageView image_small; + @BindView(R.id.intro_image_small) + ImageView image_small; - @BindView(R.id.intro_description) - TextView description; + @BindView(R.id.intro_description) + TextView description; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.intro_slide, container, false); - ButterKnife.bind(this, v); - return v; - } + @Override + public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.intro_slide, container, false); + ButterKnife.bind(this, v); + return v; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide1.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide1.java index 14a16f0b27..d9f6b9f15a 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide1.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide1.java @@ -25,14 +25,14 @@ public class IntroSlide1 extends IntroFragment { - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - background.setBackgroundColor(Color.parseColor("#222222")); - title.setText(R.string.tour_listactivity_intro_title); - image.setVisibility(View.GONE); - image_small.setImageResource(R.drawable.logo); - image_small.setVisibility(View.VISIBLE); - description.setText(R.string.tour_listactivity_final_detail); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + background.setBackgroundColor(Color.parseColor("#222222")); + title.setText(R.string.tour_listactivity_intro_title); + image.setVisibility(View.GONE); + image_small.setImageResource(R.drawable.logo); + image_small.setVisibility(View.VISIBLE); + description.setText(R.string.tour_listactivity_final_detail); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide2.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide2.java index 78eafe9d4b..065c371def 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide2.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide2.java @@ -24,12 +24,12 @@ public class IntroSlide2 extends IntroFragment { - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - background.setBackgroundColor(Color.parseColor("#f44336")); - title.setText(R.string.tour_listactivity_home_title); - image.setImageResource(R.drawable.slide2); - description.setText(R.string.tour_listactivity_home_detail); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + background.setBackgroundColor(Color.parseColor("#f44336")); + title.setText(R.string.tour_listactivity_home_title); + image.setImageResource(R.drawable.slide2); + description.setText(R.string.tour_listactivity_home_detail); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide3.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide3.java index 32cff207d3..04c02963e3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide3.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide3.java @@ -24,12 +24,12 @@ public class IntroSlide3 extends IntroFragment { - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - background.setBackgroundColor(Color.parseColor("#8bc34a")); - title.setText(R.string.categories); - image.setImageResource(R.drawable.slide3); - description.setText(R.string.tour_listactivity_tag_detail); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + background.setBackgroundColor(Color.parseColor("#8bc34a")); + title.setText(R.string.categories); + image.setImageResource(R.drawable.slide3); + description.setText(R.string.tour_listactivity_tag_detail); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide4.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide4.java index 9139324b9b..4c02840355 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide4.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide4.java @@ -24,12 +24,12 @@ public class IntroSlide4 extends IntroFragment { - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - background.setBackgroundColor(Color.parseColor("#2196f3")); - title.setText(R.string.tour_detailactivity_attachment_title); - image.setImageResource(R.drawable.slide4); - description.setText(R.string.tour_detailactivity_attachment_detail); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + background.setBackgroundColor(Color.parseColor("#2196f3")); + title.setText(R.string.tour_detailactivity_attachment_title); + image.setImageResource(R.drawable.slide4); + description.setText(R.string.tour_detailactivity_attachment_detail); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide5.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide5.java index 3cac5b1148..1cf3ec08f8 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide5.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide5.java @@ -24,12 +24,12 @@ public class IntroSlide5 extends IntroFragment { - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - background.setBackgroundColor(Color.parseColor("#9c27b0")); - title.setText(R.string.tour_detailactivity_links_title); - image.setImageResource(R.drawable.slide5); - description.setText(R.string.tour_detailactivity_links_detail); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + background.setBackgroundColor(Color.parseColor("#9c27b0")); + title.setText(R.string.tour_detailactivity_links_title); + image.setImageResource(R.drawable.slide5); + description.setText(R.string.tour_detailactivity_links_detail); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide6.java b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide6.java index dbd5124857..c220cdd57f 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide6.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/intro/IntroSlide6.java @@ -28,19 +28,19 @@ public class IntroSlide6 extends IntroFragment { - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - background.setBackgroundColor(Color.parseColor("#222222")); - title.setText(R.string.tour_listactivity_final_title); - image.setVisibility(View.GONE); - image_small.setImageResource(R.drawable.facebook); - image_small.setVisibility(View.VISIBLE); - image_small.setOnClickListener(v -> { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setData(Uri.parse(Constants.FACEBOOK_COMMUNITY)); - startActivity(intent); - }); - description.setText(R.string.tour_community); - } + @Override + public void onActivityCreated (Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + background.setBackgroundColor(Color.parseColor("#222222")); + title.setText(R.string.tour_listactivity_final_title); + image.setVisibility(View.GONE); + image_small.setImageResource(R.drawable.facebook); + image_small.setVisibility(View.VISIBLE); + image_small.setOnClickListener(v -> { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setData(Uri.parse(Constants.FACEBOOK_COMMUNITY)); + startActivity(intent); + }); + description.setText(R.string.tour_community); + } } \ No newline at end of file diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/Attachment.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/Attachment.java index 0b02959d5c..983d34c690 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/Attachment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/Attachment.java @@ -20,78 +20,77 @@ import android.os.Parcel; import android.os.Parcelable; import it.feio.android.omninotes.commons.models.BaseAttachment; - import java.util.Calendar; public class Attachment extends BaseAttachment implements Parcelable { - private Uri uri; + private Uri uri; - public Attachment(Uri uri, String mime_type) { - this(Calendar.getInstance().getTimeInMillis(), uri, null, 0, 0, mime_type); - } + public Attachment (Uri uri, String mime_type) { + this(Calendar.getInstance().getTimeInMillis(), uri, null, 0, 0, mime_type); + } - public Attachment(long id, Uri uri, String name, long size, long length, String mime_type) { - super(id, uri != null ? uri.getPath() : null, name, size, length, mime_type); - setUri(uri); - } + public Attachment (long id, Uri uri, String name, long size, long length, String mime_type) { + super(id, uri != null ? uri.getPath() : null, name, size, length, mime_type); + setUri(uri); + } - public Attachment(BaseAttachment attachment) { - super(attachment.getId(), attachment.getUriPath(), attachment.getName(), attachment.getSize(), attachment - .getLength(), attachment.getMime_type()); - this.uri = Uri.parse(attachment.getUriPath()); - } + public Attachment (BaseAttachment attachment) { + super(attachment.getId(), attachment.getUriPath(), attachment.getName(), attachment.getSize(), attachment + .getLength(), attachment.getMime_type()); + this.uri = Uri.parse(attachment.getUriPath()); + } - private Attachment(Parcel in) { - setId(in.readLong()); - setUri(Uri.parse(in.readString())); - setMime_type(in.readString()); - } + private Attachment (Parcel in) { + setId(in.readLong()); + setUri(Uri.parse(in.readString())); + setMime_type(in.readString()); + } - public Uri getUri() { - return uri; - } + public Uri getUri () { + return uri; + } - public void setUri(Uri uri) { - this.uri = uri; - setUriPath(uri != null ? uri.toString() : ""); - } + public void setUri (Uri uri) { + this.uri = uri; + setUriPath(uri != null ? uri.toString() : ""); + } - @Override - public int describeContents() { - return 0; - } + @Override + public int describeContents () { + return 0; + } - @Override - public void writeToParcel(Parcel parcel, int flags) { - parcel.writeLong(getId()); - parcel.writeString(getUri().toString()); - parcel.writeString(getMime_type()); - } + @Override + public void writeToParcel (Parcel parcel, int flags) { + parcel.writeLong(getId()); + parcel.writeString(getUri().toString()); + parcel.writeString(getMime_type()); + } - /* - * Parcelable interface must also have a static field called CREATOR, which is an object implementing the - * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /* + * Parcelable interface must also have a static field called CREATOR, which is an object implementing the + * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. + */ + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public Attachment createFromParcel(Parcel in) { - return new Attachment(in); - } + public Attachment createFromParcel (Parcel in) { + return new Attachment(in); + } - public Attachment[] newArray(int size) { - return new Attachment[size]; - } - }; + public Attachment[] newArray (int size) { + return new Attachment[size]; + } + }; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/Category.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/Category.java index 21d0974607..45bd4c2b59 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/Category.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/Category.java @@ -23,68 +23,68 @@ public class Category extends BaseCategory implements Parcelable { - private Category(Parcel in) { - setId(in.readLong()); - setName(in.readString()); - setDescription(in.readString()); - setColor(in.readString()); - } + private Category (Parcel in) { + setId(in.readLong()); + setName(in.readString()); + setDescription(in.readString()); + setColor(in.readString()); + } - public Category() { - super(); - } + public Category () { + super(); + } - public Category(BaseCategory category) { - super(category.getId(), category.getName(), category.getDescription(), category.getColor()); - } + public Category (BaseCategory category) { + super(category.getId(), category.getName(), category.getDescription(), category.getColor()); + } - public Category(Long id, String title, String description, String color) { - super(id, title, description, color); - } + public Category (Long id, String title, String description, String color) { + super(id, title, description, color); + } - public Category(Long id, String title, String description, String color, int count) { - super(id, title, description, color, count); - } + public Category (Long id, String title, String description, String color, int count) { + super(id, title, description, color, count); + } - @Override - public int describeContents() { - return 0; - } + @Override + public int describeContents () { + return 0; + } - @Override - public void writeToParcel(Parcel parcel, int flags) { - parcel.writeLong(getId()); - parcel.writeString(getName()); - parcel.writeString(getDescription()); - parcel.writeString(getColor()); - } + @Override + public void writeToParcel (Parcel parcel, int flags) { + parcel.writeLong(getId()); + parcel.writeString(getName()); + parcel.writeString(getDescription()); + parcel.writeString(getColor()); + } - @Override - public String toString() { - return getName(); - } + @Override + public String toString () { + return getName(); + } - /* - * Parcelable interface must also have a static field called CREATOR, which is an object implementing the - * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /* + * Parcelable interface must also have a static field called CREATOR, which is an object implementing the + * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. + */ + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public Category createFromParcel(Parcel in) { - return new Category(in); - } + public Category createFromParcel (Parcel in) { + return new Category(in); + } - public Category[] newArray(int size) { - return new Category[size]; - } - }; + public Category[] newArray (int size) { + return new Category[size]; + } + }; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/NavigationItem.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/NavigationItem.java index 76b7a655b5..c34b2bad98 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/NavigationItem.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/NavigationItem.java @@ -20,56 +20,56 @@ public class NavigationItem { - private int arrayIndex; - private String text; - private int icon; - private int iconSelected; + private int arrayIndex; + private String text; + private int icon; + private int iconSelected; - public NavigationItem(int arrayIndex, String text, int icon, int iconSelected) { - this.arrayIndex = arrayIndex; - this.text = text; - this.icon = icon; - this.iconSelected = iconSelected; - } + public NavigationItem (int arrayIndex, String text, int icon, int iconSelected) { + this.arrayIndex = arrayIndex; + this.text = text; + this.icon = icon; + this.iconSelected = iconSelected; + } - public int getArrayIndex() { - return arrayIndex; - } + public int getArrayIndex () { + return arrayIndex; + } - public void setArrayIndex(int arrayIndex) { - this.arrayIndex = arrayIndex; - } + public void setArrayIndex (int arrayIndex) { + this.arrayIndex = arrayIndex; + } - public String getText() { - return text; - } + public String getText () { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText (String text) { + this.text = text; + } - public int getIcon() { - return icon; - } + public int getIcon () { + return icon; + } - public void setIcon(int icon) { - this.icon = icon; - } + public void setIcon (int icon) { + this.icon = icon; + } - public int getIconSelected() { - return iconSelected; - } + public int getIconSelected () { + return iconSelected; + } - public void setIconSelected(int iconSelected) { - this.iconSelected = iconSelected; - } + public void setIconSelected (int iconSelected) { + this.iconSelected = iconSelected; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/Note.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/Note.java index 58db98d723..2f43ce21ac 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/Note.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/Note.java @@ -18,76 +18,75 @@ import android.os.Parcel; import android.os.Parcelable; - -import java.util.ArrayList; -import java.util.List; - import it.feio.android.omninotes.commons.models.BaseAttachment; import it.feio.android.omninotes.commons.models.BaseCategory; import it.feio.android.omninotes.commons.models.BaseNote; +import java.util.ArrayList; +import java.util.List; public class Note extends BaseNote implements Parcelable { - /* - * Parcelable interface must also have a static field called CREATOR, which is an object implementing the - * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /* + * Parcelable interface must also have a static field called CREATOR, which is an object implementing the + * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. + */ + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public Note createFromParcel(Parcel in) { - return new Note(in); - } + public Note createFromParcel (Parcel in) { + return new Note(in); + } - public Note[] newArray(int size) { - return new Note[size]; - } - }; - // Not saved in DB - private boolean passwordChecked = false; + public Note[] newArray (int size) { + return new Note[size]; + } + }; + // Not saved in DB + private boolean passwordChecked = false; - public Note() { - super(); - } + public Note () { + super(); + } - public Note(Long creation, Long lastModification, String title, String content, Integer archived, - Integer trashed, String alarm, String recurrenceRule, Integer reminderFired, String latitude, String longitude, Category - category, Integer locked, Integer checklist) { - super(creation, lastModification, title, content, archived, trashed, alarm, reminderFired, recurrenceRule, - latitude, - longitude, category, locked, checklist); - } + public Note (Long creation, Long lastModification, String title, String content, Integer archived, + Integer trashed, String alarm, String recurrenceRule, Integer reminderFired, String latitude, String longitude, + Category + category, Integer locked, Integer checklist) { + super(creation, lastModification, title, content, archived, trashed, alarm, reminderFired, recurrenceRule, + latitude, + longitude, category, locked, checklist); + } - public Note(Note note) { - super(note); - setPasswordChecked(note.isPasswordChecked()); - } + public Note (Note note) { + super(note); + setPasswordChecked(note.isPasswordChecked()); + } - private Note(Parcel in) { - setCreation(in.readString()); - setLastModification(in.readString()); - setTitle(in.readString()); - setContent(in.readString()); - setArchived(in.readInt()); - setTrashed(in.readInt()); - setAlarm(in.readString()); - setReminderFired(in.readInt()); - setRecurrenceRule(in.readString()); - setLatitude(in.readString()); - setLongitude(in.readString()); - setAddress(in.readString()); - super.setCategory(in.readParcelable(Category.class.getClassLoader())); - setLocked(in.readInt()); - setChecklist(in.readInt()); - in.readList(getAttachmentsList(), Attachment.class.getClassLoader()); - } + private Note (Parcel in) { + setCreation(in.readString()); + setLastModification(in.readString()); + setTitle(in.readString()); + setContent(in.readString()); + setArchived(in.readInt()); + setTrashed(in.readInt()); + setAlarm(in.readString()); + setReminderFired(in.readInt()); + setRecurrenceRule(in.readString()); + setLatitude(in.readString()); + setLongitude(in.readString()); + setAddress(in.readString()); + super.setCategory(in.readParcelable(Category.class.getClassLoader())); + setLocked(in.readInt()); + setChecklist(in.readInt()); + in.readList(getAttachmentsList(), Attachment.class.getClassLoader()); + } - public List getAttachmentsList() { + public List getAttachmentsList () { // List list = new ArrayList<>(); // for (it.feio.android.omninotes.commons.models.Attachment attachment : super.getAttachmentsList()) { // if (attachment.getClass().equals(Attachment.class)) { @@ -97,91 +96,91 @@ public List getAttachmentsList() { // } // } // return list; - // FIXME This fixes https://github.com/federicoiosue/Omni-Notes/issues/199 but could introduce other issues - return (List) super.getAttachmentsList(); - } - - public void setAttachmentsList(ArrayList attachmentsList) { - super.setAttachmentsList(attachmentsList); - } - - public void addAttachment(Attachment attachment) { - List attachmentsList = ((List) super.getAttachmentsList()); - attachmentsList.add(attachment); - setAttachmentsList(attachmentsList); - } - - public void removeAttachment(Attachment attachment) { - List attachmentsList = ((List) super.getAttachmentsList()); - attachmentsList.remove(attachment); - setAttachmentsList(attachmentsList); - } - - public List getAttachmentsListOld() { - return (List) super.getAttachmentsListOld(); - } - - public void setAttachmentsListOld(ArrayList attachmentsListOld) { - super.setAttachmentsListOld(attachmentsListOld); - } - - public boolean isPasswordChecked() { - return passwordChecked; - } - - public void setPasswordChecked(boolean passwordChecked) { - this.passwordChecked = passwordChecked; - } - - @Override - public Category getCategory() { - try { - return (Category) super.getCategory(); - } catch (ClassCastException e) { - return new Category(super.getCategory()); - } - } - - public void setCategory(Category category) { - if (category != null && category.getClass().equals(BaseCategory.class)) { - setCategory(new Category(category)); - } - super.setCategory(category); - } - - @Override - public void buildFromJson(String jsonNote) { - super.buildFromJson(jsonNote); - List attachments = new ArrayList<>(); - for (BaseAttachment attachment : getAttachmentsList()) { - attachments.add(new Attachment(attachment)); - } - setAttachmentsList(attachments); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel parcel, int flags) { - parcel.writeString(String.valueOf(getCreation())); - parcel.writeString(String.valueOf(getLastModification())); - parcel.writeString(getTitle()); - parcel.writeString(getContent()); - parcel.writeInt(isArchived() ? 1 : 0); - parcel.writeInt(isTrashed() ? 1 : 0); - parcel.writeString(getAlarm()); - parcel.writeInt(isReminderFired() ? 1 : 0); - parcel.writeString(getRecurrenceRule()); - parcel.writeString(String.valueOf(getLatitude())); - parcel.writeString(String.valueOf(getLongitude())); - parcel.writeString(getAddress()); - parcel.writeParcelable(getCategory(), 0); - parcel.writeInt(isLocked() ? 1 : 0); - parcel.writeInt(isChecklist() ? 1 : 0); - parcel.writeList(getAttachmentsList()); - } + // FIXME This fixes https://github.com/federicoiosue/Omni-Notes/issues/199 but could introduce other issues + return (List) super.getAttachmentsList(); + } + + public void setAttachmentsList (ArrayList attachmentsList) { + super.setAttachmentsList(attachmentsList); + } + + public void addAttachment (Attachment attachment) { + List attachmentsList = ((List) super.getAttachmentsList()); + attachmentsList.add(attachment); + setAttachmentsList(attachmentsList); + } + + public void removeAttachment (Attachment attachment) { + List attachmentsList = ((List) super.getAttachmentsList()); + attachmentsList.remove(attachment); + setAttachmentsList(attachmentsList); + } + + public List getAttachmentsListOld () { + return (List) super.getAttachmentsListOld(); + } + + public void setAttachmentsListOld (ArrayList attachmentsListOld) { + super.setAttachmentsListOld(attachmentsListOld); + } + + public boolean isPasswordChecked () { + return passwordChecked; + } + + public void setPasswordChecked (boolean passwordChecked) { + this.passwordChecked = passwordChecked; + } + + @Override + public Category getCategory () { + try { + return (Category) super.getCategory(); + } catch (ClassCastException e) { + return new Category(super.getCategory()); + } + } + + public void setCategory (Category category) { + if (category != null && category.getClass().equals(BaseCategory.class)) { + setCategory(new Category(category)); + } + super.setCategory(category); + } + + @Override + public void buildFromJson (String jsonNote) { + super.buildFromJson(jsonNote); + List attachments = new ArrayList<>(); + for (BaseAttachment attachment : getAttachmentsList()) { + attachments.add(new Attachment(attachment)); + } + setAttachmentsList(attachments); + } + + @Override + public int describeContents () { + return 0; + } + + @Override + public void writeToParcel (Parcel parcel, int flags) { + parcel.writeString(String.valueOf(getCreation())); + parcel.writeString(String.valueOf(getLastModification())); + parcel.writeString(getTitle()); + parcel.writeString(getContent()); + parcel.writeInt(isArchived() ? 1 : 0); + parcel.writeInt(isTrashed() ? 1 : 0); + parcel.writeString(getAlarm()); + parcel.writeInt(isReminderFired() ? 1 : 0); + parcel.writeString(getRecurrenceRule()); + parcel.writeString(String.valueOf(getLatitude())); + parcel.writeString(String.valueOf(getLongitude())); + parcel.writeString(getAddress()); + parcel.writeParcelable(getCategory(), 0); + parcel.writeInt(isLocked() ? 1 : 0); + parcel.writeInt(isChecklist() ? 1 : 0); + parcel.writeList(getAttachmentsList()); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/ONStyle.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/ONStyle.java index 0da04ae0c0..c6ae2576ef 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/ONStyle.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/ONStyle.java @@ -26,56 +26,56 @@ public class ONStyle { - public static final int DURATION_INFINITE = -1; - public static final int DURATION_SHORT = 950; - public static final int DURATION_MEDIUM = 1650; - public static final int DURATION_LONG = 2300; + public static final int DURATION_INFINITE = -1; + public static final int DURATION_SHORT = 950; + public static final int DURATION_MEDIUM = 1650; + public static final int DURATION_LONG = 2300; - public static final Configuration CONFIGURATION; - public static final Style ALERT; - public static final Style WARN; - public static final Style CONFIRM; - public static final Style INFO; + public static final Configuration CONFIGURATION; + public static final Style ALERT; + public static final Style WARN; + public static final Style CONFIRM; + public static final Style INFO; - public static final int ALERT_COLOR = R.color.alert; - public static final int WARN_COLOR = R.color.warning; - public static final int CONFIRM_COLOR = R.color.confirm; - public static final int INFO_COLOR = R.color.info; + public static final int ALERT_COLOR = R.color.alert; + public static final int WARN_COLOR = R.color.warning; + public static final int CONFIRM_COLOR = R.color.confirm; + public static final int INFO_COLOR = R.color.info; - static { - CONFIGURATION = new Configuration.Builder() - .setDuration(DURATION_SHORT) - .setInAnimation(R.animator.fade_in_support) - .setOutAnimation(R.animator.fade_out_support) - .build(); - ALERT = new Style.Builder() - .setBackgroundColor(ALERT_COLOR) - .setHeight(LayoutParams.MATCH_PARENT) - .setGravity(Gravity.CENTER) - .setTextAppearance(R.style.crouton_text) - .setConfiguration(CONFIGURATION) - .build(); - WARN = new Style.Builder() - .setBackgroundColor(WARN_COLOR) - .setHeight(LayoutParams.MATCH_PARENT) - .setGravity(Gravity.CENTER) - .setTextAppearance(R.style.crouton_text) - .setConfiguration(CONFIGURATION) - .build(); - CONFIRM = new Style.Builder() - .setBackgroundColor(CONFIRM_COLOR) - .setHeight(LayoutParams.MATCH_PARENT) - .setGravity(Gravity.CENTER) - .setTextAppearance(R.style.crouton_text) - .setConfiguration(CONFIGURATION) - .build(); - INFO = new Style.Builder() - .setBackgroundColor(INFO_COLOR) - .setHeight(LayoutParams.MATCH_PARENT) - .setGravity(Gravity.CENTER) - .setTextAppearance(R.style.crouton_text) - .setConfiguration(CONFIGURATION) - .build(); - } + static { + CONFIGURATION = new Configuration.Builder() + .setDuration(DURATION_SHORT) + .setInAnimation(R.animator.fade_in_support) + .setOutAnimation(R.animator.fade_out_support) + .build(); + ALERT = new Style.Builder() + .setBackgroundColor(ALERT_COLOR) + .setHeight(LayoutParams.MATCH_PARENT) + .setGravity(Gravity.CENTER) + .setTextAppearance(R.style.crouton_text) + .setConfiguration(CONFIGURATION) + .build(); + WARN = new Style.Builder() + .setBackgroundColor(WARN_COLOR) + .setHeight(LayoutParams.MATCH_PARENT) + .setGravity(Gravity.CENTER) + .setTextAppearance(R.style.crouton_text) + .setConfiguration(CONFIGURATION) + .build(); + CONFIRM = new Style.Builder() + .setBackgroundColor(CONFIRM_COLOR) + .setHeight(LayoutParams.MATCH_PARENT) + .setGravity(Gravity.CENTER) + .setTextAppearance(R.style.crouton_text) + .setConfiguration(CONFIGURATION) + .build(); + INFO = new Style.Builder() + .setBackgroundColor(INFO_COLOR) + .setHeight(LayoutParams.MATCH_PARENT) + .setGravity(Gravity.CENTER) + .setTextAppearance(R.style.crouton_text) + .setConfiguration(CONFIGURATION) + .build(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/PasswordValidator.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/PasswordValidator.java index 584ea655a7..69474b65b8 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/PasswordValidator.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/PasswordValidator.java @@ -19,9 +19,9 @@ public interface PasswordValidator { - enum Result { - SUCCEED, FAIL, RESTORE - } + enum Result { + SUCCEED, FAIL, RESTORE + } - void onPasswordValidated(Result result); + void onPasswordValidated (Result result); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/PushBulletMessage.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/PushBulletMessage.java index fb57466542..9da0cc2f2a 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/PushBulletMessage.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/PushBulletMessage.java @@ -19,10 +19,10 @@ public class PushBulletMessage { - public final String message; + public final String message; - public PushBulletMessage(final String message) { - this.message = message; - } + public PushBulletMessage (final String message) { + this.message = message; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/Stats.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/Stats.java index 3c2dedb0e3..42ebc91517 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/Stats.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/Stats.java @@ -19,195 +19,195 @@ public class Stats extends StatsSingleNote { - private int notesActive; - private int notesArchived; - private int notesTrashed; - private int reminders; - private int remindersFutures; - private int notesChecklist; - private int notesMasked; - private int categories; + private int notesActive; + private int notesArchived; + private int notesTrashed; + private int reminders; + private int remindersFutures; + private int notesChecklist; + private int notesMasked; + private int categories; - private int location; + private int location; - private int wordsMax; - private int wordsAvg; - private int charsMax; - private int charsAvg; - private long usageTime; + private int wordsMax; + private int wordsAvg; + private int charsMax; + private int charsAvg; + private long usageTime; - public int getNotesTotalNumber() { - return notesActive + notesArchived + notesTrashed; - } + public int getNotesTotalNumber () { + return notesActive + notesArchived + notesTrashed; + } - public int getNotesActive() { - return notesActive; - } + public int getNotesActive () { + return notesActive; + } - public void setNotesActive(int notesActive) { - this.notesActive = notesActive; - } + public void setNotesActive (int notesActive) { + this.notesActive = notesActive; + } - public int getNotesArchived() { - return notesArchived; - } + public int getNotesArchived () { + return notesArchived; + } - public void setNotesArchived(int notesArchived) { - this.notesArchived = notesArchived; - } + public void setNotesArchived (int notesArchived) { + this.notesArchived = notesArchived; + } - public int getNotesTrashed() { - return notesTrashed; - } + public int getNotesTrashed () { + return notesTrashed; + } - public void setNotesTrashed(int notesTrashed) { - this.notesTrashed = notesTrashed; - } + public void setNotesTrashed (int notesTrashed) { + this.notesTrashed = notesTrashed; + } - public int getReminders() { - return reminders; - } + public int getReminders () { + return reminders; + } - public void setReminders(int reminders) { - this.reminders = reminders; - } + public void setReminders (int reminders) { + this.reminders = reminders; + } - public int getRemindersFutures() { - return remindersFutures; - } + public int getRemindersFutures () { + return remindersFutures; + } - public void setRemindersFutures(int remindersFutures) { - this.remindersFutures = remindersFutures; - } + public void setRemindersFutures (int remindersFutures) { + this.remindersFutures = remindersFutures; + } - public int getNotesChecklist() { - return notesChecklist; - } + public int getNotesChecklist () { + return notesChecklist; + } - public void setNotesChecklist(int notesChecklist) { - this.notesChecklist = notesChecklist; - } + public void setNotesChecklist (int notesChecklist) { + this.notesChecklist = notesChecklist; + } - public int getNotesMasked() { - return notesMasked; - } + public int getNotesMasked () { + return notesMasked; + } - public void setNotesMasked(int notesMasked) { - this.notesMasked = notesMasked; - } + public void setNotesMasked (int notesMasked) { + this.notesMasked = notesMasked; + } - public int getCategories() { - return categories; - } + public int getCategories () { + return categories; + } - public void setCategories(int categories) { - this.categories = categories; - } + public void setCategories (int categories) { + this.categories = categories; + } - public int getTags() { - return tags; - } + public int getTags () { + return tags; + } - public void setTags(int tags) { - this.tags = tags; - } + public void setTags (int tags) { + this.tags = tags; + } - public int getWords() { - return words; - } + public int getWords () { + return words; + } - public void setWords(int words) { - this.words = words; - } + public void setWords (int words) { + this.words = words; + } - public int getChars() { - return chars; - } + public int getChars () { + return chars; + } - public void setChars(int chars) { - this.chars = chars; - } + public void setChars (int chars) { + this.chars = chars; + } - public int getWordsMax() { - return wordsMax; - } + public int getWordsMax () { + return wordsMax; + } - public void setWordsMax(int wordsMax) { - this.wordsMax = wordsMax; - } + public void setWordsMax (int wordsMax) { + this.wordsMax = wordsMax; + } - public int getWordsAvg() { - return wordsAvg; - } + public int getWordsAvg () { + return wordsAvg; + } - public void setWordsAvg(int wordsAvg) { - this.wordsAvg = wordsAvg; - } + public void setWordsAvg (int wordsAvg) { + this.wordsAvg = wordsAvg; + } - public int getCharsMax() { - return charsMax; - } + public int getCharsMax () { + return charsMax; + } - public void setCharsMax(int charsMax) { - this.charsMax = charsMax; - } + public void setCharsMax (int charsMax) { + this.charsMax = charsMax; + } - public int getCharsAvg() { - return charsAvg; - } + public int getCharsAvg () { + return charsAvg; + } - public void setCharsAvg(int charsAvg) { - this.charsAvg = charsAvg; - } + public void setCharsAvg (int charsAvg) { + this.charsAvg = charsAvg; + } - public int getLocation() { - return location; - } + public int getLocation () { + return location; + } - public void setLocation(int location) { - this.location = location; - } + public void setLocation (int location) { + this.location = location; + } - public long getUsageTime() { - return usageTime; - } + public long getUsageTime () { + return usageTime; + } - public void setUsageTime(long usageTime) { - this.usageTime = usageTime; - } + public void setUsageTime (long usageTime) { + this.usageTime = usageTime; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/StatsSingleNote.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/StatsSingleNote.java index 436490cf3f..b4c37a55c8 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/StatsSingleNote.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/StatsSingleNote.java @@ -20,114 +20,114 @@ public class StatsSingleNote { - protected int tags; - protected int attachments; - protected int images; - protected int videos; - protected int audioRecordings; - protected int sketches; - protected int files; - protected String categoryName; - - protected int words; - protected int chars; - - protected int checklistItemsNumber; - protected int checklistCompletedItemsNumber; - - public int getTags() { - return tags; - } - - public void setTags(int tags) { - this.tags = tags; - } - - public int getWords() { - return words; - } - - public void setWords(int words) { - this.words = words; - } - - public int getChars() { - return chars; - } - - public void setChars(int chars) { - this.chars = chars; - } - - public int getAttachments() { - return attachments; - } - - public void setAttachments(int attachments) { - this.attachments = attachments; - } - - public int getImages() { - return images; - } - - public void setImages(int images) { - this.images = images; - } - - public int getVideos() { - return videos; - } - - public void setVideos(int videos) { - this.videos = videos; - } - - public int getAudioRecordings() { - return audioRecordings; - } - - public void setAudioRecordings(int audioRecordings) { - this.audioRecordings = audioRecordings; - } - - public int getSketches() { - return sketches; - } - - public void setSketches(int sketches) { - this.sketches = sketches; - } - - public int getFiles() { - return files; - } - - public void setFiles(int files) { - this.files = files; - } - - public String getCategoryName() { - return categoryName; - } - - public void setCategoryName(String categoryName) { - this.categoryName = categoryName; - } - - public int getChecklistItemsNumber() { - return checklistItemsNumber; - } - - public void setChecklistItemsNumber(int checklistItemsNumber) { - this.checklistItemsNumber = checklistItemsNumber; - } - - public int getChecklistCompletedItemsNumber() { - return checklistCompletedItemsNumber; - } + protected int tags; + protected int attachments; + protected int images; + protected int videos; + protected int audioRecordings; + protected int sketches; + protected int files; + protected String categoryName; + + protected int words; + protected int chars; + + protected int checklistItemsNumber; + protected int checklistCompletedItemsNumber; + + public int getTags () { + return tags; + } + + public void setTags (int tags) { + this.tags = tags; + } + + public int getWords () { + return words; + } + + public void setWords (int words) { + this.words = words; + } + + public int getChars () { + return chars; + } + + public void setChars (int chars) { + this.chars = chars; + } + + public int getAttachments () { + return attachments; + } + + public void setAttachments (int attachments) { + this.attachments = attachments; + } + + public int getImages () { + return images; + } + + public void setImages (int images) { + this.images = images; + } + + public int getVideos () { + return videos; + } + + public void setVideos (int videos) { + this.videos = videos; + } + + public int getAudioRecordings () { + return audioRecordings; + } + + public void setAudioRecordings (int audioRecordings) { + this.audioRecordings = audioRecordings; + } + + public int getSketches () { + return sketches; + } + + public void setSketches (int sketches) { + this.sketches = sketches; + } + + public int getFiles () { + return files; + } + + public void setFiles (int files) { + this.files = files; + } + + public String getCategoryName () { + return categoryName; + } + + public void setCategoryName (String categoryName) { + this.categoryName = categoryName; + } + + public int getChecklistItemsNumber () { + return checklistItemsNumber; + } + + public void setChecklistItemsNumber (int checklistItemsNumber) { + this.checklistItemsNumber = checklistItemsNumber; + } + + public int getChecklistCompletedItemsNumber () { + return checklistCompletedItemsNumber; + } - public void setChecklistCompletedItemsNumber(int checklistCompletedItemsNumber) { - this.checklistCompletedItemsNumber = checklistCompletedItemsNumber; - } + public void setChecklistCompletedItemsNumber (int checklistCompletedItemsNumber) { + this.checklistCompletedItemsNumber = checklistCompletedItemsNumber; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/Tag.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/Tag.java index aaa0115b6f..7d2a6d8719 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/Tag.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/Tag.java @@ -23,54 +23,54 @@ public class Tag extends BaseTag implements Parcelable { - private Tag(Parcel in) { - setText(in.readString()); - setCount(in.readInt()); - } + private Tag (Parcel in) { + setText(in.readString()); + setCount(in.readInt()); + } - public Tag() { - super(); - } + public Tag () { + super(); + } - public Tag(String text, Integer count) { - super(text, count); - } + public Tag (String text, Integer count) { + super(text, count); + } - @Override - public int describeContents() { - return 0; - } + @Override + public int describeContents () { + return 0; + } - @Override - public void writeToParcel(Parcel parcel, int flags) { - parcel.writeString(getText()); - parcel.writeInt(getCount()); - } + @Override + public void writeToParcel (Parcel parcel, int flags) { + parcel.writeString(getText()); + parcel.writeInt(getCount()); + } - @Override - public String toString() { - return getText(); - } + @Override + public String toString () { + return getText(); + } - /* - * Parcelable interface must also have a static field called CREATOR, which is an object implementing the - * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + /* + * Parcelable interface must also have a static field called CREATOR, which is an object implementing the + * Parcelable.Creator interface. Used to un-marshal or de-serialize object from Parcel. + */ + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public Tag createFromParcel(Parcel in) { - return new Tag(in); - } + public Tag createFromParcel (Parcel in) { + return new Tag(in); + } - public Tag[] newArray(int size) { - return new Tag[size]; - } - }; + public Tag[] newArray (int size) { + return new Tag[size]; + } + }; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/UndoBarController.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/UndoBarController.java index 714c261229..ce90f6b5fd 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/UndoBarController.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/UndoBarController.java @@ -17,6 +17,8 @@ package it.feio.android.omninotes.models; +import static com.nineoldandroids.view.ViewPropertyAnimator.animate; + import android.os.Bundle; import android.os.Parcelable; import android.text.TextUtils; @@ -28,130 +30,127 @@ import com.nineoldandroids.view.ViewPropertyAnimator; import it.feio.android.checklistview.utils.AlphaManager; import it.feio.android.omninotes.R; - import java.util.Locale; -import static com.nineoldandroids.view.ViewPropertyAnimator.animate; - public class UndoBarController { - private View mBarView; - private TextView mMessageView; - private ViewPropertyAnimator mBarAnimator; + private View mBarView; + private TextView mMessageView; + private ViewPropertyAnimator mBarAnimator; // private Handler mHideHandler = new Handler(); - private UndoListener mUndoListener; + private UndoListener mUndoListener; - // State objects - private Parcelable mUndoToken; - private CharSequence mUndoMessage; - private Button mButtonView; - private boolean isVisible; + // State objects + private Parcelable mUndoToken; + private CharSequence mUndoMessage; + private Button mButtonView; + private boolean isVisible; - public interface UndoListener { + public interface UndoListener { - void onUndo(Parcelable token); - } + void onUndo (Parcelable token); + } - public UndoBarController(View undoBarView, UndoListener undoListener) { - mBarView = undoBarView; + public UndoBarController (View undoBarView, UndoListener undoListener) { + mBarView = undoBarView; // mBarAnimator = mBarView.animate(); - mBarAnimator = animate(mBarView); - mUndoListener = undoListener; + mBarAnimator = animate(mBarView); + mUndoListener = undoListener; - mMessageView = (TextView) mBarView.findViewById(R.id.undobar_message); - - mButtonView = (Button) mBarView.findViewById(R.id.undobar_button); - mButtonView.setText(mButtonView.getText().toString().toUpperCase(Locale.getDefault())); - mButtonView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - hideUndoBar(false); - mUndoListener.onUndo(mUndoToken); - } - }); + mMessageView = mBarView.findViewById(R.id.undobar_message); + mButtonView = mBarView.findViewById(R.id.undobar_button); + mButtonView.setText(mButtonView.getText().toString().toUpperCase(Locale.getDefault())); + mButtonView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick (View view) { hideUndoBar(false); - } + mUndoListener.onUndo(mUndoToken); + } + }); + hideUndoBar(false); + } - public void showUndoBar(boolean immediate, CharSequence message, Parcelable undoToken) { - mUndoToken = undoToken; - mUndoMessage = message; - mMessageView.setText(mUndoMessage); + + public void showUndoBar (boolean immediate, CharSequence message, Parcelable undoToken) { + mUndoToken = undoToken; + mUndoMessage = message; + mMessageView.setText(mUndoMessage); // mHideHandler.removeCallbacks(mHideRunnable); // mHideHandler.postDelayed(mHideRunnable, // mBarView.getResources().getInteger(R.integer.undobar_hide_delay)); - mBarView.setVisibility(View.VISIBLE); - if (immediate) { + mBarView.setVisibility(View.VISIBLE); + if (immediate) { // mBarView.setAlpha(1); - AlphaManager.setAlpha(mBarView, 1); - } else { - mBarAnimator.cancel(); - mBarAnimator - .alpha(1) - .setDuration( - mBarView.getResources() - .getInteger(android.R.integer.config_shortAnimTime)) - .setListener(null); - } - isVisible = true; + AlphaManager.setAlpha(mBarView, 1); + } else { + mBarAnimator.cancel(); + mBarAnimator + .alpha(1) + .setDuration( + mBarView.getResources() + .getInteger(android.R.integer.config_shortAnimTime)) + .setListener(null); } + isVisible = true; + } - public void hideUndoBar(boolean immediate) { + public void hideUndoBar (boolean immediate) { // mHideHandler.removeCallbacks(mHideRunnable); - if (immediate) { - mBarView.setVisibility(View.GONE); - AlphaManager.setAlpha(mBarView, 0); - mUndoMessage = null; - mUndoToken = null; - - } else { - mBarAnimator.cancel(); - mBarAnimator - .alpha(0) - .setDuration(mBarView.getResources() - .getInteger(android.R.integer.config_shortAnimTime)) - .setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - mBarView.setVisibility(View.GONE); - mUndoMessage = null; - mUndoToken = null; - } - }); - } - isVisible = false; + if (immediate) { + mBarView.setVisibility(View.GONE); + AlphaManager.setAlpha(mBarView, 0); + mUndoMessage = null; + mUndoToken = null; + + } else { + mBarAnimator.cancel(); + mBarAnimator + .alpha(0) + .setDuration(mBarView.getResources() + .getInteger(android.R.integer.config_shortAnimTime)) + .setListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd (Animator animation) { + mBarView.setVisibility(View.GONE); + mUndoMessage = null; + mUndoToken = null; + } + }); } + isVisible = false; + } - public void onSaveInstanceState(Bundle outState) { - outState.putCharSequence("undo_message", mUndoMessage); - outState.putParcelable("undo_token", mUndoToken); - } + public void onSaveInstanceState (Bundle outState) { + outState.putCharSequence("undo_message", mUndoMessage); + outState.putParcelable("undo_token", mUndoToken); + } - public void onRestoreInstanceState(Bundle savedInstanceState) { - if (savedInstanceState != null) { - mUndoMessage = savedInstanceState.getCharSequence("undo_message"); - mUndoToken = savedInstanceState.getParcelable("undo_token"); + public void onRestoreInstanceState (Bundle savedInstanceState) { + if (savedInstanceState != null) { + mUndoMessage = savedInstanceState.getCharSequence("undo_message"); + mUndoToken = savedInstanceState.getParcelable("undo_token"); - if (mUndoToken != null || !TextUtils.isEmpty(mUndoMessage)) { - showUndoBar(true, mUndoMessage, mUndoToken); - } - } + if (mUndoToken != null || !TextUtils.isEmpty(mUndoMessage)) { + showUndoBar(true, mUndoMessage, mUndoToken); + } } + } - public boolean isVisible() { - return isVisible; - } + public boolean isVisible () { + return isVisible; + } // private Runnable mHideRunnable = new Runnable() { // @Override diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/AttachmentAdapter.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/AttachmentAdapter.java index 162757782f..1713a168e7 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/AttachmentAdapter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/AttachmentAdapter.java @@ -24,12 +24,7 @@ import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; - import com.bumptech.glide.Glide; - -import java.util.Collections; -import java.util.List; - import it.feio.android.omninotes.R; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.helpers.date.DateHelper; @@ -40,115 +35,115 @@ import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Fonts; import it.feio.android.omninotes.utils.date.DateUtils; +import java.util.Collections; +import java.util.List; public class AttachmentAdapter extends BaseAdapter { - private Activity mActivity; - private List attachmentsList; - private LayoutInflater inflater; + private Activity mActivity; + private List attachmentsList; + private LayoutInflater inflater; - public AttachmentAdapter(Activity mActivity, List attachmentsList, ExpandableHeightGridView mGridView) { - this.mActivity = mActivity; - if (attachmentsList == null) { - attachmentsList = Collections.emptyList(); - } - this.attachmentsList = attachmentsList; - inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + public AttachmentAdapter (Activity mActivity, List attachmentsList, ExpandableHeightGridView mGridView) { + this.mActivity = mActivity; + if (attachmentsList == null) { + attachmentsList = Collections.emptyList(); } + this.attachmentsList = attachmentsList; + inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } - public int getCount() { - return attachmentsList.size(); - } + public int getCount () { + return attachmentsList.size(); + } - public Attachment getItem(int position) { - return attachmentsList.get(position); - } + public Attachment getItem (int position) { + return attachmentsList.get(position); + } - public long getItemId(int position) { - return 0; - } + public long getItemId (int position) { + return 0; + } - public View getView(int position, View convertView, ViewGroup parent) { - - LogDelegate.v("GridView called for position " + position); - - Attachment mAttachment = attachmentsList.get(position); - - AttachmentHolder holder; - if (convertView == null) { - convertView = inflater.inflate(R.layout.gridview_item, parent, false); - - // Overrides font sizes with the one selected from user - Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS), convertView); - - holder = new AttachmentHolder(); - holder.image = (SquareImageView) convertView.findViewById(R.id.gridview_item_picture); - holder.text = (TextView) convertView.findViewById(R.id.gridview_item_text); - convertView.setTag(holder); - } else { - holder = (AttachmentHolder) convertView.getTag(); - } - - // Draw name in case the type is an audio recording - if (mAttachment.getMime_type() != null && mAttachment.getMime_type().equals(Constants.MIME_TYPE_AUDIO)) { - String text; - - if (mAttachment.getLength() > 0) { - // Recording duration - text = DateHelper.formatShortTime(mActivity, mAttachment.getLength()); - } else { - // Recording date otherwise - text = DateUtils.getLocalizedDateTime(mActivity, mAttachment - .getUri().getLastPathSegment().split("\\.")[0], - Constants.DATE_FORMAT_SORTABLE); - } - - if (text == null) { - text = mActivity.getString(R.string.attachment); - } - holder.text.setText(text); - holder.text.setVisibility(View.VISIBLE); - } else { - holder.text.setVisibility(View.GONE); - } - - // Draw name in case the type is an audio recording (or file in the future) - if (mAttachment.getMime_type() != null && mAttachment.getMime_type().equals(Constants.MIME_TYPE_FILES)) { - holder.text.setText(mAttachment.getName()); - holder.text.setVisibility(View.VISIBLE); - } - - // Starts the AsyncTask to draw bitmap into ImageView - Uri thumbnailUri = BitmapHelper.getThumbnailUri(mActivity, mAttachment); - Glide.with(mActivity.getApplicationContext()) - .load(thumbnailUri) -// .centerCrop() -// .crossFade() - .into(holder.image); + public View getView (int position, View convertView, ViewGroup parent) { - return convertView; + LogDelegate.v("GridView called for position " + position); + + Attachment mAttachment = attachmentsList.get(position); + + AttachmentHolder holder; + if (convertView == null) { + convertView = inflater.inflate(R.layout.gridview_item, parent, false); + + // Overrides font sizes with the one selected from user + Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS), convertView); + + holder = new AttachmentHolder(); + holder.image = convertView.findViewById(R.id.gridview_item_picture); + holder.text = convertView.findViewById(R.id.gridview_item_text); + convertView.setTag(holder); + } else { + holder = (AttachmentHolder) convertView.getTag(); } + // Draw name in case the type is an audio recording + if (mAttachment.getMime_type() != null && mAttachment.getMime_type().equals(Constants.MIME_TYPE_AUDIO)) { + String text; + + if (mAttachment.getLength() > 0) { + // Recording duration + text = DateHelper.formatShortTime(mActivity, mAttachment.getLength()); + } else { + // Recording date otherwise + text = DateUtils.getLocalizedDateTime(mActivity, mAttachment + .getUri().getLastPathSegment().split("\\.")[0], + Constants.DATE_FORMAT_SORTABLE); + } + + if (text == null) { + text = mActivity.getString(R.string.attachment); + } + holder.text.setText(text); + holder.text.setVisibility(View.VISIBLE); + } else { + holder.text.setVisibility(View.GONE); + } - public List getAttachmentsList() { - return attachmentsList; - } + // Draw name in case the type is an audio recording (or file in the future) + if (mAttachment.getMime_type() != null && mAttachment.getMime_type().equals(Constants.MIME_TYPE_FILES)) { + holder.text.setText(mAttachment.getName()); + holder.text.setVisibility(View.VISIBLE); + } + // Starts the AsyncTask to draw bitmap into ImageView + Uri thumbnailUri = BitmapHelper.getThumbnailUri(mActivity, mAttachment); + Glide.with(mActivity.getApplicationContext()) + .load(thumbnailUri) +// .centerCrop() +// .crossFade() + .into(holder.image); + return convertView; + } - public class AttachmentHolder { + public List getAttachmentsList () { + return attachmentsList; + } - TextView text; - SquareImageView image; - } + + public class AttachmentHolder { + + TextView text; + SquareImageView image; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/ImageAndTextAdapter.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/ImageAndTextAdapter.java index 3b9123eb28..86c90c9a48 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/ImageAndTextAdapter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/ImageAndTextAdapter.java @@ -23,82 +23,79 @@ import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; - import com.neopixl.pixlui.components.textview.TextView; - -import java.util.ArrayList; - import it.feio.android.omninotes.R; import it.feio.android.omninotes.models.holders.ImageAndTextItem; import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Fonts; +import java.util.ArrayList; public class ImageAndTextAdapter extends BaseAdapter { - private Activity mActivity; - ArrayList items; - private LayoutInflater inflater; - + private Activity mActivity; + ArrayList items; + private LayoutInflater inflater; - public ImageAndTextAdapter(Activity mActivity, - ArrayList items) { - this.mActivity = mActivity; - this.items = items; - inflater = (LayoutInflater) mActivity - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - } + public ImageAndTextAdapter (Activity mActivity, + ArrayList items) { + this.mActivity = mActivity; + this.items = items; + inflater = (LayoutInflater) mActivity + .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } - @Override - public int getCount() { - return items.size(); - } + @Override + public int getCount () { + return items.size(); + } - @Override - public Object getItem(int position) { - return items.get(position); - } + @Override + public Object getItem (int position) { + return items.get(position); + } - @Override - public long getItemId(int position) { - return position; - } + @Override + public long getItemId (int position) { + return position; + } - public View getView(int position, View convertView, ViewGroup parent) { - ImageAndTextViewHolder holder; - if (convertView == null) { - convertView = inflater.inflate(R.layout.image_and_text_item, - parent, false); - // Overrides font sizes with the one selected from user - Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences( - Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS), - convertView); + public View getView (int position, View convertView, ViewGroup parent) { + ImageAndTextViewHolder holder; + if (convertView == null) { + convertView = inflater.inflate(R.layout.image_and_text_item, + parent, false); - holder = new ImageAndTextViewHolder(); + // Overrides font sizes with the one selected from user + Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences( + Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS), + convertView); - holder.image = (ImageView) convertView.findViewById(R.id.image); - holder.text = (TextView) convertView.findViewById(R.id.text); - convertView.setTag(holder); - } else { - holder = (ImageAndTextViewHolder) convertView.getTag(); - } + holder = new ImageAndTextViewHolder(); - // Set the results into TextViews - holder.text.setText(items.get(position).getText()); + holder.image = convertView.findViewById(R.id.image); + holder.text = convertView.findViewById(R.id.text); + convertView.setTag(holder); + } else { + holder = (ImageAndTextViewHolder) convertView.getTag(); + } - // Set the results into ImageView checking if an icon is present before - if (items.get(position).getImage() != 0) { - holder.image.setImageResource(items.get(position).getImage()); - } + // Set the results into TextViews + holder.text.setText(items.get(position).getText()); - return convertView; + // Set the results into ImageView checking if an icon is present before + if (items.get(position).getImage() != 0) { + holder.image.setImageResource(items.get(position).getImage()); } + return convertView; + } + } @@ -109,6 +106,6 @@ public View getView(int position, View convertView, ViewGroup parent) { */ class ImageAndTextViewHolder { - ImageView image; - TextView text; + ImageView image; + TextView text; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerAdapter.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerAdapter.java index f2541c0130..7c753ecc33 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerAdapter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerAdapter.java @@ -31,7 +31,6 @@ import it.feio.android.omninotes.models.NavigationItem; import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Fonts; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -39,96 +38,97 @@ public class NavDrawerAdapter extends BaseAdapter { - private Activity mActivity; - private List items = new ArrayList<>(); - private LayoutInflater inflater; + private Activity mActivity; + private List items = new ArrayList<>(); + private LayoutInflater inflater; - public NavDrawerAdapter(Activity mActivity, List items) { - this.mActivity = mActivity; - this.items = items; - inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - } + public NavDrawerAdapter (Activity mActivity, List items) { + this.mActivity = mActivity; + this.items = items; + inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } - @Override - public int getCount() { - return items.size(); - } + @Override + public int getCount () { + return items.size(); + } - @Override - public Object getItem(int position) { - return items.get(position); - } + @Override + public Object getItem (int position) { + return items.get(position); + } - @Override - public long getItemId(int position) { - return position; - } + @Override + public long getItemId (int position) { + return position; + } + + public View getView (int position, View convertView, ViewGroup parent) { + NoteDrawerAdapterViewHolder holder; + if (convertView == null) { + convertView = inflater.inflate(R.layout.drawer_list_item, parent, false); - public View getView(int position, View convertView, ViewGroup parent) { - NoteDrawerAdapterViewHolder holder; - if (convertView == null) { - convertView = inflater.inflate(R.layout.drawer_list_item, parent, false); - - // Overrides font sizes with the one selected from user - Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS), convertView); - - holder = new NoteDrawerAdapterViewHolder(); - - holder.imgIcon = (ImageView) convertView.findViewById(R.id.icon); - holder.txtTitle = (TextView) convertView.findViewById(R.id.title); - convertView.setTag(holder); - } else { - holder = (NoteDrawerAdapterViewHolder) convertView.getTag(); - } - - // Set the results into TextViews - holder.txtTitle.setText(items.get(position).getText()); - - if (isSelected(position)) { - holder.imgIcon.setImageResource(items.get(position).getIconSelected()); - holder.txtTitle.setTypeface(null, Typeface.BOLD); - int color = mActivity.getResources().getColor(R.color.colorPrimaryDark); - holder.txtTitle.setTextColor(color); - holder.imgIcon.getDrawable().mutate().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); - } else { - holder.imgIcon.setImageResource(items.get(position).getIcon()); - holder.txtTitle.setTypeface(null, Typeface.NORMAL); - holder.txtTitle.setTextColor(mActivity.getResources().getColor(R.color.drawer_text)); - } - - return convertView; + // Overrides font sizes with the one selected from user + Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS), convertView); + + holder = new NoteDrawerAdapterViewHolder(); + + holder.imgIcon = convertView.findViewById(R.id.icon); + holder.txtTitle = convertView.findViewById(R.id.title); + convertView.setTag(holder); + } else { + holder = (NoteDrawerAdapterViewHolder) convertView.getTag(); } + // Set the results into TextViews + holder.txtTitle.setText(items.get(position).getText()); + + if (isSelected(position)) { + holder.imgIcon.setImageResource(items.get(position).getIconSelected()); + holder.txtTitle.setTypeface(null, Typeface.BOLD); + int color = mActivity.getResources().getColor(R.color.colorPrimaryDark); + holder.txtTitle.setTextColor(color); + holder.imgIcon.getDrawable().mutate().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); + } else { + holder.imgIcon.setImageResource(items.get(position).getIcon()); + holder.txtTitle.setTypeface(null, Typeface.NORMAL); + holder.txtTitle.setTextColor(mActivity.getResources().getColor(R.color.drawer_text)); + } - private boolean isSelected(int position) { + return convertView; + } - // Getting actual navigation selection - String[] navigationListCodes = mActivity.getResources().getStringArray(R.array.navigation_list_codes); - // Managing temporary navigation indicator when coming from a widget - String navigationTmp = MainActivity.class.isAssignableFrom(mActivity.getClass()) ? ((MainActivity) mActivity) - .getNavigationTmp() : null; + private boolean isSelected (int position) { - String navigation = navigationTmp != null ? navigationTmp - : mActivity.getSharedPreferences(Constants.PREFS_NAME, Activity.MODE_MULTI_PROCESS) - .getString(Constants.PREF_NAVIGATION, navigationListCodes[0]); + // Getting actual navigation selection + String[] navigationListCodes = mActivity.getResources().getStringArray(R.array.navigation_list_codes); - // Finding selected item from standard navigation items or tags - int index = Arrays.asList(navigationListCodes).indexOf(navigation); + // Managing temporary navigation indicator when coming from a widget + String navigationTmp = MainActivity.class.isAssignableFrom(mActivity.getClass()) ? ((MainActivity) mActivity) + .getNavigationTmp() : null; - if (index == -1) - return false; + String navigation = navigationTmp != null ? navigationTmp + : mActivity.getSharedPreferences(Constants.PREFS_NAME, Activity.MODE_MULTI_PROCESS) + .getString(Constants.PREF_NAVIGATION, navigationListCodes[0]); - String navigationLocalized = mActivity.getResources().getStringArray(R.array.navigation_list)[index]; - return navigationLocalized.equals(items.get(position).getText()); + // Finding selected item from standard navigation items or tags + int index = Arrays.asList(navigationListCodes).indexOf(navigation); + + if (index == -1) { + return false; } + String navigationLocalized = mActivity.getResources().getStringArray(R.array.navigation_list)[index]; + return navigationLocalized.equals(items.get(position).getText()); + } + } @@ -139,6 +139,6 @@ private boolean isSelected(int position) { */ class NoteDrawerAdapterViewHolder { - ImageView imgIcon; - TextView txtTitle; + ImageView imgIcon; + TextView txtTitle; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerCategoryAdapter.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerCategoryAdapter.java index 8c11a01b53..49f0756310 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerCategoryAdapter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NavDrawerCategoryAdapter.java @@ -35,129 +35,128 @@ import it.feio.android.omninotes.models.Category; import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Fonts; - import java.util.List; public class NavDrawerCategoryAdapter extends BaseAdapter { - private Activity mActivity; - private int layout; - private List categories; - private LayoutInflater inflater; - private final String navigationTmp; + private Activity mActivity; + private int layout; + private List categories; + private LayoutInflater inflater; + private final String navigationTmp; - public NavDrawerCategoryAdapter(Activity mActivity, List categories) { - this(mActivity, categories, null); - } + public NavDrawerCategoryAdapter (Activity mActivity, List categories) { + this(mActivity, categories, null); + } - public NavDrawerCategoryAdapter(Activity mActivity, List categories, String navigationTmp) { - this.mActivity = mActivity; - this.layout = R.layout.drawer_list_item; - this.categories = categories; - this.navigationTmp = navigationTmp; - inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - } + public NavDrawerCategoryAdapter (Activity mActivity, List categories, String navigationTmp) { + this.mActivity = mActivity; + this.layout = R.layout.drawer_list_item; + this.categories = categories; + this.navigationTmp = navigationTmp; + inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } - @Override - public int getCount() { - return categories.size(); - } + @Override + public int getCount () { + return categories.size(); + } + + + @Override + public Object getItem (int position) { + return categories.get(position); + } + + + @Override + public long getItemId (int position) { + return position; + } - @Override - public Object getItem(int position) { - return categories.get(position); + public View getView (int position, View convertView, ViewGroup parent) { + + // Finds elements + Category category = categories.get(position); + + NoteDrawerCategoryAdapterViewHolder holder; + if (convertView == null) { + convertView = inflater.inflate(layout, parent, false); + + // Overrides font sizes with the one selected from user + Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS), convertView); + + holder = new NoteDrawerCategoryAdapterViewHolder(); + + holder.imgIcon = convertView.findViewById(R.id.icon); + holder.txtTitle = convertView.findViewById(R.id.title); + holder.count = convertView.findViewById(R.id.count); + convertView.setTag(holder); + } else { + holder = (NoteDrawerCategoryAdapterViewHolder) convertView.getTag(); } + // Set the results into TextViews + holder.txtTitle.setText(category.getName()); - @Override - public long getItemId(int position) { - return position; + if (isSelected(position)) { + holder.txtTitle.setTypeface(null, Typeface.BOLD); + holder.txtTitle.setTextColor(Integer.parseInt(category.getColor())); + } else { + holder.txtTitle.setTypeface(null, Typeface.NORMAL); + holder.txtTitle.setTextColor(mActivity.getResources().getColor(R.color.drawer_text)); } + // Set the results into ImageView checking if an icon is present before + if (category.getColor() != null && category.getColor().length() > 0) { + Drawable img = mActivity.getResources().getDrawable(R.drawable.ic_folder_special_black_24dp); + ColorFilter cf = new LightingColorFilter(Color.parseColor("#000000"), Integer.parseInt(category.getColor())); + // Before API 16 the object is mutable yet + if (Build.VERSION.SDK_INT >= 16) { + img.mutate().setColorFilter(cf); + } else { + img.setColorFilter(cf); + } + holder.imgIcon.setImageDrawable(img); + int padding = 4; + holder.imgIcon.setPadding(padding, padding, padding, padding); + } - public View getView(int position, View convertView, ViewGroup parent) { - - // Finds elements - Category category = categories.get(position); - - NoteDrawerCategoryAdapterViewHolder holder; - if (convertView == null) { - convertView = inflater.inflate(layout, parent, false); - - // Overrides font sizes with the one selected from user - Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS), convertView); - - holder = new NoteDrawerCategoryAdapterViewHolder(); - - holder.imgIcon = (ImageView) convertView.findViewById(R.id.icon); - holder.txtTitle = (TextView) convertView.findViewById(R.id.title); - holder.count = (android.widget.TextView) convertView.findViewById(R.id.count); - convertView.setTag(holder); - } else { - holder = (NoteDrawerCategoryAdapterViewHolder) convertView.getTag(); - } - - // Set the results into TextViews - holder.txtTitle.setText(category.getName()); - - if (isSelected(position)) { - holder.txtTitle.setTypeface(null, Typeface.BOLD); - holder.txtTitle.setTextColor(Integer.parseInt(category.getColor())); - } else { - holder.txtTitle.setTypeface(null, Typeface.NORMAL); - holder.txtTitle.setTextColor(mActivity.getResources().getColor(R.color.drawer_text)); - } - - // Set the results into ImageView checking if an icon is present before - if (category.getColor() != null && category.getColor().length() > 0) { - Drawable img = mActivity.getResources().getDrawable(R.drawable.ic_folder_special_black_24dp); - ColorFilter cf = new LightingColorFilter(Color.parseColor("#000000"), Integer.parseInt(category.getColor())); - // Before API 16 the object is mutable yet - if (Build.VERSION.SDK_INT >= 16) { - img.mutate().setColorFilter(cf); - } else { - img.setColorFilter(cf); - } - holder.imgIcon.setImageDrawable(img); - int padding = 4; - holder.imgIcon.setPadding(padding, padding, padding, padding); - } - - // Sets category count if set in preferences - if (mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).getBoolean - ("settings_show_category_count", true)) { - holder.count.setText(String.valueOf(category.getCount())); - holder.count.setVisibility(View.VISIBLE); - } - - return convertView; + // Sets category count if set in preferences + if (mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).getBoolean + ("settings_show_category_count", true)) { + holder.count.setText(String.valueOf(category.getCount())); + holder.count.setVisibility(View.VISIBLE); } + return convertView; + } - private boolean isSelected(int position) { - // Getting actual navigation selection - String[] navigationListCodes = mActivity.getResources().getStringArray( - R.array.navigation_list_codes); + private boolean isSelected (int position) { - // Managing temporary navigation indicator when coming from a widget - String navigationTmpLocal = MainActivity.class.isAssignableFrom(mActivity.getClass()) ? ((MainActivity) - mActivity).getNavigationTmp() : null; - navigationTmpLocal = this.navigationTmp != null ? this.navigationTmp : navigationTmpLocal; + // Getting actual navigation selection + String[] navigationListCodes = mActivity.getResources().getStringArray( + R.array.navigation_list_codes); - String navigation = navigationTmp != null ? navigationTmpLocal - : mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) - .getString(Constants.PREF_NAVIGATION, - navigationListCodes[0]); + // Managing temporary navigation indicator when coming from a widget + String navigationTmpLocal = MainActivity.class.isAssignableFrom(mActivity.getClass()) ? ((MainActivity) + mActivity).getNavigationTmp() : null; + navigationTmpLocal = this.navigationTmp != null ? this.navigationTmp : navigationTmpLocal; - return navigation.equals(String.valueOf(categories.get(position).getId())); - } + String navigation = navigationTmp != null ? navigationTmpLocal + : mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) + .getString(Constants.PREF_NAVIGATION, + navigationListCodes[0]); + + return navigation.equals(String.valueOf(categories.get(position).getId())); + } } @@ -169,7 +168,7 @@ private boolean isSelected(int position) { */ class NoteDrawerCategoryAdapterViewHolder { - ImageView imgIcon; - TextView txtTitle; - android.widget.TextView count; + ImageView imgIcon; + TextView txtTitle; + android.widget.TextView count; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NoteAdapter.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NoteAdapter.java index f0d4b3de4c..9fb8ac1139 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NoteAdapter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/NoteAdapter.java @@ -16,6 +16,8 @@ */ package it.feio.android.omninotes.models.adapters; +import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade; + import android.app.Activity; import android.content.Context; import android.graphics.Color; @@ -28,16 +30,9 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; - import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.nhaarman.listviewanimations.util.Insertable; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.concurrent.RejectedExecutionException; - import it.feio.android.omninotes.R; import it.feio.android.omninotes.async.TextWorkerTask; import it.feio.android.omninotes.helpers.LogDelegate; @@ -49,273 +44,275 @@ import it.feio.android.omninotes.utils.Fonts; import it.feio.android.omninotes.utils.Navigation; import it.feio.android.omninotes.utils.TextHelper; - -import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.concurrent.RejectedExecutionException; public class NoteAdapter extends ArrayAdapter implements Insertable { - private final Activity mActivity; - private final int navigation; - private List notes = new ArrayList<>(); - private SparseBooleanArray selectedItems = new SparseBooleanArray(); - private boolean expandedView; - private int layout; - private LayoutInflater inflater; - private long closestNoteReminder = Long.parseLong(Constants.TIMESTAMP_UNIX_EPOCH_FAR); - private int closestNotePosition; - - - public NoteAdapter(Activity activity, int layout, List notes) { - super(activity, R.layout.note_layout_expanded, notes); - mActivity = activity; - this.notes = notes; - this.layout = layout; - - expandedView = layout == R.layout.note_layout_expanded; - inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - navigation = Navigation.getNavigation(); - manageCloserNote(notes, navigation); + private final Activity mActivity; + private final int navigation; + private List notes = new ArrayList<>(); + private SparseBooleanArray selectedItems = new SparseBooleanArray(); + private boolean expandedView; + private int layout; + private LayoutInflater inflater; + private long closestNoteReminder = Long.parseLong(Constants.TIMESTAMP_UNIX_EPOCH_FAR); + private int closestNotePosition; + + + public NoteAdapter (Activity activity, int layout, List notes) { + super(activity, R.layout.note_layout_expanded, notes); + mActivity = activity; + this.notes = notes; + this.layout = layout; + + expandedView = layout == R.layout.note_layout_expanded; + inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + navigation = Navigation.getNavigation(); + manageCloserNote(notes, navigation); + } + + + @Override + public View getView (int position, View convertView, ViewGroup parent) { + Note note = notes.get(position); + NoteViewHolder holder; + if (convertView == null) { + convertView = inflater.inflate(layout, parent, false); + holder = buildHolder(convertView, parent); + convertView.setTag(holder); + } else { + holder = (NoteViewHolder) convertView.getTag(); } - - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - Note note = notes.get(position); - NoteViewHolder holder; - if (convertView == null) { - convertView = inflater.inflate(layout, parent, false); - holder = buildHolder(convertView, parent); - convertView.setTag(holder); - } else { - holder = (NoteViewHolder) convertView.getTag(); - } - initText(note, holder); - initIcons(note, holder); - initDates(note, holder); - initThumbnail(note, holder); - manageSelectionColor(position, note, holder); - return convertView; + initText(note, holder); + initIcons(note, holder); + initDates(note, holder); + initThumbnail(note, holder); + manageSelectionColor(position, note, holder); + return convertView; + } + + + /** + * Highlighted if is part of multiselection of notes. Remember to search for child with card ui + */ + private void manageSelectionColor (int position, Note note, NoteViewHolder holder) { + if (selectedItems.get(position)) { + holder.cardLayout.setBackgroundColor(mActivity.getResources().getColor( + R.color.list_bg_selected)); + } else { + restoreDrawable(note, holder.cardLayout, holder); } - - - /** - * Highlighted if is part of multiselection of notes. Remember to search for child with card ui - */ - private void manageSelectionColor(int position, Note note, NoteViewHolder holder) { - if (selectedItems.get(position)) { - holder.cardLayout.setBackgroundColor(mActivity.getResources().getColor( - R.color.list_bg_selected)); - } else { - restoreDrawable(note, holder.cardLayout, holder); - } + } + + + private void initThumbnail (Note note, NoteViewHolder holder) { + + if (expandedView && holder.attachmentThumbnail != null) { + // If note is locked or without attachments nothing is shown + if ((note.isLocked() && !mActivity.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS).getBoolean("settings_password_access", false)) + || note.getAttachmentsList().size() == 0) { + holder.attachmentThumbnail.setVisibility(View.GONE); + } else { + holder.attachmentThumbnail.setVisibility(View.VISIBLE); + Attachment mAttachment = note.getAttachmentsList().get(0); + Uri thumbnailUri = BitmapHelper.getThumbnailUri(mActivity, mAttachment); + + Glide.with(mActivity) + .load(thumbnailUri) + .apply(new RequestOptions().centerCrop()) + .transition(withCrossFade()) + .into(holder.attachmentThumbnail); + } } + } - private void initThumbnail(Note note, NoteViewHolder holder) { - - if (expandedView && holder.attachmentThumbnail != null) { - // If note is locked or without attachments nothing is shown - if ((note.isLocked() && !mActivity.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS).getBoolean("settings_password_access", false)) - || note.getAttachmentsList().size() == 0) { - holder.attachmentThumbnail.setVisibility(View.GONE); - } else { - holder.attachmentThumbnail.setVisibility(View.VISIBLE); - Attachment mAttachment = note.getAttachmentsList().get(0); - Uri thumbnailUri = BitmapHelper.getThumbnailUri(mActivity, mAttachment); - - Glide.with(mActivity) - .load(thumbnailUri) - .apply(new RequestOptions().centerCrop()) - .transition(withCrossFade()) - .into(holder.attachmentThumbnail); - } - } - } - + public List getNotes () { + return notes; + } - public List getNotes() { - return notes; - } + private void initDates (Note note, NoteViewHolder holder) { + String dateText = TextHelper.getDateText(mActivity, note, navigation); + holder.date.setText(dateText); + } - private void initDates(Note note, NoteViewHolder holder) { - String dateText = TextHelper.getDateText(mActivity, note, navigation); - holder.date.setText(dateText); - } + private void initIcons (Note note, NoteViewHolder holder) { + // Evaluates the archived state... + holder.archiveIcon.setVisibility(note.isArchived() ? View.VISIBLE : View.GONE); + // ...the location + holder.locationIcon.setVisibility(note.getLongitude() != null && note.getLongitude() != 0 ? View.VISIBLE : + View.GONE); - private void initIcons(Note note, NoteViewHolder holder) { - // Evaluates the archived state... - holder.archiveIcon.setVisibility(note.isArchived() ? View.VISIBLE : View.GONE); - // ...the location - holder.locationIcon.setVisibility(note.getLongitude() != null && note.getLongitude() != 0 ? View.VISIBLE : - View.GONE); - - // ...the presence of an alarm - holder.alarmIcon.setVisibility(note.getAlarm() != null ? View.VISIBLE : View.GONE); - // ...the locked with password state - holder.lockedIcon.setVisibility(note.isLocked() ? View.VISIBLE : View.GONE); - // ...the attachment icon for contracted view - if (!expandedView) { - holder.attachmentIcon.setVisibility(note.getAttachmentsList().size() > 0 ? View.VISIBLE : View.GONE); + // ...the presence of an alarm + holder.alarmIcon.setVisibility(note.getAlarm() != null ? View.VISIBLE : View.GONE); + // ...the locked with password state + holder.lockedIcon.setVisibility(note.isLocked() ? View.VISIBLE : View.GONE); + // ...the attachment icon for contracted view + if (!expandedView) { + holder.attachmentIcon.setVisibility(note.getAttachmentsList().size() > 0 ? View.VISIBLE : View.GONE); + } + } + + + private void initText (Note note, NoteViewHolder holder) { + try { + if (note.isChecklist()) { + TextWorkerTask task = new TextWorkerTask(mActivity, holder.title, holder.content, expandedView); + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, note); + } else { + Spanned[] titleAndContent = TextHelper.parseTitleAndContent(mActivity, note); + holder.title.setText(titleAndContent[0]); + holder.content.setText(titleAndContent[1]); + holder.title.setText(titleAndContent[0]); + if (titleAndContent[1].length() > 0) { + holder.content.setText(titleAndContent[1]); + holder.content.setVisibility(View.VISIBLE); + } else { + holder.content.setVisibility(View.INVISIBLE); } + } + } catch (RejectedExecutionException e) { + LogDelegate.w("Oversized tasks pool to load texts!", e); } - - - private void initText(Note note, NoteViewHolder holder) { - try { - if (note.isChecklist()) { - TextWorkerTask task = new TextWorkerTask(mActivity, holder.title, holder.content, expandedView); - task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, note); - } else { - Spanned[] titleAndContent = TextHelper.parseTitleAndContent(mActivity, note); - holder.title.setText(titleAndContent[0]); - holder.content.setText(titleAndContent[1]); - holder.title.setText(titleAndContent[0]); - if (titleAndContent[1].length() > 0) { - holder.content.setText(titleAndContent[1]); - holder.content.setVisibility(View.VISIBLE); - } else { - holder.content.setVisibility(View.INVISIBLE); - } - } - } catch (RejectedExecutionException e) { - LogDelegate.w("Oversized tasks pool to load texts!", e); + } + + + /** + * Saves the position of the closest note to align list scrolling with it on start + */ + private void manageCloserNote (List notes, int navigation) { + if (navigation == Navigation.REMINDERS) { + for (int i = 0; i < notes.size(); i++) { + long now = Calendar.getInstance().getTimeInMillis(); + long reminder = Long.parseLong(notes.get(i).getAlarm()); + if (now < reminder && reminder < closestNoteReminder) { + closestNotePosition = i; + closestNoteReminder = reminder; } + } } + } - /** - * Saves the position of the closest note to align list scrolling with it on start - */ - private void manageCloserNote(List notes, int navigation) { - if (navigation == Navigation.REMINDERS) { - for (int i = 0; i < notes.size(); i++) { - long now = Calendar.getInstance().getTimeInMillis(); - long reminder = Long.parseLong(notes.get(i).getAlarm()); - if (now < reminder && reminder < closestNoteReminder) { - closestNotePosition = i; - closestNoteReminder = reminder; - } - } - } - } + /** + * Returns the note with the nearest reminder in the future + */ + public int getClosestNotePosition () { + return closestNotePosition; + } - /** - * Returns the note with the nearest reminder in the future - */ - public int getClosestNotePosition() { - return closestNotePosition; - } + public SparseBooleanArray getSelectedItems () { + return selectedItems; + } - public SparseBooleanArray getSelectedItems() { - return selectedItems; - } + public void addSelectedItem (Integer selectedItem) { + selectedItems.put(selectedItem, true); + } - public void addSelectedItem(Integer selectedItem) { - selectedItems.put(selectedItem, true); - } + public void removeSelectedItem (Integer selectedItem) { + selectedItems.delete(selectedItem); + } - public void removeSelectedItem(Integer selectedItem) { - selectedItems.delete(selectedItem); - } + public void clearSelectedItems () { + selectedItems.clear(); + } - public void clearSelectedItems() { - selectedItems.clear(); - } + public void restoreDrawable (Note note, View v) { + restoreDrawable(note, v, null); + } - public void restoreDrawable(Note note, View v) { - restoreDrawable(note, v, null); - } + public void restoreDrawable (Note note, View v, NoteViewHolder holder) { + final int paddingBottom = v.getPaddingBottom(), paddingLeft = v.getPaddingLeft(); + final int paddingRight = v.getPaddingRight(), paddingTop = v.getPaddingTop(); + v.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); + colorNote(note, v, holder); + } - public void restoreDrawable(Note note, View v, NoteViewHolder holder) { - final int paddingBottom = v.getPaddingBottom(), paddingLeft = v.getPaddingLeft(); - final int paddingRight = v.getPaddingRight(), paddingTop = v.getPaddingTop(); - v.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); - colorNote(note, v, holder); - } + @SuppressWarnings("unused") + private void colorNote (Note note, View v) { + colorNote(note, v, null); + } - @SuppressWarnings("unused") - private void colorNote(Note note, View v) { - colorNote(note, v, null); - } + /** + * Color of category marker if note is categorized a function is active in preferences + */ + private void colorNote (Note note, View v, NoteViewHolder holder) { + String colorsPref = mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) + .getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT); - /** - * Color of category marker if note is categorized a function is active in preferences - */ - private void colorNote(Note note, View v, NoteViewHolder holder) { - - String colorsPref = mActivity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) - .getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT); - - // Checking preference - if (!colorsPref.equals("disabled")) { - - // Resetting transparent color to the view - v.setBackgroundColor(Color.parseColor("#00000000")); - - // If category is set the color will be applied on the appropriate target - if (note.getCategory() != null && note.getCategory().getColor() != null) { - if (colorsPref.equals("complete") || colorsPref.equals("list")) { - v.setBackgroundColor(Integer.parseInt(note.getCategory().getColor())); - } else { - if (holder != null) { - holder.categoryMarker.setBackgroundColor(Integer.parseInt(note.getCategory().getColor())); - } else { - v.findViewById(R.id.category_marker).setBackgroundColor(Integer.parseInt(note.getCategory().getColor())); - } - } - } else { - v.findViewById(R.id.category_marker).setBackgroundColor(0); - } - } - } + // Checking preference + if (!colorsPref.equals("disabled")) { + // Resetting transparent color to the view + v.setBackgroundColor(Color.parseColor("#00000000")); - /** - * Replaces notes - */ - public void replace(Note note, int index) { - if (notes.indexOf(note) != -1) { - notes.remove(index); + // If category is set the color will be applied on the appropriate target + if (note.getCategory() != null && note.getCategory().getColor() != null) { + if (colorsPref.equals("complete") || colorsPref.equals("list")) { + v.setBackgroundColor(Integer.parseInt(note.getCategory().getColor())); } else { - index = notes.size(); + if (holder != null) { + holder.categoryMarker.setBackgroundColor(Integer.parseInt(note.getCategory().getColor())); + } else { + v.findViewById(R.id.category_marker).setBackgroundColor(Integer.parseInt(note.getCategory().getColor())); + } } - notes.add(index, note); + } else { + v.findViewById(R.id.category_marker).setBackgroundColor(0); + } } + } - @Override - public void add(int i, @NonNull Object o) { - insert((Note) o, i); + /** + * Replaces notes + */ + public void replace (Note note, int index) { + if (notes.indexOf(note) != -1) { + notes.remove(index); + } else { + index = notes.size(); } + notes.add(index, note); + } - public void remove(List notes) { - for (Note note : notes) { - remove(note); - } - } + @Override + public void add (int i, @NonNull Object o) { + insert((Note) o, i); + } - private NoteViewHolder buildHolder(View convertView, ViewGroup parent) { - // Overrides font sizes with the one selected from user - Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS), convertView); - return new NoteViewHolder(convertView); + public void remove (List notes) { + for (Note note : notes) { + remove(note); } + } + + + private NoteViewHolder buildHolder (View convertView, ViewGroup parent) { + // Overrides font sizes with the one selected from user + Fonts.overrideTextSize(mActivity, mActivity.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS), convertView); + return new NoteViewHolder(convertView); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/PlacesAutoCompleteAdapter.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/PlacesAutoCompleteAdapter.java index 96f4a323f3..460093e5dc 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/PlacesAutoCompleteAdapter.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/adapters/PlacesAutoCompleteAdapter.java @@ -22,59 +22,58 @@ import android.widget.Filter; import android.widget.Filterable; import it.feio.android.omninotes.utils.GeocodeHelper; - import java.util.List; public class PlacesAutoCompleteAdapter extends ArrayAdapter implements Filterable { - private static final int MIN_CHARS = 7; + private static final int MIN_CHARS = 7; - private List resultList; + private List resultList; - public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) { - super(context, textViewResourceId); - } + public PlacesAutoCompleteAdapter (Context context, int textViewResourceId) { + super(context, textViewResourceId); + } - @Override - public int getCount() { - return resultList.size(); - } + @Override + public int getCount () { + return resultList.size(); + } - @Override - public String getItem(int index) { - return resultList.get(index); - } + @Override + public String getItem (int index) { + return resultList.get(index); + } - @Override - public Filter getFilter() { - return new Filter() { - @Override - protected FilterResults performFiltering(CharSequence constraint) { - FilterResults filterResults = new FilterResults(); - if (constraint != null && constraint.length() > MIN_CHARS) { - // Retrieve the autocomplete results. - resultList = GeocodeHelper.autocomplete(constraint.toString()); - // Assign the data to the FilterResults - filterResults.values = resultList; - filterResults.count = resultList.size(); - } - return filterResults; - } + @Override + public Filter getFilter () { + return new Filter() { + @Override + protected FilterResults performFiltering (CharSequence constraint) { + FilterResults filterResults = new FilterResults(); + if (constraint != null && constraint.length() > MIN_CHARS) { + // Retrieve the autocomplete results. + resultList = GeocodeHelper.autocomplete(constraint.toString()); + // Assign the data to the FilterResults + filterResults.values = resultList; + filterResults.count = resultList.size(); + } + return filterResults; + } - @Override - protected void publishResults(CharSequence constraint, FilterResults results) { - if (results != null && results.count > 0) { - notifyDataSetChanged(); - } else { - notifyDataSetInvalidated(); - } - } - }; - } + @Override + protected void publishResults (CharSequence constraint, FilterResults results) { + if (results != null && results.count > 0) { + notifyDataSetChanged(); + } else { + notifyDataSetInvalidated(); + } + } + }; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/ImageAndTextItem.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/ImageAndTextItem.java index fd0b227cbc..26d93625c1 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/ImageAndTextItem.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/ImageAndTextItem.java @@ -19,34 +19,34 @@ public class ImageAndTextItem { - public ImageAndTextItem(int image, String text) { - super(); - this.image = image; - this.text = text; - } + public ImageAndTextItem (int image, String text) { + super(); + this.image = image; + this.text = text; + } - private int image; - private String text; + private int image; + private String text; - public int getImage() { - return image; - } + public int getImage () { + return image; + } - public void setImage(int image) { - this.image = image; - } + public void setImage (int image) { + this.image = image; + } - public String getText() { - return text; - } + public String getText () { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText (String text) { + this.text = text; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/NoteViewHolder.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/NoteViewHolder.java index ea121658d8..3748925500 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/NoteViewHolder.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/holders/NoteViewHolder.java @@ -20,33 +20,45 @@ import android.support.annotation.Nullable; import android.view.View; import android.widget.ImageView; - -import com.neopixl.pixlui.components.textview.TextView; - import butterknife.BindView; import butterknife.ButterKnife; +import com.neopixl.pixlui.components.textview.TextView; import it.feio.android.omninotes.R; import it.feio.android.omninotes.models.views.SquareImageView; public class NoteViewHolder { - public NoteViewHolder(View view) { - ButterKnife.bind(this, view); - } + public NoteViewHolder (View view) { + ButterKnife.bind(this, view); + } - @BindView(R.id.root) public View root; - @BindView(R.id.card_layout) public View cardLayout; - @BindView(R.id.category_marker) public View categoryMarker; + @BindView(R.id.root) + public View root; + @BindView(R.id.card_layout) + public View cardLayout; + @BindView(R.id.category_marker) + public View categoryMarker; - @BindView(R.id.note_title) public TextView title; - @BindView(R.id.note_content) public TextView content; - @BindView(R.id.note_date) public TextView date; + @BindView(R.id.note_title) + public TextView title; + @BindView(R.id.note_content) + public TextView content; + @BindView(R.id.note_date) + public TextView date; - @BindView(R.id.archivedIcon) public ImageView archiveIcon; - @BindView(R.id.locationIcon) public ImageView locationIcon; - @BindView(R.id.alarmIcon) public ImageView alarmIcon; - @BindView(R.id.lockedIcon) public ImageView lockedIcon; - @Nullable @BindView(R.id.attachmentIcon) public ImageView attachmentIcon; - @Nullable @BindView(R.id.attachmentThumbnail) public SquareImageView attachmentThumbnail; + @BindView(R.id.archivedIcon) + public ImageView archiveIcon; + @BindView(R.id.locationIcon) + public ImageView locationIcon; + @BindView(R.id.alarmIcon) + public ImageView alarmIcon; + @BindView(R.id.lockedIcon) + public ImageView lockedIcon; + @Nullable + @BindView(R.id.attachmentIcon) + public ImageView attachmentIcon; + @Nullable + @BindView(R.id.attachmentThumbnail) + public SquareImageView attachmentThumbnail; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/AbsListViewScrollDetector.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/AbsListViewScrollDetector.java index fe16295d9f..5c9de2f86a 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/AbsListViewScrollDetector.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/AbsListViewScrollDetector.java @@ -24,68 +24,68 @@ public abstract class AbsListViewScrollDetector implements AbsListView.OnScrollListener { - private int mLastScrollY; - private int mPreviousFirstVisibleItem; - private AbsListView mListView; - private int mScrollThreshold; + private int mLastScrollY; + private int mPreviousFirstVisibleItem; + private AbsListView mListView; + private int mScrollThreshold; - public abstract void onScrollUp(); + public abstract void onScrollUp (); - public abstract void onScrollDown(); + public abstract void onScrollDown (); - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - } + @Override + public void onScrollStateChanged (AbsListView view, int scrollState) { + } - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (isSameRow(firstVisibleItem)) { - int newScrollY = getTopItemScrollY(); - boolean isSignificantDelta = Math.abs(mLastScrollY - newScrollY) > mScrollThreshold; - if (isSignificantDelta) { - if (mLastScrollY > newScrollY) { - onScrollUp(); - } else { - onScrollDown(); - } - } - mLastScrollY = newScrollY; + @Override + public void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (isSameRow(firstVisibleItem)) { + int newScrollY = getTopItemScrollY(); + boolean isSignificantDelta = Math.abs(mLastScrollY - newScrollY) > mScrollThreshold; + if (isSignificantDelta) { + if (mLastScrollY > newScrollY) { + onScrollUp(); } else { - if (firstVisibleItem > mPreviousFirstVisibleItem) { - onScrollUp(); - } else { - onScrollDown(); - } - - mLastScrollY = getTopItemScrollY(); - mPreviousFirstVisibleItem = firstVisibleItem; + onScrollDown(); } + } + mLastScrollY = newScrollY; + } else { + if (firstVisibleItem > mPreviousFirstVisibleItem) { + onScrollUp(); + } else { + onScrollDown(); + } + + mLastScrollY = getTopItemScrollY(); + mPreviousFirstVisibleItem = firstVisibleItem; } + } - public void setScrollThreshold(int scrollThreshold) { - mScrollThreshold = scrollThreshold; - } + public void setScrollThreshold (int scrollThreshold) { + mScrollThreshold = scrollThreshold; + } - public void setListView(@NonNull AbsListView listView) { - mListView = listView; - } + public void setListView (@NonNull AbsListView listView) { + mListView = listView; + } - private boolean isSameRow(int firstVisibleItem) { - return firstVisibleItem == mPreviousFirstVisibleItem; - } + private boolean isSameRow (int firstVisibleItem) { + return firstVisibleItem == mPreviousFirstVisibleItem; + } - private int getTopItemScrollY() { - if (mListView == null || mListView.getChildAt(0) == null) { - return 0; - } - View topChild = mListView.getChildAt(0); - return topChild.getTop(); + private int getTopItemScrollY () { + if (mListView == null || mListView.getChildAt(0) == null) { + return 0; } + View topChild = mListView.getChildAt(0); + return topChild.getTop(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnAttachingFileListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnAttachingFileListener.java index 0f13e377e5..b0539516f2 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnAttachingFileListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnAttachingFileListener.java @@ -22,7 +22,7 @@ public interface OnAttachingFileListener { - public void onAttachingFileErrorOccurred(Attachment mAttachment); + void onAttachingFileErrorOccurred (Attachment mAttachment); - public void onAttachingFileFinished(Attachment mAttachment); + void onAttachingFileFinished (Attachment mAttachment); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnCABItemClickedListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnCABItemClickedListener.java index 650655cb78..3d6389abbe 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnCABItemClickedListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnCABItemClickedListener.java @@ -23,5 +23,5 @@ public interface OnCABItemClickedListener { - public void onCABItemClicked(MenuItem item); + void onCABItemClicked (MenuItem item); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnDrawChangedListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnDrawChangedListener.java index 50fc80c2f1..d87b245528 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnDrawChangedListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnDrawChangedListener.java @@ -19,5 +19,5 @@ public interface OnDrawChangedListener { - public void onDrawChanged(); + void onDrawChanged (); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnFabItemClickedListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnFabItemClickedListener.java index b9248ea03f..4ebdeb0151 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnFabItemClickedListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnFabItemClickedListener.java @@ -19,5 +19,5 @@ public interface OnFabItemClickedListener { - void onFabItemClick(int id); + void onFabItemClick (int id); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnGeoUtilResultListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnGeoUtilResultListener.java index 4d48f4b464..1673c7d882 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnGeoUtilResultListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnGeoUtilResultListener.java @@ -23,11 +23,11 @@ public interface OnGeoUtilResultListener { - public void onAddressResolved(String address); + void onAddressResolved (String address); - public void onCoordinatesResolved(Location location, String address); + void onCoordinatesResolved (Location location, String address); - public void onLocationRetrieved(Location location); + void onLocationRetrieved (Location location); - public void onLocationUnavailable(); + void onLocationUnavailable (); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnNoteSaved.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnNoteSaved.java index cd75b81fbf..38d1f54d91 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnNoteSaved.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnNoteSaved.java @@ -22,5 +22,5 @@ public interface OnNoteSaved { - void onNoteSaved(Note noteSaved); + void onNoteSaved (Note noteSaved); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnPermissionRequestedListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnPermissionRequestedListener.java index 5f646fe52b..d3b880c57c 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnPermissionRequestedListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnPermissionRequestedListener.java @@ -19,5 +19,5 @@ public interface OnPermissionRequestedListener { - void onPermissionGranted(); + void onPermissionGranted (); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnReminderPickedListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnReminderPickedListener.java index b1da3b15ba..22cad3fbc2 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnReminderPickedListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnReminderPickedListener.java @@ -20,7 +20,7 @@ public interface OnReminderPickedListener { - public void onReminderPicked(long reminder); + void onReminderPicked (long reminder); - public void onRecurrenceReminderPicked(String recurrenceRule); + void onRecurrenceReminderPicked (String recurrenceRule); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnViewTouchedListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnViewTouchedListener.java index fbef73f8ad..5c4240e4a4 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnViewTouchedListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/listeners/OnViewTouchedListener.java @@ -22,5 +22,5 @@ public interface OnViewTouchedListener { - public void onViewTouchOccurred(MotionEvent ev); + void onViewTouchOccurred (MotionEvent ev); } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/DynamicNavigationLookupTable.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/DynamicNavigationLookupTable.java index e8713bacf6..7c455abea6 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/DynamicNavigationLookupTable.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/DynamicNavigationLookupTable.java @@ -18,79 +18,82 @@ package it.feio.android.omninotes.models.misc; -import java.util.List; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.async.bus.DynamicNavigationReadyEvent; import it.feio.android.omninotes.async.bus.NotesUpdatedEvent; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Note; +import java.util.List; public class DynamicNavigationLookupTable { - private static DynamicNavigationLookupTable instance; - int archived; - int trashed; - int uncategorized; - int reminders; + private static DynamicNavigationLookupTable instance; + int archived; + int trashed; + int uncategorized; + int reminders; - private DynamicNavigationLookupTable() { - EventBus.getDefault().register(this); - update(); - } + private DynamicNavigationLookupTable () { + EventBus.getDefault().register(this); + update(); + } - public static DynamicNavigationLookupTable getInstance() { - if (instance == null) { - instance = new DynamicNavigationLookupTable(); - } - return instance; - } + public static DynamicNavigationLookupTable getInstance () { + if (instance == null) { + instance = new DynamicNavigationLookupTable(); + } + return instance; + } - public void update() { - ((Runnable) () -> { - archived = trashed = uncategorized = reminders = 0; - List notes = DbHelper.getInstance().getAllNotes(false); - for (int i = 0; i < notes.size(); i++) { - if (notes.get(i).isTrashed()) trashed++; - else if (notes.get(i).isArchived()) archived++; - else if (notes.get(i).getAlarm() != null) reminders++; - if (notes.get(i).getCategory() == null || notes.get(i).getCategory().getId().equals(0L)) { - uncategorized++; - } - } - EventBus.getDefault().post(new DynamicNavigationReadyEvent()); - LogDelegate.d("Dynamic menu finished counting items"); - }).run(); - } + public void update () { + ((Runnable) () -> { + archived = trashed = uncategorized = reminders = 0; + List notes = DbHelper.getInstance().getAllNotes(false); + for (int i = 0; i < notes.size(); i++) { + if (notes.get(i).isTrashed()) { + trashed++; + } else if (notes.get(i).isArchived()) { + archived++; + } else if (notes.get(i).getAlarm() != null) { + reminders++; + } + if (notes.get(i).getCategory() == null || notes.get(i).getCategory().getId().equals(0L)) { + uncategorized++; + } + } + EventBus.getDefault().post(new DynamicNavigationReadyEvent()); + LogDelegate.d("Dynamic menu finished counting items"); + }).run(); + } - public void onEventAsync(NotesUpdatedEvent event) { - update(); - } + public void onEventAsync (NotesUpdatedEvent event) { + update(); + } - public int getArchived() { - return archived; - } + public int getArchived () { + return archived; + } - public int getTrashed() { - return trashed; - } + public int getTrashed () { + return trashed; + } - public int getReminders() { - return reminders; - } + public int getReminders () { + return reminders; + } - public int getUncategorized() { - return uncategorized; - } + public int getUncategorized () { + return uncategorized; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/PlayStoreMetadataFetcherResult.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/PlayStoreMetadataFetcherResult.java index 0c74f2ff6b..ffc9ccf6ea 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/PlayStoreMetadataFetcherResult.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/misc/PlayStoreMetadataFetcherResult.java @@ -19,59 +19,59 @@ public class PlayStoreMetadataFetcherResult { - private String datePublished; - private String fileSize; - private String numDownloads; - private String softwareVersion; - private String operatingSystems; - private String contentRating; - - public String getDatePublished() { - return datePublished; - } - - public void setDatePublished(String datePublished) { - this.datePublished = datePublished; - } - - public String getFileSize() { - return fileSize; - } - - public void setFileSize(String fileSize) { - this.fileSize = fileSize; - } - - public String getNumDownloads() { - return numDownloads; - } - - public void setNumDownloads(String numDownloads) { - this.numDownloads = numDownloads; - } - - public String getSoftwareVersion() { - return softwareVersion; - } - - public void setSoftwareVersion(String softwareVersion) { - this.softwareVersion = softwareVersion; - } - - public String getOperatingSystems() { - return operatingSystems; - } - - public void setOperatingSystems(String operatingSystems) { - this.operatingSystems = operatingSystems; - } - - public String getContentRating() { - return contentRating; - } - - public void setContentRating(String contentRating) { - this.contentRating = contentRating; - } + private String datePublished; + private String fileSize; + private String numDownloads; + private String softwareVersion; + private String operatingSystems; + private String contentRating; + + public String getDatePublished () { + return datePublished; + } + + public void setDatePublished (String datePublished) { + this.datePublished = datePublished; + } + + public String getFileSize () { + return fileSize; + } + + public void setFileSize (String fileSize) { + this.fileSize = fileSize; + } + + public String getNumDownloads () { + return numDownloads; + } + + public void setNumDownloads (String numDownloads) { + this.numDownloads = numDownloads; + } + + public String getSoftwareVersion () { + return softwareVersion; + } + + public void setSoftwareVersion (String softwareVersion) { + this.softwareVersion = softwareVersion; + } + + public String getOperatingSystems () { + return operatingSystems; + } + + public void setOperatingSystems (String operatingSystems) { + this.operatingSystems = operatingSystems; + } + + public String getContentRating () { + return contentRating; + } + + public void setContentRating (String contentRating) { + this.contentRating = contentRating; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/ExpandableHeightGridView.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/ExpandableHeightGridView.java index 75ed8efded..da21e5c6d0 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/ExpandableHeightGridView.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/ExpandableHeightGridView.java @@ -24,67 +24,66 @@ public class ExpandableHeightGridView extends GridView { - // private boolean expanded = false; - private int itemHeight; + // private boolean expanded = false; + private int itemHeight; - public ExpandableHeightGridView(Context context) { - super(context); - } + public ExpandableHeightGridView (Context context) { + super(context); + } - public ExpandableHeightGridView(Context context, AttributeSet attrs) { - super(context, attrs); - } + public ExpandableHeightGridView (Context context, AttributeSet attrs) { + super(context, attrs); + } - public ExpandableHeightGridView(Context context, AttributeSet attrs, - int defStyle) { - super(context, attrs, defStyle); - } + public ExpandableHeightGridView (Context context, AttributeSet attrs, + int defStyle) { + super(context, attrs, defStyle); + } // // public boolean isExpanded() { // return expanded; // } - @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + @Override + public void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { // if (isExpanded()) { - // Calculate entire height by providing a very large height hint. - // View.MEASURED_SIZE_MASK represents the largest height possible. - int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, - MeasureSpec.AT_MOST); - super.onMeasure(widthMeasureSpec, expandSpec); - - ViewGroup.LayoutParams params = getLayoutParams(); - params.height = getMeasuredHeight(); + // Calculate entire height by providing a very large height hint. + // View.MEASURED_SIZE_MASK represents the largest height possible. + int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, + MeasureSpec.AT_MOST); + super.onMeasure(widthMeasureSpec, expandSpec); + + ViewGroup.LayoutParams params = getLayoutParams(); + params.height = getMeasuredHeight(); // } else { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // } - } - + } // public void setExpanded(boolean expanded) { // this.expanded = expanded; // } - public void autoresize() { - // Set gridview height + public void autoresize () { + // Set gridview height // ViewGroup.LayoutParams layoutParams = getLayoutParams(); - int items = getAdapter().getCount(); - int columns = items == 1 ? 1 : 2; + int items = getAdapter().getCount(); + int columns = items == 1 ? 1 : 2; - setNumColumns(columns); + setNumColumns(columns); // itemHeight = Constants.THUMBNAIL_SIZE * 2 / columns; // layoutParams.height = ( (items / columns) + (items % columns) ) * itemHeight; //this is in pixels // // setLayoutParams(layoutParams); - } + } - public int getItemHeight() { - return itemHeight; - } + public int getItemHeight () { + return itemHeight; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/Fab.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/Fab.java index 82ea2dcaf7..f50b19005d 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/Fab.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/Fab.java @@ -17,6 +17,8 @@ package it.feio.android.omninotes.models.views; +import static android.support.v4.view.ViewCompat.animate; + import android.support.v4.view.ViewPropertyAnimatorListener; import android.view.View; import android.view.ViewGroup; @@ -31,190 +33,188 @@ import it.feio.android.omninotes.models.listeners.OnFabItemClickedListener; import it.feio.android.omninotes.utils.Constants; -import static android.support.v4.view.ViewCompat.animate; - public class Fab { - private FloatingActionsMenu fab; - private boolean fabAllowed; - private boolean fabHidden; - private boolean fabExpanded; - private final ListView listView; - private boolean expandOnLongClick; - private View overlay; + private FloatingActionsMenu fab; + private boolean fabAllowed; + private boolean fabHidden; + private boolean fabExpanded; + private final ListView listView; + private boolean expandOnLongClick; + private View overlay; + + OnFabItemClickedListener onFabItemClickedListener; + + + public Fab (View fabView, ListView listView, boolean expandOnLongClick) { + this.fab = (FloatingActionsMenu) fabView; + this.listView = listView; + this.expandOnLongClick = expandOnLongClick; + init(); + } + + + private void init () { + this.fabHidden = true; + this.fabExpanded = false; + + AddFloatingActionButton fabAddButton = fab.findViewById(R.id.fab_expand_menu_button); + fabAddButton.setOnClickListener(v -> { + if (!isExpanded() && expandOnLongClick) { + performAction(v); + } else { + performToggle(); + } + }); + fabAddButton.setOnLongClickListener(v -> { + if (!expandOnLongClick) { + performAction(v); + } else { + performToggle(); + } + return true; + }); + listView.setOnScrollListener( + new AbsListViewScrollDetector() { + public void onScrollUp () { + if (fab != null) { + fab.collapse(); + hideFab(); + } + } - OnFabItemClickedListener onFabItemClickedListener; + public void onScrollDown () { + if (fab != null) { + fab.collapse(); + showFab(); + } + } + }); + fab.findViewById(R.id.fab_checklist).setOnClickListener(onClickListener); + fab.findViewById(R.id.fab_camera).setOnClickListener(onClickListener); - public Fab(View fabView, ListView listView, boolean expandOnLongClick) { - this.fab = (FloatingActionsMenu) fabView; - this.listView = listView; - this.expandOnLongClick = expandOnLongClick; - init(); + if (!expandOnLongClick) { + View noteBtn = fab.findViewById(R.id.fab_note); + noteBtn.setVisibility(View.VISIBLE); + noteBtn.setOnClickListener(onClickListener); } + } - private void init() { - this.fabHidden = true; - this.fabExpanded = false; - - AddFloatingActionButton fabAddButton = (AddFloatingActionButton) fab.findViewById(R.id.fab_expand_menu_button); - fabAddButton.setOnClickListener(v -> { - if (!isExpanded() && expandOnLongClick) { - performAction(v); - } else { - performToggle(); - } - }); - fabAddButton.setOnLongClickListener(v -> { - if (!expandOnLongClick) { - performAction(v); - } else { - performToggle(); - } - return true; - }); - listView.setOnScrollListener( - new AbsListViewScrollDetector() { - public void onScrollUp() { - if (fab != null) { - fab.collapse(); - hideFab(); - } - } - - public void onScrollDown() { - if (fab != null) { - fab.collapse(); - showFab(); - } - } - }); - - fab.findViewById(R.id.fab_checklist).setOnClickListener(onClickListener); - fab.findViewById(R.id.fab_camera).setOnClickListener(onClickListener); - - if (!expandOnLongClick) { - View noteBtn = fab.findViewById(R.id.fab_note); - noteBtn.setVisibility(View.VISIBLE); - noteBtn.setOnClickListener(onClickListener); - } + private View.OnClickListener onClickListener = new View.OnClickListener() { + @Override + public void onClick (View v) { + onFabItemClickedListener.onFabItemClick(v.getId()); } + }; - - private View.OnClickListener onClickListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - onFabItemClickedListener.onFabItemClick(v.getId()); - } - }; - - public void performToggle() { - fabExpanded = !fabExpanded; - fab.toggle(); - } + public void performToggle () { + fabExpanded = !fabExpanded; + fab.toggle(); + } - private void toggleOverlay() { - if (this.overlay != null) { - if (fabExpanded) { - this.overlay.setVisibility(View.VISIBLE); - } else { - this.overlay.setVisibility(View.GONE); - } - } + private void toggleOverlay () { + if (this.overlay != null) { + if (fabExpanded) { + this.overlay.setVisibility(View.VISIBLE); + } else { + this.overlay.setVisibility(View.GONE); + } } - - private void performAction(View v) { - if (fabExpanded) { - fab.toggle(); - fabExpanded = false; - } else { - onFabItemClickedListener.onFabItemClick(v.getId()); - } + } + + private void performAction (View v) { + if (fabExpanded) { + fab.toggle(); + fabExpanded = false; + } else { + onFabItemClickedListener.onFabItemClick(v.getId()); } + } - public void showFab() { - if (fab != null && fabAllowed && fabHidden) { - animateFab(0, View.VISIBLE, View.VISIBLE); - fabHidden = false; - } + public void showFab () { + if (fab != null && fabAllowed && fabHidden) { + animateFab(0, View.VISIBLE, View.VISIBLE); + fabHidden = false; } + } - public void hideFab() { - if (fab != null && !fabHidden) { - fab.collapse(); - animateFab(fab.getHeight() + getMarginBottom(fab), View.VISIBLE, View.INVISIBLE); - fabHidden = true; - fabExpanded = false; - } + public void hideFab () { + if (fab != null && !fabHidden) { + fab.collapse(); + animateFab(fab.getHeight() + getMarginBottom(fab), View.VISIBLE, View.INVISIBLE); + fabHidden = true; + fabExpanded = false; } + } - public void animateFab(int translationY, final int visibilityBefore, final int visibilityAfter) { - animate(fab).setInterpolator(new AccelerateDecelerateInterpolator()) + public void animateFab (int translationY, final int visibilityBefore, final int visibilityAfter) { + animate(fab).setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(Constants.FAB_ANIMATION_TIME) .translationY(translationY) .setListener(new ViewPropertyAnimatorListener() { - @Override - public void onAnimationStart(View view) { - fab.setVisibility(visibilityBefore); - } - - @Override - public void onAnimationEnd(View view) { - fab.setVisibility(visibilityAfter); - } - - @Override - public void onAnimationCancel(View view) { - } + @Override + public void onAnimationStart (View view) { + fab.setVisibility(visibilityBefore); + } + + @Override + public void onAnimationEnd (View view) { + fab.setVisibility(visibilityAfter); + } + + @Override + public void onAnimationCancel (View view) { + } }); - } + } - public void setAllowed(boolean allowed) { - fabAllowed = allowed; - } - + public void setAllowed (boolean allowed) { + fabAllowed = allowed; + } - private int getMarginBottom(View view) { - int marginBottom = 0; - final ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); - if (layoutParams instanceof ViewGroup.MarginLayoutParams) { - marginBottom = ((ViewGroup.MarginLayoutParams) layoutParams).bottomMargin; - } - return marginBottom; - } - - public void setOnFabItemClickedListener(OnFabItemClickedListener onFabItemClickedListener) { - this.onFabItemClickedListener = onFabItemClickedListener; - } - - - public void setOverlay(View overlay) { - this.overlay = overlay; - this.overlay.setOnClickListener(v -> performToggle()); - } - - - public void setOverlay(int colorResurce) { - View overlayView = new View(OmniNotes.getAppContext()); - overlayView.setBackgroundResource(colorResurce); - RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams - .MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); - overlayView.setLayoutParams(params); - overlayView.setVisibility(View.GONE); - overlayView.setOnClickListener(v -> performToggle()); - ViewGroup parent = ((ViewGroup) fab.getParent()); - parent.addView(overlayView, parent.indexOfChild(fab)); - this.overlay = overlayView; - } - public boolean isExpanded() { - return fabExpanded; + private int getMarginBottom (View view) { + int marginBottom = 0; + final ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); + if (layoutParams instanceof ViewGroup.MarginLayoutParams) { + marginBottom = ((ViewGroup.MarginLayoutParams) layoutParams).bottomMargin; } + return marginBottom; + } + + public void setOnFabItemClickedListener (OnFabItemClickedListener onFabItemClickedListener) { + this.onFabItemClickedListener = onFabItemClickedListener; + } + + + public void setOverlay (View overlay) { + this.overlay = overlay; + this.overlay.setOnClickListener(v -> performToggle()); + } + + + public void setOverlay (int colorResurce) { + View overlayView = new View(OmniNotes.getAppContext()); + overlayView.setBackgroundResource(colorResurce); + RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams + .MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); + overlayView.setLayoutParams(params); + overlayView.setVisibility(View.GONE); + overlayView.setOnClickListener(v -> performToggle()); + ViewGroup parent = ((ViewGroup) fab.getParent()); + parent.addView(overlayView, parent.indexOfChild(fab)); + this.overlay = overlayView; + } + + public boolean isExpanded () { + return fabExpanded; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorFrameLayout.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorFrameLayout.java index 145eef2f85..3e79e21c2b 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorFrameLayout.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorFrameLayout.java @@ -21,36 +21,35 @@ import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.FrameLayout; - import it.feio.android.omninotes.models.listeners.OnViewTouchedListener; public class InterceptorFrameLayout extends FrameLayout { - private OnViewTouchedListener mOnViewTouchedListener; + private OnViewTouchedListener mOnViewTouchedListener; - public InterceptorFrameLayout(Context context) { - super(context); - } + public InterceptorFrameLayout (Context context) { + super(context); + } - public InterceptorFrameLayout(Context context, AttributeSet attrs) { - super(context, attrs); - } + public InterceptorFrameLayout (Context context, AttributeSet attrs) { + super(context, attrs); + } - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - if (mOnViewTouchedListener != null) { - mOnViewTouchedListener.onViewTouchOccurred(ev); - } - return super.onInterceptTouchEvent(ev); + @Override + public boolean onInterceptTouchEvent (MotionEvent ev) { + if (mOnViewTouchedListener != null) { + mOnViewTouchedListener.onViewTouchOccurred(ev); } + return super.onInterceptTouchEvent(ev); + } - public void setOnViewTouchedListener(OnViewTouchedListener mOnViewTouchedListener) { - this.mOnViewTouchedListener = mOnViewTouchedListener; - } + public void setOnViewTouchedListener (OnViewTouchedListener mOnViewTouchedListener) { + this.mOnViewTouchedListener = mOnViewTouchedListener; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorLinearLayout.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorLinearLayout.java index dd9a338ff6..2a657fe37d 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorLinearLayout.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/InterceptorLinearLayout.java @@ -21,36 +21,35 @@ import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.LinearLayout; - import it.feio.android.omninotes.models.listeners.OnViewTouchedListener; public class InterceptorLinearLayout extends LinearLayout { - private OnViewTouchedListener mOnViewTouchedListener; + private OnViewTouchedListener mOnViewTouchedListener; - public InterceptorLinearLayout(Context context) { - super(context); - } + public InterceptorLinearLayout (Context context) { + super(context); + } - public InterceptorLinearLayout(Context context, AttributeSet attrs) { - super(context, attrs); - } + public InterceptorLinearLayout (Context context, AttributeSet attrs) { + super(context, attrs); + } - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - if (mOnViewTouchedListener != null) { - mOnViewTouchedListener.onViewTouchOccurred(ev); - } - return super.onInterceptTouchEvent(ev); + @Override + public boolean onInterceptTouchEvent (MotionEvent ev) { + if (mOnViewTouchedListener != null) { + mOnViewTouchedListener.onViewTouchOccurred(ev); } + return super.onInterceptTouchEvent(ev); + } - public void setOnViewTouchedListener(OnViewTouchedListener mOnViewTouchedListener) { - this.mOnViewTouchedListener = mOnViewTouchedListener; - } + public void setOnViewTouchedListener (OnViewTouchedListener mOnViewTouchedListener) { + this.mOnViewTouchedListener = mOnViewTouchedListener; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/NonScrollableListView.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/NonScrollableListView.java index 1cc853204e..f0dd055105 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/NonScrollableListView.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/NonScrollableListView.java @@ -27,39 +27,39 @@ public class NonScrollableListView extends ListView { - public NonScrollableListView(Context context) { - super(context); - } - + public NonScrollableListView (Context context) { + super(context); + } - public NonScrollableListView(Context context, AttributeSet attrs) { - super(context, attrs); - } + public NonScrollableListView (Context context, AttributeSet attrs) { + super(context, attrs); + } - public NonScrollableListView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } + public NonScrollableListView (Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } - public void justifyListViewHeightBasedOnChildren() { - ListAdapter adapter = getAdapter(); + public void justifyListViewHeightBasedOnChildren () { - if (adapter == null) { - return; - } - ViewGroup vg = this; - int totalHeight = 0; - for (int i = 0; i < adapter.getCount(); i++) { - View listItem = adapter.getView(i, null, vg); - listItem.measure(0, 0); - totalHeight += listItem.getMeasuredHeight(); - } + ListAdapter adapter = getAdapter(); - ViewGroup.LayoutParams par = getLayoutParams(); - par.height = totalHeight + (getDividerHeight() * (adapter.getCount() - 1)); - setLayoutParams(par); - requestLayout(); + if (adapter == null) { + return; + } + ViewGroup vg = this; + int totalHeight = 0; + for (int i = 0; i < adapter.getCount(); i++) { + View listItem = adapter.getView(i, null, vg); + listItem.measure(0, 0); + totalHeight += listItem.getMeasuredHeight(); } + + ViewGroup.LayoutParams par = getLayoutParams(); + par.height = totalHeight + (getDividerHeight() * (adapter.getCount() - 1)); + setLayoutParams(par); + requestLayout(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SketchView.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SketchView.java index 26bc4a538c..13148ce4f3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SketchView.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SketchView.java @@ -29,97 +29,95 @@ import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; - -import java.util.ArrayList; - import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.listeners.OnDrawChangedListener; +import java.util.ArrayList; public class SketchView extends View implements OnTouchListener { - private static final float TOUCH_TOLERANCE = 4; + private static final float TOUCH_TOLERANCE = 4; - public static final int STROKE = 0; - public static final int ERASER = 1; - public static final int DEFAULT_STROKE_SIZE = 7; - public static final int DEFAULT_ERASER_SIZE = 50; + public static final int STROKE = 0; + public static final int ERASER = 1; + public static final int DEFAULT_STROKE_SIZE = 7; + public static final int DEFAULT_ERASER_SIZE = 50; - private float strokeSize = DEFAULT_STROKE_SIZE; - private int strokeColor = Color.BLACK; - private float eraserSize = DEFAULT_ERASER_SIZE; - private int backgroundColor = Color.WHITE; + private float strokeSize = DEFAULT_STROKE_SIZE; + private int strokeColor = Color.BLACK; + private float eraserSize = DEFAULT_ERASER_SIZE; + private int backgroundColor = Color.WHITE; - private Path m_Path; - private Paint m_Paint; - private float mX, mY; - private int width, height; + private Path m_Path; + private Paint m_Paint; + private float mX, mY; + private int width, height; - private ArrayList> paths = new ArrayList<>(); - private ArrayList> undonePaths = new ArrayList<>(); - private Context mContext; + private ArrayList> paths = new ArrayList<>(); + private ArrayList> undonePaths = new ArrayList<>(); + private Context mContext; - private Bitmap bitmap; + private Bitmap bitmap; - private int mode = STROKE; + private int mode = STROKE; - private OnDrawChangedListener onDrawChangedListener; + private OnDrawChangedListener onDrawChangedListener; - public SketchView(Context context, AttributeSet attr) { - super(context, attr); + public SketchView (Context context, AttributeSet attr) { + super(context, attr); - this.mContext = context; + this.mContext = context; - setFocusable(true); - setFocusableInTouchMode(true); - setBackgroundColor(backgroundColor); + setFocusable(true); + setFocusableInTouchMode(true); + setBackgroundColor(backgroundColor); - this.setOnTouchListener(this); + this.setOnTouchListener(this); - m_Paint = new Paint(); - m_Paint.setAntiAlias(true); - m_Paint.setDither(true); - m_Paint.setColor(strokeColor); - m_Paint.setStyle(Paint.Style.STROKE); - m_Paint.setStrokeJoin(Paint.Join.ROUND); - m_Paint.setStrokeCap(Paint.Cap.ROUND); - m_Paint.setStrokeWidth(strokeSize); - m_Path = new Path(); - invalidate(); - } + m_Paint = new Paint(); + m_Paint.setAntiAlias(true); + m_Paint.setDither(true); + m_Paint.setColor(strokeColor); + m_Paint.setStyle(Paint.Style.STROKE); + m_Paint.setStrokeJoin(Paint.Join.ROUND); + m_Paint.setStrokeCap(Paint.Cap.ROUND); + m_Paint.setStrokeWidth(strokeSize); + m_Path = new Path(); + invalidate(); + } - public void setMode(int mode) { - if (mode == STROKE || mode == ERASER) - this.mode = mode; + public void setMode (int mode) { + if (mode == STROKE || mode == ERASER) { + this.mode = mode; } - - - public int getMode() { - return this.mode; + } + + + public int getMode () { + return this.mode; + } + + + /** + * Change canvass background and force redraw + * + * @param bitmap saved sketch + */ + public void setBackgroundBitmap (Activity mActivity, Bitmap bitmap) { + if (!bitmap.isMutable()) { + android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig(); + // set default bitmap config if none + if (bitmapConfig == null) { + bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; + } + bitmap = bitmap.copy(bitmapConfig, true); } - - - /** - * Change canvass background and force redraw - * - * @param bitmap saved sketch - */ - public void setBackgroundBitmap(Activity mActivity, Bitmap bitmap) { - if (!bitmap.isMutable()) { - android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig(); - // set default bitmap config if none - if (bitmapConfig == null) { - bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; - } - bitmap = bitmap.copy(bitmapConfig, true); - } - this.bitmap = bitmap; + this.bitmap = bitmap; // this.bitmap = getScaledBitmap(mActivity, bitmap); // mCanvas = new Canvas(bitmap); - } - + } // private Bitmap getScaledBitmap(Activity mActivity, Bitmap bitmap) { // DisplayMetrics display = new DisplayMetrics(); @@ -134,184 +132,185 @@ public void setBackgroundBitmap(Activity mActivity, Bitmap bitmap) { // } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - width = View.MeasureSpec.getSize(widthMeasureSpec); - height = View.MeasureSpec.getSize(heightMeasureSpec); + @Override + protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { + width = View.MeasureSpec.getSize(widthMeasureSpec); + height = View.MeasureSpec.getSize(heightMeasureSpec); + + setMeasuredDimension(width, height); + } + + + public boolean onTouch (View arg0, MotionEvent event) { + float x = event.getX(); + float y = event.getY(); - setMeasuredDimension(width, height); + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + touch_start(x, y); + invalidate(); + break; + case MotionEvent.ACTION_MOVE: + touch_move(x, y); + invalidate(); + break; + case MotionEvent.ACTION_UP: + invalidate(); + break; + default: + LogDelegate.e("Wrong element choosen: " + event.getAction()); } + return true; + } - public boolean onTouch(View arg0, MotionEvent event) { - float x = event.getX(); - float y = event.getY(); - - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - touch_start(x, y); - invalidate(); - break; - case MotionEvent.ACTION_MOVE: - touch_move(x, y); - invalidate(); - break; - case MotionEvent.ACTION_UP: - invalidate(); - break; - default: - LogDelegate.e("Wrong element choosen: " + event.getAction()); - } - return true; + @Override + protected void onDraw (Canvas canvas) { + if (bitmap != null) { + canvas.drawBitmap(bitmap, 0, 0, null); } + for (Pair p : paths) { + canvas.drawPath(p.first, p.second); + } - @Override - protected void onDraw(Canvas canvas) { - if (bitmap != null) { - canvas.drawBitmap(bitmap, 0, 0, null); - } + onDrawChangedListener.onDrawChanged(); + } - for (Pair p : paths) { - canvas.drawPath(p.first, p.second); - } - onDrawChangedListener.onDrawChanged(); - } + private void touch_start (float x, float y) { + // Clearing undone list + undonePaths.clear(); + if (mode == ERASER) { + m_Paint.setColor(backgroundColor); + m_Paint.setStrokeWidth(eraserSize); + } else { + m_Paint.setColor(strokeColor); + m_Paint.setStrokeWidth(strokeSize); + } - private void touch_start(float x, float y) { - // Clearing undone list - undonePaths.clear(); - - if (mode == ERASER) { - m_Paint.setColor(backgroundColor); - m_Paint.setStrokeWidth(eraserSize); - } else { - m_Paint.setColor(strokeColor); - m_Paint.setStrokeWidth(strokeSize); - } - - // Avoids that a sketch with just erasures is saved - if (!(paths.size() == 0 && mode == ERASER && bitmap == null)) { - m_Path=new Path(); - paths.add(new Pair<>(m_Path, new Paint(m_Paint))); - } - - m_Path.moveTo(x, y); - m_Path.lineTo(++x, y); // for draw a one touch path - mX = x; - mY = y; + // Avoids that a sketch with just erasures is saved + if (!(paths.size() == 0 && mode == ERASER && bitmap == null)) { + m_Path = new Path(); + paths.add(new Pair<>(m_Path, new Paint(m_Paint))); } + m_Path.moveTo(x, y); + m_Path.lineTo(++x, y); // for draw a one touch path + mX = x; + mY = y; + } - private void touch_move(float x, float y) { - m_Path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); - mX = x; - mY = y; - } + private void touch_move (float x, float y) { + m_Path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); + mX = x; + mY = y; + } - /** - * Returns a new bitmap associated with a drawn canvas - * - * @return background bitmap with a paths drawn on it - */ - public Bitmap getBitmap() { - if (paths.size() == 0) - return null; - - if (bitmap == null) { - bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - bitmap.eraseColor(backgroundColor); - } - Canvas canvas = new Canvas(bitmap); - for (Pair p : paths) { - canvas.drawPath(p.first, p.second); - } - return bitmap; - } + /** + * Returns a new bitmap associated with a drawn canvas + * + * @return background bitmap with a paths drawn on it + */ + public Bitmap getBitmap () { + if (paths.size() == 0) { + return null; + } - public void undo() { - if (!paths.isEmpty()) { - undonePaths.add(paths.remove(paths.size() - 1)); - invalidate(); - } + if (bitmap == null) { + bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + bitmap.eraseColor(backgroundColor); } + Canvas canvas = new Canvas(bitmap); + for (Pair p : paths) { + canvas.drawPath(p.first, p.second); + } + return bitmap; + } - public void redo() { - if (!undonePaths.isEmpty()) { - paths.add(undonePaths.remove(undonePaths.size() - 1)); - invalidate(); - } + public void undo () { + if (!paths.isEmpty()) { + undonePaths.add(paths.remove(paths.size() - 1)); + invalidate(); } + } - public int getUndoneCount() { - return undonePaths.size(); + public void redo () { + if (!undonePaths.isEmpty()) { + paths.add(undonePaths.remove(undonePaths.size() - 1)); + invalidate(); } + } - public ArrayList> getPaths() { - return paths; - } + public int getUndoneCount () { + return undonePaths.size(); + } - public void setPaths(ArrayList> paths) { - this.paths = paths; - } + public ArrayList> getPaths () { + return paths; + } - public ArrayList> getUndonePaths() { - return undonePaths; - } + public void setPaths (ArrayList> paths) { + this.paths = paths; + } - public void setUndonePaths(ArrayList> undonePaths) { - this.undonePaths = undonePaths; - } + public ArrayList> getUndonePaths () { + return undonePaths; + } - public int getStrokeSize() { - return Math.round(this.strokeSize); - } + public void setUndonePaths (ArrayList> undonePaths) { + this.undonePaths = undonePaths; + } + + public int getStrokeSize () { + return Math.round(this.strokeSize); + } - public void setSize(int size, int eraserOrStroke) { - switch (eraserOrStroke) { - case STROKE: - strokeSize = size; - break; - case ERASER: - eraserSize = size; - break; - default: - LogDelegate.e("Wrong element choosen: " + eraserOrStroke); - } + public void setSize (int size, int eraserOrStroke) { + switch (eraserOrStroke) { + case STROKE: + strokeSize = size; + break; + case ERASER: + eraserSize = size; + break; + default: + LogDelegate.e("Wrong element choosen: " + eraserOrStroke); } + } - public int getStrokeColor() { - return this.strokeColor; - } + public int getStrokeColor () { + return this.strokeColor; + } - public void setStrokeColor(int color) { - strokeColor = color; - } + public void setStrokeColor (int color) { + strokeColor = color; + } - public void erase() { - paths.clear(); - undonePaths.clear(); - invalidate(); - } + public void erase () { + paths.clear(); + undonePaths.clear(); + invalidate(); + } - public void setOnDrawChangedListener(OnDrawChangedListener listener) { - this.onDrawChangedListener = listener; - } + + public void setOnDrawChangedListener (OnDrawChangedListener listener) { + this.onDrawChangedListener = listener; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SquareImageView.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SquareImageView.java index 33b30ed69f..74f1fd200f 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SquareImageView.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/SquareImageView.java @@ -21,48 +21,47 @@ import android.os.AsyncTask; import android.util.AttributeSet; import android.widget.ImageView; - import java.lang.ref.WeakReference; public class SquareImageView extends ImageView { - private WeakReference> mAsyncTaskReference; + private WeakReference> mAsyncTaskReference; - public SquareImageView(Context context) { - super(context); - setScaleType(ScaleType.CENTER_CROP); - } + public SquareImageView (Context context) { + super(context); + setScaleType(ScaleType.CENTER_CROP); + } - public SquareImageView(Context context, AttributeSet attrs) { - super(context, attrs); - } + public SquareImageView (Context context, AttributeSet attrs) { + super(context, attrs); + } - public SquareImageView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } + public SquareImageView (Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); - } + @Override + protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); + } - public void setAsyncTask(AsyncTask mAsyncTask) { - this.mAsyncTaskReference = new WeakReference>(mAsyncTask); - } + public void setAsyncTask (AsyncTask mAsyncTask) { + this.mAsyncTaskReference = new WeakReference>(mAsyncTask); + } - public AsyncTask getAsyncTask() { - if (mAsyncTaskReference != null) { - return mAsyncTaskReference.get(); - } else { - return null; - } + public AsyncTask getAsyncTask () { + if (mAsyncTaskReference != null) { + return mAsyncTaskReference.get(); + } else { + return null; } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/VerticalSeekBar.java b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/VerticalSeekBar.java index 4ab6cc1ad6..5fbca76a98 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/models/views/VerticalSeekBar.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/models/views/VerticalSeekBar.java @@ -26,103 +26,107 @@ public class VerticalSeekBar extends SeekBar { - protected OnSeekBarChangeListener changeListener; - protected int x, y, z, w; + protected OnSeekBarChangeListener changeListener; + protected int x, y, z, w; - public VerticalSeekBar(Context context) { - super(context); - } + public VerticalSeekBar (Context context) { + super(context); + } - public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } + public VerticalSeekBar (Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - public VerticalSeekBar(Context context, AttributeSet attrs) { - super(context, attrs); - } + public VerticalSeekBar (Context context, AttributeSet attrs) { + super(context, attrs); + } - @Override - protected synchronized void onSizeChanged(int w, int h, int oldw, int oldh) { - super.onSizeChanged(h, w, oldh, oldw); + @Override + protected synchronized void onSizeChanged (int w, int h, int oldw, int oldh) { + super.onSizeChanged(h, w, oldh, oldw); - this.x = w; - this.y = h; - this.z = oldw; - this.w = oldh; - } + this.x = w; + this.y = h; + this.z = oldw; + this.w = oldh; + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(heightMeasureSpec, widthMeasureSpec); - setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth()); - } - + @Override + protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(heightMeasureSpec, widthMeasureSpec); + setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth()); + } - @Override - protected void onDraw(Canvas c) { - c.rotate(-90); - c.translate(-getHeight(), 0); - super.onDraw(c); - } + @Override + protected void onDraw (Canvas c) { + c.rotate(-90); + c.translate(-getHeight(), 0); + super.onDraw(c); + } - @Override - public boolean onTouchEvent(MotionEvent event) { - if (!isEnabled()) { - return false; - } - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - setSelected(true); - setPressed(true); - if (changeListener != null) - changeListener.onStartTrackingTouch(this); - break; - case MotionEvent.ACTION_UP: - setSelected(false); - setPressed(false); - if (changeListener != null) - changeListener.onStopTrackingTouch(this); - break; - case MotionEvent.ACTION_MOVE: - int progress = getMax() - - (int) (getMax() * event.getY() / getHeight()); - setProgress(progress); - onSizeChanged(getWidth(), getHeight(), 0, 0); - if (changeListener != null) - changeListener.onProgressChanged(this, progress, true); - break; - - case MotionEvent.ACTION_CANCEL: - break; - } - return true; + @Override + public boolean onTouchEvent (MotionEvent event) { + if (!isEnabled()) { + return false; } + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + setSelected(true); + setPressed(true); + if (changeListener != null) { + changeListener.onStartTrackingTouch(this); + } + break; + case MotionEvent.ACTION_UP: + setSelected(false); + setPressed(false); + if (changeListener != null) { + changeListener.onStopTrackingTouch(this); + } + break; + case MotionEvent.ACTION_MOVE: + int progress = getMax() + - (int) (getMax() * event.getY() / getHeight()); + setProgress(progress); + onSizeChanged(getWidth(), getHeight(), 0, 0); + if (changeListener != null) { + changeListener.onProgressChanged(this, progress, true); + } + break; - @Override - public synchronized void setOnSeekBarChangeListener( - OnSeekBarChangeListener listener) { - changeListener = listener; + case MotionEvent.ACTION_CANCEL: + break; } + return true; + } + + @Override + public synchronized void setOnSeekBarChangeListener ( + OnSeekBarChangeListener listener) { + changeListener = listener; + } - @Override - public synchronized void setProgress(int progress) { - if (progress >= 0) - super.setProgress(progress); - else - super.setProgress(0); - onSizeChanged(x, y, z, w); - if (changeListener != null) - changeListener.onProgressChanged(this, progress, false); + @Override + public synchronized void setProgress (int progress) { + if (progress >= 0) { + super.setProgress(progress); + } else { + super.setProgress(0); + } + onSizeChanged(x, y, z, w); + if (changeListener != null) { + changeListener.onProgressChanged(this, progress, false); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/receiver/AlarmReceiver.java b/omniNotes/src/main/java/it/feio/android/omninotes/receiver/AlarmReceiver.java index a2b6c815fa..e71cc2013f 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/receiver/AlarmReceiver.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/receiver/AlarmReceiver.java @@ -25,9 +25,6 @@ import android.os.Build; import android.os.Bundle; import android.text.Spanned; - -import java.util.List; - import it.feio.android.omninotes.R; import it.feio.android.omninotes.SnoozeActivity; import it.feio.android.omninotes.db.DbHelper; @@ -41,105 +38,113 @@ import it.feio.android.omninotes.utils.TextHelper; import it.feio.android.omninotes.utils.notifications.NotificationChannels; import it.feio.android.omninotes.utils.notifications.NotificationsHelper; +import java.util.List; public class AlarmReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context mContext, Intent intent) { - try { - Note note = ParcelableUtil.unmarshall(intent.getExtras().getByteArray(Constants.INTENT_NOTE), Note - .CREATOR); - createNotification(mContext, note); - SnoozeActivity.setNextRecurrentReminder(note); - updateNote(note); - } catch (Exception e) { - LogDelegate.e("Error on receiving reminder", e); - } - } - - private void updateNote(Note note) { - note.setArchived(false); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && !NotificationListener.isRunning()) { - note.setReminderFired(true); - } - DbHelper.getInstance().updateNote(note, false); - } - - private void createNotification(Context mContext, Note note) { - - // Retrieving preferences - SharedPreferences prefs = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - - // Prepare text contents - Spanned[] titleAndContent = TextHelper.parseTitleAndContent(mContext, note); - String title = TextHelper.getAlternativeTitle(mContext, note, titleAndContent[0]); - String text = titleAndContent[1].toString(); - - Intent snoozeIntent = new Intent(mContext, SnoozeActivity.class); - snoozeIntent.setAction(Constants.ACTION_SNOOZE); - snoozeIntent.putExtra(Constants.INTENT_NOTE, (android.os.Parcelable) note); - PendingIntent piSnooze = PendingIntent.getActivity(mContext, getUniqueRequestCode(note), snoozeIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - - Intent postponeIntent = new Intent(mContext, SnoozeActivity.class); - postponeIntent.setAction(Constants.ACTION_POSTPONE); - postponeIntent.putExtra(Constants.INTENT_NOTE, (android.os.Parcelable) note); - PendingIntent piPostpone = PendingIntent.getActivity(mContext, getUniqueRequestCode(note), postponeIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - - String snoozeDelay = mContext.getSharedPreferences(Constants.PREFS_NAME, - Context.MODE_MULTI_PROCESS).getString("settings_notification_snooze_delay", "10"); - - // Next create the bundle and initialize it - Intent intent = new Intent(mContext, SnoozeActivity.class); - Bundle bundle = new Bundle(); - bundle.putParcelable(Constants.INTENT_NOTE, note); - intent.putExtras(bundle); - - // Sets the Activity to start in a new, empty task - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - // Workaround to fix problems with multiple notifications - intent.setAction(Constants.ACTION_NOTIFICATION_CLICK + Long.toString(System.currentTimeMillis())); - - // Creates the PendingIntent - PendingIntent notifyIntent = PendingIntent.getActivity(mContext, getUniqueRequestCode(note), intent, - PendingIntent.FLAG_UPDATE_CURRENT); - - NotificationsHelper notificationsHelper = new NotificationsHelper(mContext); - notificationsHelper.createNotification(NotificationChannels.NotificationChannelNames.Reminders, R.drawable.ic_stat_notification, title, notifyIntent).setLedActive() - .setMessage(text); - - List attachments = note.getAttachmentsList(); - if (!attachments.isEmpty() && !attachments.get(0).getMime_type().equals(Constants.MIME_TYPE_FILES)) { - Bitmap notificationIcon = BitmapHelper.getBitmapFromAttachment(mContext, note.getAttachmentsList().get(0), 128, 128); - notificationsHelper.setLargeIcon(notificationIcon); + @Override + public void onReceive (Context mContext, Intent intent) { + try { + Note note = ParcelableUtil.unmarshall(intent.getExtras().getByteArray(Constants.INTENT_NOTE), Note + .CREATOR); + createNotification(mContext, note); + SnoozeActivity.setNextRecurrentReminder(note); + updateNote(note); + } catch (Exception e) { + LogDelegate.e("Error on receiving reminder", e); + } + } + + private void updateNote (Note note) { + note.setArchived(false); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && !NotificationListener.isRunning()) { + note.setReminderFired(true); + } + DbHelper.getInstance().updateNote(note, false); + } + + private void createNotification (Context mContext, Note note) { + + // Retrieving preferences + SharedPreferences prefs = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + + // Prepare text contents + Spanned[] titleAndContent = TextHelper.parseTitleAndContent(mContext, note); + String title = TextHelper.getAlternativeTitle(mContext, note, titleAndContent[0]); + String text = titleAndContent[1].toString(); + + Intent snoozeIntent = new Intent(mContext, SnoozeActivity.class); + snoozeIntent.setAction(Constants.ACTION_SNOOZE); + snoozeIntent.putExtra(Constants.INTENT_NOTE, (android.os.Parcelable) note); + PendingIntent piSnooze = PendingIntent.getActivity(mContext, getUniqueRequestCode(note), snoozeIntent, + PendingIntent.FLAG_UPDATE_CURRENT); + + Intent postponeIntent = new Intent(mContext, SnoozeActivity.class); + postponeIntent.setAction(Constants.ACTION_POSTPONE); + postponeIntent.putExtra(Constants.INTENT_NOTE, (android.os.Parcelable) note); + PendingIntent piPostpone = PendingIntent.getActivity(mContext, getUniqueRequestCode(note), postponeIntent, + PendingIntent.FLAG_UPDATE_CURRENT); + + String snoozeDelay = mContext.getSharedPreferences(Constants.PREFS_NAME, + Context.MODE_MULTI_PROCESS).getString("settings_notification_snooze_delay", "10"); + + // Next create the bundle and initialize it + Intent intent = new Intent(mContext, SnoozeActivity.class); + Bundle bundle = new Bundle(); + bundle.putParcelable(Constants.INTENT_NOTE, note); + intent.putExtras(bundle); + + // Sets the Activity to start in a new, empty task + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + // Workaround to fix problems with multiple notifications + intent.setAction(Constants.ACTION_NOTIFICATION_CLICK + System.currentTimeMillis()); + + // Creates the PendingIntent + PendingIntent notifyIntent = PendingIntent.getActivity(mContext, getUniqueRequestCode(note), intent, + PendingIntent.FLAG_UPDATE_CURRENT); + + NotificationsHelper notificationsHelper = new NotificationsHelper(mContext); + notificationsHelper.createNotification(NotificationChannels.NotificationChannelNames.Reminders, + R.drawable.ic_stat_notification, title, notifyIntent).setLedActive() + .setMessage(text); + + List attachments = note.getAttachmentsList(); + if (!attachments.isEmpty() && !attachments.get(0).getMime_type().equals(Constants.MIME_TYPE_FILES)) { + Bitmap notificationIcon = BitmapHelper.getBitmapFromAttachment(mContext, note.getAttachmentsList().get(0), 128, + 128); + notificationsHelper.setLargeIcon(notificationIcon); + } + + notificationsHelper.getBuilder() + .addAction(R.drawable.ic_material_reminder_time_light, + TextHelper.capitalize(mContext.getString(R.string.snooze)) + ": " + snoozeDelay, piSnooze) + .addAction(R.drawable.ic_remind_later_light, TextHelper.capitalize(mContext.getString(R.string + .add_reminder)), piPostpone); + + setRingtone(prefs, notificationsHelper); + setVibrate(prefs, notificationsHelper); + + notificationsHelper.show(note.get_id()); + } + + + private void setRingtone (SharedPreferences prefs, NotificationsHelper notificationsHelper) { + String ringtone = prefs.getString("settings_notification_ringtone", null); + if (ringtone != null) { + notificationsHelper.setRingtone(ringtone); } + } - notificationsHelper.getBuilder() - .addAction(R.drawable.ic_material_reminder_time_light, TextHelper.capitalize(mContext.getString(R.string.snooze)) + ": " + snoozeDelay, piSnooze) - .addAction(R.drawable.ic_remind_later_light, TextHelper.capitalize(mContext.getString(R.string - .add_reminder)), piPostpone); - setRingtone(prefs, notificationsHelper); - setVibrate(prefs, notificationsHelper); - - notificationsHelper.show(note.get_id()); - } - - - private void setRingtone(SharedPreferences prefs, NotificationsHelper notificationsHelper) { - String ringtone = prefs.getString("settings_notification_ringtone", null); - if (ringtone != null) notificationsHelper.setRingtone(ringtone); - } - - - private void setVibrate(SharedPreferences prefs, NotificationsHelper notificationsHelper) { - if (prefs.getBoolean("settings_notification_vibration", true)) notificationsHelper.setVibration(); - } + private void setVibrate (SharedPreferences prefs, NotificationsHelper notificationsHelper) { + if (prefs.getBoolean("settings_notification_vibration", true)) { + notificationsHelper.setVibration(); + } + } - private int getUniqueRequestCode(Note note) { - return note.get_id().intValue(); - } + private int getUniqueRequestCode (Note note) { + return note.get_id().intValue(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/receiver/BootCompleteReceiver.java b/omniNotes/src/main/java/it/feio/android/omninotes/receiver/BootCompleteReceiver.java index 80327595b9..32c26324a3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/receiver/BootCompleteReceiver.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/receiver/BootCompleteReceiver.java @@ -19,20 +19,19 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; - import it.feio.android.omninotes.async.AlarmRestoreOnRebootService; import it.feio.android.omninotes.helpers.LogDelegate; public class BootCompleteReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context ctx, Intent intent) { - LogDelegate.i("System rebooted: refreshing reminders"); - if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { - AlarmRestoreOnRebootService.enqueueWork(ctx, intent); - } + @Override + public void onReceive (Context ctx, Intent intent) { + LogDelegate.i("System rebooted: refreshing reminders"); + if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { + AlarmRestoreOnRebootService.enqueueWork(ctx, intent); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/services/NotificationListener.java b/omniNotes/src/main/java/it/feio/android/omninotes/services/NotificationListener.java index 036df0fc7e..29b95dc9eb 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/services/NotificationListener.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/services/NotificationListener.java @@ -23,7 +23,6 @@ import android.provider.Settings; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.async.bus.NotificationRemovedEvent; @@ -37,49 +36,49 @@ public class NotificationListener extends NotificationListenerService { - @Override - public void onCreate() { - super.onCreate(); - EventBus.getDefault().register(this); - } + @Override + public void onCreate () { + super.onCreate(); + EventBus.getDefault().register(this); + } - @Override - public void onDestroy() { - super.onDestroy(); - EventBus.getDefault().unregister(this); - } + @Override + public void onDestroy () { + super.onDestroy(); + EventBus.getDefault().unregister(this); + } - @Override - public void onNotificationPosted(StatusBarNotification sbn) { - LogDelegate.d("Notification posted for note: " + sbn.getId()); - } + @Override + public void onNotificationPosted (StatusBarNotification sbn) { + LogDelegate.d("Notification posted for note: " + sbn.getId()); + } - @Override - public void onNotificationRemoved(StatusBarNotification sbn) { - if (sbn.getPackageName().equals(getPackageName())) { - EventBus.getDefault().post(new NotificationRemovedEvent(sbn)); - LogDelegate.d("Notification removed for note: " + sbn.getId()); - } - } + @Override + public void onNotificationRemoved (StatusBarNotification sbn) { + if (sbn.getPackageName().equals(getPackageName())) { + EventBus.getDefault().post(new NotificationRemovedEvent(sbn)); + LogDelegate.d("Notification removed for note: " + sbn.getId()); + } + } - public void onEventAsync(NotificationRemovedEvent event) { - Long nodeId = Long.valueOf(event.statusBarNotification.getTag()); - Note note = DbHelper.getInstance().getNote(nodeId); - if (!DateUtils.isFuture(note.getAlarm())) { - DbHelper.getInstance().setReminderFired(nodeId, true); - } - } + public void onEventAsync (NotificationRemovedEvent event) { + Long nodeId = Long.valueOf(event.statusBarNotification.getTag()); + Note note = DbHelper.getInstance().getNote(nodeId); + if (!DateUtils.isFuture(note.getAlarm())) { + DbHelper.getInstance().setReminderFired(nodeId, true); + } + } - public static boolean isRunning() { - ContentResolver contentResolver = OmniNotes.getAppContext().getContentResolver(); - String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners"); - return enabledNotificationListeners != null && enabledNotificationListeners.contains(NotificationListener - .class.getSimpleName()); - } + public static boolean isRunning () { + ContentResolver contentResolver = OmniNotes.getAppContext().getContentResolver(); + String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners"); + return enabledNotificationListeners != null && enabledNotificationListeners.contains(NotificationListener + .class.getSimpleName()); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/AlphaManager.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/AlphaManager.java index 54c52d8d45..4d73434bbf 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/AlphaManager.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/AlphaManager.java @@ -22,13 +22,13 @@ public class AlphaManager { - - private AlphaManager(){} - @SuppressLint("NewApi") - public static void setAlpha(View v, float alpha) { - if (v != null) { - v.setAlpha(alpha); - } + private AlphaManager () {} + + @SuppressLint("NewApi") + public static void setAlpha (View v, float alpha) { + if (v != null) { + v.setAlpha(alpha); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/AnimationsHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/AnimationsHelper.java index fce21a1c8a..bc7c6c9d2b 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/AnimationsHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/AnimationsHelper.java @@ -33,101 +33,101 @@ public class AnimationsHelper { - - private AnimationsHelper(){} - - public static void zoomListItem(Context context, final View view, ImageView expandedImageView, View targetView, - AnimatorListenerAdapter animatorListenerAdapter) { - final long animationDuration = context.getResources().getInteger(R.integer.zooming_view_anim_time); - - // Calculate the starting and ending bounds for the zoomed-in image. - final Rect startBounds = new Rect(); - final Rect finalBounds = new Rect(); - final Point globalOffset = new Point(); - - // The start bounds are the global visible rectangle of the thumbnail, - // and the final bounds are the global visible rectangle of the container - // view. Also set the container view's offset as the origin for the - // bounds, since that's the origin for the positioning animation - // properties (X, Y). - view.getGlobalVisibleRect(startBounds); - targetView.getGlobalVisibleRect(finalBounds, globalOffset); - startBounds.offset(-globalOffset.x, -globalOffset.y); - finalBounds.offset(-globalOffset.x, -globalOffset.y); - - // Adjust the start bounds to be the same aspect ratio as the final - // bounds using the "center crop" technique. This prevents undesirable - // stretching during the animation. Also calculate the start scaling - // factor (the end scaling factor is always 1.0). - float startScale; - if ((float) finalBounds.width() / finalBounds.height() - > (float) startBounds.width() / startBounds.height()) { - // Extend start bounds horizontally - startScale = (float) startBounds.height() / finalBounds.height(); - float startWidth = startScale * finalBounds.width(); - float deltaWidth = (startWidth - startBounds.width()) / 2; - startBounds.left -= deltaWidth; - startBounds.right += deltaWidth; - } else { - // Extend start bounds vertically - startScale = (float) startBounds.width() / finalBounds.width(); - float startHeight = startScale * finalBounds.height(); - float deltaHeight = (startHeight - startBounds.height()) / 2; - startBounds.top -= deltaHeight; - startBounds.bottom += deltaHeight; - } - // Hide the thumbnail and show the zoomed-in view. When the animation - // begins, it will position the zoomed-in view in the place of the - // thumbnail. - view.setAlpha(0f); - expandedImageView.setVisibility(View.VISIBLE); - - // Construct and run the parallel animation of the four translation and - // scale properties (X, Y, SCALE_X, and SCALE_Y). - AnimatorSet set = new AnimatorSet(); - set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left)) - .with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top)) - .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f)) - .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f)); - set.setDuration(animationDuration); - set.setInterpolator(new DecelerateInterpolator()); - set.addListener(animatorListenerAdapter); - set.start(); + private AnimationsHelper () {} + + public static void zoomListItem (Context context, final View view, ImageView expandedImageView, View targetView, + AnimatorListenerAdapter animatorListenerAdapter) { + final long animationDuration = context.getResources().getInteger(R.integer.zooming_view_anim_time); + + // Calculate the starting and ending bounds for the zoomed-in image. + final Rect startBounds = new Rect(); + final Rect finalBounds = new Rect(); + final Point globalOffset = new Point(); + + // The start bounds are the global visible rectangle of the thumbnail, + // and the final bounds are the global visible rectangle of the container + // view. Also set the container view's offset as the origin for the + // bounds, since that's the origin for the positioning animation + // properties (X, Y). + view.getGlobalVisibleRect(startBounds); + targetView.getGlobalVisibleRect(finalBounds, globalOffset); + startBounds.offset(-globalOffset.x, -globalOffset.y); + finalBounds.offset(-globalOffset.x, -globalOffset.y); + + // Adjust the start bounds to be the same aspect ratio as the final + // bounds using the "center crop" technique. This prevents undesirable + // stretching during the animation. Also calculate the start scaling + // factor (the end scaling factor is always 1.0). + float startScale; + if ((float) finalBounds.width() / finalBounds.height() + > (float) startBounds.width() / startBounds.height()) { + // Extend start bounds horizontally + startScale = (float) startBounds.height() / finalBounds.height(); + float startWidth = startScale * finalBounds.width(); + float deltaWidth = (startWidth - startBounds.width()) / 2; + startBounds.left -= deltaWidth; + startBounds.right += deltaWidth; + } else { + // Extend start bounds vertically + startScale = (float) startBounds.width() / finalBounds.width(); + float startHeight = startScale * finalBounds.height(); + float deltaHeight = (startHeight - startBounds.height()) / 2; + startBounds.top -= deltaHeight; + startBounds.bottom += deltaHeight; } + // Hide the thumbnail and show the zoomed-in view. When the animation + // begins, it will position the zoomed-in view in the place of the + // thumbnail. + view.setAlpha(0f); + expandedImageView.setVisibility(View.VISIBLE); + + // Construct and run the parallel animation of the four translation and + // scale properties (X, Y, SCALE_X, and SCALE_Y). + AnimatorSet set = new AnimatorSet(); + set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left)) + .with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top)) + .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f)) + .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f)); + set.setDuration(animationDuration); + set.setInterpolator(new DecelerateInterpolator()); + set.addListener(animatorListenerAdapter); + set.start(); + } + + + public static void expandOrCollapse (final View v, boolean expand) { + TranslateAnimation anim; + if (expand) { + anim = new TranslateAnimation(0.0f, 0.0f, -v.getHeight(), 0.0f); + v.setVisibility(View.VISIBLE); + } else { + anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, -v.getHeight()); + Animation.AnimationListener collapselistener = new Animation.AnimationListener() { + @Override + public void onAnimationStart (Animation animation) { + // Useless + } - public static void expandOrCollapse(final View v, boolean expand) { - TranslateAnimation anim; - if (expand) { - anim = new TranslateAnimation(0.0f, 0.0f, -v.getHeight(), 0.0f); - v.setVisibility(View.VISIBLE); - } else { - anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, -v.getHeight()); - Animation.AnimationListener collapselistener = new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - // Useless - } - - - @Override - public void onAnimationRepeat(Animation animation) { - // Useless - } + @Override + public void onAnimationRepeat (Animation animation) { + // Useless + } - @Override - public void onAnimationEnd(Animation animation) { - v.setVisibility(View.GONE); - } - }; - anim.setAnimationListener(collapselistener); + @Override + public void onAnimationEnd (Animation animation) { + v.setVisibility(View.GONE); } + }; - anim.setDuration(300); - anim.setInterpolator(new AccelerateInterpolator(0.5f)); - v.startAnimation(anim); + anim.setAnimationListener(collapselistener); } + + anim.setDuration(300); + anim.setInterpolator(new AccelerateInterpolator(0.5f)); + v.startAnimation(anim); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/AssetUtils.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/AssetUtils.java index f446e520b9..5acccced58 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/AssetUtils.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/AssetUtils.java @@ -17,28 +17,27 @@ package it.feio.android.omninotes.utils; import android.content.res.AssetManager; - import java.io.IOException; import java.util.Arrays; public class AssetUtils { - public static boolean exists(String fileName, String path, - AssetManager assetManager) throws IOException { - for (String currentFileName : assetManager.list(path)) { - if (currentFileName.equals(fileName)) { - return true; - } - } - return false; - } + public static boolean exists (String fileName, String path, + AssetManager assetManager) throws IOException { + for (String currentFileName : assetManager.list(path)) { + if (currentFileName.equals(fileName)) { + return true; + } + } + return false; + } - public static String[] list(String path, AssetManager assetManager) - throws IOException { - String[] files = assetManager.list(path); - Arrays.sort(files); - return files; - } + public static String[] list (String path, AssetManager assetManager) + throws IOException { + String[] files = assetManager.list(path); + Arrays.sort(files); + return files; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/BitmapHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/BitmapHelper.java index ef46b24292..42208a07ed 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/BitmapHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/BitmapHelper.java @@ -21,91 +21,88 @@ import android.media.ThumbnailUtils; import android.net.Uri; import android.text.TextUtils; - import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; - -import org.apache.commons.io.FilenameUtils; - -import java.util.concurrent.ExecutionException; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; import it.feio.android.omninotes.helpers.AttachmentsHelper; import it.feio.android.omninotes.models.Attachment; import it.feio.android.simplegallery.util.BitmapUtils; +import java.util.concurrent.ExecutionException; +import org.apache.commons.io.FilenameUtils; public class BitmapHelper { - /** - * Retrieves a the bitmap relative to attachment based on mime type - */ - public static Bitmap getBitmapFromAttachment(Context mContext, Attachment mAttachment, int width, int height) { - Bitmap bmp = null; - String path; - mAttachment.getUri().getPath(); - - // Video or image - if (AttachmentsHelper.typeOf(mAttachment, Constants.MIME_TYPE_VIDEO, Constants.MIME_TYPE_IMAGE, Constants.MIME_TYPE_SKETCH)) { - try { - bmp = Glide.with(OmniNotes.getAppContext()).asBitmap() - .apply(new RequestOptions() - .centerCrop() - .error(R.drawable.attachment_broken)) - .load(mAttachment.getUri()) - .submit(width, height).get(); - } catch (NullPointerException | InterruptedException | ExecutionException e) { - bmp = null; - } + /** + * Retrieves a the bitmap relative to attachment based on mime type + */ + public static Bitmap getBitmapFromAttachment (Context mContext, Attachment mAttachment, int width, int height) { + Bitmap bmp = null; + String path; + mAttachment.getUri().getPath(); - // Audio - } else if (Constants.MIME_TYPE_AUDIO.equals(mAttachment.getMime_type())) { - bmp = ThumbnailUtils.extractThumbnail( - BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources().openRawResource(R - .raw.play), width, height), width, height); + // Video or image + if (AttachmentsHelper.typeOf(mAttachment, Constants.MIME_TYPE_VIDEO, Constants.MIME_TYPE_IMAGE, + Constants.MIME_TYPE_SKETCH)) { + try { + bmp = Glide.with(OmniNotes.getAppContext()).asBitmap() + .apply(new RequestOptions() + .centerCrop() + .error(R.drawable.attachment_broken)) + .load(mAttachment.getUri()) + .submit(width, height).get(); + } catch (NullPointerException | InterruptedException | ExecutionException e) { + bmp = null; + } - // File - } else if (Constants.MIME_TYPE_FILES.equals(mAttachment.getMime_type())) { + // Audio + } else if (Constants.MIME_TYPE_AUDIO.equals(mAttachment.getMime_type())) { + bmp = ThumbnailUtils.extractThumbnail( + BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources().openRawResource(R + .raw.play), width, height), width, height); - // vCard - if (Constants.MIME_TYPE_CONTACT_EXT.equals(FilenameUtils.getExtension(mAttachment.getName()))) { - bmp = ThumbnailUtils.extractThumbnail( - BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources().openRawResource(R - .raw.vcard), width, height), width, height); - } else { - bmp = ThumbnailUtils.extractThumbnail( - BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources().openRawResource(R - .raw.files), width, height), width, height); - } - } + // File + } else if (Constants.MIME_TYPE_FILES.equals(mAttachment.getMime_type())) { - return bmp; + // vCard + if (Constants.MIME_TYPE_CONTACT_EXT.equals(FilenameUtils.getExtension(mAttachment.getName()))) { + bmp = ThumbnailUtils.extractThumbnail( + BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources().openRawResource(R + .raw.vcard), width, height), width, height); + } else { + bmp = ThumbnailUtils.extractThumbnail( + BitmapUtils.decodeSampledBitmapFromResourceMemOpt(mContext.getResources().openRawResource(R + .raw.files), width, height), width, height); + } } + return bmp; + } - public static Uri getThumbnailUri(Context mContext, Attachment mAttachment) { - Uri uri = mAttachment.getUri(); - String mimeType = StorageHelper.getMimeType(uri.toString()); - if (!TextUtils.isEmpty(mimeType)) { - String type = mimeType.split("/")[0]; - String subtype = mimeType.split("/")[1]; - switch (type) { - case "image": - case "video": - // Nothing to do, bitmap will be retrieved from this - break; - case "audio": - uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.play); - break; - default: - int drawable = "x-vcard".equals(subtype) ? R.raw.vcard : R.raw.files; - uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + drawable); - break; - } - } else { - uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.files); - } - return uri; - } + + public static Uri getThumbnailUri (Context mContext, Attachment mAttachment) { + Uri uri = mAttachment.getUri(); + String mimeType = StorageHelper.getMimeType(uri.toString()); + if (!TextUtils.isEmpty(mimeType)) { + String type = mimeType.split("/")[0]; + String subtype = mimeType.split("/")[1]; + switch (type) { + case "image": + case "video": + // Nothing to do, bitmap will be retrieved from this + break; + case "audio": + uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.play); + break; + default: + int drawable = "x-vcard".equals(subtype) ? R.raw.vcard : R.raw.files; + uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + drawable); + break; + } + } else { + uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.files); + } + return uri; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ColorsUtil.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ColorsUtil.java index 138487165e..a5da05c18f 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ColorsUtil.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ColorsUtil.java @@ -22,18 +22,18 @@ public class ColorsUtil { - public static final int COLOR_DARK = 0; - public static final int COLOR_LIGHT = 1; - private static double CONTRAST_THRESHOLD = 100; + public static final int COLOR_DARK = 0; + public static final int COLOR_LIGHT = 1; + private static double CONTRAST_THRESHOLD = 100; - public static double calculateColorLuminance(int color) { - return 0.2126 * Color.red(color) + 0.7152 * Color.green(color) + 0.0722 * Color.blue(color); - } + public static double calculateColorLuminance (int color) { + return 0.2126 * Color.red(color) + 0.7152 * Color.green(color) + 0.0722 * Color.blue(color); + } - public static int getContrastedColor(int color) { - double luminance = calculateColorLuminance(color); - return luminance > CONTRAST_THRESHOLD ? COLOR_DARK : COLOR_LIGHT; - } + public static int getContrastedColor (int color) { + double luminance = calculateColorLuminance(color); + return luminance > CONTRAST_THRESHOLD ? COLOR_DARK : COLOR_LIGHT; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConnectionManager.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConnectionManager.java index fcc03d3b0a..b3a8f9e889 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConnectionManager.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConnectionManager.java @@ -22,15 +22,15 @@ public class ConnectionManager { - /** - * Checks for available internet connection - */ - public static boolean internetAvailable(Context ctx) { - boolean result = false; - ConnectivityManager conMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); - if (conMgr.getActiveNetworkInfo() != null) { - return conMgr.getActiveNetworkInfo().isConnected(); - } - return result; + /** + * Checks for available internet connection + */ + public static boolean internetAvailable (Context ctx) { + boolean result = false; + ConnectivityManager conMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); + if (conMgr.getActiveNetworkInfo() != null) { + return conMgr.getActiveNetworkInfo().isConnected(); } + return result; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConstantsBase.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConstantsBase.java index 45544222d5..170a387e72 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConstantsBase.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ConstantsBase.java @@ -18,112 +18,112 @@ public interface ConstantsBase { - String DATABASE_NAME = "omni-notes"; - String APP_STORAGE_DIRECTORY_SB_SYNC = "db_sync"; - - String DEV_EMAIL = "omninotes@iosue.it"; - String GOOGLE_PLUS_COMMUNITY = "https://plus.google.com/communities/112276053772152071903"; - String FACEBOOK_COMMUNITY = "https://www.facebook.com/OmniNotes/"; - - // Used for updates retrieval - long UPDATE_MIN_FREQUENCY = 24L * 60L * 60L * 1000L; // 1 day - String DRIVE_FOLDER_LAST_BUILD = "https://goo.gl/gB55RE"; - - // Notes swipe - int SWIPE_MARGIN = 30; - int SWIPE_OFFSET = 100; - - // Floating action button - int FAB_ANIMATION_TIME = 200; - - // Notes content masking - String MASK_CHAR = "*"; - - int THUMBNAIL_SIZE = 300; - - String DATE_FORMAT_SORTABLE = "yyyyMMdd_HHmmss_SSS"; - String DATE_FORMAT_SORTABLE_OLD = "yyyyMMddHHmmss"; - String DATE_FORMAT_EXPORT = "yyyy.MM.dd-HH.mm"; - - String INTENT_KEY = "note_id"; - String INTENT_NOTE = "note"; - String GALLERY_TITLE = "gallery_title"; - String GALLERY_CLICKED_IMAGE = "gallery_clicked_image"; - String GALLERY_IMAGES = "gallery_images"; - String INTENT_CATEGORY = "category"; - String INTENT_GOOGLE_NOW = "com.google.android.gm.action.AUTO_SEND"; - String INTENT_WIDGET = "widget_id"; - String INTENT_UPDATE_DASHCLOCK = "update_dashclock"; - - // Custom intent actions - String ACTION_START_APP = "action_start_app"; - String ACTION_RESTART_APP = "action_restart_app"; - String ACTION_DISMISS = "action_dismiss"; - String ACTION_SNOOZE = "action_snooze"; - String ACTION_POSTPONE = "action_postpone"; - String ACTION_SHORTCUT = "action_shortcut"; - String ACTION_WIDGET = "action_widget"; - String ACTION_WIDGET_TAKE_PHOTO = "action_widget_take_photo"; - String ACTION_WIDGET_SHOW_LIST = "action_widget_show_list"; - String ACTION_SHORTCUT_WIDGET = "action_shortcut_widget"; - String ACTION_NOTIFICATION_CLICK = "action_notification_click"; - String ACTION_MERGE = "action_merge"; - String ACTION_FAB_TAKE_PHOTO = "action_fab_take_photo"; - /** - * Used to quickly add a note, save, and perform backPress (eg. Tasker+Pushbullet) * - */ - String ACTION_SEND_AND_EXIT = "action_send_and_exit"; - String ACTION_SEARCH_UNCOMPLETE_CHECKLISTS = "action_search_uncomplete_checklists"; - - String PREF_LANG = "settings_language"; - String PREF_LAST_UPDATE_CHECK = "last_update_check"; - String PREF_NAVIGATION = "navigation"; - String PREF_SORTING_COLUMN = "sorting_column"; - String PREF_PASSWORD = "password"; - String PREF_PASSWORD_QUESTION = "password_question"; - String PREF_PASSWORD_ANSWER = "password_answer"; - String PREF_KEEP_CHECKED = "keep_checked"; - String PREF_KEEP_CHECKMARKS = "show_checkmarks"; - String PREF_EXPANDED_VIEW = "expanded_view"; - String PREF_COLORS_APP_DEFAULT = "strip"; - String PREF_WIDGET_PREFIX = "widget_"; - String PREF_SHOW_UNCATEGORIZED = "settings_show_uncategorized"; - String PREF_AUTO_LOCATION = "settings_auto_location"; - String PREF_FILTER_PAST_REMINDERS = "settings_filter_past_reminders"; - String PREF_FILTER_ARCHIVED_IN_CATEGORIES = "settings_filter_archived_in_categories"; - String PREF_DYNAMIC_MENU = "settings_dynamic_menu"; - String PREF_CURRENT_APP_VERSION = "settings_current_app_version"; - String PREF_FAB_EXPANSION_BEHAVIOR = "settings_fab_expansion_behavior"; - String PREF_ATTACHMENTS_ON_BOTTOM = "settings_attachments_on_bottom"; - String PREF_SNOOZE_DEFAULT = "10"; - String PREF_TOUR_COMPLETE = "pref_tour_complete"; - String PREF_ENABLE_SWIPE = "settings_enable_swipe"; - String PREF_SEND_ANALYTICS = "settings_send_analytics"; - String PREF_PRETTIFIED_DATES = "settings_prettified_dates"; - String PREF_ENABLE_AUTOBACKUP = "settings_enable_autobackup"; - String PREF_ENABLE_FILE_LOGGING = "settings_enable_file_logging"; - - String MIME_TYPE_IMAGE = "image/jpeg"; - String MIME_TYPE_AUDIO = "audio/amr"; - String MIME_TYPE_VIDEO = "video/mp4"; - String MIME_TYPE_SKETCH = "image/png"; - String MIME_TYPE_FILES = "file/*"; - - String MIME_TYPE_IMAGE_EXT = ".jpeg"; - String MIME_TYPE_AUDIO_EXT = ".amr"; - String MIME_TYPE_VIDEO_EXT = ".mp4"; - String MIME_TYPE_SKETCH_EXT = ".png"; - String MIME_TYPE_CONTACT_EXT = ".vcf"; - - String TIMESTAMP_UNIX_EPOCH = "0"; - String TIMESTAMP_UNIX_EPOCH_FAR = "18464193800000"; - - String TAG_SPECIAL_CHARS_TO_REMOVE = "[<>\\[\\],-\\.\\(\\)\\[\\]\\{\\}\\!\\?]"; - - int MENU_SORT_GROUP_ID = 11998811; - - String MERGED_NOTES_SEPARATOR = "----------------------"; - String PROPERTIES_PARAMS_SEPARATOR = ","; - - String AUTO_BACKUP_DIR = "_autobackup"; + String DATABASE_NAME = "omni-notes"; + String APP_STORAGE_DIRECTORY_SB_SYNC = "db_sync"; + + String DEV_EMAIL = "omninotes@iosue.it"; + String GOOGLE_PLUS_COMMUNITY = "https://plus.google.com/communities/112276053772152071903"; + String FACEBOOK_COMMUNITY = "https://www.facebook.com/OmniNotes/"; + + // Used for updates retrieval + long UPDATE_MIN_FREQUENCY = 24L * 60L * 60L * 1000L; // 1 day + String DRIVE_FOLDER_LAST_BUILD = "https://goo.gl/gB55RE"; + + // Notes swipe + int SWIPE_MARGIN = 30; + int SWIPE_OFFSET = 100; + + // Floating action button + int FAB_ANIMATION_TIME = 200; + + // Notes content masking + String MASK_CHAR = "*"; + + int THUMBNAIL_SIZE = 300; + + String DATE_FORMAT_SORTABLE = "yyyyMMdd_HHmmss_SSS"; + String DATE_FORMAT_SORTABLE_OLD = "yyyyMMddHHmmss"; + String DATE_FORMAT_EXPORT = "yyyy.MM.dd-HH.mm"; + + String INTENT_KEY = "note_id"; + String INTENT_NOTE = "note"; + String GALLERY_TITLE = "gallery_title"; + String GALLERY_CLICKED_IMAGE = "gallery_clicked_image"; + String GALLERY_IMAGES = "gallery_images"; + String INTENT_CATEGORY = "category"; + String INTENT_GOOGLE_NOW = "com.google.android.gm.action.AUTO_SEND"; + String INTENT_WIDGET = "widget_id"; + String INTENT_UPDATE_DASHCLOCK = "update_dashclock"; + + // Custom intent actions + String ACTION_START_APP = "action_start_app"; + String ACTION_RESTART_APP = "action_restart_app"; + String ACTION_DISMISS = "action_dismiss"; + String ACTION_SNOOZE = "action_snooze"; + String ACTION_POSTPONE = "action_postpone"; + String ACTION_SHORTCUT = "action_shortcut"; + String ACTION_WIDGET = "action_widget"; + String ACTION_WIDGET_TAKE_PHOTO = "action_widget_take_photo"; + String ACTION_WIDGET_SHOW_LIST = "action_widget_show_list"; + String ACTION_SHORTCUT_WIDGET = "action_shortcut_widget"; + String ACTION_NOTIFICATION_CLICK = "action_notification_click"; + String ACTION_MERGE = "action_merge"; + String ACTION_FAB_TAKE_PHOTO = "action_fab_take_photo"; + /** + * Used to quickly add a note, save, and perform backPress (eg. Tasker+Pushbullet) * + */ + String ACTION_SEND_AND_EXIT = "action_send_and_exit"; + String ACTION_SEARCH_UNCOMPLETE_CHECKLISTS = "action_search_uncomplete_checklists"; + + String PREF_LANG = "settings_language"; + String PREF_LAST_UPDATE_CHECK = "last_update_check"; + String PREF_NAVIGATION = "navigation"; + String PREF_SORTING_COLUMN = "sorting_column"; + String PREF_PASSWORD = "password"; + String PREF_PASSWORD_QUESTION = "password_question"; + String PREF_PASSWORD_ANSWER = "password_answer"; + String PREF_KEEP_CHECKED = "keep_checked"; + String PREF_KEEP_CHECKMARKS = "show_checkmarks"; + String PREF_EXPANDED_VIEW = "expanded_view"; + String PREF_COLORS_APP_DEFAULT = "strip"; + String PREF_WIDGET_PREFIX = "widget_"; + String PREF_SHOW_UNCATEGORIZED = "settings_show_uncategorized"; + String PREF_AUTO_LOCATION = "settings_auto_location"; + String PREF_FILTER_PAST_REMINDERS = "settings_filter_past_reminders"; + String PREF_FILTER_ARCHIVED_IN_CATEGORIES = "settings_filter_archived_in_categories"; + String PREF_DYNAMIC_MENU = "settings_dynamic_menu"; + String PREF_CURRENT_APP_VERSION = "settings_current_app_version"; + String PREF_FAB_EXPANSION_BEHAVIOR = "settings_fab_expansion_behavior"; + String PREF_ATTACHMENTS_ON_BOTTOM = "settings_attachments_on_bottom"; + String PREF_SNOOZE_DEFAULT = "10"; + String PREF_TOUR_COMPLETE = "pref_tour_complete"; + String PREF_ENABLE_SWIPE = "settings_enable_swipe"; + String PREF_SEND_ANALYTICS = "settings_send_analytics"; + String PREF_PRETTIFIED_DATES = "settings_prettified_dates"; + String PREF_ENABLE_AUTOBACKUP = "settings_enable_autobackup"; + String PREF_ENABLE_FILE_LOGGING = "settings_enable_file_logging"; + + String MIME_TYPE_IMAGE = "image/jpeg"; + String MIME_TYPE_AUDIO = "audio/amr"; + String MIME_TYPE_VIDEO = "video/mp4"; + String MIME_TYPE_SKETCH = "image/png"; + String MIME_TYPE_FILES = "file/*"; + + String MIME_TYPE_IMAGE_EXT = ".jpeg"; + String MIME_TYPE_AUDIO_EXT = ".amr"; + String MIME_TYPE_VIDEO_EXT = ".mp4"; + String MIME_TYPE_SKETCH_EXT = ".png"; + String MIME_TYPE_CONTACT_EXT = ".vcf"; + + String TIMESTAMP_UNIX_EPOCH = "0"; + String TIMESTAMP_UNIX_EPOCH_FAR = "18464193800000"; + + String TAG_SPECIAL_CHARS_TO_REMOVE = "[<>\\[\\],-\\.\\(\\)\\[\\]\\{\\}\\!\\?]"; + + int MENU_SORT_GROUP_ID = 11998811; + + String MERGED_NOTES_SEPARATOR = "----------------------"; + String PROPERTIES_PARAMS_SEPARATOR = ","; + + String AUTO_BACKUP_DIR = "_autobackup"; } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Display.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Display.java index 39728c3678..bd2cf5d284 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Display.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Display.java @@ -29,89 +29,88 @@ import android.util.DisplayMetrics; import android.view.View; import android.view.WindowManager; - import it.feio.android.omninotes.helpers.LogDelegate; public class Display { - public static View getRootView(Activity mActivity) { - return mActivity.getWindow().getDecorView().findViewById(android.R.id.content); - } + public static View getRootView (Activity mActivity) { + return mActivity.getWindow().getDecorView().findViewById(android.R.id.content); + } - @SuppressWarnings("deprecation") - @SuppressLint("NewApi") - public static Point getUsableSize(Context mContext) { - Point displaySize = new Point(); - try { - WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); - if (manager != null) { - android.view.Display display = manager.getDefaultDisplay(); - if (display != null) { - display.getSize(displaySize); - } - } - } catch (Exception e) { - LogDelegate.e("Error checking display sizes", e); + @SuppressWarnings("deprecation") + @SuppressLint("NewApi") + public static Point getUsableSize (Context mContext) { + Point displaySize = new Point(); + try { + WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); + if (manager != null) { + android.view.Display display = manager.getDefaultDisplay(); + if (display != null) { + display.getSize(displaySize); } - return displaySize; + } + } catch (Exception e) { + LogDelegate.e("Error checking display sizes", e); } + return displaySize; + } - public static Point getVisibleSize(Activity activity) { - Point displaySize = new Point(); - Rect r = new Rect(); - activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r); - displaySize.x = r.right - r.left; - displaySize.y = r.bottom - r.top; - return displaySize; - } + public static Point getVisibleSize (Activity activity) { + Point displaySize = new Point(); + Rect r = new Rect(); + activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r); + displaySize.x = r.right - r.left; + displaySize.y = r.bottom - r.top; + return displaySize; + } - public static Point getFullSize(View view) { - Point displaySize = new Point(); - displaySize.x = view.getRootView().getWidth(); - displaySize.y = view.getRootView().getHeight(); - return displaySize; - } + public static Point getFullSize (View view) { + Point displaySize = new Point(); + displaySize.x = view.getRootView().getWidth(); + displaySize.y = view.getRootView().getHeight(); + return displaySize; + } - public static int getStatusBarHeight(Context mContext) { - int result = 0; - int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); - if (resourceId > 0) { - result = mContext.getResources().getDimensionPixelSize(resourceId); - } - return result; + public static int getStatusBarHeight (Context mContext) { + int result = 0; + int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); + if (resourceId > 0) { + result = mContext.getResources().getDimensionPixelSize(resourceId); } + return result; + } - public static int getNavigationBarHeightStandard(Context mContext) { - int resourceId = mContext.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); - if (resourceId > 0) { - return mContext.getResources().getDimensionPixelSize(resourceId); - } - return 0; + public static int getNavigationBarHeightStandard (Context mContext) { + int resourceId = mContext.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); + if (resourceId > 0) { + return mContext.getResources().getDimensionPixelSize(resourceId); } + return 0; + } - public static int getNavigationBarHeight(View view) { - return (getFullSize(view).y - getUsableSize(view.getContext()).y); - } + public static int getNavigationBarHeight (View view) { + return (getFullSize(view).y - getUsableSize(view.getContext()).y); + } - @SuppressLint("NewApi") - public static int getActionbarHeight(Object mObject) { - int res = 0; - if (AppCompatActivity.class.isAssignableFrom(mObject.getClass())) { - res = ((AppCompatActivity) mObject).getSupportActionBar().getHeight(); - } else if (Activity.class.isAssignableFrom(mObject.getClass())) { - res = ((Activity) mObject).getActionBar().getHeight(); - } - return res; + @SuppressLint("NewApi") + public static int getActionbarHeight (Object mObject) { + int res = 0; + if (AppCompatActivity.class.isAssignableFrom(mObject.getClass())) { + res = ((AppCompatActivity) mObject).getSupportActionBar().getHeight(); + } else if (Activity.class.isAssignableFrom(mObject.getClass())) { + res = ((Activity) mObject).getActionBar().getHeight(); } + return res; + } // public static int getActionBarHeight(Activity mActivity) { // Rect r = new Rect(); @@ -124,43 +123,44 @@ public static int getActionbarHeight(Object mObject) { // } - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - public static Point getScreenDimensions(Context mContext) { - WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); - android.view.Display display = wm.getDefaultDisplay(); - Point size = new Point(); - DisplayMetrics metrics = new DisplayMetrics(); - display.getRealMetrics(metrics); - size.x = metrics.widthPixels; - size.y = metrics.heightPixels; - return size; - } - - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) - public static int getNavigationBarHeightKitkat(Context mContext) { - return getScreenDimensions(mContext).y - getUsableSize(mContext).y; - } - - - public static boolean orientationLandscape(Context context) { - return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; - } - - public static int getSoftButtonsBarHeight(Activity activity) { - // getRealMetrics is only available with API 17 and + - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - DisplayMetrics metrics = new DisplayMetrics(); - activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); - int usableHeight = metrics.heightPixels; - activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); - int realHeight = metrics.heightPixels; - if (realHeight > usableHeight) - return realHeight - usableHeight; - else - return 0; - } + @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) + public static Point getScreenDimensions (Context mContext) { + WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); + android.view.Display display = wm.getDefaultDisplay(); + Point size = new Point(); + DisplayMetrics metrics = new DisplayMetrics(); + display.getRealMetrics(metrics); + size.x = metrics.widthPixels; + size.y = metrics.heightPixels; + return size; + } + + + @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) + public static int getNavigationBarHeightKitkat (Context mContext) { + return getScreenDimensions(mContext).y - getUsableSize(mContext).y; + } + + + public static boolean orientationLandscape (Context context) { + return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; + } + + public static int getSoftButtonsBarHeight (Activity activity) { + // getRealMetrics is only available with API 17 and + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + DisplayMetrics metrics = new DisplayMetrics(); + activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); + int usableHeight = metrics.heightPixels; + activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); + int realHeight = metrics.heightPixels; + if (realHeight > usableHeight) { + return realHeight - usableHeight; + } else { return 0; + } } + return 0; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileHelper.java index 3bf9692017..9ab8aee4b3 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileHelper.java @@ -17,6 +17,8 @@ package it.feio.android.omninotes.utils; +import static java.lang.Long.parseLong; + import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; @@ -26,212 +28,211 @@ import android.os.Environment; import android.provider.DocumentsContract; import android.text.TextUtils; - +import it.feio.android.omninotes.factory.MediaStoreFactory; +import it.feio.android.omninotes.helpers.LogDelegate; import java.io.File; import java.io.IOException; import java.io.InputStream; -import it.feio.android.omninotes.factory.MediaStoreFactory; -import it.feio.android.omninotes.helpers.LogDelegate; - -import static java.lang.Long.parseLong; - public class FileHelper { - /** - * Get a file path from a Uri. This will get the the path for Storage Access - * Framework Documents, as well as the _data field for the MediaStore and - * other file-based ContentProviders. - * - * @param context The context. - * @param uri The Uri to query. - */ - @SuppressLint("NewApi") - public static String getPath(final Context context, final Uri uri) { - - if (uri == null) - return null; - - final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; - - // DocumentProvider - if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { - // ExternalStorageProvider - if (isExternalStorageDocument(uri)) { - final String docId = DocumentsContract.getDocumentId(uri); - final String[] split = docId.split(":"); - final String type = split[0]; - - if ("primary".equalsIgnoreCase(type)) { - return Environment.getExternalStorageDirectory() + "/" + split[1]; - } - - // TODO handle non-primary volumes - } - // DownloadsProvider - else if (isDownloadsDocument(uri)) { - final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), - parseLong(DocumentsContract.getDocumentId(uri))); - return getDataColumn(context, contentUri, null, null); - } - // MediaProvider - else if (isMediaDocument(uri)) { - final String docId = DocumentsContract.getDocumentId(uri); - final String[] split = docId.split(":"); - final String type = split[0]; - MediaStoreFactory mediaStoreFactory = new MediaStoreFactory(); - Uri contentUri = mediaStoreFactory.createURI(type); - - final String selection = "_id=?"; - final String[] selectionArgs = new String[]{split[1]}; - - return getDataColumn(context, contentUri, selection, selectionArgs); - } - } - // MediaStore (and general) - else if ("content".equalsIgnoreCase(uri.getScheme())) { - return getDataColumn(context, uri, null, null); - } - // File - else if ("file".equalsIgnoreCase(uri.getScheme())) { - return uri.getPath(); - } - - return null; + /** + * Get a file path from a Uri. This will get the the path for Storage Access Framework Documents, as well as the _data + * field for the MediaStore and other file-based ContentProviders. + * + * @param context The context. + * @param uri The Uri to query. + */ + @SuppressLint("NewApi") + public static String getPath (final Context context, final Uri uri) { + + if (uri == null) { + return null; } + final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; - /** - * Get the value of the data column for this Uri. This is useful for - * MediaStore Uris, and other file-based ContentProviders. - * - * @param context The context. - * @param uri The Uri to query. - * @param selection (Optional) Filter used in the query. - * @param selectionArgs (Optional) Selection arguments used in the query. - * @return The value of the _data column, which is typically a file path. - */ - public static String getDataColumn(Context context, Uri uri, - String selection, String[] selectionArgs) { + // DocumentProvider + if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { + // ExternalStorageProvider + if (isExternalStorageDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; - Cursor cursor = null; - final String column = "_data"; - final String[] projection = {column}; - - try { - cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); - if (cursor != null && cursor.moveToFirst()) { - final int column_index = cursor.getColumnIndexOrThrow(column); - return cursor.getString(column_index); - } - } catch (Exception e) { - LogDelegate.e("Error retrieving uri path", e); - } finally { - if (cursor != null) - cursor.close(); + if ("primary".equalsIgnoreCase(type)) { + return Environment.getExternalStorageDirectory() + "/" + split[1]; } - return null; - } - - /** - * @param uri The Uri to check. - * @return Whether the Uri authority is ExternalStorageProvider. - */ - public static boolean isExternalStorageDocument(Uri uri) { - return "com.android.externalstorage.documents".equals(uri.getAuthority()); + // TODO handle non-primary volumes + } + // DownloadsProvider + else if (isDownloadsDocument(uri)) { + final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), + parseLong(DocumentsContract.getDocumentId(uri))); + return getDataColumn(context, contentUri, null, null); + } + // MediaProvider + else if (isMediaDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + MediaStoreFactory mediaStoreFactory = new MediaStoreFactory(); + Uri contentUri = mediaStoreFactory.createURI(type); + + final String selection = "_id=?"; + final String[] selectionArgs = new String[]{split[1]}; + + return getDataColumn(context, contentUri, selection, selectionArgs); + } } - - - /** - * @param uri The Uri to check. - * @return Whether the Uri authority is DownloadsProvider. - */ - public static boolean isDownloadsDocument(Uri uri) { - return "com.android.providers.downloads.documents".equals(uri.getAuthority()); + // MediaStore (and general) + else if ("content".equalsIgnoreCase(uri.getScheme())) { + return getDataColumn(context, uri, null, null); } - - - /** - * @param uri The Uri to check. - * @return Whether the Uri authority is MediaProvider. - */ - public static boolean isMediaDocument(Uri uri) { - return "com.android.providers.media.documents".equals(uri.getAuthority()); + // File + else if ("file".equalsIgnoreCase(uri.getScheme())) { + return uri.getPath(); } - - public static InputStream getInputStream(Context mContext, Uri mUri) { - InputStream inputStream; - try { - inputStream = mContext.getContentResolver().openInputStream(mUri); - inputStream.close(); - return inputStream; - } catch (IOException e) { - return null; - } + return null; + } + + + /** + * Get the value of the data column for this Uri. This is useful for MediaStore Uris, and other file-based + * ContentProviders. + * + * @param context The context. + * @param uri The Uri to query. + * @param selection (Optional) Filter used in the query. + * @param selectionArgs (Optional) Selection arguments used in the query. + * @return The value of the _data column, which is typically a file path. + */ + public static String getDataColumn (Context context, Uri uri, + String selection, String[] selectionArgs) { + + Cursor cursor = null; + final String column = "_data"; + final String[] projection = {column}; + + try { + cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); + if (cursor != null && cursor.moveToFirst()) { + final int column_index = cursor.getColumnIndexOrThrow(column); + return cursor.getString(column_index); + } + } catch (Exception e) { + LogDelegate.e("Error retrieving uri path", e); + } finally { + if (cursor != null) { + cursor.close(); + } } - - - /** - * Trying to retrieve file name from content resolver - */ - public static String getNameFromUri(Context mContext, Uri uri) { - String fileName = ""; - Cursor cursor = null; + return null; + } + + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is ExternalStorageProvider. + */ + public static boolean isExternalStorageDocument (Uri uri) { + return "com.android.externalstorage.documents".equals(uri.getAuthority()); + } + + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is DownloadsProvider. + */ + public static boolean isDownloadsDocument (Uri uri) { + return "com.android.providers.downloads.documents".equals(uri.getAuthority()); + } + + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is MediaProvider. + */ + public static boolean isMediaDocument (Uri uri) { + return "com.android.providers.media.documents".equals(uri.getAuthority()); + } + + + public static InputStream getInputStream (Context mContext, Uri mUri) { + InputStream inputStream; + try { + inputStream = mContext.getContentResolver().openInputStream(mUri); + inputStream.close(); + return inputStream; + } catch (IOException e) { + return null; + } + } + + + /** + * Trying to retrieve file name from content resolver + */ + public static String getNameFromUri (Context mContext, Uri uri) { + String fileName = ""; + Cursor cursor = null; + try { + cursor = mContext.getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null); + if (cursor != null) { try { - cursor = mContext.getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null); - if (cursor != null) { - try { - if (cursor.moveToFirst()) { - fileName = cursor.getString(0); - } - - } catch (Exception e) { - LogDelegate.e("Error managing diskk cache", e); - } - } else { - fileName = uri.getLastPathSegment(); - } - } catch (SecurityException e) { - return null; - } finally { - if (cursor != null) { - cursor.close(); - } + if (cursor.moveToFirst()) { + fileName = cursor.getString(0); + } + + } catch (Exception e) { + LogDelegate.e("Error managing diskk cache", e); } - return fileName; + } else { + fileName = uri.getLastPathSegment(); + } + } catch (SecurityException e) { + return null; + } finally { + if (cursor != null) { + cursor.close(); + } } + return fileName; + } - public static String getFilePrefix(File file) { - return getFilePrefix(file.getName()); - } + public static String getFilePrefix (File file) { + return getFilePrefix(file.getName()); + } - public static String getFilePrefix(String fileName) { - String prefix = fileName; - int index = fileName.indexOf("."); - if (index != -1) { - prefix = fileName.substring(0, index); - } - return prefix; + public static String getFilePrefix (String fileName) { + String prefix = fileName; + int index = fileName.indexOf("."); + if (index != -1) { + prefix = fileName.substring(0, index); } + return prefix; + } - public static String getFileExtension(File file) { - return getFileExtension(file.getName()); - } + public static String getFileExtension (File file) { + return getFileExtension(file.getName()); + } - public static String getFileExtension(String fileName) { - if (TextUtils.isEmpty(fileName)) return ""; - String extension = ""; - int index = fileName.lastIndexOf("."); - if (index != -1) { - extension = fileName.substring(index, fileName.length()); - } - return extension; + public static String getFileExtension (String fileName) { + if (TextUtils.isEmpty(fileName)) { + return ""; + } + String extension = ""; + int index = fileName.lastIndexOf("."); + if (index != -1) { + extension = fileName.substring(index); } + return extension; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileProviderHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileProviderHelper.java index 897e7e36ae..b53f556363 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileProviderHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/FileProviderHelper.java @@ -19,30 +19,29 @@ import android.net.Uri; import android.support.v4.content.FileProvider; - -import java.io.File; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.models.Attachment; +import java.io.File; public class FileProviderHelper { - /** - * Generates the FileProvider URI for a given existing file - */ - public static Uri getFileProvider(File file) { - return FileProvider.getUriForFile(OmniNotes.getAppContext(), OmniNotes.getAppContext().getPackageName() + ".authority", file); - } + /** + * Generates the FileProvider URI for a given existing file + */ + public static Uri getFileProvider (File file) { + return FileProvider.getUriForFile(OmniNotes.getAppContext(), + OmniNotes.getAppContext().getPackageName() + ".authority", file); + } - /** - * Generates a shareable URI for a given attachment by evaluating its stored (into DB) path - */ - public static Uri getShareableUri(Attachment attachment) { - File attachmentFile = new File(attachment.getUri().getPath()); - if (attachmentFile.exists()) { - return FileProviderHelper.getFileProvider(attachmentFile); - } else { - return attachment.getUri(); - } + /** + * Generates a shareable URI for a given attachment by evaluating its stored (into DB) path + */ + public static Uri getShareableUri (Attachment attachment) { + File attachmentFile = new File(attachment.getUri().getPath()); + if (attachmentFile.exists()) { + return FileProviderHelper.getFileProvider(attachmentFile); + } else { + return attachment.getUri(); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Fonts.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Fonts.java index 5549a82ca6..760ed6ab88 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Fonts.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Fonts.java @@ -22,42 +22,39 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; - -import java.util.Arrays; - import it.feio.android.checklistview.utils.DensityUtil; import it.feio.android.omninotes.R; import it.feio.android.omninotes.helpers.LogDelegate; +import java.util.Arrays; public class Fonts { - /** - * Overrides all the fonts set to TextView class descendants found in the - * view passed as parameter - */ - public static void overrideTextSize(Context context, SharedPreferences prefs, View v) { - Context privateContext = context.getApplicationContext(); - try { - if (v instanceof ViewGroup) { - ViewGroup vg = (ViewGroup) v; - for (int i = 0; i < vg.getChildCount(); i++) { - View child = vg.getChildAt(i); - overrideTextSize(privateContext, prefs, child); - } - } else if (v instanceof TextView) { - float currentSize = DensityUtil.pxToDp(((TextView) v).getTextSize(), privateContext); - int index = Arrays - .asList(privateContext.getResources().getStringArray( - R.array.text_size_values)) - .indexOf( - prefs.getString("settings_text_size", "default")); - float offset = privateContext.getResources().getIntArray( - R.array.text_size_offset)[index == -1 ? 0 : index]; - ((TextView) v).setTextSize(currentSize + offset); - } - } catch (Exception e) { - LogDelegate.e("Error setting font size", e); + /** + * Overrides all the fonts set to TextView class descendants found in the view passed as parameter + */ + public static void overrideTextSize (Context context, SharedPreferences prefs, View v) { + Context privateContext = context.getApplicationContext(); + try { + if (v instanceof ViewGroup) { + ViewGroup vg = (ViewGroup) v; + for (int i = 0; i < vg.getChildCount(); i++) { + View child = vg.getChildAt(i); + overrideTextSize(privateContext, prefs, child); } + } else if (v instanceof TextView) { + float currentSize = DensityUtil.pxToDp(((TextView) v).getTextSize(), privateContext); + int index = Arrays + .asList(privateContext.getResources().getStringArray( + R.array.text_size_values)) + .indexOf( + prefs.getString("settings_text_size", "default")); + float offset = privateContext.getResources().getIntArray( + R.array.text_size_offset)[index == -1 ? 0 : index]; + ((TextView) v).setTextSize(currentSize + offset); + } + } catch (Exception e) { + LogDelegate.e("Error setting font size", e); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/GeocodeHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/GeocodeHelper.java index c8dcb46516..900718f87e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/GeocodeHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/GeocodeHelper.java @@ -25,11 +25,14 @@ import android.location.LocationManager; import android.os.Bundle; import android.text.TextUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - +import io.nlopez.smartlocation.SmartLocation; +import io.nlopez.smartlocation.location.config.LocationParams; +import io.nlopez.smartlocation.rx.ObservableFactory; +import it.feio.android.omninotes.BuildConfig; +import it.feio.android.omninotes.OmniNotes; +import it.feio.android.omninotes.helpers.GeocodeProviderFactory; +import it.feio.android.omninotes.helpers.LogDelegate; +import it.feio.android.omninotes.models.listeners.OnGeoUtilResultListener; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; @@ -43,208 +46,203 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; - -import io.nlopez.smartlocation.SmartLocation; -import io.nlopez.smartlocation.location.config.LocationParams; -import io.nlopez.smartlocation.rx.ObservableFactory; -import it.feio.android.omninotes.BuildConfig; -import it.feio.android.omninotes.OmniNotes; -import it.feio.android.omninotes.helpers.GeocodeProviderFactory; -import it.feio.android.omninotes.helpers.LogDelegate; -import it.feio.android.omninotes.models.listeners.OnGeoUtilResultListener; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import rx.Observable; import rx.Subscriber; public class GeocodeHelper implements LocationListener { - private static final String LOG_TAG = Constants.TAG; - private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place"; - private static final String TYPE_AUTOCOMPLETE = "/autocomplete"; - private static final String OUT_JSON = "/json"; - - private static GeocodeHelper instance; - private static LocationManager locationManager; - - - private GeocodeHelper() { - instance = this; - locationManager = (LocationManager) OmniNotes.getAppContext().getSystemService(Context.LOCATION_SERVICE); - } - - - @Override - public void onLocationChanged(Location newLocation) { - } - - - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - } - - - @Override - public void onProviderEnabled(String provider) { - } - - - @Override - public void onProviderDisabled(String provider) { - } - - - public static void getLocation(OnGeoUtilResultListener onGeoUtilResultListener) { - SmartLocation.LocationControl bod = SmartLocation.with(OmniNotes.getAppContext()) - .location(GeocodeProviderFactory.getProvider(OmniNotes.getAppContext())) - .config(LocationParams.NAVIGATION).oneFix(); - - Observable locations = ObservableFactory.from(bod).timeout(2, TimeUnit.SECONDS); - locations.subscribe(new Subscriber() { - @Override - public void onNext(Location location) { - onGeoUtilResultListener.onLocationRetrieved(location); - unsubscribe(); - } - - @Override - public void onCompleted() { - } - - @Override - public void onError(Throwable e) { - onGeoUtilResultListener.onLocationUnavailable(); - unsubscribe(); - } - }); - } - - - public static void stop() { - SmartLocation.with(OmniNotes.getAppContext()).location().stop(); - if (Geocoder.isPresent()) { - SmartLocation.with(OmniNotes.getAppContext()).geocoding().stop(); - } - } - - - static String getAddressFromCoordinates(Context mContext, double latitude, - double longitude) throws IOException { - String addressString = ""; - Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); - List
addresses = geocoder.getFromLocation(latitude, longitude, 1); - if (addresses.size() > 0) { - Address address = addresses.get(0); - if (address != null) { - addressString = address.getThoroughfare() + ", " + address.getLocality(); - } - } - return addressString; - } - - - public static void getAddressFromCoordinates(Location location, - final OnGeoUtilResultListener onGeoUtilResultListener) { - if (!Geocoder.isPresent()) { - onGeoUtilResultListener.onAddressResolved(""); - } else { - SmartLocation.with(OmniNotes.getAppContext()).geocoding().reverse(location, (location1, list) -> { - String address = list.size() > 0 ? list.get(0).getAddressLine(0) : null; - onGeoUtilResultListener.onAddressResolved(address); - }); - } - } - - - public static double[] getCoordinatesFromAddress(Context mContext, String address) - throws IOException { - double[] result = new double[2]; - Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); - List
addresses = geocoder.getFromLocationName(address, 1); - if (addresses.size() > 0) { - double latitude = addresses.get(0).getLatitude(); - double longitude = addresses.get(0).getLongitude(); - result[0] = latitude; - result[1] = longitude; - } - return result; - } - - - public static void getCoordinatesFromAddress(String address, final OnGeoUtilResultListener - listener) { - SmartLocation.with(OmniNotes.getAppContext()).geocoding().direct(address, (name, results) -> { - if (results.size() > 0) { - listener.onCoordinatesResolved(results.get(0).getLocation(), address); - } - }); - } - - - public static List autocomplete(String input) { - String MAPS_API_KEY = BuildConfig.MAPS_API_KEY; - if (TextUtils.isEmpty(MAPS_API_KEY)) { - return Collections.emptyList(); - } - ArrayList resultList = null; - - HttpURLConnection conn = null; - InputStreamReader in = null; - StringBuilder jsonResults = new StringBuilder(); - try { - URL url = new URL(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON + "?key=" + MAPS_API_KEY + "&input=" + - URLEncoder.encode(input, "utf8")); - conn = (HttpURLConnection) url.openConnection(); - in = new InputStreamReader(conn.getInputStream()); - // Load the results into a StringBuilder - int read; - char[] buff = new char[1024]; - while ((read = in.read(buff)) != -1) { - jsonResults.append(buff, 0, read); - } - } catch (MalformedURLException e) { - LogDelegate.e("Error processing Places API URL"); - return null; - } catch (IOException e) { - LogDelegate.e("Error connecting to Places API"); - return null; - } finally { - if (conn != null) { - conn.disconnect(); - } - if (in != null) { - try { - in.close(); - } catch (IOException e) { - LogDelegate.e("Error closing address autocompletion InputStream"); - } - } - } - - try { - // Create a JSON object hierarchy from the results - JSONObject jsonObj = new JSONObject(jsonResults.toString()); - JSONArray predsJsonArray = jsonObj.getJSONArray("predictions"); - // Extract the Place descriptions from the results - resultList = new ArrayList<>(predsJsonArray.length()); - for (int i = 0; i < predsJsonArray.length(); i++) { - resultList.add(predsJsonArray.getJSONObject(i).getString("description")); - } - } catch (JSONException e) { - LogDelegate.e("Cannot process JSON results", e); - } finally { - if (conn != null) { - conn.disconnect(); - } - SystemHelper.closeCloseable(in); - } - return resultList; - } - - - public static boolean areCoordinates(String string) { - Pattern p = Pattern.compile("^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?),\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|" + - "([1-9]?\\d))(\\.\\d+)?)$"); - Matcher m = p.matcher(string); - return m.matches(); - } + private static final String LOG_TAG = Constants.TAG; + private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place"; + private static final String TYPE_AUTOCOMPLETE = "/autocomplete"; + private static final String OUT_JSON = "/json"; + + private static GeocodeHelper instance; + private static LocationManager locationManager; + + + private GeocodeHelper () { + instance = this; + locationManager = (LocationManager) OmniNotes.getAppContext().getSystemService(Context.LOCATION_SERVICE); + } + + + @Override + public void onLocationChanged (Location newLocation) { + } + + + @Override + public void onStatusChanged (String provider, int status, Bundle extras) { + } + + + @Override + public void onProviderEnabled (String provider) { + } + + + @Override + public void onProviderDisabled (String provider) { + } + + + public static void getLocation (OnGeoUtilResultListener onGeoUtilResultListener) { + SmartLocation.LocationControl bod = SmartLocation.with(OmniNotes.getAppContext()) + .location( + GeocodeProviderFactory.getProvider(OmniNotes.getAppContext())) + .config(LocationParams.NAVIGATION).oneFix(); + + Observable locations = ObservableFactory.from(bod).timeout(2, TimeUnit.SECONDS); + locations.subscribe(new Subscriber() { + @Override + public void onNext (Location location) { + onGeoUtilResultListener.onLocationRetrieved(location); + unsubscribe(); + } + + @Override + public void onCompleted () { + } + + @Override + public void onError (Throwable e) { + onGeoUtilResultListener.onLocationUnavailable(); + unsubscribe(); + } + }); + } + + + public static void stop () { + SmartLocation.with(OmniNotes.getAppContext()).location().stop(); + if (Geocoder.isPresent()) { + SmartLocation.with(OmniNotes.getAppContext()).geocoding().stop(); + } + } + + + static String getAddressFromCoordinates (Context mContext, double latitude, + double longitude) throws IOException { + String addressString = ""; + Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); + List
addresses = geocoder.getFromLocation(latitude, longitude, 1); + if (addresses.size() > 0) { + Address address = addresses.get(0); + if (address != null) { + addressString = address.getThoroughfare() + ", " + address.getLocality(); + } + } + return addressString; + } + + + public static void getAddressFromCoordinates (Location location, + final OnGeoUtilResultListener onGeoUtilResultListener) { + if (!Geocoder.isPresent()) { + onGeoUtilResultListener.onAddressResolved(""); + } else { + SmartLocation.with(OmniNotes.getAppContext()).geocoding().reverse(location, (location1, list) -> { + String address = list.size() > 0 ? list.get(0).getAddressLine(0) : null; + onGeoUtilResultListener.onAddressResolved(address); + }); + } + } + + + public static double[] getCoordinatesFromAddress (Context mContext, String address) + throws IOException { + double[] result = new double[2]; + Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); + List
addresses = geocoder.getFromLocationName(address, 1); + if (addresses.size() > 0) { + double latitude = addresses.get(0).getLatitude(); + double longitude = addresses.get(0).getLongitude(); + result[0] = latitude; + result[1] = longitude; + } + return result; + } + + + public static void getCoordinatesFromAddress (String address, final OnGeoUtilResultListener + listener) { + SmartLocation.with(OmniNotes.getAppContext()).geocoding().direct(address, (name, results) -> { + if (results.size() > 0) { + listener.onCoordinatesResolved(results.get(0).getLocation(), address); + } + }); + } + + + public static List autocomplete (String input) { + String MAPS_API_KEY = BuildConfig.MAPS_API_KEY; + if (TextUtils.isEmpty(MAPS_API_KEY)) { + return Collections.emptyList(); + } + ArrayList resultList = null; + + HttpURLConnection conn = null; + InputStreamReader in = null; + StringBuilder jsonResults = new StringBuilder(); + try { + URL url = new URL(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON + "?key=" + MAPS_API_KEY + "&input=" + + URLEncoder.encode(input, "utf8")); + conn = (HttpURLConnection) url.openConnection(); + in = new InputStreamReader(conn.getInputStream()); + // Load the results into a StringBuilder + int read; + char[] buff = new char[1024]; + while ((read = in.read(buff)) != -1) { + jsonResults.append(buff, 0, read); + } + } catch (MalformedURLException e) { + LogDelegate.e("Error processing Places API URL"); + return null; + } catch (IOException e) { + LogDelegate.e("Error connecting to Places API"); + return null; + } finally { + if (conn != null) { + conn.disconnect(); + } + if (in != null) { + try { + in.close(); + } catch (IOException e) { + LogDelegate.e("Error closing address autocompletion InputStream"); + } + } + } + + try { + // Create a JSON object hierarchy from the results + JSONObject jsonObj = new JSONObject(jsonResults.toString()); + JSONArray predsJsonArray = jsonObj.getJSONArray("predictions"); + // Extract the Place descriptions from the results + resultList = new ArrayList<>(predsJsonArray.length()); + for (int i = 0; i < predsJsonArray.length(); i++) { + resultList.add(predsJsonArray.getJSONObject(i).getString("description")); + } + } catch (JSONException e) { + LogDelegate.e("Cannot process JSON results", e); + } finally { + if (conn != null) { + conn.disconnect(); + } + SystemHelper.closeCloseable(in); + } + return resultList; + } + + + public static boolean areCoordinates (String string) { + Pattern p = Pattern.compile("^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?),\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|" + + "([1-9]?\\d))(\\.\\d+)?)$"); + Matcher m = p.matcher(string); + return m.matches(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/IntentChecker.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/IntentChecker.java index d9f39380f0..8359e73bfb 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/IntentChecker.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/IntentChecker.java @@ -22,70 +22,61 @@ import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; - import java.util.List; public class IntentChecker { - /** - * Retrieves - * @param ctx - * @param intent - * @return - */ - public static String resolveActivityPackage(Context ctx, Intent intent) { - ComponentName activity= intent.resolveActivity(ctx.getPackageManager()); - return activity != null ? activity.getPackageName() : ""; - } + /** + * Retrieves + */ + public static String resolveActivityPackage (Context ctx, Intent intent) { + ComponentName activity = intent.resolveActivity(ctx.getPackageManager()); + return activity != null ? activity.getPackageName() : ""; + } - /** - * Checks intent and features availability - * - * @param features - * @param ctx - * @param intent - * @return - */ - public static boolean isAvailable(Context ctx, Intent intent, String[] features) { - boolean res = getCompatiblePackages(ctx, intent).size() > 0; + /** + * Checks intent and features availability + */ + public static boolean isAvailable (Context ctx, Intent intent, String[] features) { + boolean res = getCompatiblePackages(ctx, intent).size() > 0; - if (features != null) { - for (String feature : features) { - res = res && ctx.getPackageManager().hasSystemFeature(feature); - } - } - return res; - } + if (features != null) { + for (String feature : features) { + res = res && ctx.getPackageManager().hasSystemFeature(feature); + } + } + return res; + } - /** - * Checks Intent's action - * - * @param i Intent to ckeck - * @param action Action to compare with - * @return - */ - public static boolean checkAction(Intent i, String action) { - return action.equals(i.getAction()); - } + /** + * Checks Intent's action + * + * @param i Intent to ckeck + * @param action Action to compare with + */ + public static boolean checkAction (Intent i, String action) { + return action.equals(i.getAction()); + } - /** - * Checks Intent's actions - * - * @param i Intent to ckeck - * @param actions Multiple actions to compare with - * @return - */ - public static boolean checkAction(Intent i, String... actions) { - for (String action : actions) { - if (checkAction(i, action)) return true; - } - return false; - } + /** + * Checks Intent's actions + * + * @param i Intent to ckeck + * @param actions Multiple actions to compare with + */ + public static boolean checkAction (Intent i, String... actions) { + for (String action : actions) { + if (checkAction(i, action)) { + return true; + } + } + return false; + } - private static List getCompatiblePackages(Context ctx, Intent intent) { - final PackageManager mgr = ctx.getPackageManager(); - return mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); - } + private static List getCompatiblePackages (Context ctx, Intent intent) { + final PackageManager mgr = ctx.getPackageManager(); + return mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/KeyboardUtils.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/KeyboardUtils.java index 54bc605f2b..9320ef4b5b 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/KeyboardUtils.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/KeyboardUtils.java @@ -21,60 +21,59 @@ import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; - import it.feio.android.omninotes.MainActivity; public class KeyboardUtils { - public static void showKeyboard(View view) { - if (view == null) { - return; - } + public static void showKeyboard (View view) { + if (view == null) { + return; + } - view.requestFocus(); + view.requestFocus(); - InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService( - Context.INPUT_METHOD_SERVICE); - inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); + InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService( + Context.INPUT_METHOD_SERVICE); + inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); - ((InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view, 0); + ((InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view, 0); - if (!isKeyboardShowed(view)) { - inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - } + if (!isKeyboardShowed(view)) { + inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } + } - public static boolean isKeyboardShowed(View view) { - if (view == null) { - return false; - } - InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService( - Context.INPUT_METHOD_SERVICE); - return inputManager.isActive(view); + public static boolean isKeyboardShowed (View view) { + if (view == null) { + return false; } + InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService( + Context.INPUT_METHOD_SERVICE); + return inputManager.isActive(view); + } - public static void hideKeyboard(View view) { - if (view == null) { - return; - } - InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - if (!imm.isActive()) { - return; - } - imm.hideSoftInputFromWindow(view.getWindowToken(), 0); + public static void hideKeyboard (View view) { + if (view == null) { + return; + } + InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (!imm.isActive()) { + return; + } + imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // if (!isKeyboardShowed(view)) { // imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, InputMethodManager.RESULT_HIDDEN); // } - } + } - public static void hideKeyboard(MainActivity mActivity) { - mActivity.getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); - } + public static void hideKeyboard (MainActivity mActivity) { + mActivity.getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/LoadingDialog.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/LoadingDialog.java index 927a30c1f5..695dd34c60 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/LoadingDialog.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/LoadingDialog.java @@ -22,19 +22,19 @@ public class LoadingDialog extends ProgressDialog { - Context context; + Context context; - public LoadingDialog(Context context) { - super(context); - this.context = context; - } + public LoadingDialog (Context context) { + super(context); + this.context = context; + } - @Override - public void onBackPressed() { - super.onBackPressed(); - this.cancel(); - } + @Override + public void onBackPressed () { + super.onBackPressed(); + this.cancel(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/MiscUtils.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/MiscUtils.java index 2efe8ea60c..96776f3819 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/MiscUtils.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/MiscUtils.java @@ -23,10 +23,10 @@ public class MiscUtils { - /** - * Performs a full app restart - */ - public static void restartApp(final Context mContext, Class activityClass) { + /** + * Performs a full app restart + */ + public static void restartApp (final Context mContext, Class activityClass) { // Intent intent = new Intent(mContext, activityClass); // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); @@ -35,22 +35,23 @@ public static void restartApp(final Context mContext, Class activityClass) { // PendingIntent.FLAG_CANCEL_CURRENT); // AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); - System.exit(0); - } - - - /** - * Checks Google Play Store availability - * @param context Application context - * @return True if Play Store is installed on the device - */ - public static boolean isGooglePlayAvailable(Context context) { - try { - context.getPackageManager().getPackageInfo("com.android.vending", 0); - return true; - } catch (PackageManager.NameNotFoundException e) { - return false; - } + System.exit(0); + } + + + /** + * Checks Google Play Store availability + * + * @param context Application context + * @return True if Play Store is installed on the device + */ + public static boolean isGooglePlayAvailable (Context context) { + try { + context.getPackageManager().getPackageInfo("com.android.vending", 0); + return true; + } catch (PackageManager.NameNotFoundException e) { + return false; } + } } \ No newline at end of file diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Navigation.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Navigation.java index 8b2debe740..de487b4105 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Navigation.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Navigation.java @@ -21,98 +21,99 @@ import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; import it.feio.android.omninotes.models.Category; - import java.util.ArrayList; import java.util.Arrays; public class Navigation { - public static final int NOTES = 0; - public static final int ARCHIVE = 1; - public static final int REMINDERS = 2; - public static final int TRASH = 3; - public static final int UNCATEGORIZED = 4; - public static final int CATEGORY = 5; - - - /** - * Returns actual navigation status - */ - public static int getNavigation() { - String[] navigationListCodes = OmniNotes.getAppContext().getResources().getStringArray(R.array.navigation_list_codes); - String navigation = getNavigationText(); - - if (navigationListCodes[NOTES].equals(navigation)) { - return NOTES; - } else if (navigationListCodes[ARCHIVE].equals(navigation)) { - return ARCHIVE; - } else if (navigationListCodes[REMINDERS].equals(navigation)) { - return REMINDERS; - } else if (navigationListCodes[TRASH].equals(navigation)) { - return TRASH; - } else if (navigationListCodes[UNCATEGORIZED].equals(navigation)) { - return UNCATEGORIZED; - } else { - return CATEGORY; - } - } - - - public static String getNavigationText() { - Context mContext = OmniNotes.getAppContext(); - String[] navigationListCodes = mContext.getResources().getStringArray(R.array.navigation_list_codes); - @SuppressWarnings("static-access") - String navigation = mContext.getSharedPreferences(Constants.PREFS_NAME, - mContext.MODE_MULTI_PROCESS).getString(Constants.PREF_NAVIGATION, navigationListCodes[0]); - return navigation; - } - - - /** - * Retrieves category currently shown - * - * @return id of category or null if current navigation is not a category - */ - public static Long getCategory() { - if (getNavigation() == CATEGORY) { - return Long.valueOf(OmniNotes.getAppContext().getSharedPreferences(Constants.PREFS_NAME, Context - .MODE_MULTI_PROCESS).getString(Constants.PREF_NAVIGATION, "")); - } else { - return null; - } + public static final int NOTES = 0; + public static final int ARCHIVE = 1; + public static final int REMINDERS = 2; + public static final int TRASH = 3; + public static final int UNCATEGORIZED = 4; + public static final int CATEGORY = 5; + + + /** + * Returns actual navigation status + */ + public static int getNavigation () { + String[] navigationListCodes = OmniNotes.getAppContext().getResources().getStringArray( + R.array.navigation_list_codes); + String navigation = getNavigationText(); + + if (navigationListCodes[NOTES].equals(navigation)) { + return NOTES; + } else if (navigationListCodes[ARCHIVE].equals(navigation)) { + return ARCHIVE; + } else if (navigationListCodes[REMINDERS].equals(navigation)) { + return REMINDERS; + } else if (navigationListCodes[TRASH].equals(navigation)) { + return TRASH; + } else if (navigationListCodes[UNCATEGORIZED].equals(navigation)) { + return UNCATEGORIZED; + } else { + return CATEGORY; } - - - /** - * Checks if passed parameters is the actual navigation status - */ - public static boolean checkNavigation(int navigationToCheck) { - return checkNavigation(new Integer[]{navigationToCheck}); + } + + + public static String getNavigationText () { + Context mContext = OmniNotes.getAppContext(); + String[] navigationListCodes = mContext.getResources().getStringArray(R.array.navigation_list_codes); + @SuppressWarnings("static-access") + String navigation = mContext.getSharedPreferences(Constants.PREFS_NAME, + mContext.MODE_MULTI_PROCESS).getString(Constants.PREF_NAVIGATION, navigationListCodes[0]); + return navigation; + } + + + /** + * Retrieves category currently shown + * + * @return id of category or null if current navigation is not a category + */ + public static Long getCategory () { + if (getNavigation() == CATEGORY) { + return Long.valueOf(OmniNotes.getAppContext().getSharedPreferences(Constants.PREFS_NAME, Context + .MODE_MULTI_PROCESS).getString(Constants.PREF_NAVIGATION, "")); + } else { + return null; } + } - public static boolean checkNavigation(Integer[] navigationsToCheck) { - boolean res = false; - int navigation = getNavigation(); - for (int navigationToCheck : new ArrayList<>(Arrays.asList(navigationsToCheck))) { - if (navigation == navigationToCheck) { - res = true; - break; - } - } - return res; - } + /** + * Checks if passed parameters is the actual navigation status + */ + public static boolean checkNavigation (int navigationToCheck) { + return checkNavigation(new Integer[]{navigationToCheck}); + } - /** - * Checks if passed parameters is the category user is actually navigating in - */ - public static boolean checkNavigationCategory(Category categoryToCheck) { - Context mContext = OmniNotes.getAppContext(); - String[] navigationListCodes = mContext.getResources().getStringArray(R.array.navigation_list_codes); - String navigation = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).getString(Constants.PREF_NAVIGATION, navigationListCodes[0]); - return (categoryToCheck != null && navigation.equals(String.valueOf(categoryToCheck.getId()))); + public static boolean checkNavigation (Integer[] navigationsToCheck) { + boolean res = false; + int navigation = getNavigation(); + for (int navigationToCheck : new ArrayList<>(Arrays.asList(navigationsToCheck))) { + if (navigation == navigationToCheck) { + res = true; + break; + } } + return res; + } + + + /** + * Checks if passed parameters is the category user is actually navigating in + */ + public static boolean checkNavigationCategory (Category categoryToCheck) { + Context mContext = OmniNotes.getAppContext(); + String[] navigationListCodes = mContext.getResources().getStringArray(R.array.navigation_list_codes); + String navigation = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).getString( + Constants.PREF_NAVIGATION, navigationListCodes[0]); + return (categoryToCheck != null && navigation.equals(String.valueOf(categoryToCheck.getId()))); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ParcelableUtil.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ParcelableUtil.java index 58a36b0825..b681393087 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ParcelableUtil.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ParcelableUtil.java @@ -23,30 +23,29 @@ public class ParcelableUtil { - public static byte[] marshall(Parcelable parceable) { - Parcel parcel = Parcel.obtain(); - parceable.writeToParcel(parcel, 0); - byte[] bytes = parcel.marshall(); - parcel.recycle(); - return bytes; - } - - - public static Parcel unmarshall(byte[] bytes) { - Parcel parcel = Parcel.obtain(); - parcel.unmarshall(bytes, 0, bytes.length); - parcel.setDataPosition(0); // This is extremely important! - return parcel; - } - - - public static T unmarshall(byte[] bytes, Parcelable.Creator creator) { - Parcel parcel = unmarshall(bytes); - T result = creator.createFromParcel(parcel); - parcel.recycle(); - return result; - } - + public static byte[] marshall (Parcelable parceable) { + Parcel parcel = Parcel.obtain(); + parceable.writeToParcel(parcel, 0); + byte[] bytes = parcel.marshall(); + parcel.recycle(); + return bytes; + } + + + public static Parcel unmarshall (byte[] bytes) { + Parcel parcel = Parcel.obtain(); + parcel.unmarshall(bytes, 0, bytes.length); + parcel.setDataPosition(0); // This is extremely important! + return parcel; + } + + + public static T unmarshall (byte[] bytes, Parcelable.Creator creator) { + Parcel parcel = unmarshall(bytes); + T result = creator.createFromParcel(parcel); + parcel.recycle(); + return result; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/PasswordHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/PasswordHelper.java index 10e11770af..6c5c4673b7 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/PasswordHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/PasswordHelper.java @@ -24,10 +24,8 @@ import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; - import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; - import de.greenrobot.event.EventBus; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; @@ -42,119 +40,119 @@ public class PasswordHelper { - public static void requestPassword(final Activity mActivity, final PasswordValidator mPasswordValidator) { - LayoutInflater inflater = mActivity.getLayoutInflater(); - final View v = inflater.inflate(R.layout.password_request_dialog_layout, null); - final EditText passwordEditText = (EditText) v.findViewById(R.id.password_request); - - MaterialDialog dialog = new MaterialDialog.Builder(mActivity) - .autoDismiss(false) - .title(R.string.insert_security_password) - .customView(v, false) - .positiveText(R.string.ok) - .positiveColorRes(R.color.colorPrimary) - .onPositive((dialog12, which) -> { - // When positive button is pressed password correctness is checked - String oldPassword = mActivity.getSharedPreferences(Constants.PREFS_NAME, Context - .MODE_MULTI_PROCESS) - .getString(Constants.PREF_PASSWORD, ""); - String password = passwordEditText.getText().toString(); - // The check is done on password's hash stored in preferences - boolean result = Security.md5(password).equals(oldPassword); - - // In case password is ok dialog is dismissed and result sent to callback - if (result) { - KeyboardUtils.hideKeyboard(passwordEditText); - dialog12.dismiss(); - mPasswordValidator.onPasswordValidated(PasswordValidator.Result.SUCCEED); - // If password is wrong the auth flow is not interrupted and simply a message is shown - } else { - passwordEditText.setError(mActivity.getString(R.string.wrong_password)); - } - }) - .neutralText(mActivity.getResources().getString(R.string.password_forgot)) - .onNeutral((dialog13, which) -> { - PasswordHelper.resetPassword(mActivity); - mPasswordValidator.onPasswordValidated(PasswordValidator.Result.RESTORE); - dialog13.dismiss(); - }) - .build(); - - dialog.setOnCancelListener(dialog1 -> { + public static void requestPassword (final Activity mActivity, final PasswordValidator mPasswordValidator) { + LayoutInflater inflater = mActivity.getLayoutInflater(); + final View v = inflater.inflate(R.layout.password_request_dialog_layout, null); + final EditText passwordEditText = v.findViewById(R.id.password_request); + + MaterialDialog dialog = new MaterialDialog.Builder(mActivity) + .autoDismiss(false) + .title(R.string.insert_security_password) + .customView(v, false) + .positiveText(R.string.ok) + .positiveColorRes(R.color.colorPrimary) + .onPositive((dialog12, which) -> { + // When positive button is pressed password correctness is checked + String oldPassword = mActivity.getSharedPreferences(Constants.PREFS_NAME, Context + .MODE_MULTI_PROCESS) + .getString(Constants.PREF_PASSWORD, ""); + String password = passwordEditText.getText().toString(); + // The check is done on password's hash stored in preferences + boolean result = Security.md5(password).equals(oldPassword); + + // In case password is ok dialog is dismissed and result sent to callback + if (result) { KeyboardUtils.hideKeyboard(passwordEditText); - dialog1.dismiss(); - mPasswordValidator.onPasswordValidated(PasswordValidator.Result.FAIL); - }); - - passwordEditText.setOnEditorActionListener((textView, actionId, keyEvent) -> { - if (actionId == EditorInfo.IME_ACTION_DONE) { - dialog.getActionButton(DialogAction.POSITIVE).callOnClick(); - return true; - } - return false; - }); - - dialog.show(); - - new Handler().postDelayed(() -> KeyboardUtils.showKeyboard(passwordEditText), 100); - } - - - public static void resetPassword(final Activity mActivity) { - View layout = mActivity.getLayoutInflater().inflate(R.layout.password_reset_dialog_layout, null); - final EditText answerEditText = (EditText) layout.findViewById(R.id.reset_password_answer); - - MaterialDialog dialog = new MaterialDialog.Builder(mActivity) - .title(OmniNotes.getSharedPreferences().getString(Constants.PREF_PASSWORD_QUESTION, "")) - .customView(layout, false) - .autoDismiss(false) - .contentColorRes(R.color.text_color) - .positiveText(R.string.ok) - .onPositive((dialogElement, which) -> { - // When positive button is pressed answer correctness is checked - String oldAnswer = OmniNotes.getSharedPreferences().getString(Constants.PREF_PASSWORD_ANSWER, ""); - String answer1 = answerEditText.getText().toString(); - // The check is done on password's hash stored in preferences - boolean result = Security.md5(answer1).equals(oldAnswer); - if (result) { - dialogElement.dismiss(); - removePassword(); - } else { - answerEditText.setError(mActivity.getString(R.string.wrong_answer)); - } - }).build(); - dialog.show(); - - answerEditText.setOnEditorActionListener((textView, actionId, keyEvent) -> { - if (actionId == EditorInfo.IME_ACTION_DONE) { - dialog.getActionButton(DialogAction.POSITIVE).callOnClick(); - return true; - } - return false; - }); - - new Handler().postDelayed(() -> KeyboardUtils.showKeyboard(answerEditText), 100); - } - - - public static void removePassword() { - Observable - .from(DbHelper.getInstance().getNotesWithLock(true)) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .doOnNext(note -> { - note.setLocked(false); - DbHelper.getInstance().updateNote(note, false); - }) - .doOnCompleted(() -> { - OmniNotes.getSharedPreferences().edit() - .remove(Constants.PREF_PASSWORD) - .remove(Constants.PREF_PASSWORD_QUESTION) - .remove(Constants.PREF_PASSWORD_ANSWER) - .remove("settings_password_access") - .apply(); - EventBus.getDefault().post(new PasswordRemovedEvent()); - }) - .subscribe(); - } + dialog12.dismiss(); + mPasswordValidator.onPasswordValidated(PasswordValidator.Result.SUCCEED); + // If password is wrong the auth flow is not interrupted and simply a message is shown + } else { + passwordEditText.setError(mActivity.getString(R.string.wrong_password)); + } + }) + .neutralText(mActivity.getResources().getString(R.string.password_forgot)) + .onNeutral((dialog13, which) -> { + PasswordHelper.resetPassword(mActivity); + mPasswordValidator.onPasswordValidated(PasswordValidator.Result.RESTORE); + dialog13.dismiss(); + }) + .build(); + + dialog.setOnCancelListener(dialog1 -> { + KeyboardUtils.hideKeyboard(passwordEditText); + dialog1.dismiss(); + mPasswordValidator.onPasswordValidated(PasswordValidator.Result.FAIL); + }); + + passwordEditText.setOnEditorActionListener((textView, actionId, keyEvent) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + dialog.getActionButton(DialogAction.POSITIVE).callOnClick(); + return true; + } + return false; + }); + + dialog.show(); + + new Handler().postDelayed(() -> KeyboardUtils.showKeyboard(passwordEditText), 100); + } + + + public static void resetPassword (final Activity mActivity) { + View layout = mActivity.getLayoutInflater().inflate(R.layout.password_reset_dialog_layout, null); + final EditText answerEditText = layout.findViewById(R.id.reset_password_answer); + + MaterialDialog dialog = new MaterialDialog.Builder(mActivity) + .title(OmniNotes.getSharedPreferences().getString(Constants.PREF_PASSWORD_QUESTION, "")) + .customView(layout, false) + .autoDismiss(false) + .contentColorRes(R.color.text_color) + .positiveText(R.string.ok) + .onPositive((dialogElement, which) -> { + // When positive button is pressed answer correctness is checked + String oldAnswer = OmniNotes.getSharedPreferences().getString(Constants.PREF_PASSWORD_ANSWER, ""); + String answer1 = answerEditText.getText().toString(); + // The check is done on password's hash stored in preferences + boolean result = Security.md5(answer1).equals(oldAnswer); + if (result) { + dialogElement.dismiss(); + removePassword(); + } else { + answerEditText.setError(mActivity.getString(R.string.wrong_answer)); + } + }).build(); + dialog.show(); + + answerEditText.setOnEditorActionListener((textView, actionId, keyEvent) -> { + if (actionId == EditorInfo.IME_ACTION_DONE) { + dialog.getActionButton(DialogAction.POSITIVE).callOnClick(); + return true; + } + return false; + }); + + new Handler().postDelayed(() -> KeyboardUtils.showKeyboard(answerEditText), 100); + } + + + public static void removePassword () { + Observable + .from(DbHelper.getInstance().getNotesWithLock(true)) + .subscribeOn(Schedulers.newThread()) + .observeOn(AndroidSchedulers.mainThread()) + .doOnNext(note -> { + note.setLocked(false); + DbHelper.getInstance().updateNote(note, false); + }) + .doOnCompleted(() -> { + OmniNotes.getSharedPreferences().edit() + .remove(Constants.PREF_PASSWORD) + .remove(Constants.PREF_PASSWORD_QUESTION) + .remove(Constants.PREF_PASSWORD_ANSWER) + .remove("settings_password_access") + .apply(); + EventBus.getDefault().post(new PasswordRemovedEvent()); + }) + .subscribe(); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ReminderHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ReminderHelper.java index f7d664c10a..cea2e63bf1 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ReminderHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ReminderHelper.java @@ -31,70 +31,69 @@ import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.receiver.AlarmReceiver; import it.feio.android.omninotes.utils.date.DateUtils; - import java.util.Calendar; public class ReminderHelper { - public static void addReminder(Context context, Note note) { - if (note.getAlarm() != null) { - addReminder(context, note, Long.parseLong(note.getAlarm())); - } - } - - - public static void addReminder(Context context, Note note, long reminder) { - if (DateUtils.isFuture(reminder)) { - Intent intent = new Intent(context, AlarmReceiver.class); - intent.putExtra(Constants.INTENT_NOTE, ParcelableUtil.marshall(note)); - PendingIntent sender = PendingIntent.getBroadcast(context, getRequestCode(note), intent, - PendingIntent.FLAG_CANCEL_CURRENT); - AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - am.setExact(AlarmManager.RTC_WAKEUP, reminder, sender); - } else { - am.set(AlarmManager.RTC_WAKEUP, reminder, sender); - } - } - } - - - /** - * Checks if exists any reminder for given note - */ - public static boolean checkReminder(Context context, Note note) { - return PendingIntent.getBroadcast(context, getRequestCode(note), new Intent(context, AlarmReceiver - .class), PendingIntent.FLAG_NO_CREATE) != null; - } - - - static int getRequestCode(Note note) { - Long longCode = note.getCreation() != null ? note.getCreation() : Calendar.getInstance().getTimeInMillis() / 1000L; - return longCode.intValue(); - } - - - public static void removeReminder(Context context, Note note) { - if (!TextUtils.isEmpty(note.getAlarm())) { - AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent(context, AlarmReceiver.class); - PendingIntent p = PendingIntent.getBroadcast(context, getRequestCode(note), intent, 0); - am.cancel(p); - p.cancel(); - } - } - - - public static void showReminderMessage(String reminderString) { - if (reminderString != null) { - long reminder = Long.parseLong(reminderString); - if (reminder > Calendar.getInstance().getTimeInMillis()) { - new Handler(OmniNotes.getAppContext().getMainLooper()).post(() -> Toast.makeText(OmniNotes - .getAppContext(), - OmniNotes.getAppContext().getString(R.string.alarm_set_on) + " " + DateHelper.getDateTimeShort - (OmniNotes.getAppContext(), reminder), Toast.LENGTH_LONG).show()); - } - } - } + public static void addReminder (Context context, Note note) { + if (note.getAlarm() != null) { + addReminder(context, note, Long.parseLong(note.getAlarm())); + } + } + + + public static void addReminder (Context context, Note note, long reminder) { + if (DateUtils.isFuture(reminder)) { + Intent intent = new Intent(context, AlarmReceiver.class); + intent.putExtra(Constants.INTENT_NOTE, ParcelableUtil.marshall(note)); + PendingIntent sender = PendingIntent.getBroadcast(context, getRequestCode(note), intent, + PendingIntent.FLAG_CANCEL_CURRENT); + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + am.setExact(AlarmManager.RTC_WAKEUP, reminder, sender); + } else { + am.set(AlarmManager.RTC_WAKEUP, reminder, sender); + } + } + } + + + /** + * Checks if exists any reminder for given note + */ + public static boolean checkReminder (Context context, Note note) { + return PendingIntent.getBroadcast(context, getRequestCode(note), new Intent(context, AlarmReceiver + .class), PendingIntent.FLAG_NO_CREATE) != null; + } + + + static int getRequestCode (Note note) { + Long longCode = note.getCreation() != null ? note.getCreation() : Calendar.getInstance().getTimeInMillis() / 1000L; + return longCode.intValue(); + } + + + public static void removeReminder (Context context, Note note) { + if (!TextUtils.isEmpty(note.getAlarm())) { + AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + Intent intent = new Intent(context, AlarmReceiver.class); + PendingIntent p = PendingIntent.getBroadcast(context, getRequestCode(note), intent, 0); + am.cancel(p); + p.cancel(); + } + } + + + public static void showReminderMessage (String reminderString) { + if (reminderString != null) { + long reminder = Long.parseLong(reminderString); + if (reminder > Calendar.getInstance().getTimeInMillis()) { + new Handler(OmniNotes.getAppContext().getMainLooper()).post(() -> Toast.makeText(OmniNotes + .getAppContext(), + OmniNotes.getAppContext().getString(R.string.alarm_set_on) + " " + DateHelper.getDateTimeShort + (OmniNotes.getAppContext(), reminder), Toast.LENGTH_LONG).show()); + } + } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ResourcesUtils.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ResourcesUtils.java index c122d2adad..52f9c1df91 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ResourcesUtils.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ResourcesUtils.java @@ -22,10 +22,10 @@ public class ResourcesUtils { - public enum ResourceIdentifiers {xml, id, array} + public enum ResourceIdentifiers {xml, id, array} - public static int getXmlId(Context context, ResourceIdentifiers resourceIdentifier, String resourceName) { - return context.getResources().getIdentifier(resourceName, resourceIdentifier.name(), context.getPackageName()); - } + public static int getXmlId (Context context, ResourceIdentifiers resourceIdentifier, String resourceName) { + return context.getResources().getIdentifier(resourceName, resourceIdentifier.name(), context.getPackageName()); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Security.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Security.java index 6c33a4be1a..1de9554f67 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/Security.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/Security.java @@ -18,13 +18,13 @@ package it.feio.android.omninotes.utils; import android.util.Base64; - +import it.feio.android.omninotes.helpers.LogDelegate; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; - import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; @@ -33,78 +33,77 @@ import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; -import it.feio.android.omninotes.helpers.LogDelegate; - public class Security { - public static String md5(String s) { - try { - // Create MD5 Hash - MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); - digest.update(s.getBytes()); - byte messageDigest[] = digest.digest(); + public static String md5 (String s) { + try { + // Create MD5 Hash + MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); + digest.update(s.getBytes()); + byte[] messageDigest = digest.digest(); - // Create Hex String - StringBuilder hexString = new StringBuilder(); - for (int i = 0; i < messageDigest.length; i++) - hexString.append(Integer.toHexString(0xFF & messageDigest[i])); - return hexString.toString(); + // Create Hex String + StringBuilder hexString = new StringBuilder(); + for (int i = 0; i < messageDigest.length; i++) { + hexString.append(Integer.toHexString(0xFF & messageDigest[i])); + } + return hexString.toString(); - } catch (NoSuchAlgorithmException e) { - LogDelegate.w("Something is gone wrong calculating MD5", e); - } - return ""; + } catch (NoSuchAlgorithmException e) { + LogDelegate.w("Something is gone wrong calculating MD5", e); } - - - public static String encrypt(String value, String password) { - String encrypedValue = ""; - try { - DESKeySpec keySpec = new DESKeySpec(password.getBytes("UTF8")); - SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); - SecretKey key = keyFactory.generateSecret(keySpec); - byte[] clearText = value.getBytes("UTF8"); - // Cipher is not thread safe - Cipher cipher = Cipher.getInstance("DES"); - cipher.init(Cipher.ENCRYPT_MODE, key); - encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT); - return encrypedValue; - } catch (InvalidKeyException | NoSuchPaddingException | InvalidKeySpecException | BadPaddingException | - IllegalBlockSizeException | NoSuchAlgorithmException | UnsupportedEncodingException e) { - LogDelegate.w("Something is gone wrong encrypting", e); - } - return encrypedValue; + return ""; + } + + + public static String encrypt (String value, String password) { + String encrypedValue = ""; + try { + DESKeySpec keySpec = new DESKeySpec(password.getBytes(StandardCharsets.UTF_8)); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + SecretKey key = keyFactory.generateSecret(keySpec); + byte[] clearText = value.getBytes(StandardCharsets.UTF_8); + // Cipher is not thread safe + Cipher cipher = Cipher.getInstance("DES"); + cipher.init(Cipher.ENCRYPT_MODE, key); + encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT); + return encrypedValue; + } catch (InvalidKeyException | NoSuchPaddingException | InvalidKeySpecException | BadPaddingException | + IllegalBlockSizeException | NoSuchAlgorithmException e) { + LogDelegate.w("Something is gone wrong encrypting", e); } - - - public static String decrypt(String value, String password) { - String decryptedValue; - try { - DESKeySpec keySpec = new DESKeySpec(password.getBytes("UTF8")); - SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); - SecretKey key = keyFactory.generateSecret(keySpec); - - byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT); - // cipher is not thread safe - Cipher cipher = Cipher.getInstance("DES"); - cipher.init(Cipher.DECRYPT_MODE, key); - byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes)); - - decryptedValue = new String(decrypedValueBytes); - } catch (InvalidKeyException | UnsupportedEncodingException | InvalidKeySpecException | - NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException - e) { - LogDelegate.e("Error decrypting"); - return value; - // try-catch ensure compatibility with old masked (without encryption) values - } catch (IllegalArgumentException e) { - LogDelegate.e("Error decrypting: old notes were not encrypted but just masked to users"); - return value; - } - return decryptedValue; + return encrypedValue; + } + + + public static String decrypt (String value, String password) { + String decryptedValue; + try { + DESKeySpec keySpec = new DESKeySpec(password.getBytes(StandardCharsets.UTF_8)); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + SecretKey key = keyFactory.generateSecret(keySpec); + + byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT); + // cipher is not thread safe + Cipher cipher = Cipher.getInstance("DES"); + cipher.init(Cipher.DECRYPT_MODE, key); + byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes)); + + decryptedValue = new String(decrypedValueBytes); + } catch (InvalidKeyException | InvalidKeySpecException | + NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException + e) { + LogDelegate.e("Error decrypting"); + return value; + // try-catch ensure compatibility with old masked (without encryption) values + } catch (IllegalArgumentException e) { + LogDelegate.e("Error decrypting: old notes were not encrypted but just masked to users"); + return value; } + return decryptedValue; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ShortcutHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ShortcutHelper.java index 5774ff020c..27f621c95a 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/ShortcutHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/ShortcutHelper.java @@ -24,7 +24,6 @@ import android.content.pm.ShortcutManager; import android.graphics.drawable.Icon; import android.os.Build; - import it.feio.android.omninotes.MainActivity; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; @@ -35,66 +34,65 @@ public class ShortcutHelper { - /** - * Adding shortcut on Home screen - */ - public static void addShortcut(Context context, Note note) { + /** + * Adding shortcut on Home screen + */ + public static void addShortcut (Context context, Note note) { - String shortcutTitle = note.getTitle().length() > 0 ? note.getTitle() : DateHelper.getFormattedDate(note - .getCreation(), OmniNotes.getSharedPreferences().getBoolean(Constants - .PREF_PRETTIFIED_DATES, true)); + String shortcutTitle = note.getTitle().length() > 0 ? note.getTitle() : DateHelper.getFormattedDate(note + .getCreation(), OmniNotes.getSharedPreferences().getBoolean(Constants + .PREF_PRETTIFIED_DATES, true)); - if(Build.VERSION.SDK_INT < 26) { - Intent shortcutIntent = new Intent(context, MainActivity.class); - shortcutIntent.putExtra(Constants.INTENT_KEY, note.get_id()); - shortcutIntent.setAction(Constants.ACTION_SHORTCUT); + if (Build.VERSION.SDK_INT < 26) { + Intent shortcutIntent = new Intent(context, MainActivity.class); + shortcutIntent.putExtra(Constants.INTENT_KEY, note.get_id()); + shortcutIntent.setAction(Constants.ACTION_SHORTCUT); - Intent addIntent = new Intent(); - addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); - addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutTitle); - addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, - Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_shortcut)); - addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + Intent addIntent = new Intent(); + addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutTitle); + addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_shortcut)); + addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); - context.sendBroadcast(addIntent); - } - else { - ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class); - if (shortcutManager.isRequestPinShortcutSupported()) { - Intent intent = new Intent(context.getApplicationContext(), context.getClass()); - intent.setAction(Intent.ACTION_MAIN); - ShortcutInfo pinShortcutInfo = new ShortcutInfo - .Builder(context,"pinned-shortcut") - .setIcon(Icon.createWithResource(context, R.drawable.ic_shortcut)) - .setIntent(intent) - .setShortLabel(shortcutTitle) - .build(); - Intent pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo); - //Get notified when a shortcut is pinned successfully// - PendingIntent successCallback = PendingIntent.getBroadcast(context, 0, pinnedShortcutCallbackIntent, 0); - shortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.getIntentSender() - ); - } - } + context.sendBroadcast(addIntent); + } else { + ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class); + if (shortcutManager.isRequestPinShortcutSupported()) { + Intent intent = new Intent(context.getApplicationContext(), context.getClass()); + intent.setAction(Intent.ACTION_MAIN); + ShortcutInfo pinShortcutInfo = new ShortcutInfo + .Builder(context, "pinned-shortcut") + .setIcon(Icon.createWithResource(context, R.drawable.ic_shortcut)) + .setIntent(intent) + .setShortLabel(shortcutTitle) + .build(); + Intent pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo); + //Get notified when a shortcut is pinned successfully// + PendingIntent successCallback = PendingIntent.getBroadcast(context, 0, pinnedShortcutCallbackIntent, 0); + shortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.getIntentSender() + ); + } } + } - /** - * Removes note shortcut from home launcher - */ - public static void removeshortCut(Context context, Note note) { - Intent shortcutIntent = new Intent(context, MainActivity.class); - shortcutIntent.putExtra(Constants.INTENT_KEY, note.get_id()); - shortcutIntent.setAction(Constants.ACTION_SHORTCUT); + /** + * Removes note shortcut from home launcher + */ + public static void removeshortCut (Context context, Note note) { + Intent shortcutIntent = new Intent(context, MainActivity.class); + shortcutIntent.putExtra(Constants.INTENT_KEY, note.get_id()); + shortcutIntent.setAction(Constants.ACTION_SHORTCUT); - Intent addIntent = new Intent(); - addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); - String shortcutTitle = note.getTitle().length() > 0 ? note.getTitle() : DateHelper.getFormattedDate(note - .getCreation(), OmniNotes.getSharedPreferences().getBoolean(Constants - .PREF_PRETTIFIED_DATES, true)); + Intent addIntent = new Intent(); + addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + String shortcutTitle = note.getTitle().length() > 0 ? note.getTitle() : DateHelper.getFormattedDate(note + .getCreation(), OmniNotes.getSharedPreferences().getBoolean(Constants + .PREF_PRETTIFIED_DATES, true)); - addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutTitle); + addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutTitle); - addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT"); - context.sendBroadcast(addIntent); - } + addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT"); + context.sendBroadcast(addIntent); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/StorageHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/StorageHelper.java index 702ba371b2..c8a0aed3c8 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/StorageHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/StorageHelper.java @@ -27,10 +27,10 @@ import android.text.TextUtils; import android.webkit.MimeTypeMap; import android.widget.Toast; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; - +import it.feio.android.omninotes.OmniNotes; +import it.feio.android.omninotes.R; +import it.feio.android.omninotes.helpers.LogDelegate; +import it.feio.android.omninotes.models.Attachment; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -43,497 +43,468 @@ import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; - -import it.feio.android.omninotes.OmniNotes; -import it.feio.android.omninotes.R; -import it.feio.android.omninotes.helpers.LogDelegate; -import it.feio.android.omninotes.models.Attachment; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; public class StorageHelper { - public static boolean checkStorage() { - boolean mExternalStorageAvailable; - boolean mExternalStorageWriteable; - String state = Environment.getExternalStorageState(); - - switch (state) { - case Environment.MEDIA_MOUNTED: - // We can read and write the media - mExternalStorageAvailable = mExternalStorageWriteable = true; - break; - case Environment.MEDIA_MOUNTED_READ_ONLY: - // We can only read the media - mExternalStorageAvailable = true; - mExternalStorageWriteable = false; - break; - default: - // Something else is wrong. It may be one of many other states, but - // all we need - // to know is we can neither read nor write - mExternalStorageAvailable = mExternalStorageWriteable = false; - break; - } - return mExternalStorageAvailable && mExternalStorageWriteable; + public static boolean checkStorage () { + boolean mExternalStorageAvailable; + boolean mExternalStorageWriteable; + String state = Environment.getExternalStorageState(); + + switch (state) { + case Environment.MEDIA_MOUNTED: + // We can read and write the media + mExternalStorageAvailable = mExternalStorageWriteable = true; + break; + case Environment.MEDIA_MOUNTED_READ_ONLY: + // We can only read the media + mExternalStorageAvailable = true; + mExternalStorageWriteable = false; + break; + default: + // Something else is wrong. It may be one of many other states, but + // all we need + // to know is we can neither read nor write + mExternalStorageAvailable = mExternalStorageWriteable = false; + break; } + return mExternalStorageAvailable && mExternalStorageWriteable; + } - public static String getStorageDir() { - // return Environment.getExternalStorageDirectory() + File.separator + - // Constants.TAG + File.separator; - return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); - } + public static String getStorageDir () { + // return Environment.getExternalStorageDirectory() + File.separator + + // Constants.TAG + File.separator; + return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); + } - public static File getAttachmentDir() { - return OmniNotes.getAppContext().getExternalFilesDir(null); - } + public static File getAttachmentDir () { + return OmniNotes.getAppContext().getExternalFilesDir(null); + } - /** - * Retrieves the folderwhere to store data to sync notes - * - * @param mContext - * @return - */ - public static File getDbSyncDir(Context mContext) { - File extFilesDir = mContext.getExternalFilesDir(null); - File dbSyncDir = new File(extFilesDir, Constants.APP_STORAGE_DIRECTORY_SB_SYNC); - dbSyncDir.mkdirs(); - if (dbSyncDir.exists() && dbSyncDir.isDirectory()) { - return dbSyncDir; - } else { - return null; - } + /** + * Retrieves the folderwhere to store data to sync notes + */ + public static File getDbSyncDir (Context mContext) { + File extFilesDir = mContext.getExternalFilesDir(null); + File dbSyncDir = new File(extFilesDir, Constants.APP_STORAGE_DIRECTORY_SB_SYNC); + dbSyncDir.mkdirs(); + if (dbSyncDir.exists() && dbSyncDir.isDirectory()) { + return dbSyncDir; + } else { + return null; } + } - /** - * Create a path where we will place our private file on external - */ - public static File createExternalStoragePrivateFile(Context mContext, Uri uri, String extension) { + /** + * Create a path where we will place our private file on external + */ + public static File createExternalStoragePrivateFile (Context mContext, Uri uri, String extension) { - if (!checkStorage()) { - Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show(); - return null; - } - File file = createNewAttachmentFile(mContext, extension); - - InputStream contentResolverInputStream = null; - OutputStream contentResolverOutputStream = null; - try { - contentResolverInputStream = mContext.getContentResolver().openInputStream(uri); - contentResolverOutputStream = new FileOutputStream(file); - copyFile(contentResolverInputStream, contentResolverOutputStream); - } catch (IOException e) { - try { - FileUtils.copyFile(new File(FileHelper.getPath(mContext, uri)), file); - // It's a path!! - } catch (NullPointerException e1) { - try { - FileUtils.copyFile(new File(uri.getPath()), file); - } catch (IOException e2) { - LogDelegate.e("Error writing " + file, e2); - file = null; - } - } catch (IOException e2) { - LogDelegate.e("Error writing " + file, e2); - file = null; - } - } finally { - try { - if (contentResolverInputStream != null) { - contentResolverInputStream.close(); - } - if (contentResolverOutputStream != null) { - contentResolverOutputStream.close(); - } - } catch (IOException e) { - LogDelegate.e("Error closing streams", e); - } - - } - return file; + if (!checkStorage()) { + Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show(); + return null; } - - public static boolean copyFile(File source, File destination) { - FileInputStream is = null; - FileOutputStream os = null; + File file = createNewAttachmentFile(mContext, extension); + + InputStream contentResolverInputStream = null; + OutputStream contentResolverOutputStream = null; + try { + contentResolverInputStream = mContext.getContentResolver().openInputStream(uri); + contentResolverOutputStream = new FileOutputStream(file); + copyFile(contentResolverInputStream, contentResolverOutputStream); + } catch (IOException e) { + try { + FileUtils.copyFile(new File(FileHelper.getPath(mContext, uri)), file); + // It's a path!! + } catch (NullPointerException e1) { try { - is = new FileInputStream(source); - os = new FileOutputStream(destination); - return copyFile(is, os); - } catch (FileNotFoundException e) { - LogDelegate.e("Error copying file", e); - return false; - } finally { - try { - if (is != null) { - is.close(); - } - if (os != null) { - os.close(); - } - } catch (IOException e) { - LogDelegate.e("Error closing streams", e); - } + FileUtils.copyFile(new File(uri.getPath()), file); + } catch (IOException e2) { + LogDelegate.e("Error writing " + file, e2); + file = null; } - } - - - /** - * Generic file copy method - * - * @param is Input - * @param os Output - * @return True if copy is done, false otherwise - */ - public static boolean copyFile(InputStream is, OutputStream os) { - try { - IOUtils.copy(is, os); - return true; - } catch (IOException e) { - LogDelegate.e("Error copying file", e); - return false; + } catch (IOException e2) { + LogDelegate.e("Error writing " + file, e2); + file = null; + } + } finally { + try { + if (contentResolverInputStream != null) { + contentResolverInputStream.close(); } - } - - - public static boolean deleteExternalStoragePrivateFile(Context mContext, String name) { - // Checks for external storage availability - if (!checkStorage()) { - Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show(); - return false; + if (contentResolverOutputStream != null) { + contentResolverOutputStream.close(); } - File file = new File(mContext.getExternalFilesDir(null), name); - return file.delete(); - } - + } catch (IOException e) { + LogDelegate.e("Error closing streams", e); + } - public static boolean delete(Context mContext, String path) { - if (!checkStorage()) { - Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show(); - return false; + } + return file; + } + + public static boolean copyFile (File source, File destination) { + FileInputStream is = null; + FileOutputStream os = null; + try { + is = new FileInputStream(source); + os = new FileOutputStream(destination); + return copyFile(is, os); + } catch (FileNotFoundException e) { + LogDelegate.e("Error copying file", e); + return false; + } finally { + try { + if (is != null) { + is.close(); } - try { - FileUtils.forceDelete(new File(path)); - } catch (IOException e) { - LogDelegate.e("Can't delete '" + path + "': " + e.getMessage()); - return false; + if (os != null) { + os.close(); } - return true; + } catch (IOException e) { + LogDelegate.e("Error closing streams", e); + } } - - - public static String getRealPathFromURI(Context mContext, Uri contentUri) { - String[] proj = {MediaStore.Images.Media.DATA}; - Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null); - if (cursor == null) { - return null; - } - int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); - cursor.moveToFirst(); - String path = cursor.getString(column_index); - cursor.close(); - return path; + } + + + /** + * Generic file copy method + * + * @param is Input + * @param os Output + * @return True if copy is done, false otherwise + */ + public static boolean copyFile (InputStream is, OutputStream os) { + try { + IOUtils.copy(is, os); + return true; + } catch (IOException e) { + LogDelegate.e("Error copying file", e); + return false; } + } - public static File createNewAttachmentFile(Context mContext, String extension) { - File f = null; - if (checkStorage()) { - f = new File(mContext.getExternalFilesDir(null), createNewAttachmentName(extension)); - } - return f; + public static boolean deleteExternalStoragePrivateFile (Context mContext, String name) { + // Checks for external storage availability + if (!checkStorage()) { + Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show(); + return false; } + File file = new File(mContext.getExternalFilesDir(null), name); + return file.delete(); + } - private static synchronized String createNewAttachmentName(String extension) { - Calendar now = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SORTABLE); - String name = sdf.format(now.getTime()); - name += extension != null ? extension : ""; - return name; + public static boolean delete (Context mContext, String path) { + if (!checkStorage()) { + Toast.makeText(mContext, mContext.getString(R.string.storage_not_available), Toast.LENGTH_SHORT).show(); + return false; + } + try { + FileUtils.forceDelete(new File(path)); + } catch (IOException e) { + LogDelegate.e("Can't delete '" + path + "': " + e.getMessage()); + return false; } + return true; + } - public static File createNewAttachmentFile(Context mContext) { - return createNewAttachmentFile(mContext, null); + public static String getRealPathFromURI (Context mContext, Uri contentUri) { + String[] proj = {MediaStore.Images.Media.DATA}; + Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null); + if (cursor == null) { + return null; } - - /** - * Create a path where we will place our private file on external - */ - public static File copyToBackupDir(File backupDir, String fileName, InputStream fileInputStream) { - if (!checkStorage()) { - return null; - } - if (!backupDir.exists()) { - backupDir.mkdirs(); - } - File destination = new File(backupDir, fileName); - try { - copyFile(fileInputStream, new FileOutputStream(destination)); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - return destination; + int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); + cursor.moveToFirst(); + String path = cursor.getString(column_index); + cursor.close(); + return path; + } + + + public static File createNewAttachmentFile (Context mContext, String extension) { + File f = null; + if (checkStorage()) { + f = new File(mContext.getExternalFilesDir(null), createNewAttachmentName(extension)); } + return f; + } - public static File getCacheDir(Context mContext) { - File dir = mContext.getExternalCacheDir(); - if (!dir.exists()) - dir.mkdirs(); - return dir; - } + private static synchronized String createNewAttachmentName (String extension) { + Calendar now = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SORTABLE); + String name = sdf.format(now.getTime()); + name += extension != null ? extension : ""; + return name; + } - public static File getExternalStoragePublicDir() { - File dir = new File(Environment.getExternalStorageDirectory() + File.separator + Constants.EXTERNAL_STORAGE_FOLDER + File - .separator); - if (!dir.exists()) - dir.mkdirs(); - return dir; - } - + public static File createNewAttachmentFile (Context mContext) { + return createNewAttachmentFile(mContext, null); + } - public static File getBackupDir(String backupName) { - File backupDir = new File(getExternalStoragePublicDir(), backupName); - if (!backupDir.exists() && backupDir.mkdirs()) { - createNoMediaFile(backupDir); - } - return backupDir; + /** + * Create a path where we will place our private file on external + */ + public static File copyToBackupDir (File backupDir, String fileName, InputStream fileInputStream) { + if (!checkStorage()) { + return null; + } + if (!backupDir.exists()) { + backupDir.mkdirs(); + } + File destination = new File(backupDir, fileName); + try { + copyFile(fileInputStream, new FileOutputStream(destination)); + } catch (FileNotFoundException e) { + e.printStackTrace(); } + return destination; + } - private static void createNoMediaFile(File folder) { - try { - new File(folder, ".nomedia").createNewFile(); - } catch (IOException e) { - LogDelegate.e("Error creating .nomedia file into backup folder"); - } + public static File getCacheDir (Context mContext) { + File dir = mContext.getExternalCacheDir(); + if (!dir.exists()) { + dir.mkdirs(); } + return dir; + } - public static File getSharedPreferencesFile(Context mContext) { - File appData = mContext.getFilesDir().getParentFile(); - String packageName = mContext.getApplicationContext().getPackageName(); - return new File(appData - + System.getProperty("file.separator") - + "shared_prefs" - + System.getProperty("file.separator") - + packageName - + "_preferences.xml"); + public static File getExternalStoragePublicDir () { + File dir = new File( + Environment.getExternalStorageDirectory() + File.separator + Constants.EXTERNAL_STORAGE_FOLDER + File + .separator); + if (!dir.exists()) { + dir.mkdirs(); } + return dir; + } - /** - * Returns a directory size in bytes - */ - @SuppressWarnings("deprecation") - public static long getSize(File directory) { - StatFs statFs = new StatFs(directory.getAbsolutePath()); - long blockSize = 0; - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { - blockSize = statFs.getBlockSizeLong(); - } else { - blockSize = statFs.getBlockSize(); - } - // Can't understand why on some devices this fails - } catch (NoSuchMethodError e) { - LogDelegate.e("Mysterious error", e); - } - return getSize(directory, blockSize); + public static File getBackupDir (String backupName) { + File backupDir = new File(getExternalStoragePublicDir(), backupName); + if (!backupDir.exists() && backupDir.mkdirs()) { + createNoMediaFile(backupDir); } + return backupDir; + } - private static long getSize(File directory, long blockSize) { - if (blockSize == 0) { - throw new InvalidParameterException("Blocksize can't be 0"); - } - File[] files = directory.listFiles(); - if (files != null) { - - // space used by directory itself - long size = directory.length(); - - for (File file : files) { - if (file.isDirectory()) { - // space used by subdirectory - size += getSize(file, blockSize); - } else { - // file size need to rounded up to full block sizes - // (not a perfect function, it adds additional block to 0 sized files - // and file who perfectly fill their blocks) - size += (file.length() / blockSize + 1) * blockSize; - } - } - return size; - } else { - return 0; - } + private static void createNoMediaFile (File folder) { + try { + new File(folder, ".nomedia").createNewFile(); + } catch (IOException e) { + LogDelegate.e("Error creating .nomedia file into backup folder"); } + } + + + public static File getSharedPreferencesFile (Context mContext) { + File appData = mContext.getFilesDir().getParentFile(); + String packageName = mContext.getApplicationContext().getPackageName(); + return new File(appData + + System.getProperty("file.separator") + + "shared_prefs" + + System.getProperty("file.separator") + + packageName + + "_preferences.xml"); + } + + + /** + * Returns a directory size in bytes + */ + @SuppressWarnings("deprecation") + public static long getSize (File directory) { + StatFs statFs = new StatFs(directory.getAbsolutePath()); + long blockSize = 0; + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { + blockSize = statFs.getBlockSizeLong(); + } else { + blockSize = statFs.getBlockSize(); + } + // Can't understand why on some devices this fails + } catch (NoSuchMethodError e) { + LogDelegate.e("Mysterious error", e); + } + return getSize(directory, blockSize); + } - public static boolean copyDirectory(File sourceLocation, File targetLocation) { - boolean res = true; - - // If target is a directory the method will be iterated - if (sourceLocation.isDirectory()) { - if (!targetLocation.exists()) { - targetLocation.mkdirs(); - } + private static long getSize (File directory, long blockSize) { + if (blockSize == 0) { + throw new InvalidParameterException("Blocksize can't be 0"); + } + File[] files = directory.listFiles(); + if (files != null) { - String[] children = sourceLocation.list(); - for (int i = 0; i < sourceLocation.listFiles().length; i++) { - res = res && copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, - children[i])); - } + // space used by directory itself + long size = directory.length(); - // Otherwise a file copy will be performed + for (File file : files) { + if (file.isDirectory()) { + // space used by subdirectory + size += getSize(file, blockSize); } else { - res = copyFile(sourceLocation, targetLocation); + // file size need to rounded up to full block sizes + // (not a perfect function, it adds additional block to 0 sized files + // and file who perfectly fill their blocks) + size += (file.length() / blockSize + 1) * blockSize; } - return res; + } + return size; + } else { + return 0; } + } - /** - * Retrieves uri mime-type using ContentResolver - * - * @param mContext - * @param uri - * @return - */ - public static String getMimeType(Context mContext, Uri uri) { - ContentResolver cR = mContext.getContentResolver(); - String mimeType = cR.getType(uri); - if (mimeType == null) { - mimeType = getMimeType(uri.toString()); - } - return mimeType; - } + public static boolean copyDirectory (File sourceLocation, File targetLocation) { + boolean res = true; + // If target is a directory the method will be iterated + if (sourceLocation.isDirectory()) { + if (!targetLocation.exists()) { + targetLocation.mkdirs(); + } + String[] children = sourceLocation.list(); + for (int i = 0; i < sourceLocation.listFiles().length; i++) { + res = res && copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, + children[i])); + } - public static String getMimeType(String url) { - String type = null; - String extension = MimeTypeMap.getFileExtensionFromUrl(url); - if (extension != null) { - MimeTypeMap mime = MimeTypeMap.getSingleton(); - type = mime.getMimeTypeFromExtension(extension); - } - return type; + // Otherwise a file copy will be performed + } else { + res = copyFile(sourceLocation, targetLocation); } - - - /** - * Retrieves uri mime-type between the ones managed by application - * - * @param mContext - * @param uri - * @return - */ - public static String getMimeTypeInternal(Context mContext, Uri uri) { - String mimeType = getMimeType(mContext, uri); - mimeType = getMimeTypeInternal(mContext, mimeType); - return mimeType; + return res; + } + + + /** + * Retrieves uri mime-type using ContentResolver + */ + public static String getMimeType (Context mContext, Uri uri) { + ContentResolver cR = mContext.getContentResolver(); + String mimeType = cR.getType(uri); + if (mimeType == null) { + mimeType = getMimeType(uri.toString()); } + return mimeType; + } - /** - * Retrieves mime-type between the ones managed by application from given string - * - * @param mContext - * @param mimeType - * @return - */ - public static String getMimeTypeInternal(Context mContext, String mimeType) { - if (mimeType != null) { - if (mimeType.contains("image/")) { - mimeType = Constants.MIME_TYPE_IMAGE; - } else if (mimeType.contains("audio/")) { - mimeType = Constants.MIME_TYPE_AUDIO; - } else if (mimeType.contains("video/")) { - mimeType = Constants.MIME_TYPE_VIDEO; - } else { - mimeType = Constants.MIME_TYPE_FILES; - } - } - return mimeType; + public static String getMimeType (String url) { + String type = null; + String extension = MimeTypeMap.getFileExtensionFromUrl(url); + if (extension != null) { + MimeTypeMap mime = MimeTypeMap.getSingleton(); + type = mime.getMimeTypeFromExtension(extension); } - - - /** - * Creates a new attachment file copying data from source file - * - * @param mContext - * @param uri - * @return - */ - public static Attachment createAttachmentFromUri(Context mContext, Uri uri) { - return createAttachmentFromUri(mContext, uri, false); + return type; + } + + + /** + * Retrieves uri mime-type between the ones managed by application + */ + public static String getMimeTypeInternal (Context mContext, Uri uri) { + String mimeType = getMimeType(mContext, uri); + mimeType = getMimeTypeInternal(mContext, mimeType); + return mimeType; + } + + + /** + * Retrieves mime-type between the ones managed by application from given string + */ + public static String getMimeTypeInternal (Context mContext, String mimeType) { + if (mimeType != null) { + if (mimeType.contains("image/")) { + mimeType = Constants.MIME_TYPE_IMAGE; + } else if (mimeType.contains("audio/")) { + mimeType = Constants.MIME_TYPE_AUDIO; + } else if (mimeType.contains("video/")) { + mimeType = Constants.MIME_TYPE_VIDEO; + } else { + mimeType = Constants.MIME_TYPE_FILES; + } } - - - /** - * Creates a fiile to be used as attachment. - */ - public static Attachment createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) { - String name = FileHelper.getNameFromUri(mContext, uri); - String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri)).toLowerCase( - Locale.getDefault()); - File f; - if (moveSource) { - f = createNewAttachmentFile(mContext, extension); - try { - FileUtils.moveFile(new File(uri.getPath()), f); - } catch (IOException e) { - LogDelegate.e("Can't move file " + uri.getPath()); - } - } else { - f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension); - } - Attachment mAttachment = null; - if (f != null) { - mAttachment = new Attachment(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri)); - mAttachment.setName(name); - mAttachment.setSize(f.length()); - } - return mAttachment; + return mimeType; + } + + + /** + * Creates a new attachment file copying data from source file + */ + public static Attachment createAttachmentFromUri (Context mContext, Uri uri) { + return createAttachmentFromUri(mContext, uri, false); + } + + + /** + * Creates a fiile to be used as attachment. + */ + public static Attachment createAttachmentFromUri (Context mContext, Uri uri, boolean moveSource) { + String name = FileHelper.getNameFromUri(mContext, uri); + String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri)).toLowerCase( + Locale.getDefault()); + File f; + if (moveSource) { + f = createNewAttachmentFile(mContext, extension); + try { + FileUtils.moveFile(new File(uri.getPath()), f); + } catch (IOException e) { + LogDelegate.e("Can't move file " + uri.getPath()); + } + } else { + f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension); } - - - /** - * Creates new attachment from web content - * - * @param mContext - * @param url - * @return - * @throws IOException - */ - public static File createNewAttachmentFileFromHttp(Context mContext, String url) - throws IOException { - if (TextUtils.isEmpty(url)) { - return null; - } - return getFromHttp(url, createNewAttachmentFile(mContext, FileHelper.getFileExtension(url))); + Attachment mAttachment = null; + if (f != null) { + mAttachment = new Attachment(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri)); + mAttachment.setName(name); + mAttachment.setSize(f.length()); } + return mAttachment; + } - /** - * Retrieves a file from its web url - * - * @param url - * @return - * @throws IOException - */ - public static File getFromHttp(String url, File file) throws IOException { - URL imageUrl = new URL(url); - FileUtils.copyURLToFile(imageUrl, file); - return file; + /** + * Creates new attachment from web content + */ + public static File createNewAttachmentFileFromHttp (Context mContext, String url) + throws IOException { + if (TextUtils.isEmpty(url)) { + return null; } + return getFromHttp(url, createNewAttachmentFile(mContext, FileHelper.getFileExtension(url))); + } + + + /** + * Retrieves a file from its web url + */ + public static File getFromHttp (String url, File file) throws IOException { + URL imageUrl = new URL(url); + FileUtils.copyURLToFile(imageUrl, file); + return file; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/SystemHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/SystemHelper.java index 7757aa01df..882ce67f9e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/SystemHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/SystemHelper.java @@ -19,21 +19,19 @@ import android.app.Activity; import android.content.Context; - +import it.feio.android.omninotes.helpers.LogDelegate; import java.io.Closeable; import java.io.IOException; -import it.feio.android.omninotes.helpers.LogDelegate; - /** * Various utility methods */ public class SystemHelper { - /** - * Performs a full app restart - */ - public static void restartApp(final Context mContext, Class activityClass) { + /** + * Performs a full app restart + */ + public static void restartApp (final Context mContext, Class activityClass) { // Intent intent = new Intent(mContext, activityClass); // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); @@ -42,31 +40,32 @@ public static void restartApp(final Context mContext, Class activityClass) { // PendingIntent.FLAG_CANCEL_CURRENT); // AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); - System.exit(0); - } + System.exit(0); + } - /** - * Performs closure of multiple closeables objects - * - * @param closeables Objects to close - */ - public static void closeCloseable(Closeable... closeables) { - for (Closeable closeable : closeables) { - if (closeable != null) { - try { - closeable.close(); - } catch (IOException e) { - LogDelegate.w("Can't close " + closeable, e); - } - } + /** + * Performs closure of multiple closeables objects + * + * @param closeables Objects to close + */ + public static void closeCloseable (Closeable... closeables) { + for (Closeable closeable : closeables) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException e) { + LogDelegate.w("Can't close " + closeable, e); } + } } + } - public static void copyToClipboard(Context context, String text) { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE); - android.content.ClipData clip = android.content.ClipData.newPlainText("text label", text); - clipboard.setPrimaryClip(clip); - } + public static void copyToClipboard (Context context, String text) { + android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService( + Activity.CLIPBOARD_SERVICE); + android.content.ClipData clip = android.content.ClipData.newPlainText("text label", text); + clipboard.setPrimaryClip(clip); + } } \ No newline at end of file diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/TagsHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/TagsHelper.java index 18e9289f88..1b863ab4b8 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/TagsHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/TagsHelper.java @@ -17,137 +17,134 @@ package it.feio.android.omninotes.utils; -import android.support.v4.util.Pair; - -import org.apache.commons.lang.StringUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import static it.feio.android.omninotes.utils.ConstantsBase.TAG_SPECIAL_CHARS_TO_REMOVE; +import android.support.v4.util.Pair; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.models.Note; import it.feio.android.omninotes.models.Tag; import it.feio.android.pixlui.links.UrlCompleter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import org.apache.commons.lang.StringUtils; import rx.Observable; -import static it.feio.android.omninotes.utils.ConstantsBase.TAG_SPECIAL_CHARS_TO_REMOVE; - public class TagsHelper { - public static List getAllTags() { - return DbHelper.getInstance().getTags(); - } + public static List getAllTags () { + return DbHelper.getInstance().getTags(); + } - public static HashMap retrieveTags(Note note) { - HashMap tagsMap = new HashMap<>(); - String[] words = (note.getTitle() + " " + note.getContent()).replaceAll("\n", " ").trim().split(" "); - for (String word: words) { - String parsedHashtag = UrlCompleter.parseHashtag(word); - if (StringUtils.isNotEmpty(parsedHashtag)) { - int count = tagsMap.get(parsedHashtag) == null ? 0 : tagsMap.get(parsedHashtag); - tagsMap.put(parsedHashtag, ++count); - } - } - return tagsMap; - } - - - public static Pair> addTagToNote(List tags, Integer[] selectedTags, Note note) { - StringBuilder sbTags = new StringBuilder(); - List tagsToRemove = new ArrayList<>(); - HashMap tagsMap = retrieveTags(note); - - List selectedTagsList = Arrays.asList(selectedTags); - for (int i = 0; i < tags.size(); i++) { - if (mapContainsTag(tagsMap, tags.get(i))) { - if (!selectedTagsList.contains(i)) { - tagsToRemove.add(tags.get(i)); - } - } else { - if (selectedTagsList.contains(i)) { - if (sbTags.length() > 0) { - sbTags.append(" "); - } - sbTags.append(tags.get(i)); - } - } - } - return Pair.create(sbTags.toString(), tagsToRemove); + public static HashMap retrieveTags (Note note) { + HashMap tagsMap = new HashMap<>(); + String[] words = (note.getTitle() + " " + note.getContent()).replaceAll("\n", " ").trim().split(" "); + for (String word : words) { + String parsedHashtag = UrlCompleter.parseHashtag(word); + if (StringUtils.isNotEmpty(parsedHashtag)) { + int count = tagsMap.get(parsedHashtag) == null ? 0 : tagsMap.get(parsedHashtag); + tagsMap.put(parsedHashtag, ++count); + } } + return tagsMap; + } - private static boolean mapContainsTag(HashMap tagsMap, Tag tag) { - for (String tagsMapItem : tagsMap.keySet()) { - if (tagsMapItem.equals(tag.getText())) { - return true; - } - } - return false; - } - - - public static Pair removeTag(String noteTitle, String noteContent, List tagsToRemove) { - String title = noteTitle, content = noteContent; - for (Tag tagToRemove : tagsToRemove) { - if (StringUtils.isNotEmpty(title)) { - title = Observable.from(title.replaceAll(TAG_SPECIAL_CHARS_TO_REMOVE, " ").split("\\s")) - .map(String::trim) - .filter(s -> !s.matches(tagToRemove.getText())) - .reduce((s, s2) -> s + " " + s2) - .toBlocking() - .singleOrDefault(""); - } - if (StringUtils.isNotEmpty(content)) { - content = Observable.from(content.replaceAll(TAG_SPECIAL_CHARS_TO_REMOVE, " ").split("\\s")) - .map(String::trim) - .filter(s -> !s.matches(tagToRemove.getText())) - .reduce((s, s2) -> s + " " + s2) - .toBlocking() - .singleOrDefault(""); - } + public static Pair> addTagToNote (List tags, Integer[] selectedTags, Note note) { + StringBuilder sbTags = new StringBuilder(); + List tagsToRemove = new ArrayList<>(); + HashMap tagsMap = retrieveTags(note); + List selectedTagsList = Arrays.asList(selectedTags); + for (int i = 0; i < tags.size(); i++) { + if (mapContainsTag(tagsMap, tags.get(i))) { + if (!selectedTagsList.contains(i)) { + tagsToRemove.add(tags.get(i)); + } + } else { + if (selectedTagsList.contains(i)) { + if (sbTags.length() > 0) { + sbTags.append(" "); + } + sbTags.append(tags.get(i)); } - return new Pair<>(title, content); + } } + return Pair.create(sbTags.toString(), tagsToRemove); + } - public static String[] getTagsArray(List tags) { - String[] tagsArray = new String[tags.size()]; - for (int i = 0; i < tags.size(); i++) { - tagsArray[i] = tags.get(i).getText().substring(1) + " (" + tags.get(i).getCount() + ")"; - } - return tagsArray; + private static boolean mapContainsTag (HashMap tagsMap, Tag tag) { + for (String tagsMapItem : tagsMap.keySet()) { + if (tagsMapItem.equals(tag.getText())) { + return true; + } } + return false; + } + + + public static Pair removeTag (String noteTitle, String noteContent, List tagsToRemove) { + String title = noteTitle, content = noteContent; + for (Tag tagToRemove : tagsToRemove) { + if (StringUtils.isNotEmpty(title)) { + title = Observable.from(title.replaceAll(TAG_SPECIAL_CHARS_TO_REMOVE, " ").split("\\s")) + .map(String::trim) + .filter(s -> !s.matches(tagToRemove.getText())) + .reduce((s, s2) -> s + " " + s2) + .toBlocking() + .singleOrDefault(""); + } + if (StringUtils.isNotEmpty(content)) { + content = Observable.from(content.replaceAll(TAG_SPECIAL_CHARS_TO_REMOVE, " ").split("\\s")) + .map(String::trim) + .filter(s -> !s.matches(tagToRemove.getText())) + .reduce((s, s2) -> s + " " + s2) + .toBlocking() + .singleOrDefault(""); + } - - public static Integer[] getPreselectedTagsArray(Note note, List tags) { - List notes = new ArrayList<>(); - notes.add(note); - return getPreselectedTagsArray(notes, tags); } + return new Pair<>(title, content); + } - public static Integer[] getPreselectedTagsArray(List notes, List tags) { - final Integer[] preSelectedTags; - if (notes.size() == 1) { - List t = new ArrayList<>(); - for (String noteTag : TagsHelper.retrieveTags(notes.get(0)).keySet()) { - for (Tag tag : tags) { - if (tag.getText().equals(noteTag)) { - t.add(tags.indexOf(tag)); - break; - } - } - } - preSelectedTags = t.toArray(new Integer[t.size()]); - } else { - preSelectedTags = new Integer[]{}; + public static String[] getTagsArray (List tags) { + String[] tagsArray = new String[tags.size()]; + for (int i = 0; i < tags.size(); i++) { + tagsArray[i] = tags.get(i).getText().substring(1) + " (" + tags.get(i).getCount() + ")"; + } + return tagsArray; + } + + + public static Integer[] getPreselectedTagsArray (Note note, List tags) { + List notes = new ArrayList<>(); + notes.add(note); + return getPreselectedTagsArray(notes, tags); + } + + + public static Integer[] getPreselectedTagsArray (List notes, List tags) { + final Integer[] preSelectedTags; + if (notes.size() == 1) { + List t = new ArrayList<>(); + for (String noteTag : TagsHelper.retrieveTags(notes.get(0)).keySet()) { + for (Tag tag : tags) { + if (tag.getText().equals(noteTag)) { + t.add(tags.indexOf(tag)); + break; + } } - return preSelectedTags; + } + preSelectedTags = t.toArray(new Integer[t.size()]); + } else { + preSelectedTags = new Integer[]{}; } + return preSelectedTags; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/TextHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/TextHelper.java index c05b59042d..f055075341 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/TextHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/TextHelper.java @@ -27,7 +27,6 @@ import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.date.DateHelper; import it.feio.android.omninotes.models.Note; - import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -35,132 +34,129 @@ public class TextHelper { - /** - * @param note - * @return - */ - public static Spanned[] parseTitleAndContent(Context mContext, Note note) { - - final int CONTENT_SUBSTRING_LENGTH = 300; - - String titleText = note.getTitle(); - String contentText = limit(note.getContent().trim(), CONTENT_SUBSTRING_LENGTH, false, true); - - // Masking title and content string if note is locked - if (note.isLocked() - && !mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).getBoolean( - "settings_password_access", false)) { - // This checks if a part of content is used as title and should be partially masked - if (!note.getTitle().equals(titleText) && titleText.length() > 3) { - titleText = limit(titleText, 4, false, false); - } - contentText = ""; - } - - // Replacing checkmarks symbols with html entities - Spanned contentSpanned; - if (note.isChecklist() && !TextUtils.isEmpty(contentText)) { - contentSpanned = Html.fromHtml(contentText - .replace(it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM, - it.feio.android.checklistview.interfaces.Constants.CHECKED_ENTITY) - .replace(it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM, - it.feio.android.checklistview.interfaces.Constants.UNCHECKED_ENTITY) - .replace(System.getProperty("line.separator"), "
")); - } else { - contentSpanned = new SpannedString(contentText); - } - - return new Spanned[]{new SpannedString(titleText), contentSpanned}; + /** + * + */ + public static Spanned[] parseTitleAndContent (Context mContext, Note note) { + + final int CONTENT_SUBSTRING_LENGTH = 300; + + String titleText = note.getTitle(); + String contentText = limit(note.getContent().trim(), CONTENT_SUBSTRING_LENGTH, false, true); + + // Masking title and content string if note is locked + if (note.isLocked() + && !mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).getBoolean( + "settings_password_access", false)) { + // This checks if a part of content is used as title and should be partially masked + if (!note.getTitle().equals(titleText) && titleText.length() > 3) { + titleText = limit(titleText, 4, false, false); + } + contentText = ""; } - - private static String limit(String value, int length, boolean singleLine, boolean elipsize) { - StringBuilder buf = new StringBuilder(value); - int indexNewLine = buf.indexOf(System.getProperty("line.separator")); - int endIndex = singleLine && indexNewLine < length ? indexNewLine : length < buf.length() ? length : -1; - if (endIndex != -1) { - buf.setLength(endIndex); - if (elipsize) { - buf.append("..."); - } - } - return buf.toString(); + // Replacing checkmarks symbols with html entities + Spanned contentSpanned; + if (note.isChecklist() && !TextUtils.isEmpty(contentText)) { + contentSpanned = Html.fromHtml(contentText + .replace(it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM, + it.feio.android.checklistview.interfaces.Constants.CHECKED_ENTITY) + .replace(it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM, + it.feio.android.checklistview.interfaces.Constants.UNCHECKED_ENTITY) + .replace(System.getProperty("line.separator"), "
")); + } else { + contentSpanned = new SpannedString(contentText); } - - public static String capitalize(String string) { - return string.substring(0, 1).toUpperCase(Locale.getDefault()) + string.substring(1, - string.length()).toLowerCase(Locale.getDefault()); - } + return new Spanned[]{new SpannedString(titleText), contentSpanned}; + } - /** - * Checks if a query conditions searches for category - * @param sqlCondition query "where" condition - * @return Category id - */ - public static String checkIntentCategory(String sqlCondition) { - String pattern = DbHelper.KEY_CATEGORY + "\\s*=\\s*([\\d]+)"; - Pattern p = Pattern.compile(pattern); - Matcher matcher = p.matcher(sqlCondition); - if (matcher.find() && matcher.group(1) != null) { - return matcher.group(1).trim(); - } - return null; + private static String limit (String value, int length, boolean singleLine, boolean elipsize) { + StringBuilder buf = new StringBuilder(value); + int indexNewLine = buf.indexOf(System.getProperty("line.separator")); + int endIndex = singleLine && indexNewLine < length ? indexNewLine : length < buf.length() ? length : -1; + if (endIndex != -1) { + buf.setLength(endIndex); + if (elipsize) { + buf.append("..."); + } + } + return buf.toString(); + } + + + public static String capitalize (String string) { + return string.substring(0, 1).toUpperCase(Locale.getDefault()) + string.substring(1 + ).toLowerCase(Locale.getDefault()); + } + + + /** + * Checks if a query conditions searches for category + * + * @param sqlCondition query "where" condition + * @return Category id + */ + public static String checkIntentCategory (String sqlCondition) { + String pattern = DbHelper.KEY_CATEGORY + "\\s*=\\s*([\\d]+)"; + Pattern p = Pattern.compile(pattern); + Matcher matcher = p.matcher(sqlCondition); + if (matcher.find() && matcher.group(1) != null) { + return matcher.group(1).trim(); + } + return null; + } + + + /** + * Choosing which date must be shown depending on sorting criteria + * + * @return String ith formatted date + */ + public static String getDateText (Context mContext, Note note, int navigation) { + String dateText; + String sort_column; + SharedPreferences prefs = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); + + // Reminder screen forces sorting + if (Navigation.REMINDERS == navigation) { + sort_column = DbHelper.KEY_REMINDER; + } else { + sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, ""); } - - /** - * Choosing which date must be shown depending on sorting criteria - * @return String ith formatted date - */ - public static String getDateText(Context mContext, Note note, int navigation) { - String dateText; - String sort_column; - SharedPreferences prefs = mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS); - - // Reminder screen forces sorting - if (Navigation.REMINDERS == navigation) { - sort_column = DbHelper.KEY_REMINDER; + switch (sort_column) { + case DbHelper.KEY_CREATION: + dateText = mContext.getString(R.string.creation) + " " + DateHelper.getFormattedDate(note.getCreation + (), prefs.getBoolean(Constants.PREF_PRETTIFIED_DATES, true)); + break; + case DbHelper.KEY_REMINDER: + if (note.getAlarm() == null) { + dateText = mContext.getString(R.string.no_reminder_set); } else { - sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, ""); - } - - switch (sort_column) { - case DbHelper.KEY_CREATION: - dateText = mContext.getString(R.string.creation) + " " + DateHelper.getFormattedDate(note.getCreation - (), prefs.getBoolean(Constants.PREF_PRETTIFIED_DATES, true)); - break; - case DbHelper.KEY_REMINDER: - if (note.getAlarm() == null) { - dateText = mContext.getString(R.string.no_reminder_set); - } else { - dateText = mContext.getString(R.string.alarm_set_on) + " " + DateHelper.getDateTimeShort(mContext, - Long.parseLong(note.getAlarm())); - } - break; - default: - dateText = mContext.getString(R.string.last_update) + " " + DateHelper.getFormattedDate(note - .getLastModification(), prefs.getBoolean(Constants.PREF_PRETTIFIED_DATES, true)); - break; + dateText = mContext.getString(R.string.alarm_set_on) + " " + DateHelper.getDateTimeShort(mContext, + Long.parseLong(note.getAlarm())); } - return dateText; + break; + default: + dateText = mContext.getString(R.string.last_update) + " " + DateHelper.getFormattedDate(note + .getLastModification(), prefs.getBoolean(Constants.PREF_PRETTIFIED_DATES, true)); + break; } + return dateText; + } - /** - * Gets an alternative title if empty - * @param context - * @param note - * @param spanned - * @return - */ - public static String getAlternativeTitle(Context context, Note note, Spanned spanned) { - if (spanned.length() > 0) { - return spanned.toString(); - } - return context.getString(R.string.note) + " " + context.getString(R.string.creation) + " " + DateHelper - .getDateTimeShort(context, note.getCreation()); - } + /** + * Gets an alternative title if empty + */ + public static String getAlternativeTitle (Context context, Note note, Spanned spanned) { + if (spanned.length() > 0) { + return spanned.toString(); + } + return context.getString(R.string.note) + " " + context.getString(R.string.creation) + " " + DateHelper + .getDateTimeShort(context, note.getCreation()); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DatePickerDialogFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DatePickerDialogFragment.java index fc3ee89c49..24a19df76e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DatePickerDialogFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DatePickerDialogFragment.java @@ -21,20 +21,17 @@ import android.app.DatePickerDialog.OnDateSetListener; import android.app.Dialog; import android.content.DialogInterface; -import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.widget.DatePicker; - import java.util.Calendar; /** *

This class provides a usable {@link android.app.DatePickerDialog} wrapped as a {@link android.support.v4.app - * * .DialogFragment}, - * using the compatibility package v4. Its main advantage is handling Issue 34833 - * automatically for you.

+ * * .DialogFragment}, using the compatibility package v4. Its main advantage is handling Issue 34833 automatically for + * you.

*

*

Current implementation (because I wanted that way =) ):

*

@@ -60,80 +57,80 @@ * @author davidcesarino@gmail.com * @version 2012.0828 * @see Android Issue 34833 - * @see Jelly Bean DatePickerDialog — is there a way to cancel? + * @see Jelly Bean DatePickerDialog — is there a way to + * cancel? */ public class DatePickerDialogFragment extends DialogFragment { - public static final String DEFAULT_DATE = "default_date"; - - private OnDateSetListener mListener; - private Long defaultDate; - + public static final String DEFAULT_DATE = "default_date"; - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - if (getArguments().containsKey(DEFAULT_DATE)) { - this.defaultDate = getArguments().getLong(DEFAULT_DATE); - } - - try { - mListener = (OnDateSetListener) activity; - } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() - + " must implement OnDateSetListener"); - } - } + private OnDateSetListener mListener; + private Long defaultDate; - @Override - public void onDetach() { - this.mListener = null; - super.onDetach(); + @Override + public void onAttach (Activity activity) { + super.onAttach(activity); + if (getArguments().containsKey(DEFAULT_DATE)) { + this.defaultDate = getArguments().getLong(DEFAULT_DATE); } - - @NonNull - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Use the current date as the default date in the picker - Calendar cal = DateUtils.getCalendar(defaultDate); - int y = cal.get(Calendar.YEAR); - int m = cal.get(Calendar.MONTH); - int d = cal.get(Calendar.DAY_OF_MONTH); - - // Jelly Bean introduced a bug in DatePickerDialog (and possibly - // TimePickerDialog as well), and one of the possible solutions is - // to postpone the creation of both the listener and the BUTTON_* . - // - // Passing a null here won't harm because DatePickerDialog checks for a null - // whenever it reads the listener that was passed here. >>> This seems to be - // true down to 1.5 / API 3, up to 4.1.1 / API 16. <<< No worries. For now. - // - // See my own question and answer, and details I included for the issue: - // - // http://stackoverflow.com/a/11493752/489607 - // http://code.google.com/p/android/issues/detail?id=34833 - // - // Of course, suggestions welcome. - - final DatePickerDialog picker = new DatePickerDialog(getActivity(), DatePickerDialog.THEME_HOLO_LIGHT, - mListener, y, m, d); - picker.setTitle(""); - - picker.setButton(DialogInterface.BUTTON_POSITIVE, - getActivity().getString(android.R.string.ok), - (dialog, which) -> { - DatePicker dp = picker.getDatePicker(); - mListener.onDateSet(dp, - dp.getYear(), dp.getMonth(), dp.getDayOfMonth()); - }); - picker.setButton(DialogInterface.BUTTON_NEGATIVE, - getActivity().getString(android.R.string.cancel), - (dialog, which) -> {}); - - return picker; + try { + mListener = (OnDateSetListener) activity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + + " must implement OnDateSetListener"); } + } + + + @Override + public void onDetach () { + this.mListener = null; + super.onDetach(); + } + + + @NonNull + @Override + public Dialog onCreateDialog (Bundle savedInstanceState) { + // Use the current date as the default date in the picker + Calendar cal = DateUtils.getCalendar(defaultDate); + int y = cal.get(Calendar.YEAR); + int m = cal.get(Calendar.MONTH); + int d = cal.get(Calendar.DAY_OF_MONTH); + + // Jelly Bean introduced a bug in DatePickerDialog (and possibly + // TimePickerDialog as well), and one of the possible solutions is + // to postpone the creation of both the listener and the BUTTON_* . + // + // Passing a null here won't harm because DatePickerDialog checks for a null + // whenever it reads the listener that was passed here. >>> This seems to be + // true down to 1.5 / API 3, up to 4.1.1 / API 16. <<< No worries. For now. + // + // See my own question and answer, and details I included for the issue: + // + // http://stackoverflow.com/a/11493752/489607 + // http://code.google.com/p/android/issues/detail?id=34833 + // + // Of course, suggestions welcome. + + final DatePickerDialog picker = new DatePickerDialog(getActivity(), DatePickerDialog.THEME_HOLO_LIGHT, + mListener, y, m, d); + picker.setTitle(""); + + picker.setButton(DialogInterface.BUTTON_POSITIVE, + getActivity().getString(android.R.string.ok), + (dialog, which) -> { + DatePicker dp = picker.getDatePicker(); + mListener.onDateSet(dp, + dp.getYear(), dp.getMonth(), dp.getDayOfMonth()); + }); + picker.setButton(DialogInterface.BUTTON_NEGATIVE, + getActivity().getString(android.R.string.cancel), + (dialog, which) -> {}); + + return picker; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DateUtils.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DateUtils.java index 9150004f00..9370307287 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DateUtils.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/DateUtils.java @@ -17,19 +17,16 @@ package it.feio.android.omninotes.utils.date; import android.content.Context; - -import org.apache.commons.lang.StringUtils; -import org.ocpsoft.prettytime.PrettyTime; - +import it.feio.android.omninotes.OmniNotes; +import it.feio.android.omninotes.helpers.LogDelegate; +import it.feio.android.omninotes.utils.Constants; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; - -import it.feio.android.omninotes.OmniNotes; -import it.feio.android.omninotes.helpers.LogDelegate; -import it.feio.android.omninotes.utils.Constants; +import org.apache.commons.lang.StringUtils; +import org.ocpsoft.prettytime.PrettyTime; /** @@ -37,169 +34,170 @@ */ public class DateUtils { - private DateUtils() { - throw new IllegalStateException("Utility class"); - } + private DateUtils () { + throw new IllegalStateException("Utility class"); + } - public static String getString(long date, String format) { - Date d = new Date(date); - return getString(d, format); - } + public static String getString (long date, String format) { + Date d = new Date(date); + return getString(d, format); + } - public static String getString(Date d, String format) { - SimpleDateFormat sdf = new SimpleDateFormat(format); - return sdf.format(d); - } + public static String getString (Date d, String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(d); + } - public static Calendar getDateFromString(String str, String format) { - Calendar cal = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat(format); - try { - cal.setTime(sdf.parse(str)); - } catch (ParseException e) { - LogDelegate.e("Malformed datetime string" + e.getMessage()); + public static Calendar getDateFromString (String str, String format) { + Calendar cal = Calendar.getInstance(); + SimpleDateFormat sdf = new SimpleDateFormat(format); + try { + cal.setTime(sdf.parse(str)); + } catch (ParseException e) { + LogDelegate.e("Malformed datetime string" + e.getMessage()); - } catch (NullPointerException e) { - LogDelegate.e("Date or time not set"); - } - return cal; + } catch (NullPointerException e) { + LogDelegate.e("Date or time not set"); } - - - public static Calendar getLongFromDateTime(String date, String dateFormat, String time, String timeFormat) { - Calendar cal = Calendar.getInstance(); - Calendar cDate = Calendar.getInstance(); - Calendar cTime = Calendar.getInstance(); - SimpleDateFormat sdfDate = new SimpleDateFormat(dateFormat); - SimpleDateFormat sdfTime = new SimpleDateFormat(timeFormat); - try { - cDate.setTime(sdfDate.parse(date)); - cTime.setTime(sdfTime.parse(time)); - } catch (ParseException e) { - LogDelegate.e("Date or time parsing error: " + e.getMessage()); - } - cal.set(Calendar.YEAR, cDate.get(Calendar.YEAR)); - cal.set(Calendar.MONTH, cDate.get(Calendar.MONTH)); - cal.set(Calendar.DAY_OF_MONTH, cDate.get(Calendar.DAY_OF_MONTH)); - cal.set(Calendar.HOUR_OF_DAY, cTime.get(Calendar.HOUR_OF_DAY)); - cal.set(Calendar.MINUTE, cTime.get(Calendar.MINUTE)); - cal.set(Calendar.SECOND, 0); - return cal; + return cal; + } + + + public static Calendar getLongFromDateTime (String date, String dateFormat, String time, String timeFormat) { + Calendar cal = Calendar.getInstance(); + Calendar cDate = Calendar.getInstance(); + Calendar cTime = Calendar.getInstance(); + SimpleDateFormat sdfDate = new SimpleDateFormat(dateFormat); + SimpleDateFormat sdfTime = new SimpleDateFormat(timeFormat); + try { + cDate.setTime(sdfDate.parse(date)); + cTime.setTime(sdfTime.parse(time)); + } catch (ParseException e) { + LogDelegate.e("Date or time parsing error: " + e.getMessage()); } - - - public static Calendar getCalendar(Long dateTime) { - Calendar cal = Calendar.getInstance(); - if (dateTime != null && dateTime != 0) { - cal.setTimeInMillis(dateTime); - } - return cal; + cal.set(Calendar.YEAR, cDate.get(Calendar.YEAR)); + cal.set(Calendar.MONTH, cDate.get(Calendar.MONTH)); + cal.set(Calendar.DAY_OF_MONTH, cDate.get(Calendar.DAY_OF_MONTH)); + cal.set(Calendar.HOUR_OF_DAY, cTime.get(Calendar.HOUR_OF_DAY)); + cal.set(Calendar.MINUTE, cTime.get(Calendar.MINUTE)); + cal.set(Calendar.SECOND, 0); + return cal; + } + + + public static Calendar getCalendar (Long dateTime) { + Calendar cal = Calendar.getInstance(); + if (dateTime != null && dateTime != 0) { + cal.setTimeInMillis(dateTime); } - - - public static String getLocalizedDateTime(Context mContext, - String dateString, String format) { - String res = null; - SimpleDateFormat sdf = new SimpleDateFormat(format); - Date date = null; - try { - date = sdf.parse(dateString); - } catch (ParseException e) { - sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SORTABLE_OLD); - try { - date = sdf.parse(dateString); - } catch (ParseException e1) { - LogDelegate.e("String is not formattable into date"); - } - } - - if (date != null) { - String dateFormatted = android.text.format.DateUtils.formatDateTime(mContext, date.getTime(), android - .text.format.DateUtils.FORMAT_ABBREV_MONTH); - String timeFormatted = android.text.format.DateUtils.formatDateTime(mContext, date.getTime(), android - .text.format.DateUtils.FORMAT_SHOW_TIME); - res = dateFormatted + " " + timeFormatted; - } - - return res; + return cal; + } + + + public static String getLocalizedDateTime (Context mContext, + String dateString, String format) { + String res = null; + SimpleDateFormat sdf = new SimpleDateFormat(format); + Date date = null; + try { + date = sdf.parse(dateString); + } catch (ParseException e) { + sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SORTABLE_OLD); + try { + date = sdf.parse(dateString); + } catch (ParseException e1) { + LogDelegate.e("String is not formattable into date"); + } } - - public static boolean is24HourMode(Context mContext) { - boolean res = true; - Calendar c = Calendar.getInstance(); - String timeFormatted = android.text.format.DateUtils.formatDateTime(mContext, c.getTimeInMillis(), android - .text.format.DateUtils.FORMAT_SHOW_TIME); - res = !timeFormatted.toLowerCase().contains("am") && !timeFormatted.toLowerCase().contains("pm"); - return res; + if (date != null) { + String dateFormatted = android.text.format.DateUtils.formatDateTime(mContext, date.getTime(), android + .text.format.DateUtils.FORMAT_ABBREV_MONTH); + String timeFormatted = android.text.format.DateUtils.formatDateTime(mContext, date.getTime(), android + .text.format.DateUtils.FORMAT_SHOW_TIME); + res = dateFormatted + " " + timeFormatted; } - - public static boolean isSameDay(long date1, long date2) { - Calendar cal1 = Calendar.getInstance(); - Calendar cal2 = Calendar.getInstance(); - cal1.setTimeInMillis(date1); - cal2.setTimeInMillis(date2); - return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get - (Calendar.DAY_OF_YEAR); + return res; + } + + + public static boolean is24HourMode (Context mContext) { + boolean res = true; + Calendar c = Calendar.getInstance(); + String timeFormatted = android.text.format.DateUtils.formatDateTime(mContext, c.getTimeInMillis(), android + .text.format.DateUtils.FORMAT_SHOW_TIME); + res = !timeFormatted.toLowerCase().contains("am") && !timeFormatted.toLowerCase().contains("pm"); + return res; + } + + + public static boolean isSameDay (long date1, long date2) { + Calendar cal1 = Calendar.getInstance(); + Calendar cal2 = Calendar.getInstance(); + cal1.setTimeInMillis(date1); + cal2.setTimeInMillis(date2); + return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get + (Calendar.DAY_OF_YEAR); + } + + + public static long getNextMinute () { + return Calendar.getInstance().getTimeInMillis() + 1000 * 60; + } + + /** + * Returns actually set reminder if that is on the future, next-minute-reminder otherwise + */ + public static long getPresetReminder (Long currentReminder) { + long now = Calendar.getInstance().getTimeInMillis(); + return currentReminder != null && currentReminder > now ? currentReminder : getNextMinute(); + } + + public static Long getPresetReminder (String alarm) { + long alarmChecked = alarm == null ? 0 : Long.parseLong(alarm); + return getPresetReminder(alarmChecked); + } + + /** + * Checks if a epoch-date timestamp is in the future + */ + public static boolean isFuture (String timestamp) { + return !StringUtils.isEmpty(timestamp) && isFuture(Long.parseLong(timestamp)); + } + + /** + * Checks if a epoch-date timestamp is in the future + */ + public static boolean isFuture (Long timestamp) { + return timestamp != null && timestamp > Calendar.getInstance().getTimeInMillis(); + } + + public static String prettyTime (String timeInMillisec) { + if (timeInMillisec == null) { + return ""; } + return prettyTime(Long.parseLong(timeInMillisec), + OmniNotes.getAppContext().getResources().getConfiguration().locale); + } - public static long getNextMinute() { - return Calendar.getInstance().getTimeInMillis() + 1000 * 60; - } + public static String prettyTime (Long timeInMillisec) { + return prettyTime(timeInMillisec, OmniNotes.getAppContext().getResources().getConfiguration().locale); + } - /** - * Returns actually set reminder if that is on the future, next-minute-reminder otherwise - * @param currentReminder - * @return - */ - public static long getPresetReminder(Long currentReminder) { - long now = Calendar.getInstance().getTimeInMillis(); - return currentReminder != null && currentReminder > now ? currentReminder : getNextMinute(); - } - - public static Long getPresetReminder(String alarm) { - long alarmChecked = alarm == null ? 0 : Long.parseLong(alarm); - return getPresetReminder(alarmChecked); - } - /** - * Checks if a epoch-date timestamp is in the future - */ - public static boolean isFuture(String timestamp) { - return !StringUtils.isEmpty(timestamp) && isFuture(Long.parseLong(timestamp)); + public static String prettyTime (Long timeInMillisec, Locale locale) { + if (timeInMillisec == null) { + return ""; } - - /** - * Checks if a epoch-date timestamp is in the future - */ - public static boolean isFuture(Long timestamp) { - return timestamp != null && timestamp > Calendar.getInstance().getTimeInMillis(); + Date d = new Date(timeInMillisec); + PrettyTime pt = new PrettyTime(); + if (locale != null) { + pt.setLocale(locale); } - - public static String prettyTime(String timeInMillisec) { - if (timeInMillisec == null) { - return ""; - } - return prettyTime(Long.parseLong(timeInMillisec), OmniNotes.getAppContext().getResources().getConfiguration().locale); - } - - - public static String prettyTime(Long timeInMillisec) { - return prettyTime(timeInMillisec, OmniNotes.getAppContext().getResources().getConfiguration().locale); - } - - - public static String prettyTime(Long timeInMillisec, Locale locale) { - if (timeInMillisec == null) return ""; - Date d = new Date(timeInMillisec); - PrettyTime pt = new PrettyTime(); - if (locale != null) { - pt.setLocale(locale); - } - return pt.format(d); - } + return pt.format(d); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/ReminderPickers.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/ReminderPickers.java index cb4076449f..032a317e8b 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/ReminderPickers.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/ReminderPickers.java @@ -28,151 +28,151 @@ import com.sleepbot.datetimepicker.time.TimePickerDialog; import it.feio.android.omninotes.models.listeners.OnReminderPickedListener; import it.feio.android.omninotes.utils.Constants; - import java.util.Calendar; -public class ReminderPickers implements OnDateSetListener, OnTimeSetListener, RecurrencePickerDialog.OnRecurrenceSetListener { - - public static final int TYPE_GOOGLE = 0; - public static final int TYPE_AOSP = 1; - - private FragmentActivity mActivity; - private OnReminderPickedListener mOnReminderPickedListener; - private int pickerType; - - private int reminderYear; - private int reminderMonth; - private int reminderDay; - private int hourOfDay; - private int minutes; - - private boolean timePickerCalledAlready = false; - private boolean recurrencePickerCalledAlready = false; - private long presetDateTime; - private String recurrenceRule; - - - public ReminderPickers(FragmentActivity mActivity, - OnReminderPickedListener mOnReminderPickedListener, int pickerType) { - this.mActivity = mActivity; - this.mOnReminderPickedListener = mOnReminderPickedListener; - this.pickerType = pickerType; - } - +public class ReminderPickers implements OnDateSetListener, OnTimeSetListener, + RecurrencePickerDialog.OnRecurrenceSetListener { - public void pick() { - pick(null); - } + public static final int TYPE_GOOGLE = 0; + public static final int TYPE_AOSP = 1; + private FragmentActivity mActivity; + private OnReminderPickedListener mOnReminderPickedListener; + private int pickerType; - public void pick(Long presetDateTime) { - pick(presetDateTime, ""); - } + private int reminderYear; + private int reminderMonth; + private int reminderDay; + private int hourOfDay; + private int minutes; + private boolean timePickerCalledAlready = false; + private boolean recurrencePickerCalledAlready = false; + private long presetDateTime; + private String recurrenceRule; - public void pick(Long presetDateTime, String recurrenceRule) { - this.presetDateTime = DateUtils.getCalendar(presetDateTime).getTimeInMillis(); - this.recurrenceRule = recurrenceRule; - if (pickerType == TYPE_AOSP) { - timePickerCalledAlready = false; - // Timepicker will be automatically called after date is inserted by user - showDatePickerDialog(this.presetDateTime); - } else { - showDateTimeSelectors(this.presetDateTime); - } - } + public ReminderPickers (FragmentActivity mActivity, + OnReminderPickedListener mOnReminderPickedListener, int pickerType) { + this.mActivity = mActivity; + this.mOnReminderPickedListener = mOnReminderPickedListener; + this.pickerType = pickerType; + } - /** - * Show date and time pickers - */ - protected void showDateTimeSelectors(long reminder) { - - // Sets actual time or previously saved in note - final Calendar now = DateUtils.getCalendar(reminder); - DatePickerDialog mCalendarDatePickerDialog = DatePickerDialog.newInstance( - (dialog, year, monthOfYear, dayOfMonth) -> { - reminderYear = year; - reminderMonth = monthOfYear; - reminderDay = dayOfMonth; - TimePickerDialog mRadialTimePickerDialog = TimePickerDialog.newInstance( - (radialPickerLayout, hour, minute) -> { - hourOfDay = hour; - minutes = minute; - showRecurrencePickerDialog(recurrenceRule); - }, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), - DateUtils.is24HourMode(mActivity)); - mRadialTimePickerDialog.show(mActivity.getSupportFragmentManager(), Constants.TAG); - }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); - mCalendarDatePickerDialog.show(mActivity.getSupportFragmentManager(), Constants.TAG); - } + public void pick () { + pick(null); + } - /** - * Shows fallback date and time pickers for smaller screens - */ - public void showDatePickerDialog(long presetDateTime) { - Bundle b = new Bundle(); - b.putLong(DatePickerDialogFragment.DEFAULT_DATE, presetDateTime); - DialogFragment picker = new DatePickerDialogFragment(); - picker.setArguments(b); - picker.show(mActivity.getSupportFragmentManager(), Constants.TAG); - } + public void pick (Long presetDateTime) { + pick(presetDateTime, ""); + } - private void showTimePickerDialog(long presetDateTime) { - TimePickerFragment newFragment = new TimePickerFragment(); - Bundle bundle = new Bundle(); - bundle.putLong(TimePickerFragment.DEFAULT_TIME, presetDateTime); - newFragment.setArguments(bundle); - newFragment.show(mActivity.getSupportFragmentManager(), Constants.TAG); + public void pick (Long presetDateTime, String recurrenceRule) { + this.presetDateTime = DateUtils.getCalendar(presetDateTime).getTimeInMillis(); + this.recurrenceRule = recurrenceRule; + if (pickerType == TYPE_AOSP) { + timePickerCalledAlready = false; + // Timepicker will be automatically called after date is inserted by user + showDatePickerDialog(this.presetDateTime); + } else { + showDateTimeSelectors(this.presetDateTime); } - - - private void showRecurrencePickerDialog(String recurrenceRule) { - RecurrencePickerDialog recurrencePickerDialog = new RecurrencePickerDialog(); - if (recurrenceRule != null && recurrenceRule.length() > 0) { - Bundle bundle = new Bundle(); - bundle.putString(RecurrencePickerDialog.BUNDLE_RRULE, recurrenceRule); - recurrencePickerDialog.setArguments(bundle); - } - recurrencePickerDialog.setOnRecurrenceSetListener(this); - recurrencePickerDialog.show(mActivity.getSupportFragmentManager(), "recurrencePicker"); + } + + + /** + * Show date and time pickers + */ + protected void showDateTimeSelectors (long reminder) { + + // Sets actual time or previously saved in note + final Calendar now = DateUtils.getCalendar(reminder); + DatePickerDialog mCalendarDatePickerDialog = DatePickerDialog.newInstance( + (dialog, year, monthOfYear, dayOfMonth) -> { + reminderYear = year; + reminderMonth = monthOfYear; + reminderDay = dayOfMonth; + TimePickerDialog mRadialTimePickerDialog = TimePickerDialog.newInstance( + (radialPickerLayout, hour, minute) -> { + hourOfDay = hour; + minutes = minute; + showRecurrencePickerDialog(recurrenceRule); + }, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), + DateUtils.is24HourMode(mActivity)); + mRadialTimePickerDialog.show(mActivity.getSupportFragmentManager(), Constants.TAG); + }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); + mCalendarDatePickerDialog.show(mActivity.getSupportFragmentManager(), Constants.TAG); + } + + + /** + * Shows fallback date and time pickers for smaller screens + */ + + public void showDatePickerDialog (long presetDateTime) { + Bundle b = new Bundle(); + b.putLong(DatePickerDialogFragment.DEFAULT_DATE, presetDateTime); + DialogFragment picker = new DatePickerDialogFragment(); + picker.setArguments(b); + picker.show(mActivity.getSupportFragmentManager(), Constants.TAG); + } + + + private void showTimePickerDialog (long presetDateTime) { + TimePickerFragment newFragment = new TimePickerFragment(); + Bundle bundle = new Bundle(); + bundle.putLong(TimePickerFragment.DEFAULT_TIME, presetDateTime); + newFragment.setArguments(bundle); + newFragment.show(mActivity.getSupportFragmentManager(), Constants.TAG); + } + + + private void showRecurrencePickerDialog (String recurrenceRule) { + RecurrencePickerDialog recurrencePickerDialog = new RecurrencePickerDialog(); + if (recurrenceRule != null && recurrenceRule.length() > 0) { + Bundle bundle = new Bundle(); + bundle.putString(RecurrencePickerDialog.BUNDLE_RRULE, recurrenceRule); + recurrencePickerDialog.setArguments(bundle); } - - - @Override - public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { - reminderYear = year; - reminderMonth = monthOfYear; - reminderDay = dayOfMonth; - if (!timePickerCalledAlready) { // Used to avoid native bug that calls onPositiveButtonPressed in the onClose() - timePickerCalledAlready = true; - showTimePickerDialog(presetDateTime); - } + recurrencePickerDialog.setOnRecurrenceSetListener(this); + recurrencePickerDialog.show(mActivity.getSupportFragmentManager(), "recurrencePicker"); + } + + + @Override + public void onDateSet (DatePicker view, int year, int monthOfYear, int dayOfMonth) { + reminderYear = year; + reminderMonth = monthOfYear; + reminderDay = dayOfMonth; + if (!timePickerCalledAlready) { // Used to avoid native bug that calls onPositiveButtonPressed in the onClose() + timePickerCalledAlready = true; + showTimePickerDialog(presetDateTime); } + } - @Override - public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) { - this.hourOfDay = hourOfDay; - this.minutes = minute; - if (!recurrencePickerCalledAlready) { // Used to avoid native bug that calls onPositiveButtonPressed in the onClose() - recurrencePickerCalledAlready = true; - showRecurrencePickerDialog(recurrenceRule); - } + @Override + public void onTimeSet (android.widget.TimePicker view, int hourOfDay, int minute) { + this.hourOfDay = hourOfDay; + this.minutes = minute; + if (!recurrencePickerCalledAlready) { // Used to avoid native bug that calls onPositiveButtonPressed in the onClose() + recurrencePickerCalledAlready = true; + showRecurrencePickerDialog(recurrenceRule); } + } - @Override - public void onRecurrenceSet(final String rrule) { - Calendar c = Calendar.getInstance(); - c.set(reminderYear, reminderMonth, reminderDay, hourOfDay, minutes, 0); - if (mOnReminderPickedListener != null) { - mOnReminderPickedListener.onReminderPicked(c.getTimeInMillis()); - mOnReminderPickedListener.onRecurrenceReminderPicked(rrule); - } + @Override + public void onRecurrenceSet (final String rrule) { + Calendar c = Calendar.getInstance(); + c.set(reminderYear, reminderMonth, reminderDay, hourOfDay, minutes, 0); + if (mOnReminderPickedListener != null) { + mOnReminderPickedListener.onReminderPicked(c.getTimeInMillis()); + mOnReminderPickedListener.onRecurrenceReminderPicked(rrule); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/TimePickerFragment.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/TimePickerFragment.java index 6275f1e726..ed7eae9e14 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/TimePickerFragment.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/date/TimePickerFragment.java @@ -24,49 +24,49 @@ import android.support.v4.app.DialogFragment; import android.widget.TextView; import it.feio.android.omninotes.R; - import java.util.Calendar; public class TimePickerFragment extends DialogFragment { - public static final String DEFAULT_TIME = "default_time"; + public static final String DEFAULT_TIME = "default_time"; - TextView timer_label; - private Activity mActivity; - private OnTimeSetListener mListener; - private Long defaultTime = null; + TextView timer_label; + private Activity mActivity; + private OnTimeSetListener mListener; + private Long defaultTime = null; - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - mActivity = activity; - if (getArguments().containsKey(DEFAULT_TIME)) { - this.defaultTime = getArguments().getLong(DEFAULT_TIME); - } + @Override + public void onAttach (Activity activity) { + super.onAttach(activity); + mActivity = activity; + if (getArguments().containsKey(DEFAULT_TIME)) { + this.defaultTime = getArguments().getLong(DEFAULT_TIME); + } - try { - mListener = (OnTimeSetListener) mActivity; - } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() - + " must implement OnTimeSetListener"); - } + try { + mListener = (OnTimeSetListener) mActivity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + + " must implement OnTimeSetListener"); } + } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { + @Override + public Dialog onCreateDialog (Bundle savedInstanceState) { - Calendar cal = DateUtils.getCalendar(defaultTime); - int hour = cal.get(Calendar.HOUR_OF_DAY); - int minute = cal.get(Calendar.MINUTE); + Calendar cal = DateUtils.getCalendar(defaultTime); + int hour = cal.get(Calendar.HOUR_OF_DAY); + int minute = cal.get(Calendar.MINUTE); - // Create a new instance of TimePickerDialog and return it - boolean is24HourMode = DateUtils.is24HourMode(mActivity); - TimePickerDialog tpd = new TimePickerDialog(mActivity, R.style.Theme_AppCompat_Dialog_NoBackgroundOrDim, mListener, hour, minute, is24HourMode); - tpd.setTitle(""); - return tpd; - } + // Create a new instance of TimePickerDialog and return it + boolean is24HourMode = DateUtils.is24HourMode(mActivity); + TimePickerDialog tpd = new TimePickerDialog(mActivity, R.style.Theme_AppCompat_Dialog_NoBackgroundOrDim, mListener, + hour, minute, is24HourMode); + tpd.setTitle(""); + return tpd; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannel.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannel.java index 182f910611..77ff1cf15e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannel.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannel.java @@ -19,13 +19,13 @@ public class NotificationChannel { - int importance; - String name; - String description; + int importance; + String name; + String description; - NotificationChannel(int importance, String name, String description) { - this.importance = importance; - this.name = name; - this.description = description; - } + NotificationChannel (int importance, String name, String description) { + this.importance = importance; + this.name = name; + this.description = description; + } } \ No newline at end of file diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannels.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannels.java index 63bc2f1c71..32beb64049 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannels.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationChannels.java @@ -20,30 +20,28 @@ import android.annotation.TargetApi; import android.app.NotificationManager; import android.os.Build; - -import java.util.ArrayList; -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; +import java.util.ArrayList; +import java.util.List; @TargetApi(Build.VERSION_CODES.O) public class NotificationChannels { - private static List channels = new ArrayList() {{ - add(new NotificationChannel(NotificationManager.IMPORTANCE_DEFAULT, OmniNotes.getAppContext().getString(R.string - .channel_backups_name), OmniNotes.getAppContext().getString(R.string - .channel_backups_description))); - add(new NotificationChannel(NotificationManager.IMPORTANCE_DEFAULT, OmniNotes.getAppContext().getString(R.string - .channel_reminders_name), OmniNotes.getAppContext().getString(R.string - .channel_reminders_description))); - }}; - - public static List getChannels() { - return channels; - } - - public enum NotificationChannelNames { - Backups, Reminders - } + private static List channels = new ArrayList() {{ + add(new NotificationChannel(NotificationManager.IMPORTANCE_DEFAULT, OmniNotes.getAppContext().getString(R.string + .channel_backups_name), OmniNotes.getAppContext().getString(R.string + .channel_backups_description))); + add(new NotificationChannel(NotificationManager.IMPORTANCE_DEFAULT, OmniNotes.getAppContext().getString(R.string + .channel_reminders_name), OmniNotes.getAppContext().getString(R.string + .channel_reminders_description))); + }}; + + public static List getChannels () { + return channels; + } + + public enum NotificationChannelNames { + Backups, Reminders + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationsHelper.java b/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationsHelper.java index 035962fa1d..6a839bbe6d 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationsHelper.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/utils/notifications/NotificationsHelper.java @@ -31,160 +31,160 @@ import android.os.Build; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.Builder; - import it.feio.android.omninotes.R; public class NotificationsHelper { - private Context mContext; - private Builder mBuilder; - private NotificationManager mNotificationManager; - - public NotificationsHelper(Context mContext) { - this.mContext = mContext.getApplicationContext(); - if (mNotificationManager == null) { - mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); - } - } - - /** - * Create the NotificationChannel, but only on API 26+ because the NotificationChannel class is new and not in - * the support library - */ - @TargetApi(Build.VERSION_CODES.O) - public void initNotificationChannels() { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { - for (it.feio.android.omninotes.utils.notifications.NotificationChannel notificationChannel : NotificationChannels.getChannels()) { - NotificationChannel channel = new NotificationChannel(notificationChannel.name, notificationChannel - .name, notificationChannel.importance); - channel.setDescription(notificationChannel.description); - mNotificationManager.createNotificationChannel(channel); - } - } - } - - /** - * Creation of notification on operations completed - */ - public NotificationsHelper createNotification(NotificationChannels.NotificationChannelNames channelId, int - smallIcon, String title, PendingIntent notifyIntent) { - mBuilder = new NotificationCompat.Builder(mContext, channelId.name()).setSmallIcon(smallIcon).setContentTitle(title) - .setAutoCancel(true).setColor(mContext.getResources().getColor(R.color.colorAccent)); - mBuilder.setContentIntent(notifyIntent); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - setLargeIcon(R.drawable.logo_notification_lollipop); - } else { - setLargeIcon(R.mipmap.ic_launcher); - } - - return this; - } - - public Builder getBuilder() { - return mBuilder; - } - - public NotificationsHelper setLargeIcon(Bitmap largeIconBitmap) { - mBuilder.setLargeIcon(largeIconBitmap); - return this; - } - - public NotificationsHelper setLargeIcon(int largeIconResource) { - Bitmap largeIconBitmap = BitmapFactory.decodeResource(mContext.getResources(), largeIconResource); - return setLargeIcon(largeIconBitmap); - } - - public NotificationsHelper setRingtone(String ringtone) { - if (ringtone != null) { - mBuilder.setSound(Uri.parse(ringtone)); - } - return this; - } - - public NotificationsHelper setVibration() { - return setVibration(null); - } - - public NotificationsHelper setVibration(long[] pattern) { - if (pattern == null || pattern.length == 0) { - pattern = new long[]{500, 500}; - } - mBuilder.setVibrate(pattern); - return this; - } - - public NotificationsHelper setLedActive() { - mBuilder.setLights(Color.BLUE, 1000, 1000); - return this; - } - - public NotificationsHelper setIcon(int icon) { - mBuilder.setSmallIcon(icon); - return this; - } - - public NotificationsHelper setMessage(String message) { - mBuilder.setContentText(message); - return this; - } - - public NotificationsHelper setIndeterminate() { - mBuilder.setProgress(0, 0, true); - return this; - } - - public NotificationsHelper setOngoing() { - mBuilder.setOngoing(true); - return this; - } - - public NotificationsHelper show() { - show(0); - return this; - } - - public NotificationsHelper show(long id) { - Notification mNotification = mBuilder.build(); - if (mNotification.contentIntent == null) { - // Creates a dummy PendingIntent - mBuilder.setContentIntent(PendingIntent.getActivity(mContext, 0, new Intent(), - PendingIntent.FLAG_UPDATE_CURRENT)); - } - // Builds an anonymous Notification object from the builder, and passes it to the NotificationManager - mNotificationManager.notify(String.valueOf(id), 0, mBuilder.build()); - return this; - } - - public NotificationsHelper start(NotificationChannels.NotificationChannelNames channelId, int - smallIcon, String title) { - createNotification(channelId, smallIcon, title, null).setIndeterminate().setOngoing(); - mNotificationManager.notify(0, mBuilder.setOnlyAlertOnce(true).build()); - return this; - } - - public void updateMessage(String message) { - updateMessage(0, message); - } - - public void updateMessage(int id, String message) { - mNotificationManager.notify(id, mBuilder.setContentText(message).build()); - } - - public void finish(Intent intent, String message) { - finish(0, intent, message); - } - - public void finish(int id, Intent intent, String message) { - mBuilder.setContentTitle(message).setProgress(0,0,false).setOngoing(false); - mNotificationManager.notify(id, mBuilder.build()); - } - - public void cancel() { - mNotificationManager.cancel(0); - } - - public void cancel(int id) { - mNotificationManager.cancel(id); - } + private Context mContext; + private Builder mBuilder; + private NotificationManager mNotificationManager; + + public NotificationsHelper (Context mContext) { + this.mContext = mContext.getApplicationContext(); + if (mNotificationManager == null) { + mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); + } + } + + /** + * Create the NotificationChannel, but only on API 26+ because the NotificationChannel class is new and not in the + * support library + */ + @TargetApi(Build.VERSION_CODES.O) + public void initNotificationChannels () { + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { + for (it.feio.android.omninotes.utils.notifications.NotificationChannel notificationChannel : NotificationChannels.getChannels()) { + NotificationChannel channel = new NotificationChannel(notificationChannel.name, notificationChannel + .name, notificationChannel.importance); + channel.setDescription(notificationChannel.description); + mNotificationManager.createNotificationChannel(channel); + } + } + } + + /** + * Creation of notification on operations completed + */ + public NotificationsHelper createNotification (NotificationChannels.NotificationChannelNames channelId, int + smallIcon, String title, PendingIntent notifyIntent) { + mBuilder = new NotificationCompat.Builder(mContext, channelId.name()).setSmallIcon(smallIcon).setContentTitle(title) + .setAutoCancel(true).setColor( + mContext.getResources().getColor(R.color.colorAccent)); + mBuilder.setContentIntent(notifyIntent); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + setLargeIcon(R.drawable.logo_notification_lollipop); + } else { + setLargeIcon(R.mipmap.ic_launcher); + } + + return this; + } + + public Builder getBuilder () { + return mBuilder; + } + + public NotificationsHelper setLargeIcon (Bitmap largeIconBitmap) { + mBuilder.setLargeIcon(largeIconBitmap); + return this; + } + + public NotificationsHelper setLargeIcon (int largeIconResource) { + Bitmap largeIconBitmap = BitmapFactory.decodeResource(mContext.getResources(), largeIconResource); + return setLargeIcon(largeIconBitmap); + } + + public NotificationsHelper setRingtone (String ringtone) { + if (ringtone != null) { + mBuilder.setSound(Uri.parse(ringtone)); + } + return this; + } + + public NotificationsHelper setVibration () { + return setVibration(null); + } + + public NotificationsHelper setVibration (long[] pattern) { + if (pattern == null || pattern.length == 0) { + pattern = new long[]{500, 500}; + } + mBuilder.setVibrate(pattern); + return this; + } + + public NotificationsHelper setLedActive () { + mBuilder.setLights(Color.BLUE, 1000, 1000); + return this; + } + + public NotificationsHelper setIcon (int icon) { + mBuilder.setSmallIcon(icon); + return this; + } + + public NotificationsHelper setMessage (String message) { + mBuilder.setContentText(message); + return this; + } + + public NotificationsHelper setIndeterminate () { + mBuilder.setProgress(0, 0, true); + return this; + } + + public NotificationsHelper setOngoing () { + mBuilder.setOngoing(true); + return this; + } + + public NotificationsHelper show () { + show(0); + return this; + } + + public NotificationsHelper show (long id) { + Notification mNotification = mBuilder.build(); + if (mNotification.contentIntent == null) { + // Creates a dummy PendingIntent + mBuilder.setContentIntent(PendingIntent.getActivity(mContext, 0, new Intent(), + PendingIntent.FLAG_UPDATE_CURRENT)); + } + // Builds an anonymous Notification object from the builder, and passes it to the NotificationManager + mNotificationManager.notify(String.valueOf(id), 0, mBuilder.build()); + return this; + } + + public NotificationsHelper start (NotificationChannels.NotificationChannelNames channelId, int + smallIcon, String title) { + createNotification(channelId, smallIcon, title, null).setIndeterminate().setOngoing(); + mNotificationManager.notify(0, mBuilder.setOnlyAlertOnce(true).build()); + return this; + } + + public void updateMessage (String message) { + updateMessage(0, message); + } + + public void updateMessage (int id, String message) { + mNotificationManager.notify(id, mBuilder.setContentText(message).build()); + } + + public void finish (Intent intent, String message) { + finish(0, intent, message); + } + + public void finish (int id, Intent intent, String message) { + mBuilder.setContentTitle(message).setProgress(0, 0, false).setOngoing(false); + mNotificationManager.notify(id, mBuilder.build()); + } + + public void cancel () { + mNotificationManager.cancel(0); + } + + public void cancel (int id) { + mNotificationManager.cancel(id); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListRemoteViewsFactory.java b/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListRemoteViewsFactory.java index 269f9f2fb2..a1fbc36177 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListRemoteViewsFactory.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListRemoteViewsFactory.java @@ -28,11 +28,7 @@ import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService.RemoteViewsFactory; - import com.bumptech.glide.request.target.AppWidgetTarget; - -import java.util.List; - import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; import it.feio.android.omninotes.db.DbHelper; @@ -43,155 +39,155 @@ import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Navigation; import it.feio.android.omninotes.utils.TextHelper; +import java.util.List; public class ListRemoteViewsFactory implements RemoteViewsFactory { - private static boolean showThumbnails = true; - private static boolean showTimestamps = true; - private final int WIDTH = 80; - private final int HEIGHT = 80; - private OmniNotes app; - private int appWidgetId; - private List notes; - private int navigation; - - private AppWidgetTarget appWidgetTarget; - - - - public ListRemoteViewsFactory(Application app, Intent intent) { - this.app = (OmniNotes) app; - appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + private static boolean showThumbnails = true; + private static boolean showTimestamps = true; + private final int WIDTH = 80; + private final int HEIGHT = 80; + private OmniNotes app; + private int appWidgetId; + private List notes; + private int navigation; + + private AppWidgetTarget appWidgetTarget; + + + public ListRemoteViewsFactory (Application app, Intent intent) { + this.app = (OmniNotes) app; + appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + } + + public static void updateConfiguration (Context mContext, int mAppWidgetId, String sqlCondition, + boolean thumbnails, boolean timestamps) { + LogDelegate.d("Widget configuration updated"); + mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).edit() + .putString(Constants.PREF_WIDGET_PREFIX + mAppWidgetId, sqlCondition).commit(); + showThumbnails = thumbnails; + showTimestamps = timestamps; + } + + @Override + public void onCreate () { + LogDelegate.d("Created widget " + appWidgetId); + String condition = app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) + .getString( + Constants.PREF_WIDGET_PREFIX + + appWidgetId, ""); + notes = DbHelper.getInstance().getNotes(condition, true); + } + + @Override + public void onDataSetChanged () { + LogDelegate.d("onDataSetChanged widget " + appWidgetId); + navigation = Navigation.getNavigation(); + + String condition = app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) + .getString( + Constants.PREF_WIDGET_PREFIX + + appWidgetId, ""); + notes = DbHelper.getInstance().getNotes(condition, true); + } + + @Override + public void onDestroy () { + app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) + .edit() + .remove(Constants.PREF_WIDGET_PREFIX + + appWidgetId).commit(); + } + + @Override + public int getCount () { + return notes.size(); + } + + @Override + public RemoteViews getViewAt (int position) { + RemoteViews row = new RemoteViews(app.getPackageName(), R.layout.note_layout_widget); + + Note note = notes.get(position); + + Spanned[] titleAndContent = TextHelper.parseTitleAndContent(app, note); + + row.setTextViewText(R.id.note_title, titleAndContent[0]); + row.setTextViewText(R.id.note_content, titleAndContent[1]); + + color(note, row); + + if (!note.isLocked() && showThumbnails && note.getAttachmentsList().size() > 0) { + Attachment mAttachment = note.getAttachmentsList().get(0); + Bitmap bmp = BitmapHelper.getBitmapFromAttachment(app, mAttachment, WIDTH, HEIGHT); + row.setBitmap(R.id.attachmentThumbnail, "setImageBitmap", bmp); + row.setInt(R.id.attachmentThumbnail, "setVisibility", View.VISIBLE); + } else { + row.setInt(R.id.attachmentThumbnail, "setVisibility", View.GONE); } - - public static void updateConfiguration(Context mContext, int mAppWidgetId, String sqlCondition, - boolean thumbnails, boolean timestamps) { - LogDelegate.d("Widget configuration updated"); - mContext.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS).edit() - .putString(Constants.PREF_WIDGET_PREFIX + String.valueOf(mAppWidgetId), sqlCondition).commit(); - showThumbnails = thumbnails; - showTimestamps = timestamps; + if (showTimestamps) { + row.setTextViewText(R.id.note_date, TextHelper.getDateText(app, note, navigation)); + } else { + row.setTextViewText(R.id.note_date, ""); } - @Override - public void onCreate() { - LogDelegate.d("Created widget " + appWidgetId); - String condition = app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) - .getString( - Constants.PREF_WIDGET_PREFIX - + String.valueOf(appWidgetId), ""); - notes = DbHelper.getInstance().getNotes(condition, true); - } - - @Override - public void onDataSetChanged() { - LogDelegate.d("onDataSetChanged widget " + appWidgetId); - navigation = Navigation.getNavigation(); - - String condition = app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) - .getString( - Constants.PREF_WIDGET_PREFIX - + String.valueOf(appWidgetId), ""); - notes = DbHelper.getInstance().getNotes(condition, true); - } - - @Override - public void onDestroy() { - app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) - .edit() - .remove(Constants.PREF_WIDGET_PREFIX - + String.valueOf(appWidgetId)).commit(); - } - - @Override - public int getCount() { - return notes.size(); - } - - @Override - public RemoteViews getViewAt(int position) { - RemoteViews row = new RemoteViews(app.getPackageName(), R.layout.note_layout_widget); - - Note note = notes.get(position); - - Spanned[] titleAndContent = TextHelper.parseTitleAndContent(app, note); - - row.setTextViewText(R.id.note_title, titleAndContent[0]); - row.setTextViewText(R.id.note_content, titleAndContent[1]); - - color(note, row); - - if (!note.isLocked() && showThumbnails && note.getAttachmentsList().size() > 0) { - Attachment mAttachment = note.getAttachmentsList().get(0); - Bitmap bmp = BitmapHelper.getBitmapFromAttachment(app, mAttachment, WIDTH, HEIGHT); - row.setBitmap(R.id.attachmentThumbnail, "setImageBitmap", bmp); - row.setInt(R.id.attachmentThumbnail, "setVisibility", View.VISIBLE); + // Next, set a fill-intent, which will be used to fill in the pending intent template + // that is set on the collection view in StackWidgetProvider. + Bundle extras = new Bundle(); + extras.putParcelable(Constants.INTENT_NOTE, note); + Intent fillInIntent = new Intent(); + fillInIntent.putExtras(extras); + // Make it possible to distinguish the individual on-click + // action of a given item + row.setOnClickFillInIntent(R.id.root, fillInIntent); + + return row; + } + + @Override + public RemoteViews getLoadingView () { + return null; + } + + @Override + public int getViewTypeCount () { + return 1; + } + + @Override + public long getItemId (int position) { + return position; + } + + @Override + public boolean hasStableIds () { + return false; + } + + private void color (Note note, RemoteViews row) { + + String colorsPref = app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) + .getString("settings_colors_widget", + Constants.PREF_COLORS_APP_DEFAULT); + + // Checking preference + if (!colorsPref.equals("disabled")) { + + // Resetting transparent color to the view + row.setInt(R.id.tag_marker, "setBackgroundColor", Color.parseColor("#00000000")); + + // If tag is set the color will be applied on the appropriate target + if (note.getCategory() != null && note.getCategory().getColor() != null) { + if (colorsPref.equals("list")) { + row.setInt(R.id.card_layout, "setBackgroundColor", Integer.parseInt(note.getCategory().getColor())); } else { - row.setInt(R.id.attachmentThumbnail, "setVisibility", View.GONE); - } - if(showTimestamps) { - row.setTextViewText(R.id.note_date, TextHelper.getDateText(app, note, navigation)); - } else { - row.setTextViewText(R.id.note_date, ""); - } - - // Next, set a fill-intent, which will be used to fill in the pending intent template - // that is set on the collection view in StackWidgetProvider. - Bundle extras = new Bundle(); - extras.putParcelable(Constants.INTENT_NOTE, note); - Intent fillInIntent = new Intent(); - fillInIntent.putExtras(extras); - // Make it possible to distinguish the individual on-click - // action of a given item - row.setOnClickFillInIntent(R.id.root, fillInIntent); - - return row; - } - - @Override - public RemoteViews getLoadingView() { - return null; - } - - @Override - public int getViewTypeCount() { - return 1; - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public boolean hasStableIds() { - return false; - } - - private void color(Note note, RemoteViews row) { - - String colorsPref = app.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS) - .getString("settings_colors_widget", - Constants.PREF_COLORS_APP_DEFAULT); - - // Checking preference - if (!colorsPref.equals("disabled")) { - - // Resetting transparent color to the view - row.setInt(R.id.tag_marker, "setBackgroundColor", Color.parseColor("#00000000")); - - // If tag is set the color will be applied on the appropriate target - if (note.getCategory() != null && note.getCategory().getColor() != null) { - if (colorsPref.equals("list")) { - row.setInt(R.id.card_layout, "setBackgroundColor", Integer.parseInt(note.getCategory().getColor())); - } else { - row.setInt(R.id.tag_marker, "setBackgroundColor", Integer.parseInt(note.getCategory().getColor())); - } - } else { - row.setInt(R.id.tag_marker, "setBackgroundColor", 0); - } + row.setInt(R.id.tag_marker, "setBackgroundColor", Integer.parseInt(note.getCategory().getColor())); } + } else { + row.setInt(R.id.tag_marker, "setBackgroundColor", 0); + } } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetProvider.java b/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetProvider.java index 0b6c46e793..00e7dfbde2 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetProvider.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetProvider.java @@ -24,7 +24,6 @@ import android.net.Uri; import android.util.SparseArray; import android.widget.RemoteViews; - import it.feio.android.omninotes.MainActivity; import it.feio.android.omninotes.R; import it.feio.android.omninotes.utils.Constants; @@ -32,52 +31,52 @@ public class ListWidgetProvider extends WidgetProvider { - @Override - protected RemoteViews getRemoteViews(Context mContext, int widgetId, - boolean isSmall, boolean isSingleLine, - SparseArray pendingIntentsMap) { - RemoteViews views; - if (isSmall) { - views = new RemoteViews(mContext.getPackageName(), - R.layout.widget_layout_small); - views.setOnClickPendingIntent(R.id.list, - pendingIntentsMap.get(R.id.list)); - } else if (isSingleLine) { - views = new RemoteViews(mContext.getPackageName(), - R.layout.widget_layout); - views.setOnClickPendingIntent(R.id.add, - pendingIntentsMap.get(R.id.add)); - views.setOnClickPendingIntent(R.id.list, - pendingIntentsMap.get(R.id.list)); - views.setOnClickPendingIntent(R.id.camera, - pendingIntentsMap.get(R.id.camera)); - } else { - views = new RemoteViews(mContext.getPackageName(), - R.layout.widget_layout_list); - views.setOnClickPendingIntent(R.id.add, - pendingIntentsMap.get(R.id.add)); - views.setOnClickPendingIntent(R.id.list, - pendingIntentsMap.get(R.id.list)); - views.setOnClickPendingIntent(R.id.camera, - pendingIntentsMap.get(R.id.camera)); + @Override + protected RemoteViews getRemoteViews (Context mContext, int widgetId, + boolean isSmall, boolean isSingleLine, + SparseArray pendingIntentsMap) { + RemoteViews views; + if (isSmall) { + views = new RemoteViews(mContext.getPackageName(), + R.layout.widget_layout_small); + views.setOnClickPendingIntent(R.id.list, + pendingIntentsMap.get(R.id.list)); + } else if (isSingleLine) { + views = new RemoteViews(mContext.getPackageName(), + R.layout.widget_layout); + views.setOnClickPendingIntent(R.id.add, + pendingIntentsMap.get(R.id.add)); + views.setOnClickPendingIntent(R.id.list, + pendingIntentsMap.get(R.id.list)); + views.setOnClickPendingIntent(R.id.camera, + pendingIntentsMap.get(R.id.camera)); + } else { + views = new RemoteViews(mContext.getPackageName(), + R.layout.widget_layout_list); + views.setOnClickPendingIntent(R.id.add, + pendingIntentsMap.get(R.id.add)); + views.setOnClickPendingIntent(R.id.list, + pendingIntentsMap.get(R.id.list)); + views.setOnClickPendingIntent(R.id.camera, + pendingIntentsMap.get(R.id.camera)); - // Set up the intent that starts the ListViewService, which will - // provide the views for this collection. - Intent intent = new Intent(mContext, ListWidgetService.class); - // Add the app widget ID to the intent extras. - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId); - intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); + // Set up the intent that starts the ListViewService, which will + // provide the views for this collection. + Intent intent = new Intent(mContext, ListWidgetService.class); + // Add the app widget ID to the intent extras. + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId); + intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); - views.setRemoteAdapter(R.id.widget_list, intent); + views.setRemoteAdapter(R.id.widget_list, intent); - Intent clickIntent = new Intent(mContext, MainActivity.class); - clickIntent.setAction(Constants.ACTION_WIDGET); - PendingIntent clickPI = PendingIntent.getActivity(mContext, 0, - clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); + Intent clickIntent = new Intent(mContext, MainActivity.class); + clickIntent.setAction(Constants.ACTION_WIDGET); + PendingIntent clickPI = PendingIntent.getActivity(mContext, 0, + clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); - views.setPendingIntentTemplate(R.id.widget_list, clickPI); - } - return views; + views.setPendingIntentTemplate(R.id.widget_list, clickPI); } + return views; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetService.java b/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetService.java index 3f067f3cfb..8a8b9e439e 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetService.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/widget/ListWidgetService.java @@ -23,8 +23,8 @@ public class ListWidgetService extends RemoteViewsService { - @Override - public RemoteViewsFactory onGetViewFactory(Intent intent) { - return new ListRemoteViewsFactory(this.getApplication(), intent); - } + @Override + public RemoteViewsFactory onGetViewFactory (Intent intent) { + return new ListRemoteViewsFactory(this.getApplication(), intent); + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/widget/SimpleWidgetProvider.java b/omniNotes/src/main/java/it/feio/android/omninotes/widget/SimpleWidgetProvider.java index a225d5fd8c..d41e247acd 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/widget/SimpleWidgetProvider.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/widget/SimpleWidgetProvider.java @@ -22,26 +22,25 @@ import android.content.Context; import android.util.SparseArray; import android.widget.RemoteViews; - import it.feio.android.omninotes.R; public class SimpleWidgetProvider extends WidgetProvider { - @Override - protected RemoteViews getRemoteViews(Context mContext, int widgetId, boolean isSmall, boolean isSingleLine, - SparseArray pendingIntentsMap) { - RemoteViews views; - if (isSmall) { - views = new RemoteViews(mContext.getPackageName(), R.layout.widget_layout_small); - views.setOnClickPendingIntent(R.id.list, pendingIntentsMap.get(R.id.list)); - } else { - views = new RemoteViews(mContext.getPackageName(), R.layout.widget_layout); - views.setOnClickPendingIntent(R.id.add, pendingIntentsMap.get(R.id.add)); - views.setOnClickPendingIntent(R.id.list, pendingIntentsMap.get(R.id.list)); - views.setOnClickPendingIntent(R.id.camera, pendingIntentsMap.get(R.id.camera)); - } - return views; + @Override + protected RemoteViews getRemoteViews (Context mContext, int widgetId, boolean isSmall, boolean isSingleLine, + SparseArray pendingIntentsMap) { + RemoteViews views; + if (isSmall) { + views = new RemoteViews(mContext.getPackageName(), R.layout.widget_layout_small); + views.setOnClickPendingIntent(R.id.list, pendingIntentsMap.get(R.id.list)); + } else { + views = new RemoteViews(mContext.getPackageName(), R.layout.widget_layout); + views.setOnClickPendingIntent(R.id.add, pendingIntentsMap.get(R.id.add)); + views.setOnClickPendingIntent(R.id.list, pendingIntentsMap.get(R.id.list)); + views.setOnClickPendingIntent(R.id.camera, pendingIntentsMap.get(R.id.camera)); } + return views; + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetConfigurationActivity.java b/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetConfigurationActivity.java index 2b3ae97351..b47dd2e950 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetConfigurationActivity.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetConfigurationActivity.java @@ -26,102 +26,100 @@ import android.widget.CheckBox; import android.widget.RadioGroup; import android.widget.Spinner; - -import java.util.ArrayList; - import it.feio.android.omninotes.R; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.Category; import it.feio.android.omninotes.models.adapters.NavDrawerCategoryAdapter; +import java.util.ArrayList; public class WidgetConfigurationActivity extends Activity { - private Spinner categorySpinner; - private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; - private String sqlCondition; - private RadioGroup mRadioGroup; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setResult(RESULT_CANCELED); - - setContentView(R.layout.activity_widget_configuration); - - mRadioGroup = (RadioGroup) findViewById(R.id.widget_config_radiogroup); - mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> { - switch (checkedId) { - case R.id.widget_config_notes: - categorySpinner.setEnabled(false); - break; - - case R.id.widget_config_categories: - categorySpinner.setEnabled(true); - break; - - default: - LogDelegate.e("Wrong element choosen: " + checkedId); - } - }); - - categorySpinner = (Spinner) findViewById(R.id.widget_config_spinner); - categorySpinner.setEnabled(false); - DbHelper db = DbHelper.getInstance(); - ArrayList categories = db.getCategories(); - categorySpinner.setAdapter(new NavDrawerCategoryAdapter(this, categories)); - - Button configOkButton = (Button) findViewById(R.id.widget_config_confirm); - configOkButton.setOnClickListener(v -> { - - if (mRadioGroup.getCheckedRadioButtonId() == R.id.widget_config_notes) { - sqlCondition = " WHERE " + DbHelper.KEY_ARCHIVED + " IS NOT 1 AND " + DbHelper.KEY_TRASHED + " IS" + - " NOT 1 "; - - } else { - Category tag = (Category) categorySpinner.getSelectedItem(); - sqlCondition = " WHERE " + DbHelper.TABLE_NOTES + "." - + DbHelper.KEY_CATEGORY + " = " + tag.getId() - + " AND " + DbHelper.KEY_ARCHIVED + " IS NOT 1" - + " AND " + DbHelper.KEY_TRASHED + " IS NOT 1"; - } - - CheckBox showThumbnailsCheckBox = (CheckBox) findViewById(R.id.show_thumbnails); - CheckBox showTimestampsCheckBox = (CheckBox) findViewById(R.id.show_timestamps); - - // Updating the ListRemoteViewsFactory parameter to get the list - // of notes - ListRemoteViewsFactory.updateConfiguration(getApplicationContext(), mAppWidgetId, - sqlCondition, showThumbnailsCheckBox.isChecked(), showTimestampsCheckBox.isChecked()); - - Intent resultValue = new Intent(); - resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, - mAppWidgetId); - setResult(RESULT_OK, resultValue); - - finish(); - }); - - // Checks if no tags are available and then disable that option - if (categories.size() == 0) { - mRadioGroup.setVisibility(View.GONE); - categorySpinner.setVisibility(View.GONE); - } - - Intent intent = getIntent(); - Bundle extras = intent.getExtras(); - if (extras != null) { - mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, - AppWidgetManager.INVALID_APPWIDGET_ID); - } - - // If they gave us an intent without the widget id, just bail. - if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { - finish(); - } + private Spinner categorySpinner; + private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; + private String sqlCondition; + private RadioGroup mRadioGroup; + + + @Override + protected void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setResult(RESULT_CANCELED); + + setContentView(R.layout.activity_widget_configuration); + + mRadioGroup = findViewById(R.id.widget_config_radiogroup); + mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> { + switch (checkedId) { + case R.id.widget_config_notes: + categorySpinner.setEnabled(false); + break; + + case R.id.widget_config_categories: + categorySpinner.setEnabled(true); + break; + + default: + LogDelegate.e("Wrong element choosen: " + checkedId); + } + }); + + categorySpinner = findViewById(R.id.widget_config_spinner); + categorySpinner.setEnabled(false); + DbHelper db = DbHelper.getInstance(); + ArrayList categories = db.getCategories(); + categorySpinner.setAdapter(new NavDrawerCategoryAdapter(this, categories)); + + Button configOkButton = findViewById(R.id.widget_config_confirm); + configOkButton.setOnClickListener(v -> { + + if (mRadioGroup.getCheckedRadioButtonId() == R.id.widget_config_notes) { + sqlCondition = " WHERE " + DbHelper.KEY_ARCHIVED + " IS NOT 1 AND " + DbHelper.KEY_TRASHED + " IS" + + " NOT 1 "; + + } else { + Category tag = (Category) categorySpinner.getSelectedItem(); + sqlCondition = " WHERE " + DbHelper.TABLE_NOTES + "." + + DbHelper.KEY_CATEGORY + " = " + tag.getId() + + " AND " + DbHelper.KEY_ARCHIVED + " IS NOT 1" + + " AND " + DbHelper.KEY_TRASHED + " IS NOT 1"; + } + + CheckBox showThumbnailsCheckBox = findViewById(R.id.show_thumbnails); + CheckBox showTimestampsCheckBox = findViewById(R.id.show_timestamps); + + // Updating the ListRemoteViewsFactory parameter to get the list + // of notes + ListRemoteViewsFactory.updateConfiguration(getApplicationContext(), mAppWidgetId, + sqlCondition, showThumbnailsCheckBox.isChecked(), showTimestampsCheckBox.isChecked()); + + Intent resultValue = new Intent(); + resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, + mAppWidgetId); + setResult(RESULT_OK, resultValue); + + finish(); + }); + + // Checks if no tags are available and then disable that option + if (categories.size() == 0) { + mRadioGroup.setVisibility(View.GONE); + categorySpinner.setVisibility(View.GONE); + } + + Intent intent = getIntent(); + Bundle extras = intent.getExtras(); + if (extras != null) { + mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + } + + // If they gave us an intent without the widget id, just bail. + if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { + finish(); } + } } diff --git a/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetProvider.java b/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetProvider.java index a7d47ff310..13a519ab12 100644 --- a/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetProvider.java +++ b/omniNotes/src/main/java/it/feio/android/omninotes/widget/WidgetProvider.java @@ -27,7 +27,6 @@ import android.os.Bundle; import android.util.SparseArray; import android.widget.RemoteViews; - import it.feio.android.omninotes.MainActivity; import it.feio.android.omninotes.R; import it.feio.android.omninotes.helpers.LogDelegate; @@ -36,78 +35,79 @@ public abstract class WidgetProvider extends AppWidgetProvider { - public static final String EXTRA_WORD = "it.feio.android.omninotes.widget.WORD"; - public static final String TOAST_ACTION = "it.feio.android.omninotes.widget.NOTE"; - public static final String EXTRA_ITEM = "it.feio.android.omninotes.widget.EXTRA_FIELD"; - - - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - // Get all ids - ComponentName thisWidget = new ComponentName(context, getClass()); - int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); - for (int appWidgetId : allWidgetIds) { - LogDelegate.d("WidgetProvider onUpdate() widget " + appWidgetId); - // Get the layout for and attach an on-click listener to views - setLayout(context, appWidgetManager, appWidgetId); - } - super.onUpdate(context, appWidgetManager, appWidgetIds); - } + public static final String EXTRA_WORD = "it.feio.android.omninotes.widget.WORD"; + public static final String TOAST_ACTION = "it.feio.android.omninotes.widget.NOTE"; + public static final String EXTRA_ITEM = "it.feio.android.omninotes.widget.EXTRA_FIELD"; - @Override - public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, - Bundle newOptions) { - LogDelegate.d("Widget size changed"); - setLayout(context, appWidgetManager, appWidgetId); + @Override + public void onUpdate (Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + // Get all ids + ComponentName thisWidget = new ComponentName(context, getClass()); + int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); + for (int appWidgetId : allWidgetIds) { + LogDelegate.d("WidgetProvider onUpdate() widget " + appWidgetId); + // Get the layout for and attach an on-click listener to views + setLayout(context, appWidgetManager, appWidgetId); } - - - private void setLayout(Context context, AppWidgetManager appWidgetManager, int widgetId) { - - // Create an Intent to launch DetailActivity - Intent intentDetail = new Intent(context, MainActivity.class); - intentDetail.setAction(Constants.ACTION_WIDGET); - intentDetail.putExtra(Constants.INTENT_WIDGET, widgetId); - PendingIntent pendingIntentDetail = PendingIntent.getActivity(context, widgetId, intentDetail, - Intent.FLAG_ACTIVITY_NEW_TASK); - - // Create an Intent to launch ListActivity - Intent intentList = new Intent(context, MainActivity.class); - intentList.setAction(Constants.ACTION_WIDGET_SHOW_LIST); - intentList.putExtra(Constants.INTENT_WIDGET, widgetId); - PendingIntent pendingIntentList = PendingIntent.getActivity(context, widgetId, intentList, - Intent.FLAG_ACTIVITY_NEW_TASK); - - // Create an Intent to launch DetailActivity to take a photo - Intent intentDetailPhoto = new Intent(context, MainActivity.class); - intentDetailPhoto.setAction(Constants.ACTION_WIDGET_TAKE_PHOTO); - intentDetailPhoto.putExtra(Constants.INTENT_WIDGET, widgetId); - PendingIntent pendingIntentDetailPhoto = PendingIntent.getActivity(context, widgetId, intentDetailPhoto, - Intent.FLAG_ACTIVITY_NEW_TASK); - - // Check various dimensions aspect of widget to choose between layouts - boolean isSmall = false; - boolean isSingleLine = true; - Bundle options = appWidgetManager.getAppWidgetOptions(widgetId); - // Width check - isSmall = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) < 110; - // Height check - isSingleLine = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) < 110; - - // Creation of a map to associate PendingIntent(s) to views - SparseArray map = new SparseArray<>(); - map.put(R.id.list, pendingIntentList); - map.put(R.id.add, pendingIntentDetail); - map.put(R.id.camera, pendingIntentDetailPhoto); - - RemoteViews views = getRemoteViews(context, widgetId, isSmall, isSingleLine, map); - - // Tell the AppWidgetManager to perform an update on the current app widget - appWidgetManager.updateAppWidget(widgetId, views); - } - - - abstract protected RemoteViews getRemoteViews(Context context, int widgetId, boolean isSmall, boolean isSingleLine, SparseArray pendingIntentsMap); + super.onUpdate(context, appWidgetManager, appWidgetIds); + } + + + @Override + public void onAppWidgetOptionsChanged (Context context, AppWidgetManager appWidgetManager, int appWidgetId, + Bundle newOptions) { + LogDelegate.d("Widget size changed"); + setLayout(context, appWidgetManager, appWidgetId); + } + + + private void setLayout (Context context, AppWidgetManager appWidgetManager, int widgetId) { + + // Create an Intent to launch DetailActivity + Intent intentDetail = new Intent(context, MainActivity.class); + intentDetail.setAction(Constants.ACTION_WIDGET); + intentDetail.putExtra(Constants.INTENT_WIDGET, widgetId); + PendingIntent pendingIntentDetail = PendingIntent.getActivity(context, widgetId, intentDetail, + Intent.FLAG_ACTIVITY_NEW_TASK); + + // Create an Intent to launch ListActivity + Intent intentList = new Intent(context, MainActivity.class); + intentList.setAction(Constants.ACTION_WIDGET_SHOW_LIST); + intentList.putExtra(Constants.INTENT_WIDGET, widgetId); + PendingIntent pendingIntentList = PendingIntent.getActivity(context, widgetId, intentList, + Intent.FLAG_ACTIVITY_NEW_TASK); + + // Create an Intent to launch DetailActivity to take a photo + Intent intentDetailPhoto = new Intent(context, MainActivity.class); + intentDetailPhoto.setAction(Constants.ACTION_WIDGET_TAKE_PHOTO); + intentDetailPhoto.putExtra(Constants.INTENT_WIDGET, widgetId); + PendingIntent pendingIntentDetailPhoto = PendingIntent.getActivity(context, widgetId, intentDetailPhoto, + Intent.FLAG_ACTIVITY_NEW_TASK); + + // Check various dimensions aspect of widget to choose between layouts + boolean isSmall = false; + boolean isSingleLine = true; + Bundle options = appWidgetManager.getAppWidgetOptions(widgetId); + // Width check + isSmall = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) < 110; + // Height check + isSingleLine = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) < 110; + + // Creation of a map to associate PendingIntent(s) to views + SparseArray map = new SparseArray<>(); + map.put(R.id.list, pendingIntentList); + map.put(R.id.add, pendingIntentDetail); + map.put(R.id.camera, pendingIntentDetailPhoto); + + RemoteViews views = getRemoteViews(context, widgetId, isSmall, isSingleLine, map); + + // Tell the AppWidgetManager to perform an update on the current app widget + appWidgetManager.updateAppWidget(widgetId, views); + } + + + abstract protected RemoteViews getRemoteViews (Context context, int widgetId, boolean isSmall, boolean isSingleLine, + SparseArray pendingIntentsMap); } diff --git a/omniNotes/src/play/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java b/omniNotes/src/play/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java index 316cd73788..4dc914b3b2 100644 --- a/omniNotes/src/play/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java +++ b/omniNotes/src/play/java/it/feio/android/omninotes/helpers/GeocodeProviderFactory.java @@ -18,13 +18,12 @@ package it.feio.android.omninotes.helpers; import android.content.Context; - import io.nlopez.smartlocation.location.LocationProvider; import io.nlopez.smartlocation.location.providers.LocationGooglePlayServicesWithFallbackProvider; public class GeocodeProviderFactory { - public static LocationProvider getProvider(Context context) { - return new LocationGooglePlayServicesWithFallbackProvider(context); - } + public static LocationProvider getProvider (Context context) { + return new LocationGooglePlayServicesWithFallbackProvider(context); + } } diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/BaseUnitTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/BaseUnitTest.java index c51b68f908..4e294beed9 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/BaseUnitTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/BaseUnitTest.java @@ -22,11 +22,11 @@ public class BaseUnitTest { - protected Note getNote(Long id, String title, String content) { - Note note = new Note(); - note.set_id(id); - note.setTitle(title); - note.setContent(content); - return note; - } + protected Note getNote (Long id, String title, String content) { + Note note = new Note(); + note.set_id(id); + note.setTitle(title); + note.setContent(content); + return note; + } } diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/ResourceAwareTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/ResourceAwareTest.java index d34aaa17bd..ac10e77f53 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/ResourceAwareTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/ResourceAwareTest.java @@ -18,8 +18,12 @@ package it.feio.android.omninotes; import android.support.annotation.NonNull; - -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -29,7 +33,7 @@ public class ResourceAwareTest { private static final String BASE_PATH = resolveBasePath(MODULE_NAME); - private static String resolveBasePath(String moduleName) { + private static String resolveBasePath (String moduleName) { final String path = "./" + moduleName + "/src/test/res/"; if (Arrays.asList(new File("./").list()).contains(moduleName)) { return path; // version for call unit tests from Android Studio @@ -40,34 +44,28 @@ private static String resolveBasePath(String moduleName) { /** * Retrieves test resouce InputStream - * - * @throws IOException */ - public static FileInputStream getResourceAsStream(@NonNull final String path) throws IOException { + public static FileInputStream getResourceAsStream (@NonNull final String path) throws IOException { return new FileInputStream(BASE_PATH + path); } /** * Retrieves test resouce as {@link File} object - * - * @throws IOException */ - public static File getResourceAsFile(@NonNull final String path) throws IOException { + public static File getResourceAsFile (@NonNull final String path) throws IOException { return new File(BASE_PATH + path); } /** * Reads file content and returns string. - * - * @throws IOException */ - public static String readFile(@NonNull final String path) throws IOException { + public static String readFile (@NonNull final String path) throws IOException { final StringBuilder sb = new StringBuilder(); String strLine; try (final BufferedReader reader = - new BufferedReader(new InputStreamReader(new FileInputStream(BASE_PATH + path), "UTF-8"))) { + new BufferedReader(new InputStreamReader(new FileInputStream(BASE_PATH + path), StandardCharsets.UTF_8))) { while ((strLine = reader.readLine()) != null) { sb.append(strLine); } diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/helpers/NotesHelperTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/helpers/NotesHelperTest.java index d735556693..df2da780bc 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/helpers/NotesHelperTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/helpers/NotesHelperTest.java @@ -17,67 +17,64 @@ package it.feio.android.omninotes.helpers; -import junit.framework.Assert; - -import org.apache.commons.lang.StringUtils; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import it.feio.android.omninotes.BaseUnitTest; -import it.feio.android.omninotes.models.Note; -import it.feio.android.omninotes.utils.Constants; - import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import it.feio.android.omninotes.BaseUnitTest; +import it.feio.android.omninotes.models.Note; +import it.feio.android.omninotes.utils.Constants; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import junit.framework.Assert; +import org.apache.commons.lang.StringUtils; +import org.junit.Test; + public class NotesHelperTest extends BaseUnitTest { - @Test - public void haveSameIdShouldFail() { - Note note1 = getNote(1L, "test title", "test content"); - Note note2 = getNote(2L, "test title", "test content"); - assertFalse(NotesHelper.haveSameId(note1, note2)); - } + @Test + public void haveSameIdShouldFail () { + Note note1 = getNote(1L, "test title", "test content"); + Note note2 = getNote(2L, "test title", "test content"); + assertFalse(NotesHelper.haveSameId(note1, note2)); + } - @Test - public void haveSameIdShouldSucceed() { - Note note1 = getNote(3L, "test title", "test content"); - Note note2 = getNote(3L, "different test title", "different test content"); - assertTrue(NotesHelper.haveSameId(note1, note2)); - } + @Test + public void haveSameIdShouldSucceed () { + Note note1 = getNote(3L, "test title", "test content"); + Note note2 = getNote(3L, "different test title", "different test content"); + assertTrue(NotesHelper.haveSameId(note1, note2)); + } - @Test - public void mergingNotesDoesntDuplicateFirstTitle() { - final String FIRST_NOTE_TITLE = "test title 1"; - Note note1 = getNote(4L, FIRST_NOTE_TITLE, ""); - Note note2 = getNote(5L, "test title 2", ""); - Note mergedNote = NotesHelper.mergeNotes(Arrays.asList(note1, note2), false); - assertFalse(mergedNote.getContent().contains(FIRST_NOTE_TITLE)); - } + @Test + public void mergingNotesDoesntDuplicateFirstTitle () { + final String FIRST_NOTE_TITLE = "test title 1"; + Note note1 = getNote(4L, FIRST_NOTE_TITLE, ""); + Note note2 = getNote(5L, "test title 2", ""); + Note mergedNote = NotesHelper.mergeNotes(Arrays.asList(note1, note2), false); + assertFalse(mergedNote.getContent().contains(FIRST_NOTE_TITLE)); + } - @Test - public void mergeNotes() { - int notesNumber = 3; - List notes = new ArrayList<>(); - for (int i = 0; i < notesNumber; i++) { - Note note = new Note(); - note.setTitle("Merged note " + i + " title"); - note.setContent("Merged note " + i + " content"); - notes.add(note); - } - Note mergeNote = NotesHelper.mergeNotes(notes, false); + @Test + public void mergeNotes () { + int notesNumber = 3; + List notes = new ArrayList<>(); + for (int i = 0; i < notesNumber; i++) { + Note note = new Note(); + note.setTitle("Merged note " + i + " title"); + note.setContent("Merged note " + i + " content"); + notes.add(note); + } + Note mergeNote = NotesHelper.mergeNotes(notes, false); - assertNotNull(mergeNote); - Assert.assertEquals("Merged note 0 title", mergeNote.getTitle()); - Assert.assertTrue(mergeNote.getContent().contains("Merged note 0 content")); - Assert.assertTrue(mergeNote.getContent().contains("Merged note 1 content")); - Assert.assertTrue(mergeNote.getContent().contains("Merged note 2 content")); - assertEquals(StringUtils.countMatches(mergeNote.getContent(), Constants.MERGED_NOTES_SEPARATOR), 2); - } + assertNotNull(mergeNote); + Assert.assertEquals("Merged note 0 title", mergeNote.getTitle()); + Assert.assertTrue(mergeNote.getContent().contains("Merged note 0 content")); + Assert.assertTrue(mergeNote.getContent().contains("Merged note 1 content")); + Assert.assertTrue(mergeNote.getContent().contains("Merged note 2 content")); + assertEquals(StringUtils.countMatches(mergeNote.getContent(), Constants.MERGED_NOTES_SEPARATOR), 2); + } } diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/DefaultWordCounterTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/DefaultWordCounterTest.java index 898c6ce05e..2c5ea64fb1 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/DefaultWordCounterTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/DefaultWordCounterTest.java @@ -17,45 +17,44 @@ package it.feio.android.omninotes.helpers.count; -import org.junit.Test; +import static junit.framework.Assert.assertEquals; import it.feio.android.omninotes.BaseUnitTest; import it.feio.android.omninotes.models.Note; - -import static junit.framework.Assert.assertEquals; +import org.junit.Test; public class DefaultWordCounterTest extends BaseUnitTest { - private final String CHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM; - private final String UNCHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM; - - @Test - public void countChars() { - Note note = getNote(1L, "one two", "three four five\nAnother line"); - assertEquals(30, new DefaultWordCounter().countChars(note)); - } - - @Test - public void countChecklistChars() { - String content = CHECKED_SYM + "done\n" + UNCHECKED_SYM + "undone yet"; - Note note = getNote(1L, "checklist", content); - note.setChecklist(true); - assertEquals(22, new DefaultWordCounter().countChars(note)); - } - - @Test - public void getWords() { - Note note = getNote(1L, "one two", "three\n four five"); - assertEquals(5, new DefaultWordCounter().countWords(note)); - note.setTitle("singleword"); - assertEquals(4, new DefaultWordCounter().countWords(note)); - } - - @Test - public void getChecklistWords() { - String content = CHECKED_SYM + "done\n" + UNCHECKED_SYM + "undone yet"; - Note note = getNote(1L, "checklist", content); - note.setChecklist(true); - assertEquals(4, new DefaultWordCounter().countWords(note)); - } + private final String CHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM; + private final String UNCHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM; + + @Test + public void countChars () { + Note note = getNote(1L, "one two", "three four five\nAnother line"); + assertEquals(30, new DefaultWordCounter().countChars(note)); + } + + @Test + public void countChecklistChars () { + String content = CHECKED_SYM + "done\n" + UNCHECKED_SYM + "undone yet"; + Note note = getNote(1L, "checklist", content); + note.setChecklist(true); + assertEquals(22, new DefaultWordCounter().countChars(note)); + } + + @Test + public void getWords () { + Note note = getNote(1L, "one two", "three\n four five"); + assertEquals(5, new DefaultWordCounter().countWords(note)); + note.setTitle("singleword"); + assertEquals(4, new DefaultWordCounter().countWords(note)); + } + + @Test + public void getChecklistWords () { + String content = CHECKED_SYM + "done\n" + UNCHECKED_SYM + "undone yet"; + Note note = getNote(1L, "checklist", content); + note.setChecklist(true); + assertEquals(4, new DefaultWordCounter().countWords(note)); + } } \ No newline at end of file diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounterTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounterTest.java index 46add5791c..1089127ed2 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounterTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/helpers/count/IdeogramsWordCounterTest.java @@ -17,45 +17,44 @@ package it.feio.android.omninotes.helpers.count; -import org.junit.Test; +import static junit.framework.Assert.assertEquals; import it.feio.android.omninotes.BaseUnitTest; import it.feio.android.omninotes.models.Note; - -import static junit.framework.Assert.assertEquals; +import org.junit.Test; public class IdeogramsWordCounterTest extends BaseUnitTest { - private final String CHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM; - private final String UNCHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM; - - @Test - public void countChars() { - Note note = getNote(1L, "这是中文测试", "這是中文測試\n これは日本語のテストです"); - assertEquals(24, new IdeogramsWordCounter().countChars(note)); - } - - @Test - public void countChecklistChars() { - String content = CHECKED_SYM + "這是中文測試\n" + UNCHECKED_SYM + "これは日本語のテストです"; - Note note = getNote(1L, "这是中文测试", content); - note.setChecklist(true); - assertEquals(24, new IdeogramsWordCounter().countChars(note)); - } - - @Test - public void getWords() { - Note note = getNote(1L, "这是中文测试", "這是中文測試\n これは日本語のテストです"); - assertEquals(24, new IdeogramsWordCounter().countWords(note)); - note.setTitle("这"); - assertEquals(19, new IdeogramsWordCounter().countWords(note)); - } - - @Test - public void getChecklistWords() { - String content = CHECKED_SYM + "這是中文測試\n" + UNCHECKED_SYM + "これは日本語のテストです"; - Note note = getNote(1L, "这是中文测试", content); - note.setChecklist(true); - assertEquals(24, new IdeogramsWordCounter().countWords(note)); - } + private final String CHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM; + private final String UNCHECKED_SYM = it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM; + + @Test + public void countChars () { + Note note = getNote(1L, "这是中文测试", "這是中文測試\n これは日本語のテストです"); + assertEquals(24, new IdeogramsWordCounter().countChars(note)); + } + + @Test + public void countChecklistChars () { + String content = CHECKED_SYM + "這是中文測試\n" + UNCHECKED_SYM + "これは日本語のテストです"; + Note note = getNote(1L, "这是中文测试", content); + note.setChecklist(true); + assertEquals(24, new IdeogramsWordCounter().countChars(note)); + } + + @Test + public void getWords () { + Note note = getNote(1L, "这是中文测试", "這是中文測試\n これは日本語のテストです"); + assertEquals(24, new IdeogramsWordCounter().countWords(note)); + note.setTitle("这"); + assertEquals(19, new IdeogramsWordCounter().countWords(note)); + } + + @Test + public void getChecklistWords () { + String content = CHECKED_SYM + "這是中文測試\n" + UNCHECKED_SYM + "これは日本語のテストです"; + Note note = getNote(1L, "这是中文测试", content); + note.setChecklist(true); + assertEquals(24, new IdeogramsWordCounter().countWords(note)); + } } \ No newline at end of file diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/utils/TagsHelperTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/utils/TagsHelperTest.java index 677067e013..1557ff3b6c 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/utils/TagsHelperTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/utils/TagsHelperTest.java @@ -17,84 +17,84 @@ package it.feio.android.omninotes.utils; -import android.support.v4.util.Pair; - -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import it.feio.android.omninotes.models.Note; -import it.feio.android.omninotes.models.Tag; - import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import android.support.v4.util.Pair; +import it.feio.android.omninotes.models.Note; +import it.feio.android.omninotes.models.Tag; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.junit.Before; +import org.junit.Test; + public class TagsHelperTest { - private static String TAG1 = "#mixed"; - private static String TAG2 = "#123numbered"; - private static String TAG3 = "#tags"; - private static String TAG4 = "#tag"; - private static String TAG5 = "#numberedAfter123"; - - private Note note; - - - @Before - public void setup() { - note = new Note(); - note.setContent("Random content with " + TAG1 + " " + TAG2 + " " + TAG3 + "(and another with similar prefix: " + TAG4 + ") and " + TAG5); - } - - - @Test - public void retrievesTagsFromNote() { - HashMap tags = TagsHelper.retrieveTags(note); - assertEquals(tags.size(), 4); - assertTrue(tags.containsKey(TAG1) && tags.containsKey(TAG3) && tags.containsKey(TAG4) && tags.containsKey(TAG5)); - assertFalse(tags.containsKey(TAG2)); - } - - - @Test - public void retrievesTagsFromNoteMultilanguage() { - note.setContent("#привет"); - HashMap tags = TagsHelper.retrieveTags(note); - assertTrue(tags.containsKey("#привет")); - - note.setContent("#中华人民共和国"); - tags = TagsHelper.retrieveTags(note); - assertTrue(tags.containsKey("#中华人民共和国")); - } - - - @Test - public void removesTagsFromNote() { - Pair pair = TagsHelper.removeTag(note.getTitle(), note.getContent(), singletonList(new Tag(TAG4, 4))); - note.setTitle(pair.first); - note.setContent(pair.second); - HashMap tags = TagsHelper.retrieveTags(note); - assertTrue(tags.containsKey(TAG1)); - assertFalse(tags.containsKey(TAG2)); - assertTrue(tags.containsKey(TAG3)); - assertFalse(tags.containsKey(TAG4)); - } - - - @Test - public void addsTagsToNote() { - String newTag = "#addedTag"; - List tags = new ArrayList<>(); - tags.add(new Tag(newTag, 1)); - tags.add(new Tag(TAG3, 1)); - Pair> newTags = TagsHelper.addTagToNote(tags, new Integer[]{0, 1}, note); - assertTrue(newTags.first.contains(newTag)); - assertFalse(newTags.first.contains(TAG3)); - } + private static String TAG1 = "#mixed"; + private static String TAG2 = "#123numbered"; + private static String TAG3 = "#tags"; + private static String TAG4 = "#tag"; + private static String TAG5 = "#numberedAfter123"; + + private Note note; + + + @Before + public void setup () { + note = new Note(); + note.setContent( + "Random content with " + TAG1 + " " + TAG2 + " " + TAG3 + "(and another with similar prefix: " + TAG4 + ") and " + + TAG5); + } + + + @Test + public void retrievesTagsFromNote () { + HashMap tags = TagsHelper.retrieveTags(note); + assertEquals(tags.size(), 4); + assertTrue(tags.containsKey(TAG1) && tags.containsKey(TAG3) && tags.containsKey(TAG4) && tags.containsKey(TAG5)); + assertFalse(tags.containsKey(TAG2)); + } + + + @Test + public void retrievesTagsFromNoteMultilanguage () { + note.setContent("#привет"); + HashMap tags = TagsHelper.retrieveTags(note); + assertTrue(tags.containsKey("#привет")); + + note.setContent("#中华人民共和国"); + tags = TagsHelper.retrieveTags(note); + assertTrue(tags.containsKey("#中华人民共和国")); + } + + + @Test + public void removesTagsFromNote () { + Pair pair = TagsHelper.removeTag(note.getTitle(), note.getContent(), + singletonList(new Tag(TAG4, 4))); + note.setTitle(pair.first); + note.setContent(pair.second); + HashMap tags = TagsHelper.retrieveTags(note); + assertTrue(tags.containsKey(TAG1)); + assertFalse(tags.containsKey(TAG2)); + assertTrue(tags.containsKey(TAG3)); + assertFalse(tags.containsKey(TAG4)); + } + + + @Test + public void addsTagsToNote () { + String newTag = "#addedTag"; + List tags = new ArrayList<>(); + tags.add(new Tag(newTag, 1)); + tags.add(new Tag(TAG3, 1)); + Pair> newTags = TagsHelper.addTagToNote(tags, new Integer[]{0, 1}, note); + assertTrue(newTags.first.contains(newTag)); + assertFalse(newTags.first.contains(TAG3)); + } } diff --git a/omniNotes/src/test/java/it/feio/android/omninotes/utils/date/DateUtilsTest.java b/omniNotes/src/test/java/it/feio/android/omninotes/utils/date/DateUtilsTest.java index 5848e6ccbf..5ff005096c 100644 --- a/omniNotes/src/test/java/it/feio/android/omninotes/utils/date/DateUtilsTest.java +++ b/omniNotes/src/test/java/it/feio/android/omninotes/utils/date/DateUtilsTest.java @@ -17,6 +17,11 @@ package it.feio.android.omninotes.utils.date; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; + +import java.util.Calendar; +import java.util.Locale; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,67 +29,61 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.util.Calendar; -import java.util.Locale; - -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; - @RunWith(PowerMockRunner.class) @PrepareForTest({DateUtils.class}) public class DateUtilsTest { - @Test - public void prettyTime() { - long now = Calendar.getInstance().getTimeInMillis(); - - String prettyTime = DateUtils.prettyTime(now, Locale.ENGLISH); - Assert.assertEquals(prettyTime.toLowerCase(), "moments ago"); - - prettyTime = DateUtils.prettyTime(now + 10 * 60 * 1000, Locale.ENGLISH); - Assert.assertEquals(prettyTime.toLowerCase(), "10 minutes from now"); - - prettyTime = DateUtils.prettyTime(now + 24 * 60 * 60 * 1000, Locale.ITALIAN); - Assert.assertEquals(prettyTime.toLowerCase(), "fra 24 ore"); - - prettyTime = DateUtils.prettyTime(now + 25 * 60 * 60 * 1000, Locale.ITALIAN); - Assert.assertEquals(prettyTime.toLowerCase(), "fra 1 giorno"); - - prettyTime = DateUtils.prettyTime(null, Locale.JAPANESE); - Assert.assertNotNull(prettyTime.toLowerCase()); - Assert.assertEquals(prettyTime.toLowerCase().length(), 0); - } - - @Test - public void getPresetReminder() { - long mockedNextMinute = 1497315847L; - Long testReminder = null; - PowerMockito.stub(PowerMockito.method(DateUtils.class, "getNextMinute")).toReturn(mockedNextMinute); - junit.framework.Assert.assertEquals(mockedNextMinute, DateUtils.getPresetReminder(testReminder)); - } - - @Test - public void isFuture() { - String nextMinute = String.valueOf(Calendar.getInstance().getTimeInMillis() + 60000); - String previousMinute = String.valueOf(Calendar.getInstance().getTimeInMillis() - 60000); - assertTrue(DateUtils.isFuture(nextMinute)); - assertFalse(DateUtils.isFuture(previousMinute)); - } - - @Test - public void isFutureManagesNullValues() { - Long longValue = null; - assertFalse(DateUtils.isFuture(longValue)); - } - - @Test - public void isSameDay() { - long today = Calendar.getInstance().getTimeInMillis(); - long tomorrow = today + (1000 * 60 * 60 * 24); - assertTrue(DateUtils.isSameDay(today, today)); - assertFalse(DateUtils.isSameDay(today, tomorrow)); - } + @Test + public void prettyTime () { + long now = Calendar.getInstance().getTimeInMillis(); + + String prettyTime = DateUtils.prettyTime(now, Locale.ENGLISH); + Assert.assertEquals(prettyTime.toLowerCase(), "moments ago"); + + prettyTime = DateUtils.prettyTime(now + 10 * 60 * 1000, Locale.ENGLISH); + Assert.assertEquals(prettyTime.toLowerCase(), "10 minutes from now"); + + prettyTime = DateUtils.prettyTime(now + 24 * 60 * 60 * 1000, Locale.ITALIAN); + Assert.assertEquals(prettyTime.toLowerCase(), "fra 24 ore"); + + prettyTime = DateUtils.prettyTime(now + 25 * 60 * 60 * 1000, Locale.ITALIAN); + Assert.assertEquals(prettyTime.toLowerCase(), "fra 1 giorno"); + + prettyTime = DateUtils.prettyTime(null, Locale.JAPANESE); + Assert.assertNotNull(prettyTime.toLowerCase()); + Assert.assertEquals(prettyTime.toLowerCase().length(), 0); + } + + @Test + public void getPresetReminder () { + long mockedNextMinute = 1497315847L; + Long testReminder = null; + PowerMockito.stub(PowerMockito.method(DateUtils.class, "getNextMinute")).toReturn(mockedNextMinute); + junit.framework.Assert.assertEquals(mockedNextMinute, DateUtils.getPresetReminder(testReminder)); + } + + @Test + public void isFuture () { + String nextMinute = String.valueOf(Calendar.getInstance().getTimeInMillis() + 60000); + String previousMinute = String.valueOf(Calendar.getInstance().getTimeInMillis() - 60000); + assertTrue(DateUtils.isFuture(nextMinute)); + assertFalse(DateUtils.isFuture(previousMinute)); + } + + @Test + public void isFutureManagesNullValues () { + Long longValue = null; + assertFalse(DateUtils.isFuture(longValue)); + } + + @Test + public void isSameDay () { + long today = Calendar.getInstance().getTimeInMillis(); + long tomorrow = today + (1000 * 60 * 60 * 24); + assertTrue(DateUtils.isSameDay(today, today)); + assertFalse(DateUtils.isSameDay(today, tomorrow)); + } // @Test // public void getString() throws ParseException {