Search in sources :

Example 1 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method showTagsDialog.

protected void showTagsDialog() {
    ArrayList<String> tags = new ArrayList<>(getCol().getTags().all());
    ArrayList<String> selTags = new ArrayList<>(mCurrentCard.note().getTags());
    TagsDialog.TagsDialogListener tagsDialogListener = (selectedTags, option) -> {
        if (!mCurrentCard.note().getTags().equals(selectedTags)) {
            String tagString = TextUtils.join(" ", selectedTags);
            Note note = mCurrentCard.note();
            note.setTagsFromStr(tagString);
            note.flush();
            // Reload current card to reflect tag changes
            displayCardQuestion(true);
        }
    };
    TagsDialog dialog = TagsDialog.newInstance(TagsDialog.TYPE_ADD_TAG, selTags, tags);
    dialog.setTagsDialogListener(tagsDialogListener);
    showDialogFragment(dialog);
}
Also used : JavascriptInterface(android.webkit.JavascriptInterface) UI_PLAY_END(com.ichi2.bd.MainHandlerConstant.UI_PLAY_END) Version(com.github.zafarkhaja.semver.Version) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) JsResult(android.webkit.JsResult) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AbstractSched(com.ichi2.libanki.sched.AbstractSched) RangeSeekBar(com.jaygoo.widget.RangeSeekBar) RenderProcessGoneDetail(android.webkit.RenderProcessGoneDetail) HitTestResult(android.webkit.WebView.HitTestResult) ActionBar(androidx.appcompat.app.ActionBar) FileSaveListener(com.ichi2.bd.FileSaveListener) Decks(com.ichi2.libanki.Decks) Matcher(java.util.regex.Matcher) Handler(android.os.Handler) DeckConfig(com.ichi2.libanki.DeckConfig) Map(java.util.Map) JSONException(com.ichi2.utils.JSONException) THEME_NIGHT_BLACK(com.ichi2.themes.Themes.THEME_NIGHT_BLACK) OnRangeChangedListener(com.jaygoo.widget.OnRangeChangedListener) ContextCompat(androidx.core.content.ContextCompat) TargetApi(android.annotation.TargetApi) Log(android.util.Log) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ConnectivityManager(android.net.ConnectivityManager) HtmlUtils(com.ichi2.utils.HtmlUtils) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) TtsMode(com.baidu.tts.client.TtsMode) IntentFilter(android.content.IntentFilter) CardMarker(com.ichi2.anki.reviewer.CardMarker) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) BE_VIP(com.ichi2.anki.DeckPicker.BE_VIP) IdRes(androidx.annotation.IdRes) StringRes(androidx.annotation.StringRes) Nullable(androidx.annotation.Nullable) Message(android.os.Message) Consts(com.ichi2.libanki.Consts) OKHttpUtil(com.ichi2.utils.OKHttpUtil) CompatHelper(com.ichi2.compat.CompatHelper) WebViewDebugging(com.ichi2.utils.WebViewDebugging) DiffEngine(com.ichi2.utils.DiffEngine) TypedAnswer(com.ichi2.anki.cardviewer.TypedAnswer) WebResourceResponse(android.webkit.WebResourceResponse) Dialog(android.app.Dialog) SystemClock(android.os.SystemClock) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) CardAppearance.calculateDynamicFontSize(com.ichi2.anki.cardviewer.CardAppearance.calculateDynamicFontSize) ViewAnimation(com.ichi2.anim.ViewAnimation) ArrayList(java.util.ArrayList) REFRESH_VOICE_INFO(com.ichi2.anki.DeckPicker.REFRESH_VOICE_INFO) WebResourceRequest(android.webkit.WebResourceRequest) Toast(android.widget.Toast) Menu(android.view.Menu) Connection(com.ichi2.async.Connection) Response(okhttp3.Response) Call(okhttp3.Call) CardAppearance(com.ichi2.anki.cardviewer.CardAppearance) WebChromeClient(android.webkit.WebChromeClient) LinkedHashSet(java.util.LinkedHashSet) PRINT(com.ichi2.bd.MainHandlerConstant.PRINT) CheckResult(androidx.annotation.CheckResult) MissingImageHandler(com.ichi2.anki.cardviewer.MissingImageHandler) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) IOException(java.io.IOException) SoundSide(com.ichi2.libanki.Sound.SoundSide) File(java.io.File) Gravity(android.view.Gravity) Lock(java.util.concurrent.locks.Lock) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) FileUtil(com.ichi2.utils.FileUtil) Configuration(android.content.res.Configuration) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) EditText(android.widget.EditText) SpeechSynthesizerListener(com.baidu.tts.client.SpeechSynthesizerListener) ImageButton(android.widget.ImageButton) REQUEST_CODE_SPEAK_SETTING(com.ichi2.anki.SpeakSettingActivity.REQUEST_CODE_SPEAK_SETTING) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) HtmlColors(com.ichi2.themes.HtmlColors) GestureDetectorCompat(androidx.core.view.GestureDetectorCompat) WindowManager(android.view.WindowManager) NonBlockSyntherizer(com.ichi2.bd.NonBlockSyntherizer) FormBody(okhttp3.FormBody) ByteArrayInputStream(java.io.ByteArrayInputStream) ViewerCommand(com.ichi2.anki.cardviewer.ViewerCommand) Gson(com.google.gson.Gson) Locale(java.util.Locale) WebViewClient(android.webkit.WebViewClient) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) WebView(android.webkit.WebView) InitConfig(com.ichi2.bd.InitConfig) Auth(com.ichi2.bd.Auth) SimpleOnGestureListener(android.view.GestureDetector.SimpleOnGestureListener) SynthesizerTool(com.baidu.tts.client.SynthesizerTool) BroadcastReceiver(android.content.BroadcastReceiver) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) IOfflineResourceConst(com.ichi2.bd.IOfflineResourceConst) MySyntherizer(com.ichi2.bd.MySyntherizer) List(java.util.List) TextView(android.widget.TextView) ActivityNotFoundException(android.content.ActivityNotFoundException) SpeechSynthesizer(com.baidu.tts.client.SpeechSynthesizer) KEY_SELECT_ONLINE_SPEAK_ENGINE(com.ichi2.libanki.Consts.KEY_SELECT_ONLINE_SPEAK_ENGINE) Toolbar(androidx.appcompat.widget.Toolbar) RelativeLayout(android.widget.RelativeLayout) THEME_NIGHT_DARK(com.ichi2.themes.Themes.THEME_NIGHT_DARK) OfflineResource(com.ichi2.bd.OfflineResource) AudioView(com.ichi2.anki.multimediacard.AudioView) Pattern(java.util.regex.Pattern) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) EditorInfo(android.view.inputmethod.EditorInfo) Snackbar(com.google.android.material.snackbar.Snackbar) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KEY_SHOW_TTS_ICON(com.ichi2.libanki.Consts.KEY_SHOW_TTS_ICON) Note(com.ichi2.libanki.Note) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) UI_CHANGE_SYNTHES_TEXT_SELECTION(com.ichi2.bd.MainHandlerConstant.UI_CHANGE_SYNTHES_TEXT_SELECTION) KeyEvent(android.view.KeyEvent) Pair(android.util.Pair) Intent(android.content.Intent) ReviewerCustomFonts(com.ichi2.anki.reviewer.ReviewerCustomFonts) HashMap(java.util.HashMap) REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML(com.ichi2.anki.DeckPicker.REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML) Collection(com.ichi2.libanki.Collection) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) RequestBody(okhttp3.RequestBody) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) HashSet(java.util.HashSet) ConnectivityManagerCompat(androidx.core.net.ConnectivityManagerCompat) SuppressLint(android.annotation.SuppressLint) JSONArray(com.ichi2.utils.JSONArray) MotionEvent(android.view.MotionEvent) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) LinkedList(java.util.LinkedList) Sound(com.ichi2.libanki.Sound) Utils(com.ichi2.libanki.Utils) LoggerProxy(com.baidu.tts.chainofresponsibility.logger.LoggerProxy) Consumer(com.ichi2.utils.FunctionalInterfaces.Consumer) Function(com.ichi2.utils.FunctionalInterfaces.Function) UI_CHANGE_INPUT_TEXT_SELECTION(com.ichi2.bd.MainHandlerConstant.UI_CHANGE_INPUT_TEXT_SELECTION) FlagDef(com.ichi2.anki.reviewer.CardMarker.FlagDef) LayoutInflater(android.view.LayoutInflater) ReviewerUi(com.ichi2.anki.reviewer.ReviewerUi) CollectionTask(com.ichi2.async.CollectionTask) Chronometer(android.widget.Chronometer) Themes(com.ichi2.themes.Themes) Template(com.ichi2.libanki.template.Template) Color(android.graphics.Color) WebResourceError(android.webkit.WebResourceError) UI_PLAY_START(com.ichi2.bd.MainHandlerConstant.UI_PLAY_START) AdaptionUtil(com.ichi2.utils.AdaptionUtil) Card(com.ichi2.libanki.Card) Activity(android.app.Activity) VisibleForTesting(androidx.annotation.VisibleForTesting) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) OnClickListener(android.view.View.OnClickListener) Note(com.ichi2.libanki.Note) ArrayList(java.util.ArrayList) TagsDialog(com.ichi2.anki.dialogs.TagsDialog)

