|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: 2021-2026 NewPipe contributors <https://newpipe.net> |
| 3 | + * SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | + */ |
| 5 | + |
| 6 | +package org.schabi.newpipe.util |
| 7 | + |
| 8 | +import android.text.Selection |
| 9 | +import android.text.Spannable |
| 10 | +import android.widget.TextView |
| 11 | +import org.schabi.newpipe.util.external_communication.ShareUtils |
| 12 | + |
| 13 | +object NewPipeTextViewHelper { |
| 14 | + /** |
| 15 | + * Share the selected text of [NewPipeTextViews][org.schabi.newpipe.views.NewPipeTextView] and |
| 16 | + * [NewPipeEditTexts][org.schabi.newpipe.views.NewPipeEditText] with |
| 17 | + * [ShareUtils.shareText]. |
| 18 | + * |
| 19 | + * |
| 20 | + * |
| 21 | + * This allows EMUI users to get the Android share sheet instead of the EMUI share sheet when |
| 22 | + * using the `Share` command of the popup menu which appears when selecting text. |
| 23 | + * |
| 24 | + * |
| 25 | + * @param textView the [TextView] on which sharing the selected text. It should be a |
| 26 | + * [org.schabi.newpipe.views.NewPipeTextView] or a [org.schabi.newpipe.views.NewPipeEditText] |
| 27 | + * (even if [standard TextViews][TextView] are supported). |
| 28 | + */ |
| 29 | + @JvmStatic |
| 30 | + fun shareSelectedTextWithShareUtils(textView: TextView) { |
| 31 | + val textViewText = textView.getText() |
| 32 | + shareSelectedTextIfNotNullAndNotEmpty(textView, getSelectedText(textView, textViewText)) |
| 33 | + if (textViewText is Spannable) { |
| 34 | + Selection.setSelection(textViewText, textView.selectionEnd) |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private fun getSelectedText(textView: TextView, text: CharSequence?): CharSequence? { |
| 39 | + if (!textView.hasSelection() || text == null) { |
| 40 | + return null |
| 41 | + } |
| 42 | + |
| 43 | + val start = textView.selectionStart |
| 44 | + val end = textView.selectionEnd |
| 45 | + return if (start > end) { |
| 46 | + text.subSequence(end, start) |
| 47 | + } else { |
| 48 | + text.subSequence(start, end) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private fun shareSelectedTextIfNotNullAndNotEmpty( |
| 53 | + textView: TextView, |
| 54 | + selectedText: CharSequence? |
| 55 | + ) { |
| 56 | + if (!selectedText.isNullOrEmpty()) { |
| 57 | + ShareUtils.shareText(textView.getContext(), "", selectedText.toString()) |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments