Search in sources :

Example 31 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project Anki-Android by Ramblurr.

the class CardEditor method setNote.

private void setNote(Note note) {
    try {
        if (note == null) {
            mCurrentDid = mCol.getDecks().current().getLong("id");
            if (mCol.getDecks().isDyn(mCurrentDid)) {
                mCurrentDid = 1;
            }
            JSONObject model = mCol.getModels().current();
            mEditorNote = new Note(mCol, model);
            mEditorNote.model().put("did", mCurrentDid);
            mModelButton.setText(getResources().getString(R.string.CardEditorModel, model.getString("name")));
            JSONArray tags = model.getJSONArray("tags");
            for (int i = 0; i < tags.length(); i++) {
                mEditorNote.addTag(tags.getString(i));
            }
        } else {
            mEditorNote = note;
            mCurrentDid = mCurrentEditedCard.getDid();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    mCurrentTags = mEditorNote.getTags();
    updateDeck();
    updateTags();
    populateEditFields();
    swapText(true);
}
Also used : JSONObject(org.json.JSONObject) Note(com.ichi2.libanki.Note) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 32 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project Anki-Android by Ramblurr.

the class CardEditor method onCreateDialog.

@Override
protected Dialog onCreateDialog(int id) {
    StyledDialog dialog = null;
    Resources res = getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(this);
    switch(id) {
        case DIALOG_TAGS_SELECT:
            builder.setTitle(R.string.card_details_tags);
            builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (mAddNote) {
                        try {
                            JSONArray ja = new JSONArray();
                            for (String t : selectedTags) {
                                ja.put(t);
                            }
                            mCol.getModels().current().put("tags", ja);
                            mCol.getModels().setChanged();
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                        mEditorNote.setTags(selectedTags);
                    }
                    mCurrentTags = selectedTags;
                    updateTags();
                }
            });
            builder.setNegativeButton(res.getString(R.string.cancel), null);
            mNewTagEditText = (EditText) new EditText(this);
            mNewTagEditText.setHint(R.string.add_new_tag);
            InputFilter filter = new InputFilter() {

                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    for (int i = start; i < end; i++) {
                        if (source.charAt(i) == ' ' || source.charAt(i) == ',') {
                            return "";
                        }
                    }
                    return null;
                }
            };
            mNewTagEditText.setFilters(new InputFilter[] { filter });
            ImageView mAddTextButton = new ImageView(this);
            mAddTextButton.setImageResource(R.drawable.ic_addtag);
            mAddTextButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    String tag = mNewTagEditText.getText().toString();
                    if (tag.length() != 0) {
                        if (mEditorNote.hasTag(tag)) {
                            mNewTagEditText.setText("");
                            return;
                        }
                        selectedTags.add(tag);
                        actualizeTagDialog(mTagsDialog);
                        mNewTagEditText.setText("");
                    }
                }
            });
            FrameLayout frame = new FrameLayout(this);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
            params.rightMargin = 10;
            mAddTextButton.setLayoutParams(params);
            frame.addView(mNewTagEditText);
            frame.addView(mAddTextButton);
            builder.setView(frame, false, true);
            dialog = builder.create();
            mTagsDialog = dialog;
            break;
        case DIALOG_DECK_SELECT:
            ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>();
            // Use this array to know which ID is associated with each
            // Item(name)
            final ArrayList<Long> dialogDeckIds = new ArrayList<Long>();
            ArrayList<JSONObject> decks = mCol.getDecks().all();
            Collections.sort(decks, new JSONNameComparator());
            builder.setTitle(R.string.deck);
            for (JSONObject d : decks) {
                try {
                    if (d.getInt("dyn") == 0) {
                        dialogDeckItems.add(d.getString("name"));
                        dialogDeckIds.add(d.getLong("id"));
                    }
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
            // Convert to Array
            String[] items = new String[dialogDeckItems.size()];
            dialogDeckItems.toArray(items);
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    long newId = dialogDeckIds.get(item);
                    if (mCurrentDid != newId) {
                        if (mAddNote) {
                            try {
                                // TODO: mEditorNote.setDid(newId);
                                mEditorNote.model().put("did", newId);
                                mCol.getModels().setChanged();
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        mCurrentDid = newId;
                        updateDeck();
                    }
                }
            });
            dialog = builder.create();
            mDeckSelectDialog = dialog;
            break;
        case DIALOG_MODEL_SELECT:
            ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
            // Use this array to know which ID is associated with each
            // Item(name)
            final ArrayList<Long> dialogIds = new ArrayList<Long>();
            ArrayList<JSONObject> models = mCol.getModels().all();
            Collections.sort(models, new JSONNameComparator());
            builder.setTitle(R.string.note_type);
            for (JSONObject m : models) {
                try {
                    dialogItems.add(m.getString("name"));
                    dialogIds.add(m.getLong("id"));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
            // Convert to Array
            String[] items2 = new String[dialogItems.size()];
            dialogItems.toArray(items2);
            builder.setItems(items2, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    long oldModelId;
                    try {
                        oldModelId = mCol.getModels().current().getLong("id");
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    long newId = dialogIds.get(item);
                    if (oldModelId != newId) {
                        mCol.getModels().setCurrent(mCol.getModels().get(newId));
                        JSONObject cdeck = mCol.getDecks().current();
                        try {
                            cdeck.put("mid", newId);
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                        mCol.getDecks().save(cdeck);
                        int size = mEditFields.size();
                        String[] oldValues = new String[size];
                        for (int i = 0; i < size; i++) {
                            oldValues[i] = mEditFields.get(i).getText().toString();
                        }
                        setNote();
                        resetEditFields(oldValues);
                        mTimerHandler.removeCallbacks(checkDuplicatesRunnable);
                        duplicateCheck(false);
                    }
                }
            });
            dialog = builder.create();
            break;
        case DIALOG_RESET_CARD:
            builder.setTitle(res.getString(R.string.reset_card_dialog_title));
            builder.setMessage(res.getString(R.string.reset_card_dialog_message));
            builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                // for (long cardId :
                // mDeck.getCardsFromFactId(mEditorNote.getId())) {
                // mDeck.cardFromId(cardId).resetCard();
                // }
                // mDeck.reset();
                // setResult(Reviewer.RESULT_EDIT_CARD_RESET);
                // mCardReset = true;
                // Themes.showThemedToast(CardEditor.this,
                // getResources().getString(
                // R.string.reset_card_dialog_confirmation), true);
                }
            });
            builder.setNegativeButton(res.getString(R.string.no), null);
            builder.setCancelable(true);
            dialog = builder.create();
            break;
        case DIALOG_INTENT_INFORMATION:
            dialog = createDialogIntentInformation(builder, res);
    }
    return dialog;
}
Also used : DialogInterface(android.content.DialogInterface) Builder(com.ichi2.themes.StyledDialog.Builder) StyledDialog(com.ichi2.themes.StyledDialog) ArrayList(java.util.ArrayList) ImageView(android.widget.ImageView) EditText(android.widget.EditText) InputFilter(android.text.InputFilter) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Spanned(android.text.Spanned) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ListView(android.widget.ListView) OnClickListener(android.content.DialogInterface.OnClickListener) JSONObject(org.json.JSONObject) FrameLayout(android.widget.FrameLayout) Builder(com.ichi2.themes.StyledDialog.Builder) OnClickListener(android.content.DialogInterface.OnClickListener) Resources(android.content.res.Resources)

Example 33 with TAGS

use of com.ichi2.anki.CardBrowser.Column.TAGS in project Anki-Android by Ramblurr.

the class CardBrowser method updateCardInList.

private void updateCardInList(Card card, String updatedCardTags) {
    Note note = card.note();
    int pos;
    for (Card c : note.cards()) {
        pos = getPosition(mCards, c.getId());
        if (pos < 0 || pos >= mCards.size()) {
            continue;
        }
        if (updatedCardTags != null) {
            mCards.get(pos).put("tags", updatedCardTags);
        }
        String sfld = note.getSFld();
        mCards.get(pos).put("sfld", sfld);
        if (mWholeCollection) {
            String deckName;
            try {
                deckName = mCol.getDecks().get(card.getDid()).getString("name");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            mCards.get(pos).put("deck", deckName);
        }
        String flags = Integer.toString((c.getQueue() == -1 ? 1 : 0) + (note.hasTag("marked") ? 2 : 0));
        mCards.get(pos).put("flags", flags);
    }
    updateList();
}
Also used : Note(com.ichi2.libanki.Note) JSONException(org.json.JSONException) Card(com.ichi2.libanki.Card)

Example 34 with TAGS

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

the class NoteEditor method onCollectionLoaded.

// Finish initializing the activity after the collection has been correctly loaded
@Override
protected void onCollectionLoaded(Collection col) {
    super.onCollectionLoaded(col);
    Intent intent = getIntent();
    Timber.d("NoteEditor() onCollectionLoaded: caller: %d", mCaller);
    registerExternalStorageListener();
    View mainView = findViewById(android.R.id.content);
    mToolbar = findViewById(R.id.editor_toolbar);
    mToolbar.setFormatListener(formatter -> {
        View currentFocus = getCurrentFocus();
        if (!(currentFocus instanceof FieldEditText)) {
            return;
        }
        modifyCurrentSelection(formatter, (FieldEditText) currentFocus);
    });
    enableToolbar(mainView);
    mFieldsLayoutContainer = findViewById(R.id.CardEditorEditFieldsLayout);
    mTagsButton = findViewById(R.id.CardEditorTagText);
    mCardsButton = findViewById(R.id.CardEditorCardsText);
    mCardsButton.setOnClickListener(v -> {
        Timber.i("NoteEditor:: Cards button pressed. Opening template editor");
        showCardTemplateEditor();
    });
    mAedictIntent = false;
    mCurrentEditedCard = null;
    switch(mCaller) {
        case CALLER_NOCALLER:
            Timber.e("no caller could be identified, closing");
            finishWithoutAnimation();
            return;
        case CALLER_REVIEWER:
            mCurrentEditedCard = AbstractFlashcardViewer.getEditorCard();
            if (mCurrentEditedCard == null) {
                finishWithoutAnimation();
                return;
            }
            mEditorNote = mCurrentEditedCard.note();
            mAddNote = false;
            break;
        case CALLER_STUDYOPTIONS:
        case CALLER_DECKPICKER:
        case CALLER_REVIEWER_ADD:
        case CALLER_CARDBROWSER_ADD:
        case CALLER_CARDEDITOR:
            mAddNote = true;
            break;
        case CALLER_CARDBROWSER_EDIT:
            mCurrentEditedCard = CardBrowser.sCardBrowserCard;
            if (mCurrentEditedCard == null) {
                finishWithoutAnimation();
                return;
            }
            mEditorNote = mCurrentEditedCard.note();
            mAddNote = false;
            break;
        case CALLER_CARDEDITOR_INTENT_ADD:
            {
                fetchIntentInformation(intent);
                if (mSourceText == null) {
                    finishWithoutAnimation();
                    return;
                }
                if ("Aedict Notepad".equals(mSourceText[0]) && addFromAedict(mSourceText[1])) {
                    finishWithoutAnimation();
                    return;
                }
                mAddNote = true;
                break;
            }
        default:
            break;
    }
    // Note type Selector
    mNoteTypeSpinner = findViewById(R.id.note_type_spinner);
    ArrayList<Model> models = getCol().getModels().all();
    Collections.sort(models, NamedJSONComparator.instance);
    final ArrayList<String> modelNames = new ArrayList<>(models.size());
    mAllModelIds = new ArrayList<>(models.size());
    for (JSONObject m : models) {
        modelNames.add(m.getString("name"));
        mAllModelIds.add(m.getLong("id"));
    }
    ArrayAdapter<String> noteTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, modelNames);
    mNoteTypeSpinner.setAdapter(noteTypeAdapter);
    noteTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Deck Selector
    TextView deckTextView = findViewById(R.id.CardEditorDeckText);
    // If edit mode and more than one card template distinguish between "Deck" and "Card deck"
    if (!mAddNote && mEditorNote.model().getJSONArray("tmpls").length() > 1) {
        deckTextView.setText(R.string.CardEditorCardDeck);
    }
    mNoteDeckSpinner = findViewById(R.id.note_deck_spinner);
    ArrayList<Deck> decks = getCol().getDecks().all();
    Collections.sort(decks, DeckComparator.instance);
    final ArrayList<String> deckNames = new ArrayList<>(decks.size());
    mAllDeckIds = new ArrayList<>(decks.size());
    for (Deck d : decks) {
        // add current deck and all other non-filtered decks to deck list
        long thisDid = d.getLong("id");
        if (d.getInt("dyn") == 0 || (!mAddNote && mCurrentEditedCard != null && mCurrentEditedCard.getDid() == thisDid)) {
            deckNames.add(d.getString("name"));
            mAllDeckIds.add(thisDid);
        }
    }
    ArrayAdapter<String> noteDeckAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, deckNames);
    mNoteDeckSpinner.setAdapter(noteDeckAdapter);
    noteDeckAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mNoteDeckSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // Timber.i("NoteEditor:: onItemSelected() fired on mNoteDeckSpinner with pos = %d", pos);
            mCurrentDid = mAllDeckIds.get(pos);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        // Do Nothing
        }
    });
    mCurrentDid = intent.getLongExtra(EXTRA_DID, mCurrentDid);
    setDid(mEditorNote);
    setNote(mEditorNote, FieldChangeType.onActivityCreation(shouldReplaceNewlines()));
    if (mAddNote) {
        mNoteTypeSpinner.setOnItemSelectedListener(new SetNoteTypeListener());
        setTitle(R.string.menu_add_note);
        // set information transferred by intent
        String contents = null;
        String[] tags = intent.getStringArrayExtra(EXTRA_TAGS);
        if (mSourceText != null) {
            if (mAedictIntent && (mEditFields.size() == 3) && mSourceText[1].contains("[")) {
                contents = mSourceText[1].replaceFirst("\\[", "\u001f" + mSourceText[0] + "\u001f");
                contents = contents.substring(0, contents.length() - 1);
            } else if (mEditFields.size() > 0) {
                mEditFields.get(0).setText(mSourceText[0]);
                if (mEditFields.size() > 1) {
                    mEditFields.get(1).setText(mSourceText[1]);
                }
            }
        } else {
            contents = intent.getStringExtra(EXTRA_CONTENTS);
        }
        if (contents != null) {
            setEditFieldTexts(contents);
        }
        if (tags != null) {
            setTags(tags);
        }
    } else {
        mNoteTypeSpinner.setOnItemSelectedListener(new EditNoteTypeListener());
        setTitle(R.string.cardeditor_title_edit_card);
    }
    findViewById(R.id.CardEditorTagButton).setOnClickListener(v -> {
        Timber.i("NoteEditor:: Tags button pressed... opening tags editor");
        showTagsDialog();
    });
    if (!mAddNote && mCurrentEditedCard != null) {
        Timber.i("onCollectionLoaded() Edit note activity successfully started with card id %d", mCurrentEditedCard.getId());
    }
    if (mAddNote) {
        Timber.i("onCollectionLoaded() Edit note activity successfully started in add card mode with node id %d", mEditorNote.getId());
    }
    // don't open keyboard if not adding note
    if (!mAddNote) {
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
    // set focus to FieldEditText 'first' on startup like Anki desktop
    if (mEditFields != null && !mEditFields.isEmpty()) {
        mEditFields.getFirst().requestFocus();
    }
}
Also used : ArrayList(java.util.ArrayList) Deck(com.ichi2.libanki.Deck) Intent(android.content.Intent) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) SuppressLint(android.annotation.SuppressLint) JSONObject(com.ichi2.utils.JSONObject) Model(com.ichi2.libanki.Model) OnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) TextView(android.widget.TextView) ArrayAdapter(android.widget.ArrayAdapter)

Example 35 with TAGS

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

the class CardBrowser method updateCardsInList.

/**
 * @param cards           Cards that were changed
 * @param updatedCardTags Mapping note id -> updated tags
 */
private void updateCardsInList(List<Card> cards, Map<Long, String> updatedCardTags) {
    List<CardCache> cardList = getCards();
    Map<Long, Integer> idToPos = getPositionMap(cardList);
    for (Card c : cards) {
        // get position in the mCards search results HashMap
        Integer pos = idToPos.get(c.getId());
        if (pos == null || pos >= getCardCount()) {
            continue;
        }
        // update Q & A etc
        cardList.get(pos).load(true, mColumn1Index, mColumn2Index);
    }
    updateList();
}
Also used : Card(com.ichi2.libanki.Card)

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