Example 2 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project AnkiChinaAndroid by ankichinateam.

the class ContentProviderTest method testUpdateTags.

/**
 * Update tags on a note
 */
@Test
public void testUpdateTags() {
    // get the first card due
    // ----------------------
    Collection col = getCol();
    Card card = getFirstCardFromScheduler(col);
    Note note = card.note();
    long noteId = note.getId();
    // make sure the tag is what we expect initially
    // ---------------------------------------------
    List<String> tagList = note.getTags();
    assertEquals("only one tag", 1, tagList.size());
    assertEquals("check tag value", TEST_TAG, tagList.get(0));
    // update tags
    // -----------
    String tag2 = "mynewtag";
    ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext().getContentResolver();
    Uri updateNoteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId));
    ContentValues values = new ContentValues();
    values.put(FlashCardsContract.Note.TAGS, TEST_TAG + " " + tag2);
    int updateCount = cr.update(updateNoteUri, values, null, null);
    assertEquals("updateCount is 1", 1, updateCount);
    // lookup the note now and verify tags
    // -----------------------------------
    Note noteAfterUpdate = col.getNote(noteId);
    List<String> newTagList = noteAfterUpdate.getTags();
    assertEquals("two tags", 2, newTagList.size());
    assertEquals("check first tag", TEST_TAG, newTagList.get(0));
    assertEquals("check second tag", tag2, newTagList.get(1));
}
Also used : ContentValues(android.content.ContentValues) Note(com.ichi2.libanki.Note) Collection(com.ichi2.libanki.Collection) Uri(android.net.Uri) Card(com.ichi2.libanki.Card) ContentResolver(android.content.ContentResolver) Test(org.junit.Test)

