Search in sources :

Example 31 with TaskData

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

the class CollectionTask method doInBackGroundFindEmptyCards.

public TaskData doInBackGroundFindEmptyCards(TaskData param) {
    Collection col = getCol();
    List<Long> cids = col.emptyCids();
    return new TaskData(new Object[] { cids });
}
Also used : Collection(com.ichi2.libanki.Collection)

Example 32 with TaskData

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

the class CollectionTask method doInBackgroundConfChange.

private TaskData doInBackgroundConfChange(TaskData param) {
    Timber.d("doInBackgroundConfChange");
    Collection col = getCol();
    Object[] data = param.getObjArray();
    Deck deck = (Deck) data[0];
    DeckConfig conf = (DeckConfig) data[1];
    try {
        long newConfId = conf.getLong("id");
        // If new config has a different sorting order, reorder the cards
        int oldOrder = col.getDecks().getConf(deck.getLong("conf")).getJSONObject("new").getInt("order");
        int newOrder = col.getDecks().getConf(newConfId).getJSONObject("new").getInt("order");
        if (oldOrder != newOrder) {
            switch(newOrder) {
                case 0:
                    col.getSched().randomizeCards(deck.getLong("id"));
                    break;
                case 1:
                    col.getSched().orderCards(deck.getLong("id"));
                    break;
            }
        }
        col.getDecks().setConf(deck, newConfId);
        col.save();
        return new TaskData(true);
    } catch (JSONException e) {
        return new TaskData(false);
    }
}
Also used : Collection(com.ichi2.libanki.Collection) Deck(com.ichi2.libanki.Deck) JSONException(com.ichi2.utils.JSONException) JSONObject(com.ichi2.utils.JSONObject) DeckConfig(com.ichi2.libanki.DeckConfig)

Example 33 with TaskData

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

the class CollectionTask method doInBackgroundSaveModel.

/**
 * Handles everything for a model change at once - template add / deletes as well as content updates
 */
