Search in sources :

Example 36 with Time

use of com.ichi2.libanki.utils.Time in project Anki-Android by Ramblurr.

the class StudyOptionsFragment method updateValuesFromDeck.

private void updateValuesFromDeck(boolean reset) {
    String fullName;
    if (!AnkiDroidApp.colIsOpen()) {
        return;
    }
    JSONObject deck = AnkiDroidApp.getCol().getDecks().current();
    try {
        fullName = deck.getString("name");
        String[] name = fullName.split("::");
        StringBuilder nameBuilder = new StringBuilder();
        if (name.length > 0) {
            nameBuilder.append(name[0]);
        }
        if (name.length > 1) {
            nameBuilder.append("\n").append(name[1]);
        }
        if (name.length > 3) {
            nameBuilder.append("...");
        }
        if (name.length > 2) {
            nameBuilder.append("\n").append(name[name.length - 1]);
        }
        mTextDeckName.setText(nameBuilder.toString());
        // open cram deck option if deck is opened for the first time
        if (mCramInitialConfig != null) {
            openCramDeckOptions(mCramInitialConfig);
            return;
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (!mFragmented) {
        getActivity().setTitle(fullName);
    }
    String desc;
    try {
        if (deck.getInt("dyn") == 0) {
            desc = AnkiDroidApp.getCol().getDecks().getActualDescription();
            mTextDeckDescription.setMaxLines(3);
        } else {
            desc = getResources().getString(R.string.dyn_deck_desc);
            mTextDeckDescription.setMaxLines(5);
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (desc.length() > 0) {
        mTextDeckDescription.setText(Html.fromHtml(desc));
        mTextDeckDescription.setVisibility(View.VISIBLE);
    } else {
        mTextDeckDescription.setVisibility(View.GONE);
    }
    DeckTask.launchDeckTask(DeckTask.TASK_TYPE_UPDATE_VALUES_FROM_DECK, mUpdateValuesFromDeckListener, new DeckTask.TaskData(AnkiDroidApp.getCol(), new Object[] { reset, mSmallChart != null }));
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) TaskData(com.ichi2.async.DeckTask.TaskData) DeckTask(com.ichi2.async.DeckTask)

Example 37 with Time

use of com.ichi2.libanki.utils.Time in project Anki-Android by Ramblurr.

the class CustomFontsReviewerExt method getCustomFontsMap.

/**
     * Returns a map from custom fonts names to the corresponding {@link AnkiFont} object.
     *
     * <p>The list of constructed lazily the first time is needed.
     */
private static Map<String, AnkiFont> getCustomFontsMap(Context context) {
    List<AnkiFont> fonts = Utils.getCustomFonts(context);
    Map<String, AnkiFont> customFontsMap = new HashMap<String, AnkiFont>();
    for (AnkiFont f : fonts) {
        customFontsMap.put(f.getName(), f);
    }
    return customFontsMap;
}
Also used : AnkiFont(com.ichi2.anki.AnkiFont) HashMap(java.util.HashMap)

Example 38 with Time

use of com.ichi2.libanki.utils.Time in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundLoadTutorial.

private TaskData doInBackgroundLoadTutorial(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundLoadTutorial");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = params[0].getCollection();
    col.getDb().getDatabase().beginTransaction();
    String title = res.getString(R.string.help_tutorial);
    try {
        // get deck or create it
        long did = col.getDecks().id(title);
        // reset todays counts
        JSONObject d = col.getDecks().get(did);
        for (String t : new String[] { "new", "rev", "lrn", "time" }) {
            String k = t + "Today";
            JSONArray ja = new JSONArray();
            ja.put(col.getSched().getToday());
            ja.put(0);
            d.put(k, ja);
        }
        // save deck
        col.getDecks().save(d);
        if (col.getSched().cardCount("(" + did + ")") > 0) {
            // deck does already exist. Remove all cards and recreate them
            // to ensure the correct order
            col.remCards(col.getDecks().cids(did));
        }
        JSONObject model = col.getModels().byName(title);
        // }
        if (model == null) {
            model = col.getModels().addBasicModel(col, title);
        }
        model.put("did", did);
        String[] questions = res.getStringArray(R.array.tutorial_questions);
        String[] answers = res.getStringArray(R.array.tutorial_answers);
        String[] sampleQuestions = res.getStringArray(R.array.tutorial_capitals_questions);
        String[] sampleAnswers = res.getStringArray(R.array.tutorial_capitals_answers);
        int len = Math.min(questions.length, answers.length);
        for (int i = 0; i < len + Math.min(sampleQuestions.length, sampleAnswers.length); i++) {
            Note note = col.newNote(model);
            if (note.values().length < 2) {
                return new TaskData(false);
            }
            note.values()[0] = (i < len) ? questions[i] : sampleQuestions[i - len];
            note.values()[1] = (i < len) ? answers[i] : sampleAnswers[i - len];
            col.addNote(note);
        }
        // deck.setSessionTimeLimit(0);
        if (col.getSched().cardCount("(" + did + ")") == 0) {
            // error, delete deck
            col.getDecks().rem(did, true);
            return new TaskData(false);
        } else {
            col.save();
            col.getDecks().select(did);
            col.getDb().getDatabase().setTransactionSuccessful();
            return new TaskData(true);
        }
    } catch (SQLException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial");
        return new DeckTask.TaskData(false);
    } catch (JSONException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial");
        return new DeckTask.TaskData(false);
    } finally {
        col.getDb().getDatabase().endTransaction();
    }
}
Also used : SQLException(android.database.SQLException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Note(com.ichi2.libanki.Note) Collection(com.ichi2.libanki.Collection) Resources(android.content.res.Resources)

Example 39 with Time

use of com.ichi2.libanki.utils.Time in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundOpenCollection.

private TaskData doInBackgroundOpenCollection(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection");
    long time = Utils.intNow(1000);
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    String collectionFile = params[0].getString();
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext());
    // see, if a collection is still opened
    Collection oldCol = AnkiDroidApp.getCol();
    Collection col = null;
    publishProgress(new TaskData(res.getString(R.string.open_collection)));
    if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) {
        // android's delete db bug
        if (BackupManager.safetyBackupNeeded(collectionFile)) {
            publishProgress(new TaskData(res.getString(R.string.backup_collection)));
            BackupManager.performBackup(collectionFile);
        }
        publishProgress(new TaskData(res.getString(R.string.open_collection)));
        // load collection
        try {
            col = AnkiDroidApp.openCollection(collectionFile);
        } catch (RuntimeException e) {
            BackupManager.restoreCollectionIfMissing(collectionFile);
            Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e);
            AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection");
            return new TaskData(false);
        }
        // create tutorial deck if needed
        if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) {
            prefs.edit().remove("createTutorial").commit();
            publishProgress(new TaskData(res.getString(R.string.tutorial_load)));
            doInBackgroundLoadTutorial(new TaskData(col));
        }
    } else {
        // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it");
        col = oldCol;
    }
    Object[] counts = null;
    DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
    if (result != null) {
        counts = result.getObjArray();
    }
    if (prefs.getBoolean("splashScreen", false)) {
        long millies = Utils.intNow(1000) - time;
        if (millies < 1000) {
            try {
                Thread.sleep(1200 - millies);
            } catch (InterruptedException e) {
            }
        }
    }
    return new TaskData(col, counts);
}
Also used : SharedPreferences(android.content.SharedPreferences) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) Resources(android.content.res.Resources)

