Search in sources :

Example 16 with Deck

use of com.ichi2.libanki.Deck 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 17 with Deck

use of com.ichi2.libanki.Deck in project AnkiChinaAndroid by ankichinateam.

the class AnkiDroidApp method onCreate.

/**
 * On application creation.
 */
@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
    if (sInstance != null) {
        Timber.i("onCreate() called multiple times");
        // 5887 - fix crash.
        if (sInstance.getResources() == null) {
            Timber.w("Skipping re-initialisation - no resources. Maybe uninstalling app?");
            return;
        }
    }
    sInstance = this;
    // Get preferences
    SharedPreferences preferences = getSharedPrefs(this);
    Consts.LOGIN_SERVER = preferences.getInt(Consts.KEY_ANKI_ACCOUNT_SERVER, 0);
    // Setup logging and crash reporting
    acraCoreConfigBuilder = new CoreConfigurationBuilder(this);
    if (BuildConfig.DEBUG) {
        // Enable verbose error logging and do method tracing to put the Class name as log tag
        Timber.plant(new DebugTree());
        setDebugACRAConfig(preferences);
    } else {
        Timber.plant(new ProductionCrashReportingTree());
        setProductionACRAConfig(preferences);
    }
    Timber.tag(TAG);
    Timber.d("Startup - Application Start");
    // Analytics falls back to a sensible default if this is not set.
    if (ACRA.isACRASenderServiceProcess() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        try {
            WebViewDebugging.setDataDirectorySuffix("acra");
        } catch (Exception e) {
            Timber.w(e, "Failed to set WebView data directory");
        }
    }
    // analytics after ACRA, they both install UncaughtExceptionHandlers but Analytics chains while ACRA does not
    UsageAnalytics.initialize(this);
    if (BuildConfig.DEBUG) {
        UsageAnalytics.setDryRun(true);
    }
    // Stop after analytics and logging are initialised.
    if (ACRA.isACRASenderServiceProcess()) {
        Timber.d("Skipping AnkiDroidApp.onCreate from ACRA sender process");
        return;
    }
    if (AdaptionUtil.isUserATestClient()) {
        UIUtils.showThemedToast(this.getApplicationContext(), getString(R.string.user_is_a_robot), false);
    }
    CardBrowserContextMenu.ensureConsistentStateWithSharedPreferences(this);
    AnkiCardContextMenu.ensureConsistentStateWithSharedPreferences(this);
    NotificationChannels.setup(getApplicationContext());
    // Configure WebView to allow file scheme pages to access cookies.
    CookieManager.setAcceptFileSchemeCookies(true);
    // Prepare Cookies to be synchronized between RAM and permanent storage.
    CompatHelper.getCompat().prepareWebViewCookies(this.getApplicationContext());
    // Set good default values for swipe detection
    final ViewConfiguration vc = ViewConfiguration.get(this);
    DEFAULT_SWIPE_MIN_DISTANCE = vc.getScaledPagingTouchSlop();
    DEFAULT_SWIPE_THRESHOLD_VELOCITY = vc.getScaledMinimumFlingVelocity();
    // Forget the last deck that was used in the CardBrowser
    CardBrowser.clearLastDeckId();
    // Create the AnkiDroid directory if missing. Send exception report if inaccessible.
    if (Permissions.hasStorageAccessPermission(this)) {
        try {
            String dir = CollectionHelper.getCurrentAnkiDroidDirectory(this);
            CollectionHelper.initializeAnkiDroidDirectory(dir);
        } catch (StorageAccessException e) {
            Timber.e(e, "Could not initialize AnkiDroid directory");
            String defaultDir = CollectionHelper.getDefaultAnkiDroidDirectory();
            if (isSdCardMounted() && CollectionHelper.getCurrentAnkiDroidDirectory(this).equals(defaultDir)) {
                // Don't send report if the user is using a custom directory as SD cards trip up here a lot
                sendExceptionReport(e, "AnkiDroidApp.onCreate");
            }
        }
    }
    Timber.i("AnkiDroidApp: Starting Services");
    new BootService().onReceive(this, new Intent(this, BootService.class));
    // Register BroadcastReceiver NotificationService
    NotificationService ns = new NotificationService();
    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
    lbm.registerReceiver(ns, new IntentFilter(NotificationService.INTENT_ACTION));
}
Also used : IntentFilter(android.content.IntentFilter) SharedPreferences(android.content.SharedPreferences) StorageAccessException(com.ichi2.anki.exception.StorageAccessException) Intent(android.content.Intent) NotificationService(com.ichi2.anki.services.NotificationService) LocalBroadcastManager(androidx.localbroadcastmanager.content.LocalBroadcastManager) ManuallyReportedException(com.ichi2.anki.exception.ManuallyReportedException) StorageAccessException(com.ichi2.anki.exception.StorageAccessException) CoreConfigurationBuilder(org.acra.config.CoreConfigurationBuilder) DebugTree(timber.log.Timber.DebugTree) ViewConfiguration(android.view.ViewConfiguration) BootService(com.ichi2.anki.services.BootService)