Example 3 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project AnkiChinaAndroid by ankichinateam.

the class ImportTest method testCsv.

@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
public void testCsv() throws IOException {
    String file = Shared.getTestFilePath(InstrumentationRegistry.getInstrumentation().getTargetContext(), "text-2fields.txt");
    TextImporter i = new TextImporter(testCol, file);
    i.initMapping();
    i.run();
    if (TestEnvironment.isDisplayingDefaultEnglishStrings()) {
        assertThat(i.getLog(), contains("‘多すぎる too many fields’ had 3 fields, expected 2", "‘not, enough, fields’ had 1 fields, expected 2", "Appeared twice in file: 飲む", "Empty first field:  to play", "5 notes added, 0 notes updated, 0 notes unchanged."));
    } else {
        assertThat(i.getLog(), hasSize(5));
    }
    assertEquals(5, i.getTotal());
    // if we run the import again, it should update instead
    i.run();
    if (TestEnvironment.isDisplayingDefaultEnglishStrings()) {
        assertThat(i.getLog(), contains("‘多すぎる too many fields’ had 3 fields, expected 2", "‘not, enough, fields’ had 1 fields, expected 2", "Appeared twice in file: 飲む", "Empty first field:  to play", "0 notes added, 0 notes updated, 5 notes unchanged.", "First field matched: 食べる", "First field matched: 飲む", "First field matched: テスト", "First field matched: to eat", "First field matched: 遊ぶ"));
    } else {
        assertThat(i.getLog(), hasSize(10));
    }
    assertEquals(5, i.getTotal());
    // but importing should not clobber tags if they're unmapped
    Note n = testCol.getNote(testCol.getDb().queryLongScalar("select id from notes"));
    n.addTag("test");
    n.flush();
    i.run();
    n.load();
    assertThat(n.getTags(), contains("test"));
    assertThat(n.getTags(), hasSize(1));
    // if add-only mode, count will be 0
    i.setImportMode(NoteImporter.ImportMode.IGNORE_MODE);
    i.run();
    assertEquals(0, i.getTotal());
    // and if dupes mode, will reimport everything
    assertEquals(5, testCol.cardCount());
    i.setImportMode(NoteImporter.ImportMode.ADD_MODE);
    i.run();
    // includes repeated field
    assertEquals(6, i.getTotal());
    assertEquals(11, testCol.cardCount());
}
Also used : Note(com.ichi2.libanki.Note) TextImporter(com.ichi2.libanki.importer.TextImporter) Test(org.junit.Test) SdkSuppress(androidx.test.filters.SdkSuppress)