private TaskData doInBackgroundSaveModel(TaskData param) {
    Timber.d("doInBackgroundSaveModel");
    Collection col = getCol();
    Object[] args = param.getObjArray();
    Model model = (Model) args[0];
    ArrayList<Object[]> templateChanges = (ArrayList<Object[]>) args[1];
    Model oldModel = col.getModels().get(model.getLong("id"));
    // TODO need to save all the cards that will go away, for undo
    // (do I need to remove them from graves during undo also?)
    // - undo (except for cards) could just be Models.update(model) / Models.flush() / Collection.reset() (that was prior "undo")
    JSONArray newTemplates = model.getJSONArray("tmpls");
    col.getDb().getDatabase().beginTransaction();
    try {
        for (Object[] change : templateChanges) {
            JSONArray oldTemplates = oldModel.getJSONArray("tmpls");
            switch((TemporaryModel.ChangeType) change[1]) {
                case ADD:
                    Timber.d("doInBackgroundSaveModel() adding template %s", change[0]);
                    try {
                        col.getModels().addTemplate(oldModel, newTemplates.getJSONObject((int) change[0]));
                    } catch (Exception e) {
                        Timber.e(e, "Unable to add template %s to model %s", change[0], model.getLong("id"));
                        return new TaskData(e.getLocalizedMessage(), false);
                    }
                    break;
                case DELETE:
                    Timber.d("doInBackgroundSaveModel() deleting template currently at ordinal %s", change[0]);
                    try {
                        col.getModels().remTemplate(oldModel, oldTemplates.getJSONObject((int) change[0]));
                    } catch (Exception e) {
                        Timber.e(e, "Unable to delete template %s from model %s", change[0], model.getLong("id"));
                        return new TaskData(e.getLocalizedMessage(), false);
                    }
                    break;
                default:
                    Timber.w("Unknown change type? %s", change[1]);
                    break;
            }
        }
        col.getModels().save(model, true);
        col.getModels().update(model);
        col.reset();
        col.save();
        if (col.getDb().getDatabase().inTransaction()) {
            col.getDb().getDatabase().setTransactionSuccessful();
        } else {
            Timber.i("CollectionTask::SaveModel was not in a transaction? Cannot mark transaction successful.");
        }
    } finally {
        if (col.getDb().getDatabase().inTransaction()) {
            col.getDb().getDatabase().endTransaction();
        } else {
            Timber.i("CollectionTask::SaveModel was not in a transaction? Cannot end transaction.");
        }
    }
    return new TaskData(true);
}
Also used : Model(com.ichi2.libanki.Model) TemporaryModel(com.ichi2.anki.TemporaryModel) ArrayList(java.util.ArrayList) JSONArray(com.ichi2.utils.JSONArray) Collection(com.ichi2.libanki.Collection) JSONObject(com.ichi2.utils.JSONObject) JSONException(com.ichi2.utils.JSONException) CancellationException(java.util.concurrent.CancellationException) FileNotFoundException(java.io.FileNotFoundException) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) ImportExportException(com.ichi2.anki.exception.ImportExportException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 34 with TaskData

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

the class CollectionTask method doInBackgroundRenderBrowserQA.

private TaskData doInBackgroundRenderBrowserQA(TaskData param) {
    // TODO: Convert this to accept the following to make thread-safe:
    // (Range<Position>, Function<Position, BrowserCard>)
    Timber.d("doInBackgroundRenderBrowserQA");
    Collection col = getCol();
    List<CardBrowser.CardCache> cards = (List<CardBrowser.CardCache>) param.getObjArray()[0];
    Integer startPos = (Integer) param.getObjArray()[1];
    Integer n = (Integer) param.getObjArray()[2];
    int column1Index = (Integer) param.getObjArray()[3];
    int column2Index = (Integer) param.getObjArray()[4];
    List<Long> invalidCardIds = new ArrayList<>();
    // for each specified card in the browser list
    for (int i = startPos; i < startPos + n; i++) {
        // Stop if cancelled
        if (isCancelled()) {
            Timber.d("doInBackgroundRenderBrowserQA was aborted");
            return null;
        }
        if (i < 0 || i >= cards.size()) {
            continue;
        }
        CardBrowser.CardCache card;
        try {
            card = cards.get(i);
        } catch (IndexOutOfBoundsException e) {
            // we won't reach any more cards.
            continue;
        }
        if (card.isLoaded()) {
            // We've already rendered the answer, we don't need to do it again.
            continue;
        }
        // Extract card item
        try {
            // Ensure that card still exists.
            card.getCard();
        } catch (WrongId e) {
            // #5891 - card can be inconsistent between the deck browser screen and the collection.
            // Realistically, we can skip any exception as it's a rendering task which should not kill the
            // process
            long cardId = card.getId();
            Timber.e(e, "Could not process card '%d' - skipping and removing from sight", cardId);
            invalidCardIds.add(cardId);
            continue;
        }
        // Update item
        card.load(false, column1Index, column2Index);
        float progress = (float) i / n * 100;
        publishProgress(new TaskData((int) progress));
    }
    return new TaskData(new Object[] { cards, invalidCardIds });
}
Also used : ArrayList(java.util.ArrayList) CardBrowser(com.ichi2.anki.CardBrowser) Collection(com.ichi2.libanki.Collection) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) WrongId(com.ichi2.libanki.WrongId)

Example 35 with TaskData

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

the class CollectionTask method doInBackgroundUpdateValuesFromDeck.

private TaskData doInBackgroundUpdateValuesFromDeck(TaskData param) {
    Timber.d("doInBackgroundUpdateValuesFromDeck");
    try {
        Collection col = getCol();
        AbstractSched sched = col.getSched();
        Object[] obj = param.getObjArray();
        boolean reset = (Boolean) obj[0];
        if (reset) {
            // reset actually required because of counts, which is used in getCollectionTaskListener
            sched.resetCounts();
        }
        int[] counts = sched.counts();
        int totalNewCount = sched.totalNewForCurrentDeck();
        int totalCount = sched.cardCount();
        return new TaskData(new Object[] { counts[0], counts[1], counts[2], totalNewCount, totalCount, sched.eta(counts) });
    } catch (RuntimeException e) {
        Timber.e(e, "doInBackgroundUpdateValuesFromDeck - an error occurred");
        return null;
    }
}
Also used : AbstractSched(com.ichi2.libanki.sched.AbstractSched) Collection(com.ichi2.libanki.Collection) JSONObject(com.ichi2.utils.JSONObject)

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