Example 18 with Deck

use of com.ichi2.libanki.Deck in project AnkiChinaAndroid by ankichinateam.

the class CardBrowser method deckDropDownItemChanged.

/**
 * Performs changes relating to the Deck DropDown Item changing
 * Exists as mActionBarSpinner.setSelection() caused a loop in roboelectirc (calling onItemSelected())
 */
private void deckDropDownItemChanged(int position) {
    if (position == 0) {
        mRestrictOnDeck = "";
        saveLastDeckId(ALL_DECKS_ID);
    } else {
        Deck deck = mDropDownDecks.get(position - 1);
        mRestrictOnDeck = "deck:\"" + deck.getString("name") + "\" ";
        saveLastDeckId(deck.getLong("id"));
    }
    searchCards();
}
Also used : Deck(com.ichi2.libanki.Deck)

Example 19 with Deck

use of com.ichi2.libanki.Deck in project AnkiChinaAndroid by ankichinateam.

the class CardTemplateEditor method onDeckSelected.

/**
 * When a deck is selected via Deck Override
 */
@Override
public void onDeckSelected(@Nullable SelectableDeck deck) {
    if (Models.isCloze(getTempModel().getModel())) {
        Timber.w("Attempted to set deck for cloze model");
        UIUtils.showThemedToast(this, getString(R.string.model_manager_deck_override_cloze_error), true);
        return;
    }
    int ordinal = mViewPager.getCurrentItem();
    JSONObject template = getTempModel().getTemplate(ordinal);
    String templateName = template.getString("name");
    if (deck != null && Decks.isDynamic(getCol(), deck.getDeckId())) {
        Timber.w("Attempted to set default deck of %s to dynamic deck %s", templateName, deck.getName());
        UIUtils.showThemedToast(this, getString(R.string.model_manager_deck_override_dynamic_deck_error), true);
        return;
    }
    String message;
    if (deck == null) {
        Timber.i("Removing default template from template '%s'", templateName);
        template.put("did", null);
        message = getString(R.string.model_manager_deck_override_removed_message, templateName);
    } else {
        Timber.i("Setting template '%s' to '%s'", templateName, deck.getName());
        template.put("did", deck.getDeckId());
        message = getString(R.string.model_manager_deck_override_added_message, templateName, deck.getName());
    }
    UIUtils.showThemedToast(this, message, true);
    // Deck Override can change from "on" <-> "off"
    supportInvalidateOptionsMenu();
}
Also used : JSONObject(com.ichi2.utils.JSONObject)

Example 20 with Deck

use of com.ichi2.libanki.Deck in project AnkiChinaAndroid by ankichinateam.

the class NoteEditor method hasUnsavedChanges.

private boolean hasUnsavedChanges() {
    if (!collectionHasLoaded()) {
        return false;
    }
    // changed note type?
    if (!mAddNote && mCurrentEditedCard != null) {
        final JSONObject newModel = getCurrentlySelectedModel();
        final JSONObject oldModel = mCurrentEditedCard.model();
        if (!newModel.equals(oldModel)) {
            return true;
        }
    }
    // changed deck?
    if (!mAddNote && mCurrentEditedCard != null && mCurrentEditedCard.getDid() != mCurrentDid) {
        return true;
    }
    // changed fields?
    if (mFieldEdited) {
        return true;
    }
    // changed tags?
    return mTagsEdited;
}
Also used : JSONObject(com.ichi2.utils.JSONObject)

Aggregations

Deck (com.ichi2.libanki.Deck)100 Collection (com.ichi2.libanki.Collection)97 JSONObject (com.ichi2.utils.JSONObject)88 Test (org.junit.Test)80 JSONArray (com.ichi2.utils.JSONArray)55 Card (com.ichi2.libanki.Card)53 Note (com.ichi2.libanki.Note)50 ArrayList (java.util.ArrayList)47 RobolectricTest (com.ichi2.anki.RobolectricTest)44 DeckConfig (com.ichi2.libanki.DeckConfig)37 JSONException (com.ichi2.utils.JSONException)34 NonNull (androidx.annotation.NonNull)30 HashMap (java.util.HashMap)29 Model (com.ichi2.libanki.Model)23 Map (java.util.Map)22 Intent (android.content.Intent)21 Resources (android.content.res.Resources)18 TextView (android.widget.TextView)18 SharedPreferences (android.content.SharedPreferences)17 Cursor (android.database.Cursor)17