Example 4 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project AnkiChinaAndroid by ankichinateam.

the class NoteEditor method showTagsDialog.

private void showTagsDialog() {
    if (mSelectedTags == null) {
        mSelectedTags = new ArrayList<>(0);
    }
    ArrayList<String> tags = new ArrayList<>(getCol().getTags().all());
    ArrayList<String> selTags = new ArrayList<>(mSelectedTags);
    TagsDialog.TagsDialogListener tagsDialogListener = (selectedTags, option) -> {
        if (!mSelectedTags.equals(selectedTags)) {
            mTagsEdited = true;
        }
        mSelectedTags = selectedTags;
        updateTags();
    };
    TagsDialog dialog = TagsDialog.newInstance(TagsDialog.TYPE_ADD_TAG, selTags, tags);
    dialog.setTagsDialogListener(tagsDialogListener);
    showDialogFragment(dialog);
}
Also used : Arrays(java.util.Arrays) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) Drawable(android.graphics.drawable.Drawable) AudioRecordingField(com.ichi2.anki.multimediacard.fields.AudioRecordingField) Map(java.util.Map) ClipboardManager(android.content.ClipboardManager) ContextCompat(androidx.core.content.ContextCompat) TargetApi(android.annotation.TargetApi) FieldChangeType(com.ichi2.anki.noteeditor.FieldState.FieldChangeType) IntentFilter(android.content.IntentFilter) IField(com.ichi2.anki.multimediacard.fields.IField) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) PopupMenuWithIcons(com.ichi2.anki.widgets.PopupMenuWithIcons) StringRes(androidx.annotation.StringRes) Nullable(androidx.annotation.Nullable) Consts(com.ichi2.libanki.Consts) CompatHelper(com.ichi2.compat.CompatHelper) DiscardChangesDialog(com.ichi2.anki.dialogs.DiscardChangesDialog) Models(com.ichi2.libanki.Models) TextWatcher(android.text.TextWatcher) DialogFragment(androidx.fragment.app.DialogFragment) ClozeUtils(com.ichi2.libanki.Note.ClozeUtils) KeyUtils(com.ichi2.utils.KeyUtils) Direction(com.ichi2.anim.ActivityTransitionAnimation.Direction) IMultimediaEditableNote(com.ichi2.anki.multimediacard.IMultimediaEditableNote) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) Editable(android.text.Editable) ImageField(com.ichi2.anki.multimediacard.fields.ImageField) ArrayList(java.util.ArrayList) NOT_FOUND_NOTE_TYPE(com.ichi2.libanki.Models.NOT_FOUND_NOTE_TYPE) MenuInflater(android.view.MenuInflater) Menu(android.view.Menu) IntegerDialog(com.ichi2.anki.dialogs.IntegerDialog) CheckResult(androidx.annotation.CheckResult) ContentResolverUtil(com.ichi2.utils.ContentResolverUtil) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Toolbar(com.ichi2.anki.noteeditor.Toolbar) CustomToolbarButton(com.ichi2.anki.noteeditor.CustomToolbarButton) File(java.io.File) TextViewUtil(com.ichi2.utils.TextViewUtil) ArrayAdapter(android.widget.ArrayAdapter) SharedPreferences(android.content.SharedPreferences) FileUtil(com.ichi2.utils.FileUtil) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) EditText(android.widget.EditText) RequiresApi(androidx.annotation.RequiresApi) ImageButton(android.widget.ImageButton) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) MultimediaEditFieldActivity(com.ichi2.anki.multimediacard.activity.MultimediaEditFieldActivity) WindowManager(android.view.WindowManager) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) Locale(java.util.Locale) EFieldType(com.ichi2.anki.multimediacard.fields.EFieldType) View(android.view.View) TaskData(com.ichi2.async.TaskData) AdapterView(android.widget.AdapterView) MultimediaEditableNote(com.ichi2.anki.multimediacard.impl.MultimediaEditableNote) LocaleSelectionDialog(com.ichi2.anki.dialogs.LocaleSelectionDialog) EXTRA_PROCESS_TEXT(com.ichi2.compat.Compat.EXTRA_PROCESS_TEXT) BroadcastReceiver(android.content.BroadcastReceiver) FieldState(com.ichi2.anki.noteeditor.FieldState) Timber(timber.log.Timber) TextField(com.ichi2.anki.multimediacard.fields.TextField) List(java.util.List) TextView(android.widget.TextView) OnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Typeface(android.graphics.Typeface) Note(com.ichi2.libanki.Note) Context(android.content.Context) KeyEvent(android.view.KeyEvent) AudioClipField(com.ichi2.anki.multimediacard.fields.AudioClipField) Pair(android.util.Pair) NamedJSONComparator(com.ichi2.utils.NamedJSONComparator) Intent(android.content.Intent) HashMap(java.util.HashMap) Collection(com.ichi2.libanki.Collection) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) MapUtil(com.ichi2.utils.MapUtil) HashSet(java.util.HashSet) SuppressLint(android.annotation.SuppressLint) JSONArray(com.ichi2.utils.JSONArray) WidgetStatus(com.ichi2.widget.WidgetStatus) Model(com.ichi2.libanki.Model) Build(android.os.Build) LinkedList(java.util.LinkedList) DeckComparator(com.ichi2.utils.DeckComparator) Utils(com.ichi2.libanki.Utils) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) NoteService(com.ichi2.anki.servicelayer.NoteService) Consumer(com.ichi2.utils.FunctionalInterfaces.Consumer) CollectionTask(com.ichi2.async.CollectionTask) Themes(com.ichi2.themes.Themes) Spinner(android.widget.Spinner) PopupMenu(androidx.appcompat.widget.PopupMenu) ACTION_PROCESS_TEXT(com.ichi2.compat.Compat.ACTION_PROCESS_TEXT) ADD_NOTE(com.ichi2.async.CollectionTask.TASK_TYPE.ADD_NOTE) AdaptionUtil(com.ichi2.utils.AdaptionUtil) Card(com.ichi2.libanki.Card) VisibleForTesting(androidx.annotation.VisibleForTesting) Collections(java.util.Collections) NoteFieldDecorator(com.ichi2.utils.NoteFieldDecorator) Resources(android.content.res.Resources) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) TagsDialog(com.ichi2.anki.dialogs.TagsDialog)

