use of com.ichi2.anki.CardBrowser.Column.QUESTION in project AnkiChinaAndroid by ankichinateam.
the class DeckInfoListAdapter method onBindViewHolder.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder tempHolder, int position) {
if (tempHolder instanceof HeaderViewHolder) {
HeaderViewHolder holder = (HeaderViewHolder) tempHolder;
holder.mTextDeckName.setText(mTextDeckName);
holder.mDeckListHeader.setVisibility(mDeckList.isEmpty() ? View.GONE : View.VISIBLE);
// holder.mTextCongratsMessage.setText(mTextCongratsMessage);
holder.mTextDeckDescription.setText(mTextDeckDescription != null && mTextDeckDescription.length() > 0 ? formatDescription(mTextDeckDescription) : "");
holder.mTextTodayNew.setText(mTextTodayNew);
holder.mTextTodayRev.setText(mTextTodayRev);
holder.mTextCountHandled.setText(mTextCountHandled);
holder.mTextCountLearning.setText(mTextCountLearning);
holder.mTextCountNew.setText(mTextCountNew);
holder.mTextCountHard.setText(mTextCountHard);
holder.mTextTotal.setText(mTextTotal);
holder.mTextHandledPercent.setText(mTextHandledPercent);
holder.mTextHandledNum.setText(mTextHandledNum);
holder.mTextETA.setText(mTextETA);
holder.mButtonStart.setText(mTextButtonStart);
holder.mButtonStart.setOnClickListener(mButtonStartClickListener);
holder.mSelfStudyAskIcon.setOnClickListener(v -> {
if (mSelfStudyQADialog == null) {
mSelfStudyQADialog = new Dialog(mContext, R.style.CommonDialogTheme);
View view = View.inflate(mContext, R.layout.pop_window_self_study_introduce, null);
mSelfStudyQADialog.setContentView(view);
Window window = mSelfStudyQADialog.getWindow();
WindowManager.LayoutParams lps = window.getAttributes();
lps.width = WindowManager.LayoutParams.MATCH_PARENT;
window.setAttributes(lps);
window.setGravity(Gravity.BOTTOM);
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
mSelfStudyQADialog.show();
});
holder.mStudyProgress.setProgress(mStudyProgress);
// holder.mDeckInfoLayout.setVisibility(mDeckInfoLayoutVisible);
// holder.mTextCongratsMessage.setVisibility(mTextCongratsMessageVisible);
holder.mTextDeckDescription.setVisibility(mTextDeckDescriptionVisible);
holder.mButtonStart.setEnabled(mButtonStartEnable);
holder.mSelfStudyHandle.setTag(SelfStudyActivity.TAB_STUDY_STATE);
holder.mSelfStudyMark.setTag(SelfStudyActivity.TAB_MARK_STATE);
holder.mSelfStudyAnswer.setTag(SelfStudyActivity.TAB_ANSWER_STATE);
holder.mSelfStudyCustom.setTag(SelfStudyActivity.TAB_CUSTOM_STATE);
holder.mSelfStudyHandle.setOnClickListener(mSelfStudyClickListener);
holder.mSelfStudyMark.setOnClickListener(mSelfStudyClickListener);
holder.mSelfStudyAnswer.setOnClickListener(mSelfStudyClickListener);
holder.mSelfStudyCustom.setOnClickListener(mSelfStudyClickListener);
holder.mTextStudySetting.setVisibility(mCurrentDeck == null || mCurrentDeck.optInt("dyn", 0) == 1 ? View.GONE : View.VISIBLE);
holder.mTextStudySetting.setOnClickListener(v -> {
Intent i = new Intent(mContext, StudySettingActivity.class);
i.putExtra("did", mCurrentDeck.optLong("id"));
mContext.startActivityForResultWithAnimation(i, DECK_OPTIONS, ActivityTransitionAnimation.FADE);
});
if (AD_IMAGE_URL != null && !AD_IMAGE_URL.isEmpty() && AD_LINK_URL != null && !AD_LINK_URL.isEmpty()) {
holder.mAdLayout.setVisibility(View.VISIBLE);
CornerTransform transformation = new CornerTransform(mContext, AdaptionUtil.dip2px(mContext, 9));
transformation.setExceptCorner(false, false, false, false);
RequestOptions coverRequestOptions = new RequestOptions().transform(transformation).diskCacheStrategy(// 不做磁盘缓存
DiskCacheStrategy.NONE).skipMemoryCache(// 不做内存缓存
true);
Glide.with(mContext).asBitmap().load(AD_IMAGE_URL).apply(coverRequestOptions).into(holder.mAdImage);
holder.mAdLayout.setOnClickListener(v -> WebViewActivity.openUrlInApp(mContext, AD_LINK_URL, ""));
} else {
holder.mAdLayout.setVisibility(View.GONE);
}
} else if (tempHolder instanceof ViewHolder) {
position--;
ViewHolder holder = (ViewHolder) tempHolder;
AbstractDeckTreeNode node = mDeckList.get(position);
// Set the expander icon and padding according to whether or not there are any subdecks
RelativeLayout deckLayout = holder.deckLayout;
// int rightPadding = (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_right_padding);
if (mHasSubdecks) {
int smallPadding = (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_left_padding_small);
deckLayout.setPadding(smallPadding, 0, (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_right_padding), 0);
holder.deckExpander.setVisibility(View.VISIBLE);
// Create the correct expander for this deck
setDeckExpander(holder.deckExpander, holder.indentView, node);
} else {
holder.deckExpander.setVisibility(View.GONE);
int normalPadding = (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_left_padding);
deckLayout.setPadding(normalPadding, 0, (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_right_padding), 0);
}
if (node.hasChildren()) {
holder.deckExpander.setTag(node.getDid());
holder.deckExpander.setOnClickListener(mDeckExpanderClickListener);
} else {
holder.deckExpander.setOnClickListener(null);
}
// holder.deckLayout.setBackgroundResource(mRowCurrentDrawable);
// Set background colour. The current deck has its own color
// if (isCurrentlySelectedDeck(node)) {
// Timber.d("can be shown:%s", node.getDid());
// Timber.d("mHasSubdecks:%s", node.hasChildren() + "");
// if (mCurrentIDs.contains(node.getDid())) {
// holder.deckLayout.setVisibility(View.VISIBLE);
// holder.deckLayout.setBackgroundResource(mRowCurrentDrawable);
// if (mPartiallyTransparentForBackground) {
// setBackgroundAlpha(holder.deckLayout, SELECTED_DECK_ALPHA_AGAINST_BACKGROUND);
// }
// } else {
// holder.deckLayout.setVisibility(View.GONE);
// CompatHelper.getCompat().setSelectableBackground(holder.deckLayout);
// }
// Set deck name and colour. Filtered decks have their own colour
holder.deckName.setText(node.getLastDeckNameComponent());
if (mCol.getDecks().isDyn(node.getDid())) {
holder.deckName.setTextColor(mDeckNameDynColor);
} else {
if (node.getDepth() == Decks.path(mCurrentDeck.optString("name")).length) {
holder.deckName.setTextColor(mDeckNameDefaultColor);
} else {
holder.deckName.setTextColor(mDeckNameDefaultColorChild);
}
}
if (node.shouldDisplayCounts()) {
// holder.deckNew.setText(String.valueOf(node.getNewCount()));
// holder.deckLearn.setText(String.valueOf(node.getLrnCount()));
// holder.deckRev.setText(String.valueOf(node.getRevCount()+node.getLrnCount()));
holder.deckNew.setText(String.valueOf(node.getNewCount() + node.getRevCount() + node.getLrnCount()));
String ids = Stats.deckLimit(node.getDid(), mCol);
holder.deckRev.setText(String.valueOf(mCol.cardCount(ids)));
}
// Store deck ID in layout's tag for easy retrieval in our click listeners
holder.deckLayout.setTag(node.getDid());
holder.countsLayout.setTag(node.getDid());
holder.endIcon.setTag(node.getDid());
// holder.endLayout.setTag(node.getDid());
// Set click listeners
holder.deckLayout.setOnClickListener(mDeckClickListener);
holder.deckLayout.setOnLongClickListener(mDeckLongClickListener);
holder.countsLayout.setOnClickListener(mCountsClickListener);
holder.endIcon.setOnClickListener(mCountsClickListener);
// holder.endLayout.setOnClickListener(mCountsClickListener);
} else if (mCurrentDeck != null) {
if (tempHolder instanceof CardsListAdapter.CardsViewHolder) {
CardsListAdapter.CardsViewHolder holder = (CardsListAdapter.CardsViewHolder) tempHolder;
CardBrowser.CardCache card = mCards.get(position - mDeckList.size() - 1 - 1);
Timber.i("refresh card:%s", card.getId());
String question = card.getColumnHeaderText(CardBrowser.Column.SFLD);
if (card.getColumnHeaderText(CardBrowser.Column.SUSPENDED).equals("True")) {
holder.deckQuestion.setTextColor(ContextCompat.getColor(mContext, R.color.new_primary_text_third_color));
// holder.deckAnswer.setTextColor(ContextCompat.getColor(mContext, R.color.new_primary_text_third_color));
}
String firstColumnStr = question.isEmpty() ? card.getColumnHeaderText(CardBrowser.Column.MEDIA_NAME) : card.getColumnHeaderText(CardBrowser.Column.SFLD);
Pattern pattern = Pattern.compile("(?<=≯#).*?(?=#≮)");
Matcher matcher = pattern.matcher(firstColumnStr);
String val = "";
if (matcher.find()) {
val = matcher.group(0);
try {
String key = mModelKeys.getString(String.valueOf(card.getCard().model().getLong("id")));
Timber.i("match key:%s", key);
holder.deckQuestion.setText(HtmlUtils.delHTMLTag(firstColumnStr.substring(0, firstColumnStr.indexOf("≯#")) + AESUtil.decrypt(val, key) + firstColumnStr.substring(firstColumnStr.indexOf("#≮") + 2)));
// holder.deckQuestion.setText(firstColumnStr.substring(0, firstColumnStr.indexOf("≯#")) + aesUtil.getDecryptedMessage(val) + firstColumnStr.substring(firstColumnStr.indexOf("#≮") + 2));
} catch (Exception e) {
e.printStackTrace();
holder.deckQuestion.setText(firstColumnStr);
}
} else {
holder.deckQuestion.setText(firstColumnStr);
}
// holder.deckAnswer.setText(card.getColumnHeaderText(CardBrowser.Column.ANSWER));
holder.reviewCount.setText(card.getColumnHeaderText(CardBrowser.Column.REVIEWS));
holder.forgetCount.setText(card.getColumnHeaderText(CardBrowser.Column.LAPSES));
holder.due.setText(card.getColumnHeaderText(CardBrowser.Column.DUE2));
holder.mark.setTag(card.getId());
holder.flag.setTag(card.getId());
holder.itemRoot.setTag(card.getId());
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.itemRoot.getLayoutParams();
layoutParams.rightMargin = 0;
holder.itemRoot.setLayoutParams(layoutParams);
if (card.getCard().note().hasTag("marked")) {
holder.mark.setImageResource(R.mipmap.mark_star_normal);
} else {
holder.mark.setImageResource(R.mipmap.note_star_unselected);
}
if (getFlagRes(card.getCard()) != -1) {
holder.flag.setImageResource(getFlagRes(card.getCard()));
} else {
holder.flag.setImageResource(R.mipmap.note_flag_unselected);
}
holder.mark.setOnClickListener(v -> {
CollectionTask.launchCollectionTask(DISMISS_MULTI, markCardHandler(), new TaskData(new Object[] { new long[] { (long) v.getTag() }, Collection.DismissType.MARK_NOTE_MULTI }));
notifyDataSetChanged();
});
holder.flag.setOnClickListener(v -> {
if (mListPop == null) {
mListPop = new ListPopupWindow(mContext);
for (int i = 0; i < mFlagRes.length; i++) {
Map<String, Object> map = new HashMap<>();
map.put("img", mFlagRes[i]);
map.put("content", mFlagContent[i]);
mFlagList.add(map);
}
mListPop.setAdapter(new SimpleAdapter(mContext, mFlagList, R.layout.item_flags_list, new String[] { "img", "content" }, new int[] { R.id.flag_icon, R.id.flag_text }));
mListPop.setWidth(v.getRootView().getWidth() / 2);
mListPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
// 设置是否是模式
mListPop.setModal(true);
}
mListPop.setOnItemClickListener((parent, view, position1, id) -> {
CollectionTask.launchCollectionTask(DISMISS_MULTI, flagCardHandler(), new TaskData(new Object[] { new long[] { (long) v.getTag() }, Collection.DismissType.FLAG, position1 }));
notifyDataSetChanged();
mListPop.dismiss();
});
mListPop.setAnchorView(v);
mListPop.show();
});
holder.itemRoot.setOnClickListener(v -> {
Intent previewer = new Intent(mContext, Previewer.class);
long[] ids = getAllCardIds();
long targetId = (long) v.getTag();
// }
for (int i = 0; i < ids.length; i++) {
if (ids[i] == targetId) {
previewer.putExtra("index", i);
break;
}
}
previewer.putExtra("cardList", ids);
mContext.startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
});
// holder.itemRoot.setOnLongClickListener(mDeckLongClickListener);
} else if (tempHolder instanceof BrowserTabViewHolder) {
BrowserTabViewHolder holder = (BrowserTabViewHolder) tempHolder;
String[] tabArray = mContext.getResources().getStringArray(R.array.deck_info_browser_tab);
holder.cardsCount.setText(String.format("筛选出%d张卡片", mCards.size()));
// CardsListAdapter mCardsAdapter = new CardsListAdapter(mContext.getLayoutInflater(), mContext, new CardsListAdapter.CardListAdapterCallback() {
// @Override
// public List<CardBrowser.CardCache> getCards() {
// if (mCards == null) {
// mCards = new ArrayList<>();
// }
// return mCards;
// }
//
//
// @Override
// public void onChangeMultiMode(boolean isMultiMode) {
// }
//
//
// @Override
// public void onItemSelect(int count) {
// }
// });
// mCardsAdapter.setStudyCountLayoutRes(R.layout.item_option_study_count);
// mCardsAdapter.setDeckClickListener(view -> {
// Intent previewer = new Intent(mContext, Previewer.class);
// long[] ids = getAllCardIds();
// long targetId = (long) view.getTag();
// if (ids.length > 100) {
// //为提高效率 直接复制卡牌
// long[] finalIds = new long[ids.length + 1];
// finalIds[0] = targetId;
// System.arraycopy(ids, 0, finalIds, 1, ids.length);
// previewer.putExtra("cardList", finalIds);
// } else {
// for (int i = 0; i < ids.length; i++) {
// if (ids[i] == targetId) {
// ids[i] = ids[0];
// ids[0] = targetId;
// }
// }
// previewer.putExtra("cardList", ids);
// }
// previewer.putExtra("index", 0);
// mContext.startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
// });
// holder.mList .setAdapter(mCardsAdapter);
// holder.mList.setRecycledViewPool(new RecyclerView.RecycledViewPool());
// holder.mList.setNestedScrollingEnabled(false);
// holder.mList.setHasFixedSize(true);
// holder.mList.setLayoutManager(new LinearLayoutManager(mContext));
holder.mMore.setTag(SelfStudyActivity.TAB_MAIN_STATE);
holder.mFixBottom.setVisibility(mDeckList.isEmpty() ? View.GONE : View.VISIBLE);
holder.mMore.setOnClickListener(mSelfStudyClickListener);
holder.mTabLayout.removeAllTabs();
LinearLayout linearLayout = (LinearLayout) holder.mTabLayout.getChildAt(0);
linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
linearLayout.setDividerDrawable(ContextCompat.getDrawable(mContext, // 设置分割线的样式
R.drawable.divider_vertical));
// 设置分割线间隔
linearLayout.setDividerPadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18, mContext.getResources().getDisplayMetrics()));
for (int i = 0; i < tabArray.length; i++) {
TabLayout.Tab tab = holder.mTabLayout.newTab();
View view = mContext.getLayoutInflater().inflate(R.layout.item_option_tab, null);
((TextView) view.findViewById(R.id.name)).setText(tabArray[i]);
tab.setCustomView(view);
view.setTag(i);
int finalI = i;
view.setOnClickListener(v -> {
if (mContext.colIsOpen()) {
mCurrentSelectedTab = finalI;
holder.mTabLayout.selectTab(holder.mTabLayout.getTabAt(finalI));
// estimate maximum number of cards that could be visible (assuming worst-case minimum row height of 20dp)
int numCardsToRender = (int) Math.ceil(holder.mList.getHeight() / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, mContext.getResources().getDisplayMetrics())) + 5;
Timber.i("I wanna get %d cards", numCardsToRender);
// Perform database query to get all card ids
mSearchCardsHandler = new SearchCardsHandler();
String searchText = getRestrictByTab(finalI) + "deck:\"" + mCurrentDeck.getString("name") + "\" ";
CollectionTask.launchCollectionTask(SEARCH_CARDS, mSearchCardsHandler, new TaskData(new Object[] { searchText, true, numCardsToRender, 0, 0 }));
}
});
holder.mTabLayout.addTab(tab);
}
holder.mTabLayout.selectTab(holder.mTabLayout.getTabAt(mCurrentSelectedTab));
if (!mInitBrowserCards) {
mInitBrowserCards = true;
holder.mTabLayout.getTabAt(0).getCustomView().performClick();
}
}
}
}
use of com.ichi2.anki.CardBrowser.Column.QUESTION in project AnkiChinaAndroid by ankichinateam.
the class CardsListAdapter method onBindViewHolder.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder tempHolder, int position) {
// Timber.i("onBindViewHolder:%s", position);
if (tempHolder instanceof CardsViewHolder) {
position--;
CardsViewHolder holder = (CardsViewHolder) tempHolder;
CardBrowser.CardCache card = mCallback.getCards().get(position);
String question = card.getColumnHeaderText(CardBrowser.Column.SFLD);
if (card.getColumnHeaderText(CardBrowser.Column.SUSPENDED).equals("True")) {
holder.deckQuestion.setTextColor(ContextCompat.getColor(mContext, R.color.new_primary_text_third_color));
// holder.deckAnswer.setTextColor(ContextCompat.getColor(mContext, R.color.new_primary_text_third_color));
}
String firstColumnStr = question.isEmpty() ? card.getColumnHeaderText(CardBrowser.Column.MEDIA_NAME) : card.getColumnHeaderText(CardBrowser.Column.SFLD);
Pattern pattern = Pattern.compile("(?<=≯#).*?(?=#≮)");
Matcher matcher = pattern.matcher(firstColumnStr);
String val = "";
if (matcher.find()) {
val = matcher.group(0);
try {
String key = mModelKeys.getString(String.valueOf(card.getCard().model().getLong("id")));
Timber.i("match key:%s", key);
holder.deckQuestion.setText(HtmlUtils.delHTMLTag(firstColumnStr.substring(0, firstColumnStr.indexOf("≯#")) + AESUtil.decrypt(val, key) + firstColumnStr.substring(firstColumnStr.indexOf("#≮") + 2)));
// holder.deckQuestion.setText(firstColumnStr.substring(0, firstColumnStr.indexOf("≯#")) + aesUtil.getDecryptedMessage(val) + firstColumnStr.substring(firstColumnStr.indexOf("#≮") + 2));
} catch (Exception e) {
e.printStackTrace();
holder.deckQuestion.setText(firstColumnStr);
}
} else {
holder.deckQuestion.setText(firstColumnStr);
}
Timber.i("match content:%s", val);
// if(mModelKeys!=null&&( key=mModelKeys.getString(String.valueOf(card.getCard().model().getLong("id"))))!=JSONObject.NULL){
// holder.deckQuestion.setText(AESUtil.decrypt(firstColumnStr,key));
// }else {
// holder.deckQuestion.setText((mModelKeys!=null&&( key=mModelKeys.getString(String.valueOf(card.getCard().model().getLong("id"))))!=JSONObject.NULL)?AESUtil.decrypt(firstColumnStr,key):firstColumnStr);
// }
// holder.deckQuestion.setText((mModelKeys!=null&&( key=mModelKeys.getString(String.valueOf(card.getCard().model().getLong("id"))))!=JSONObject.NULL)?AESUtil.decrypt(firstColumnStr,key):firstColumnStr);
// if (question.isEmpty()) {
//
// holder.deckQuestion.setText(card.getColumnHeaderText(CardBrowser.Column.MEDIA_NAME));
// } else {
// holder.deckQuestion.setText(card.getColumnHeaderText(CardBrowser.Column.SFLD));
// }
// holder.deckAnswer.setText(card.getColumnHeaderText(CardBrowser.Column.ANSWER));
holder.reviewCount.setText(card.getColumnHeaderText(CardBrowser.Column.REVIEWS));
holder.forgetCount.setText(card.getColumnHeaderText(CardBrowser.Column.LAPSES));
holder.due.setText(card.getColumnHeaderText(CardBrowser.Column.DUE2));
holder.mark.setTag(card.getId());
holder.flag.setTag(card.getId());
holder.itemRoot.setTag(card.getId());
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.itemRoot.getLayoutParams();
if (mMultiCheckableMode) {
layoutParams.rightMargin = -60;
holder.itemRoot.setLayoutParams(layoutParams);
holder.stick.setVisibility(View.VISIBLE);
} else {
layoutParams.rightMargin = 0;
holder.itemRoot.setLayoutParams(layoutParams);
holder.stick.setVisibility(View.GONE);
}
holder.stick.setChecked(mSelectedPosition.contains(card.getId()));
// Timber.i("mSelectedPosition size " + mSelectedPosition.size() + "," + card.getId());
holder.stick.setOnClickListener(v -> {
if (mSelectedPosition.contains(card.getId())) {
mSelectedPosition.remove(card.getId());
mCheckedCards.remove(card);
} else {
mSelectedPosition.add(card.getId());
mCheckedCards.add(card);
}
mCallback.onItemSelect(mSelectedPosition.size());
});
// });
if (card.getCard().note().hasTag("marked")) {
holder.mark.setImageResource(R.mipmap.mark_star_normal);
// holder.mark.setVisibility(View.VISIBLE);
} else {
holder.mark.setImageResource(R.mipmap.note_star_unselected);
// holder.flag.setVisibility(View.GONE);
}
if (getFlagRes(card.getCard()) != -1) {
holder.flag.setImageResource(getFlagRes(card.getCard()));
// holder.flag.setVisibility(View.VISIBLE);
} else {
// holder.flag.setImageDrawable(mEmptyFlag);
holder.flag.setImageResource(R.mipmap.note_flag_unselected);
// holder.flag.setVisibility(View.GONE);
}
holder.mark.setOnClickListener(mMarkClickListener);
holder.flag.setOnClickListener(mSetFlagClickListener);
holder.itemRoot.setOnClickListener(mDeckClickListener);
holder.itemRoot.setOnLongClickListener(mDeckLongClickListener);
} else {
HeaderViewHolder holder = (HeaderViewHolder) tempHolder;
holder.cardsCount.setText(String.format("筛选出%d张卡片", getItemCount() - 1));
holder.cardsCount.setVisibility(isMultiCheckableMode() ? View.GONE : View.VISIBLE);
if (holder.order != null) {
holder.order.setOnClickListener(mIvOrderClickListener);
holder.orderText.setOnClickListener(mTvOrderClickListener);
holder.orderText.setText(mOrderName);
holder.order.setSelected(mAsc);
}
}
}
use of com.ichi2.anki.CardBrowser.Column.QUESTION in project AnkiChinaAndroid by ankichinateam.
the class CardTemplateEditorTest method testDeleteTemplateWithSelectivelyGeneratedCards.
/**
* In a model with two card templates using different fields, some notes may only use card 1,
* and some may only use card 2. If you delete the 2nd template,
* it will cause the notes that only use card 2 to disappear.
*
* So the unit test would then be to make a model like the "basic (optional reverse card)"
* with two fields Enable1 and Enable2, and two templates "card 1" and "card 2".
* Both cards use selective generation, so they're empty unless the corresponding field is set.
*
* So then in the unit test you make the model, add the two templates, then you add two notes,
* with Enable1 and Enable2 respectively set to "y".
* Then you try to delete one of the templates and it should fail
*
* (question: but I thought deleting one should work - still one card left to maintain the note,
* and second template delete should fail since we finally get to a place where no cards are left?
* I am having trouble creating selectively generated cards though - I can do one optional field but not 2 ugh)
*/
@Test
public void testDeleteTemplateWithSelectivelyGeneratedCards() {
String modelName = "Basic (optional reversed card)";
Model collectionBasicModelOriginal = getCurrentDatabaseModelCopy(modelName);
// Start the CardTemplateEditor with a specific model, and make sure the model starts unchanged
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("modelId", collectionBasicModelOriginal.getLong("id"));
ActivityController<CardTemplateEditor> templateEditorController = Robolectric.buildActivity(CardTemplateEditor.class, intent).create().start().resume().visible();
saveControllerForCleanup(templateEditorController);
CardTemplateEditor testEditor = (CardTemplateEditor) templateEditorController.get();
Assert.assertFalse("Model should not have changed yet", testEditor.modelHasChanged());
Assert.assertEquals("Model should have 2 templates now", 2, testEditor.getTempModel().getTemplateCount());
Assert.assertFalse("Ordinal pending add?", TemporaryModel.isOrdinalPendingAdd(testEditor.getTempModel(), 0));
Assert.assertFalse("Ordinal pending add?", TemporaryModel.isOrdinalPendingAdd(testEditor.getTempModel(), 1));
// Try to delete Card 1 template - click delete, check confirm for card delete popup indicating it was possible, then dismiss it
ShadowActivity shadowTestEditor = shadowOf(testEditor);
Assert.assertTrue("Unable to click?", shadowTestEditor.clickMenuItem(R.id.action_delete));
advanceRobolectricLooper();
Assert.assertEquals("Wrong dialog shown?", "Delete the “Card 1” card type, and its 0 cards?", getDialogText(true));
clickDialogButton(DialogAction.NEGATIVE, true);
advanceRobolectricLooper();
Assert.assertFalse("Model should not have changed", testEditor.modelHasChanged());
// Create note with forward and back info, Add Reverse is empty, so should only be one card
Note selectiveGeneratedNote = getCol().newNote(collectionBasicModelOriginal);
selectiveGeneratedNote.setField(0, "TestFront");
selectiveGeneratedNote.setField(1, "TestBack");
String[] fields = selectiveGeneratedNote.getFields();
for (String field : fields) {
Timber.d("Got a field: %s", field);
}
getCol().addNote(selectiveGeneratedNote);
Assert.assertEquals("selective generation should result in one card", 1, getModelCardCount(collectionBasicModelOriginal));
// Try to delete the template again, but there's selective generation means it would orphan the note
Assert.assertTrue("Unable to click?", shadowTestEditor.clickMenuItem(R.id.action_delete));
advanceRobolectricLooper();
Assert.assertEquals("Did not show dialog about deleting only card?", getResourceString(R.string.card_template_editor_would_delete_note), getDialogText(true));
clickDialogButton(DialogAction.POSITIVE, true);
advanceRobolectricLooper();
Assert.assertNull("Can delete used template?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 0 }));
Assert.assertEquals("Change already in database?", collectionBasicModelOriginal.toString().trim(), getCurrentDatabaseModelCopy(modelName).toString().trim());
Assert.assertFalse("Ordinal pending add?", TemporaryModel.isOrdinalPendingAdd(testEditor.getTempModel(), 0));
Assert.assertEquals("Change incorrectly added to list?", 0, testEditor.getTempModel().getTemplateChanges().size());
// Assert can delete 'Card 2'
Assert.assertNotNull("Cannot delete unused template?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 1 }));
// Edit note to have Add Reverse set to 'y' so we get a second card
selectiveGeneratedNote.setField(2, "y");
selectiveGeneratedNote.flush();
// - assert two cards
Assert.assertEquals("should be two cards now", 2, getModelCardCount(collectionBasicModelOriginal));
// - assert can delete either Card template but not both
Assert.assertNotNull("Cannot delete template?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 0 }));
Assert.assertNotNull("Cannot delete template?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 1 }));
Assert.assertNull("Can delete both templates?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 0, 1 }));
// A couple more notes to make sure things are okay
Note secondNote = getCol().newNote(collectionBasicModelOriginal);
secondNote.setField(0, "TestFront2");
secondNote.setField(1, "TestBack2");
secondNote.setField(2, "y");
getCol().addNote(secondNote);
// - assert can delete either Card template but not both
Assert.assertNotNull("Cannot delete template?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 0 }));
Assert.assertNotNull("Cannot delete template?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 1 }));
Assert.assertNull("Can delete both templates?", getCol().getModels().getCardIdsForModel(collectionBasicModelOriginal.getLong("id"), new int[] { 0, 1 }));
}
use of com.ichi2.anki.CardBrowser.Column.QUESTION in project AnkiChinaAndroid by ankichinateam.
the class ModelTest method test_chained_mods.
@Test
public void test_chained_mods() throws ConfirmModSchemaException {
Collection col = getCol();
col.getModels().setCurrent(col.getModels().byName("Cloze"));
Model m = col.getModels().current();
Models mm = col.getModels();
// We replace the default Cloze template
JSONObject t = Models.newTemplate("ChainedCloze");
t.put("qfmt", "{{cloze:text:Text}}");
t.put("afmt", "{{cloze:text:Text}}");
mm.addTemplateModChanged(m, t);
mm.save(m);
col.getModels().remTemplate(m, m.getJSONArray("tmpls").getJSONObject(0));
Note note = col.newNote();
String q1 = "<span style=\"color:red\">phrase</span>";
String a1 = "<b>sentence</b>";
String q2 = "<span style=\"color:red\">en chaine</span>";
String a2 = "<i>chained</i>";
note.setItem("Text", "This {{c1::" + q1 + "::" + a1 + "}} demonstrates {{c1::" + q2 + "::" + a2 + "}} clozes.");
assertEquals(1, col.addNote(note));
String question = note.cards().get(0).q();
/* TODO: chained modifier
assertThat("Question «"+question+"» does not contain the expected string", question, containsString("This <span class=cloze>[sentence]</span> demonstrates <span class=cloze>[chained]</span> clozes.")
);
assertThat(note.cards().get(0).a(), containsString("This <span class=cloze>phrase</span> demonstrates <span class=cloze>en chaine</span> clozes."
));
*/
}
use of com.ichi2.anki.CardBrowser.Column.QUESTION in project Anki-Android by ankidroid.
the class AbstractFlashcardViewer method displayCardQuestion.
protected void displayCardQuestion(boolean reload) {
Timber.d("displayCardQuestion()");
sDisplayAnswer = false;
mBackButtonPressedToReturn = false;
setInterface();
mTypeAnswer.setInput("");
mTypeAnswer.updateInfo(mCurrentCard, getResources());
if (!mCurrentCard.isEmpty() && mTypeAnswer.validForEditText()) {
// Show text entry based on if the user wants to write the answer
mAnswerField.setVisibility(View.VISIBLE);
LanguageHintService.applyLanguageHint(mAnswerField, mTypeAnswer.getLanguageHint());
} else {
mAnswerField.setVisibility(View.GONE);
}
CardHtml content = mHtmlGenerator.generateHtml(mCurrentCard, reload, Side.FRONT);
updateCard(content);
hideEaseButtons();
mAutomaticAnswer.onDisplayQuestion();
// If Card-based TTS is enabled, we "automatic display" after the TTS has finished as we don't know the duration
if (!mTTS.isEnabled()) {
mAutomaticAnswer.scheduleAutomaticDisplayAnswer(mUseTimerDynamicMS);
}
Timber.i("AbstractFlashcardViewer:: Question successfully shown for card id %d", mCurrentCard.getId());
}
Aggregations