Search in sources :

Example 1 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method answerCard.

protected void answerCard(@Consts.BUTTON_TYPE int ease) {
    if (mInAnswer) {
        return;
    }
    mIsSelecting = false;
    hideLookupButton();
    int buttonNumber = getCol().getSched().answerButtons(mCurrentCard);
    // Detect invalid ease for current card (e.g. by using keyboard shortcut or gesture).
    if (buttonNumber < ease) {
        return;
    }
    // Set the dots appearing below the toolbar
    switch(ease) {
        case EASE_1:
            mChosenAnswer.setText("\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, R.color.material_red_500));
            break;
        case EASE_2:
            mChosenAnswer.setText("\u2022\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, buttonNumber == Consts.BUTTON_FOUR ? R.color.material_blue_grey_600 : R.color.material_green_500));
            break;
        case EASE_3:
            mChosenAnswer.setText("\u2022\u2022\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, buttonNumber == Consts.BUTTON_FOUR ? R.color.material_green_500 : R.color.material_light_blue_500));
            break;
        case EASE_4:
            mChosenAnswer.setText("\u2022\u2022\u2022\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, R.color.material_light_blue_500));
            break;
        default:
            Timber.w("Unknown easy type %s", ease);
            break;
    }
    // remove chosen answer hint after a while
    mTimerHandler.removeCallbacks(removeChosenAnswerText);
    mTimerHandler.postDelayed(removeChosenAnswerText, mShowChosenAnswerLength);
    mSoundPlayer.stopSounds();
    stopOnlineSpeaking();
    mCurrentEase = ease;
    CollectionTask.launchCollectionTask(ANSWER_CARD, mAnswerCardHandler(true), new TaskData(mCurrentCard, mCurrentEase));
}
Also used : SuppressLint(android.annotation.SuppressLint) TaskData(com.ichi2.async.TaskData)

Example 2 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method dismiss.

protected void dismiss(Collection.DismissType type) {
    blockControls(false);
    CollectionTask.launchCollectionTask(DISMISS, mDismissCardHandler, new TaskData(new Object[] { mCurrentCard, type }));
}
Also used : JSONObject(com.ichi2.utils.JSONObject) TaskData(com.ichi2.async.TaskData)

Example 3 with TaskData

use of com.ichi2.async.TaskData 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)

Example 4 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class AnkiActivity method exportApkg.

@Override
public void exportApkg(String filename, Long did, boolean includeSched, boolean includeMedia, boolean exportCard, boolean exportApkg) {
    File exportDir = new File(getExternalCacheDir(), "export");
    exportDir.mkdirs();
    File exportPath;
    String timeStampSuffix = "-" + TimeUtils.getTimestamp(getCol().getTime());
    if (filename != null) {
        // filename has been explicitly specified
        exportPath = new File(exportDir, filename);
    } else if (did != null) {
        // filename not explicitly specified, but a deck has been specified so use deck name
        exportPath = new File(exportDir, getCol().getDecks().get(did).getString("name").replaceAll("\\W+", "_") + timeStampSuffix + ".apkg");
    } else if (!includeSched) {
        // full export without scheduling is assumed to be shared with someone else -- use "All Decks.apkg"
        exportPath = new File(exportDir, "All Decks" + timeStampSuffix + ".apkg");
    } else {
        // full collection export -- use "collection.colpkg"
        File colPath = new File(getCol().getPath());
        String newFileName = colPath.getName().replace(".anki2", timeStampSuffix + ".colpkg");
        exportPath = new File(exportDir, newFileName);
    }
    // add input arguments to new generic structure
    Object[] inputArgs = new Object[7];
    inputArgs[0] = getCol();
    inputArgs[1] = exportPath.getPath();
    inputArgs[2] = did;
    inputArgs[3] = includeSched;
    inputArgs[4] = includeMedia;
    inputArgs[5] = exportApkg;
    inputArgs[6] = exportCard;
    try {
        CollectionTask.launchCollectionTask(EXPORT_APKG, exportListener(), new TaskData(inputArgs));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : JSONObject(com.ichi2.utils.JSONObject) File(java.io.File) JSONException(com.ichi2.utils.JSONException) IOException(java.io.IOException) ActivityNotFoundException(android.content.ActivityNotFoundException) DeckRenameException(com.ichi2.anki.exception.DeckRenameException) TaskData(com.ichi2.async.TaskData)

Example 5 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class ModelFieldEditor method addFieldDialog.

// ----------------------------------------------------------------------------
// CONTEXT MENU DIALOGUES
// ----------------------------------------------------------------------------
/*
    * Creates a dialog to create a field
    */
private void addFieldDialog() {
    mFieldNameInput = new EditText(this);
    mFieldNameInput.setSingleLine(true);
    new MaterialDialog.Builder(this).title(R.string.model_field_editor_add).positiveText(R.string.dialog_ok).customView(mFieldNameInput, true).onPositive((dialog, which) -> {
        String fieldName = mFieldNameInput.getText().toString().replaceAll("[\\n\\r]", "");
        if (fieldName.length() == 0) {
            UIUtils.showThemedToast(this, getResources().getString(R.string.toast_empty_name), true);
        } else if (containsField(fieldName)) {
            UIUtils.showThemedToast(this, getResources().getString(R.string.toast_duplicate_field), true);
        } else {
            // Name is valid, now field is added
            changeHandler listener = changeFieldHandler();
            try {
                mCol.modSchema();
                CollectionTask.launchCollectionTask(ADD_FIELD, listener, new TaskData(new Object[] { mMod, fieldName }));
            } catch (ConfirmModSchemaException e) {
                // Create dialogue to for schema change
                ConfirmationDialog c = new ConfirmationDialog();
                c.setArgs(getResources().getString(R.string.full_sync_confirmation));
                Runnable confirm = () -> {
                    mCol.modSchemaNoCheck();
                    String fieldName1 = mFieldNameInput.getText().toString().replaceAll("[\\n\\r]", "");
                    CollectionTask.launchCollectionTask(ADD_FIELD, listener, new TaskData(new Object[] { mMod, fieldName1 }));
                    dismissContextMenu();
                };
                c.setConfirm(confirm);
                c.setCancel(mConfirmDialogCancel);
                ModelFieldEditor.this.showDialogFragment(c);
            }
            mCol.getModels().update(mMod);
            fullRefreshList();
        }
    }).negativeText(R.string.dialog_cancel).show();
}
Also used : EditText(android.widget.EditText) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) TaskData(com.ichi2.async.TaskData) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog)

Aggregations

Collection (com.ichi2.libanki.Collection)67 TaskData (com.ichi2.async.TaskData)46 JSONObject (com.ichi2.utils.JSONObject)35 Card (com.ichi2.libanki.Card)16 JSONException (com.ichi2.utils.JSONException)15 ArrayList (java.util.ArrayList)14 JSONObject (org.json.JSONObject)13 Resources (android.content.res.Resources)12 HashMap (java.util.HashMap)12 SharedPreferences (android.content.SharedPreferences)11 Deck (com.ichi2.libanki.Deck)11 Intent (android.content.Intent)10 View (android.view.View)9 TextView (android.widget.TextView)9 ConfirmationDialog (com.ichi2.anki.dialogs.ConfirmationDialog)9 TaskListener (com.ichi2.async.TaskListener)9 Map (java.util.Map)9 VisibleForTesting (androidx.annotation.VisibleForTesting)8 CollectionTask (com.ichi2.async.CollectionTask)8 IOException (java.io.IOException)8