public void OnCompleted(int task, int splitLineIndex, string pastedText, List <List <object> > tempLines, int curPos, long tempStartPos, long tempEndPos, bool isRemaining, List <Bookmark> foundBookmarks) { try { foreach (List <object> line in tempLines) { object lastWord = null; foreach (object word in line) { if (lastWord != null && (lastWord is int || lastWord.GetType() != word.GetType())) { dumpFileWriter.BaseStream.WriteByte(Convert.ToByte(" ")); } if (word is string) { if (((string)word).Length == 0) { dumpFileWriter.BaseStream.WriteByte(Convert.ToByte("\n\r")); } else { dumpFileWriter.BaseStream.WriteByte(Convert.ToByte((string)word)); } } else { dumpFileWriter.BaseStream.WriteByte(Convert.ToByte(Dict.PinyinToTones(Dict.GetPinyin((int)word)))); } lastWord = word; } } if (isRemaining && !dumpCancelled) { int progress = (int)Math.Round((double)tempEndPos * 100 / Activity.textLen); dumpProgress.Progress = progress; dumpProgressText.Text = Convert.ToString(progress) + "%"; Activity.DumpPinyin((int)tempStartPos, tempEndPos); } else { dumpFileWriter.Flush(); dumpFileWriter.Close(); dumpStartButton.Enabled = true; dumpProgress.Visibility = ViewStates.Gone; dumpProgressText.Visibility = ViewStates.Gone; Toast.MakeText(Activity.Application, "Saved to " + dumpFilePath, ToastLength.Long).Show(); } } catch (Exception e) { Toast.MakeText(Activity.Application, e.Message, ToastLength.Long).Show(); } }
public int GetWordWidth(object word) { if (pinyinPaint == null) { Init(); } if (word is string) { Regex rx = new Regex(@"[^\w]*"); if (!rx.IsMatch((string)word)) { charPaint.SetTypeface(Typeface.Default); } else { charPaint.SetTypeface(charTypeface); } float wordWidth = charPaint.MeasureText((string)word); return((int)Math.Round(wordWidth)); } else { charPaint.SetTypeface(charTypeface); int entry = (int)word; if (pinyinType.Equals("none")) { string key = Dict.GetCh(entry); charPaint.GetTextBounds(key, 0, key.Length, charBounds); return(charBounds.Width() + hMargin * 2); } else { string pinyin = Dict.PinyinToTones(Dict.GetPinyin(entry)), key = Dict.GetCh(entry); pinyinPaint.GetTextBounds(pinyin, 0, pinyin.Length, pinyinBounds); charPaint.GetTextBounds(key, 0, key.Length, charBounds); return(Math.Max(pinyinBounds.Width(), charBounds.Width()) + hMargin * 2); } } }
public void OnCompleted(int task, int splitLineIndex, string pastedText, List <List <object> > tempLines, int curPos, long tempStartPos, long tempEndPos, bool isRemaining, List <Bookmark> foundBookmarks) { StringBuilder pinyin = new StringBuilder(""); RemoteViews smallView = null; if (Build.VERSION.SdkInt < BuildVersionCodes.JellyBean) { foreach (List <object> line in tempLines) { object lastWord = null; foreach (object word in line) { if (lastWord != null && (lastWord is int? || lastWord.GetType() != word.GetType())) { pinyin.Append(" "); } if (word is string) { pinyin.Append((string)word); } else { pinyin.Append(Dict.PinyinToTones(Dict.GetPinyin((int)word))); } lastWord = word; } } smallView = new RemoteViews(Service.PackageName, Resource.Layout.Notification_Small); smallView.SetTextViewText(Resource.Id.notifsmall_text, pinyin); } else { smallView = new RemoteViews(Service.PackageName, Resource.Layout.Notification_Big); } Service.dict = null; NotificationCompat.Builder mBuilder = (new NotificationCompat.Builder(Service.ApplicationContext)) .SetSmallIcon(Resource.Drawable.notification) .SetContentTitle("ChineseReader") .SetContentText(pinyin) .SetContent(smallView) .SetPriority(NotificationCompat.PriorityMax) .SetVibrate(new long[0]); Intent resultIntent = new Intent(Service.Application, typeof(MainActivity)); resultIntent.SetAction(Intent.ActionSend); resultIntent.SetType("text/plain"); resultIntent.PutExtra(Intent.ExtraText, pastedText); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. global::Android.Support.V4.App.TaskStackBuilder stackBuilder = global::Android.Support.V4.App.TaskStackBuilder.Create(Service.ApplicationContext); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.AddParentStack(Class.FromType(typeof(MainActivity))); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.AddNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent); mBuilder.SetContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager)Service.GetSystemService(Context.NotificationService); mNotificationManager.CancelAll(); // mId allows you to update the notification_big later on. Notification notif = mBuilder.Build(); if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean) { LineView lv = new LineView(Service.context); lv.line = tempLines[0]; lv.lines = tempLines; lv.hlIndex = new Point(-1, -1); lv.top = new List <string>(); lv.bottom = new List <string>(); lv.tones = new List <int>(); lv.charTypeface = Typeface.Default; int wordHeight = (int)(lv.WordHeight); int lineCount = (int)System.Math.Min(tempLines.Count, System.Math.Floor(256 * lv.scale / wordHeight) + 1); int width = (int)System.Math.Round((double)AnnTask.screenWidth); lv.Measure(width, wordHeight); lv.Layout(0, 0, width, wordHeight); Bitmap bitmap = Bitmap.CreateBitmap(width, (int)System.Math.Min(System.Math.Max(64 * lv.scale, wordHeight * lineCount), 256 * lv.scale), Bitmap.Config.Argb8888); Canvas canvas = new Canvas(bitmap); Paint whiteBg = new Paint(); whiteBg.Color = Color.ParseColor("FFFFFFFF"); canvas.DrawRect(0, 0, canvas.Width, canvas.Height, whiteBg); for (int i = 0; i < lineCount; i++) { lv.lines = tempLines; lv.line = tempLines[i]; lv.bottom.Clear(); lv.top.Clear(); lv.tones.Clear(); int count = lv.lines[i].Count; if (count == 0 || lv.line[count - 1] is string && ((string)lv.line[count - 1]).Length == 0 || tempEndPos >= pastedText.Length && i == tempLines.Count - 1) { lv.lastLine = true; } else { lv.lastLine = false; } for (int j = 0; j < count; j++) { object word = lv.lines[i][j]; if (word is string) { lv.bottom.Add((string)word); lv.top.Add(""); lv.tones.Add(0); } else { int entry = (int)word; string key = Dict.GetCh(entry); lv.bottom.Add(key); if (Service.sharedPrefs.GetString("pref_pinyinType", "marks").Equals("none")) { lv.top.Add(""); } else { lv.top.Add(Dict.PinyinToTones(Dict.GetPinyin(entry))); } if (Service.sharedPrefs.GetString("pref_toneColors", "none").Equals("none")) { lv.tones.Add(0); } else { int tones = int.Parse(Regex.Replace(Dict.GetPinyin(entry), @"[\\D]", "")); int reverseTones = 0; while (tones != 0) { reverseTones = reverseTones * 10 + tones % 10; tones = tones / 10; } lv.tones.Add(reverseTones); } } } lv.Draw(canvas); canvas.Translate(0, wordHeight); } RemoteViews bigView = new RemoteViews(Service.PackageName, Resource.Layout.Notification_Big); bigView.SetImageViewBitmap(Resource.Id.notif_img, bitmap); smallView.SetImageViewBitmap(Resource.Id.notif_img, Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, (int)(64 * lv.scale))); notif.BigContentView = bigView; } mNotificationManager.Notify(NOTIFICATION_ID, notif); }
public virtual void show(View anchor, List <object> line, int wordNum, int showX, bool redraw) { try { this.showX = showX; if (redraw) { this.dismiss(); } if (line != null) { this.line = line; this.wordIndex = wordNum; this.entry = (int)line[wordNum]; splitButton.Visibility = ViewStates.Visible; bookmarkButton.Visibility = ViewStates.Visible; } else { this.entry = wordNum; splitButton.Visibility = ViewStates.Gone; bookmarkButton.Visibility = ViewStates.Gone; } string sTrad = Dict.GetCh(entry, "traditional"); string sSimp = Dict.GetCh(entry, "simplified"); SpannableStringBuilder text = new SpannableStringBuilder(); if (sSimp.Length > 1) { List <object> subWords = BreakWord(sSimp); foreach (object word in subWords) { if (word is int) { //was found string ch = Dict.GetCh((int)word, "simplified"); text.Append(ch).Append(new Java.Lang.String(" ")); WordSpan clickable = new WordSpan(this); clickable.link = ch; text.SetSpan(clickable, text.Length() - ch.Length - 1, text.Length() - 1, SpanTypes.User); } else { text.Append((string)word).Append(new Java.Lang.String(" ")); } } } else { text.Append(sSimp).Append(new Java.Lang.String(" ")); text.SetSpan(new AbsoluteSizeSpan(24, true), text.Length() - sSimp.Length - 1, text.Length() - 1, SpanTypes.User); splitButton.Visibility = ViewStates.Gone; } if (!sTrad.Equals(sSimp)) { text.Append(sTrad); } mChars.SetText(text, TextView.BufferType.Spannable); text.Clear(); string pinyin = Dict.PinyinToTones(Dict.GetPinyin(entry)); text.Append("[ ").Append(new Java.Lang.String(pinyin)).Append(new Java.Lang.String(" ] ")); appendInlineButtons(text, pinyin); text.Append("\n"); string[] parts = Regex.Split(Regex.Replace(Dict.GetEnglish(entry), @"/", "\n• "), @"\\$"); int i = 0; foreach (string s in parts) { if (i++ % 2 == 1) { pinyin = Dict.PinyinToTones(s); text.Append("\n\n[ ").Append(new Java.Lang.String(pinyin)).Append(new Java.Lang.String(" ] ")); appendInlineButtons(text, pinyin); text.Append("\n"); } else { text.Append("• "); int beforeAppended = text.Length(); int bracketIndex, bracketEnd = 0; while ((bracketIndex = s.IndexOf("[", bracketEnd, StringComparison.Ordinal)) > -1) { text.Append(s, bracketEnd, bracketIndex); bracketEnd = s.IndexOf("]", bracketIndex); text.Append(Dict.PinyinToTones(s.SubstringSpecial(bracketIndex, bracketEnd))); } text.Append(s, bracketEnd, s.Length); int afterAppended = text.Length(); for (int m = beforeAppended; m < afterAppended; m++) { if (text.CharAt(m) >= '\u25CB' && text.CharAt(m) <= '\u9FA5') { int n = m + 1; while (n < text.Length() && text.CharAt(n) >= '\u25CB' && text.CharAt(n) <= '\u9FA5') { n++; } WordSpan clickable = new WordSpan(this); clickable.link = text.SubSequence(m, n - m).ToString(); text.SetSpan(clickable, m, n, SpanTypes.User); } } } } mContent.SetText(text, TextView.BufferType.Spannable); LinearLayout bookmarkTitleLayout = (LinearLayout)mRootView.FindViewById(Resource.Id.bookmark); if (mContext.annoMode != AnnotationActivity.ANNOTATE_FILE) { bookmarkButton.Visibility = ViewStates.Gone; bookmarkTitleLayout.Visibility = ViewStates.Gone; } else { int lineNum = mContext.lines.IndexOf(line); long bookmarkPos = mContext.GetPosition(mContext.lines, lineNum + 1, wordIndex, true); int bookmarksPos = Bookmark.SearchClosest(bookmarkPos, mContext.mBookmarks); bool isBookmarked = mContext.mBookmarks.Count > bookmarksPos && mContext.mBookmarks[bookmarksPos].mPosition == bookmarkPos; ToggleBookmark(bookmarkButton, isBookmarked); if (isBookmarked) { bookmarkTitleLayout.Visibility = ViewStates.Visible; ((TextView)mRootView.FindViewById(Resource.Id.bookmarkTitle)).Text = mContext.mBookmarks[bookmarksPos].mTitle; } else { bookmarkTitleLayout.Visibility = ViewStates.Gone; } } ToggleStar(null, AnnotationActivity.sharedPrefs.GetString("stars", "").StartsWith(Dict.GetCh(entry, "simplified") + "\n") || AnnotationActivity.sharedPrefs.GetString("stars", "").Contains("\n" + Dict.GetCh(entry, "simplified") + "\n")); this.parent = anchor; float xPos = 0, yPos = 0, arrowPos; int[] location = new int[2]; anchor.GetLocationOnScreen(location); Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.Width, location[1] + anchor.Height); if (redraw) { mWindow.ShowAtLocation(anchor, GravityFlags.NoGravity, 0, 0); } mBubble.Measure(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); float rootHeight = mBubble.MeasuredHeight; float rootWidth = mBubble.MeasuredWidth; xPos = showX - (rootWidth / 2); if ((xPos + rootWidth) > screenX) { xPos = screenX - rootWidth; } else if (xPos < 0) { xPos = 0; } arrowPos = showX - xPos; float dyTop = anchorRect.Top - 60 * scale; float dyBottom = screenY - anchorRect.Bottom - 20 * scale; bool onTop = dyBottom <rootHeight && dyTop> dyBottom; if (onTop) { if (rootHeight + 20 * scale > dyTop) { yPos = 60 * scale; rootHeight = anchorRect.Top - yPos - 20 * scale; } else { yPos = anchorRect.Top - rootHeight - 20 * scale; } } else { yPos = anchorRect.Bottom; if (rootHeight > dyBottom) { rootHeight = dyBottom; } } showArrow((onTop ? Resource.Id.arrow_down : Resource.Id.arrow_up), arrowPos, rootWidth); mWindow.Update((int)Math.Round(xPos), (int)Math.Round(yPos), (int)Math.Round(rootWidth), (int)Math.Round(rootHeight + 21 * scale)); mScroll.FullScroll(FocusSearchDirection.Up); } catch (Exception e) { Toast.MakeText(mContext, "Error: " + e.Message, ToastLength.Long).Show(); } }
private void BookmarkButton_Click(object sender, EventArgs e) { int lineNum = mContext.lines.IndexOf(line); long bookmarkPos = mContext.GetPosition(mContext.lines, lineNum + 1, wordIndex, true); int bookmarksPos = Bookmark.SearchClosest(bookmarkPos, mContext.mBookmarks); if (mContext.mBookmarks.Count > bookmarksPos && mContext.mBookmarks[bookmarksPos].mPosition == bookmarkPos) { mContext.mBookmarks.RemoveAt(bookmarksPos); if (!Bookmark.SaveToFile(mContext.mBookmarks, mContext.curFilePath + ".bookmarks")) { Toast.MakeText(mContext, "Bookmarks could not be stored. File location is not writable.", ToastLength.Long).Show(); } int foundBookmarksPos = Bookmark.SearchClosest(bookmarkPos, mContext.mFoundBookmarks); if (mContext.mFoundBookmarks.Count > foundBookmarksPos && mContext.mFoundBookmarks[foundBookmarksPos].mPosition == bookmarkPos) { mContext.mFoundBookmarks.RemoveAt(foundBookmarksPos); } mContext.linesAdapter.NotifyItemChanged(lineNum + 1); show(mContext.linesLayoutManager.FindViewByPosition(lineNum + 1), line, wordIndex, showX, false); } else { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.SetTitle("New bookmark"); EditText inputBookmark = new EditText(mContext); inputBookmark.InputType = InputTypes.TextFlagCapSentences; inputBookmark.Text = Dict.PinyinToTones(Dict.GetPinyin(entry)); inputBookmark.SelectAll(); builder.SetView(inputBookmark); builder.SetCancelable(true); builder.SetPositiveButton("OK", delegate { try { int lineNum1 = mContext.lines.IndexOf(line); long bookmarkPos1 = mContext.GetPosition(mContext.lines, lineNum1 + 1, wordIndex, true); int bookmarksPos1 = Bookmark.SearchClosest(bookmarkPos1, mContext.mBookmarks); int foundBookmarksPos1 = Bookmark.SearchClosest(bookmarkPos1, mContext.mFoundBookmarks); Bookmark newBookmark = new Bookmark(bookmarkPos1, inputBookmark.Text.ToString()); newBookmark.SetAnnotatedPosition(lineNum1, wordIndex); mContext.mFoundBookmarks.Insert(foundBookmarksPos1, newBookmark); mContext.mBookmarks.Insert(bookmarksPos1, newBookmark); if (!Bookmark.SaveToFile(mContext.mBookmarks, mContext.curFilePath + ".bookmarks")) { Toast.MakeText(mContext, "Bookmarks could not be stored. File location is not writable.", ToastLength.Long).Show(); } mContext.linesAdapter.NotifyItemChanged(lineNum1 + 1); show(mContext.linesLayoutManager.FindViewByPosition(lineNum1 + 1), line, wordIndex, showX, false); } catch (FormatException) { Toast.MakeText(mContext, "", ToastLength.Long).Show(); } }); builder.SetNegativeButton("Cancel", delegate { }); AlertDialog dialog = builder.Create(); dialog.Window.SetSoftInputMode(SoftInput.StateVisible); dialog.Show(); } }
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder is LineViewHolder) { List <object> line = mLines[position - 1]; LineView curView = ((LineViewHolder)holder).mLineView; curView.line = line; curView.lines = mLines; curView.hlIndex = context.hlIndex; curView.bookmarks.Clear(); if (context.mFoundBookmarks.Count > 0) { for (int i = 0; i < line.Count; i++) { Bookmark itsBookmark = Bookmark.SearchAnnotated(position - 1, i, context.mFoundBookmarks); if (itsBookmark != null) { curView.bookmarks.Add(itsBookmark); } else { curView.bookmarks.Add(null); } } } if (curView.top == null) { curView.top = new List <string>(); } else { curView.top.Clear(); } if (curView.bottom == null) { curView.bottom = new List <string>(); } else { curView.bottom.Clear(); } if (curView.tones == null) { curView.tones = new List <int>(); } else { curView.tones.Clear(); } int count = line.Count; for (int i = 0; i < count; i++) { var word = line[i]; if (word is string) { curView.bottom.Add((string)word); curView.top.Add(""); curView.tones.Add(0); } else { int entry = (int)word; string key = Dict.GetCh(entry); curView.bottom.Add(key); if (AnnotationActivity.sharedPrefs.GetString("pref_pinyinType", "marks").Equals("none")) { curView.top.Add(""); } else { curView.top.Add(Dict.PinyinToTones(Dict.GetPinyin(entry))); } if (AnnotationActivity.sharedPrefs.GetString("pref_toneColors", "none").Equals("none")) { curView.tones.Add(0); } else { int tones = int.Parse(Regex.Replace(Dict.GetPinyin(entry), @"[\d]", "")); int reverseTones = 0; while (tones != 0) { reverseTones = reverseTones * 10 + tones % 10; tones = tones / 10; } curView.tones.Add(reverseTones); } } } if (count == 0 || line[count - 1] is string && ((string)line[count - 1]).Length == 0 || context.endPos >= context.textLen && position - 1 == ItemCount - 3) { curView.lastLine = true; } else { curView.lastLine = false; } curView.UpdateVars(); } else { if (position == 0 && ShowHeader || position == mLines.Count + 1 && ShowFooter) { ((ProgressViewHolder)holder).progressBar.Visibility = ViewStates.Visible; } else { ((ProgressViewHolder)holder).progressBar.Visibility = ViewStates.Gone; } } }
public void StarredExport(int exportId) { string stars = sharedPrefs.GetString("stars", ""); if (stars == null || stars.Length < 2) { Toast.MakeText(this, "Starred list is empty. Nothing to export.", ToastLength.Long).Show(); return; } System.Random random = new System.Random(); SQLiteDatabase db = OpenOrCreateDatabase("anki.db", FileCreationMode.Private, null); string[] commands = Regex.Split(GetString(Resource.String.anki_scheme), ";;"); foreach (string command in commands) { db.ExecSQL(command); } int oldIndex = 0; int nIndex; while ((nIndex = stars.IndexOf("\n", oldIndex)) > -1) { int entry = Dict.BinarySearch(stars.SubstringSpecial(oldIndex, nIndex), false); oldIndex = nIndex + 1; if (entry == -1) { continue; } string id = Convert.ToString(Math.Abs(random.Next())), uuid = UUID.RandomUUID().ToString().SubstringSpecial(0, 10); StringBuilder english = new StringBuilder(); if (exportId == Resource.Id.menu_starred_export_pinyin) { english.Append(Dict.PinyinToTones(Dict.GetPinyin(entry))).Append("<br/>"); } english.Append(Dict.GetCh(entry)).Append("\u001F"); if (exportId == Resource.Id.menu_starred_export) { english.Append("[ ").Append(Dict.PinyinToTones(Dict.GetPinyin(entry))).Append(" ]<br/>"); } string[] parts = Regex.Split(Regex.Replace(Dict.GetEnglish(entry), @"/", "<br/>• "), @"\\$"); int j = 0; foreach (string str in parts) { if (j++ % 2 == 1) { english.Append("<br/><br/>[ ").Append(Dict.PinyinToTones(str)).Append(" ]<br/>"); } else { english.Append("• "); int bracketIndex, bracketEnd = 0; while ((bracketIndex = str.IndexOf("[", bracketEnd)) > -1) { english.Append(str, bracketEnd, bracketIndex); bracketEnd = str.IndexOf("]", bracketIndex); english.Append(Dict.PinyinToTones(str.SubstringSpecial(bracketIndex, bracketEnd))); } english.Append(str, bracketEnd, str.Length); } } db.ExecSQL("insert into notes values(?, ?, 1399962367564, 1400901624, -1, '', ?, 0, 147133787, 0, '')", new Java.Lang.Object[] { id, uuid, english.ToString() }); db.ExecSQL("insert into cards values(?, ?, 1400901287521, 0, 1400901624, -1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, '')", new Java.Lang.Object[] { Convert.ToString(random.Next()), id }); } db.Close(); try { File dir = new File(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "/AnkiDroid"); if (!dir.Exists()) { dir = new File(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "/ChineseReader"); } dir.Mkdirs(); System.IO.Stream fos = new System.IO.FileStream(dir.AbsolutePath + "/chinesereader_starred.apkg", System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.Stream fiz = new System.IO.FileStream(GetDatabasePath("anki.db").Path, System.IO.FileMode.Open, System.IO.FileAccess.Read); ZipOutputStream zos = new ZipOutputStream(fos); zos.PutNextEntry(new ZipEntry("collection.anki2")); byte[] buffer = new byte[1024]; int readLen = 0; while ((readLen = fiz.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, readLen); } zos.CloseEntry(); zos.PutNextEntry(new ZipEntry("media")); buffer[0] = 0x7b; buffer[1] = 0x7d; zos.Write(buffer, 0, 2); zos.CloseEntry(); zos.Flush(); zos.Close(); fiz.Close(); fos.Flush(); fos.Close(); Toast.MakeText(this, "Successfully exported to " + dir.AbsolutePath + "/chinesereader_starred.apkg", ToastLength.Long).Show(); } catch (Exception e) { Toast.MakeText(this, "Could not export: " + e.Message, ToastLength.Long).Show(); } }