Example 5 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project AnkiChinaAndroid by ankichinateam.

the class NoteEditor method saveNote.

@VisibleForTesting
void saveNote() {
    final Resources res = getResources();
    if (mSelectedTags == null) {
        mSelectedTags = new ArrayList<>(0);
    }
    // treat add new note and edit existing note independently
    if (mAddNote) {
        // DEFECT: This does not block addition if cloze transpositions are in non-cloze fields.
        if (isClozeType() && !hasClozeDeletions()) {
            displayErrorSavingNote();
            return;
        }
        // load all of the fields into the note
        for (FieldEditText f : mEditFields) {
            updateField(f);
        }
        // Save deck to model
        mEditorNote.model().put("did", mCurrentDid);
        // Save tags to model
        mEditorNote.setTagsFromStr(tagsAsString(mSelectedTags));
        JSONArray tags = new JSONArray();
        for (String t : mSelectedTags) {
            tags.put(t);
        }
        getCol().getModels().current().put("tags", tags);
        getCol().getModels().setChanged();
        mReloadRequired = true;
        CollectionTask.launchCollectionTask(ADD_NOTE, saveNoteHandler(), new TaskData(mEditorNote));
    } else {
        // Check whether note type has been changed
        final Model newModel = getCurrentlySelectedModel();
        final Model oldModel = (mCurrentEditedCard == null) ? null : mCurrentEditedCard.model();
        File target = new File(FileUtil.createTmpDir(this), mCurrentEditedCard.getId() + ".wav");
        if (target.exists()) {
            Timber.i("editing card audio is exists,delete it");
            target.delete();
        }
        if (!newModel.equals(oldModel)) {
            mReloadRequired = true;
            if (mModelChangeCardMap.size() < mEditorNote.numberOfCards() || mModelChangeCardMap.containsValue(null)) {
                // If cards will be lost via the new mapping then show a confirmation dialog before proceeding with the change
                ConfirmationDialog dialog = new ConfirmationDialog();
                dialog.setArgs(res.getString(R.string.confirm_map_cards_to_nothing));
                Runnable confirm = () -> {
                    // Bypass the check once the user confirms
                    changeNoteTypeWithErrorHandling(oldModel, newModel);
                };
                dialog.setConfirm(confirm);
                showDialogFragment(dialog);
            } else {
                // Otherwise go straight to changing note type
                changeNoteTypeWithErrorHandling(oldModel, newModel);
            }
            return;
        }
        // Regular changes in note content
        boolean modified = false;
        // changed did? this has to be done first as remFromDyn() involves a direct write to the database
        if (mCurrentEditedCard != null && mCurrentEditedCard.getDid() != mCurrentDid) {
            mReloadRequired = true;
            // remove card from filtered deck first (if relevant)
            getCol().getSched().remFromDyn(new long[] { mCurrentEditedCard.getId() });
            // refresh the card object to reflect the database changes in remFromDyn()
            mCurrentEditedCard.load();
            // also reload the note object
            mEditorNote = mCurrentEditedCard.note();
            // then set the card ID to the new deck
            mCurrentEditedCard.setDid(mCurrentDid);
            modified = true;
        }
        // now load any changes to the fields from the form
        for (FieldEditText f : mEditFields) {
            modified = modified | updateField(f);
        }
        // added tag?
        for (String t : mSelectedTags) {
            modified = modified || !mEditorNote.hasTag(t);
        }
        // removed tag?
        modified = modified || mEditorNote.getTags().size() > mSelectedTags.size();
        if (modified) {
            mEditorNote.setTagsFromStr(tagsAsString(mSelectedTags));
            mChanged = true;
        }
        closeNoteEditor();
    }
}
Also used : JSONArray(com.ichi2.utils.JSONArray) Model(com.ichi2.libanki.Model) Resources(android.content.res.Resources) File(java.io.File) TaskData(com.ichi2.async.TaskData) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) VisibleForTesting(androidx.annotation.VisibleForTesting)

Aggregations

JSONObject (com.ichi2.utils.JSONObject)27 Note (com.ichi2.libanki.Note)18 JSONArray (com.ichi2.utils.JSONArray)18 ArrayList (java.util.ArrayList)13 Card (com.ichi2.libanki.Card)12 Collection (com.ichi2.libanki.Collection)12 Model (com.ichi2.libanki.Model)11 Map (java.util.Map)10 HashMap (java.util.HashMap)9 SuppressLint (android.annotation.SuppressLint)8 Resources (android.content.res.Resources)8 Deck (com.ichi2.libanki.Deck)8 JSONException (com.ichi2.utils.JSONException)8 JSONException (org.json.JSONException)8 Intent (android.content.Intent)7 View (android.view.View)7 TextView (android.widget.TextView)7 Pair (android.util.Pair)5 ContentValues (android.content.ContentValues)4 Uri (android.net.Uri)4