Example 40 with Time

use of com.ichi2.libanki.utils.Time in project Anki-Android by Ramblurr.

the class Media method _changes.

private Pair<List<String>, List<String>> _changes() {
    Map<String, Pair<String, Long>> cache = new HashMap<String, Pair<String, Long>>();
    Map<String, Boolean> used = new HashMap<String, Boolean>();
    Cursor cur = null;
    try {
        cur = mMediaDb.getDatabase().query("media", new String[] { "fname", "csum", "mod" }, null, null, null, null, null);
        while (cur.moveToNext()) {
            cache.put(cur.getString(0), new Pair<String, Long>(cur.getString(1), cur.getLong(1)));
            used.put(cur.getString(0), false);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    List<String> added = new ArrayList<String>();
    List<String> removed = new ArrayList<String>();
    File mediaDir = new File(getDir());
    for (File f : mediaDir.listFiles()) {
        // ignore folders and thumbs.db
        if (f.isDirectory()) {
            continue;
        }
        String fname = f.getName();
        if (fname.compareTo("thumbs.db") == 0) {
            continue;
        }
        // and files with invalid chars
        boolean bad = false;
        for (String c : new String[] { "\0", "/", "\\", ":" }) {
            if (fname.contains(c)) {
                bad = true;
                break;
            }
        }
        if (bad) {
            continue;
        }
        // empty files are invalid; clean them up and continue
        if (f.length() == 0) {
            f.delete();
            continue;
        }
        // newly added?
        if (!cache.containsKey(fname)) {
            added.add(fname);
        } else {
            // modified since last time?
            if ((f.lastModified() / 1000) != cache.get(fname).second) {
                // and has different checksum?
                if (_checksum(f.getAbsolutePath()).compareTo(cache.get(fname).first) != 0) {
                    added.add(fname);
                }
            }
            // mark as used
            used.put(fname, true);
        }
    }
    // look for any entries in the cache that no longer exist on disk
    for (String fname : used.keySet()) {
        if (!used.get(fname)) {
            removed.add(fname);
        }
    }
    return new Pair<List<String>, List<String>>(added, removed);
}
Also used : HashMap(java.util.HashMap) SQLException(android.database.SQLException) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) ZipFile(java.util.zip.ZipFile) File(java.io.File) Pair(com.ichi2.anki.Pair)

Aggregations

Test (org.junit.Test)27 Collection (com.ichi2.libanki.Collection)26 JSONObject (com.ichi2.utils.JSONObject)26 RobolectricTest (com.ichi2.anki.RobolectricTest)19 Card (com.ichi2.libanki.Card)19 Note (com.ichi2.libanki.Note)15 JSONArray (com.ichi2.utils.JSONArray)15 Deck (com.ichi2.libanki.Deck)11 ArrayList (java.util.ArrayList)11 DeckConfig (com.ichi2.libanki.DeckConfig)10 IOException (java.io.IOException)10 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)9 HashMap (java.util.HashMap)9 Cursor (android.database.Cursor)8 Nullable (androidx.annotation.Nullable)8 JSONException (com.ichi2.utils.JSONException)8 SharedPreferences (android.content.SharedPreferences)7 Resources (android.content.res.Resources)7 File (java.io.File)7 View (android.view.View)5