PreviewTextFileFragment.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. *
  3. * Nextcloud Android client application
  4. *
  5. * @author Tobias Kaminsky
  6. * Copyright (C) 2019 Tobias Kaminsky
  7. * Copyright (C) 2019 Nextcloud GmbH
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. package com.owncloud.android.ui.preview;
  23. import android.accounts.Account;
  24. import android.os.AsyncTask;
  25. import android.os.Bundle;
  26. import android.os.Handler;
  27. import android.view.Menu;
  28. import android.view.MenuInflater;
  29. import android.view.MenuItem;
  30. import android.view.View;
  31. import android.widget.TextView;
  32. import com.nextcloud.client.account.UserAccountManager;
  33. import com.owncloud.android.R;
  34. import com.owncloud.android.datamodel.OCFile;
  35. import com.owncloud.android.files.FileMenuFilter;
  36. import com.owncloud.android.lib.common.utils.Log_OC;
  37. import com.owncloud.android.ui.activity.FileDisplayActivity;
  38. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  39. import com.owncloud.android.ui.dialog.RemoveFilesDialogFragment;
  40. import com.owncloud.android.utils.DisplayUtils;
  41. import com.owncloud.android.utils.MimeTypeUtil;
  42. import org.jetbrains.annotations.NotNull;
  43. import org.mozilla.universalchardet.ReaderFactory;
  44. import java.io.BufferedWriter;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.Reader;
  48. import java.io.StringWriter;
  49. import java.lang.ref.WeakReference;
  50. import java.util.LinkedList;
  51. import java.util.List;
  52. import java.util.Scanner;
  53. import javax.inject.Inject;
  54. import androidx.annotation.NonNull;
  55. import androidx.appcompat.widget.SearchView;
  56. import androidx.core.view.MenuItemCompat;
  57. public class PreviewTextFileFragment extends PreviewTextFragment {
  58. private static final String EXTRA_FILE = "FILE";
  59. private static final String EXTRA_ACCOUNT = "ACCOUNT";
  60. private static final String TAG = PreviewTextFileFragment.class.getSimpleName();
  61. private TextLoadAsyncTask textLoadAsyncTask;
  62. private Account account;
  63. @Inject UserAccountManager accountManager;
  64. /**
  65. * Creates an empty fragment for previews.
  66. * <p>
  67. * MUST BE KEPT: the system uses it when tries to re-instantiate a fragment automatically (for instance, when the
  68. * device is turned a aside).
  69. * <p>
  70. * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
  71. */
  72. public PreviewTextFileFragment() {
  73. super();
  74. account = null;
  75. }
  76. /**
  77. * {@inheritDoc}
  78. */
  79. @Override
  80. public void onCreate(Bundle savedInstanceState) {
  81. super.onCreate(savedInstanceState);
  82. setHasOptionsMenu(true);
  83. OCFile file = getFile();
  84. Bundle args = getArguments();
  85. if (file == null) {
  86. file = args.getParcelable(FileDisplayActivity.EXTRA_FILE);
  87. }
  88. if (account == null) {
  89. account = args.getParcelable(FileDisplayActivity.EXTRA_ACCOUNT);
  90. }
  91. if (args.containsKey(FileDisplayActivity.EXTRA_SEARCH_QUERY)) {
  92. mSearchQuery = args.getString(FileDisplayActivity.EXTRA_SEARCH_QUERY);
  93. }
  94. mSearchOpen = args.getBoolean(FileDisplayActivity.EXTRA_SEARCH, false);
  95. if (savedInstanceState == null) {
  96. if (file == null) {
  97. throw new IllegalStateException("Instanced with a NULL OCFile");
  98. }
  99. if (account == null) {
  100. throw new IllegalStateException("Instanced with a NULL ownCloud Account");
  101. }
  102. } else {
  103. file = savedInstanceState.getParcelable(EXTRA_FILE);
  104. account = savedInstanceState.getParcelable(EXTRA_ACCOUNT);
  105. }
  106. mHandler = new Handler();
  107. setFile(file);
  108. }
  109. /**
  110. * {@inheritDoc}
  111. */
  112. @Override
  113. public void onSaveInstanceState(@NonNull Bundle outState) {
  114. outState.putParcelable(PreviewTextFileFragment.EXTRA_FILE, getFile());
  115. outState.putParcelable(PreviewTextFileFragment.EXTRA_ACCOUNT, account);
  116. super.onSaveInstanceState(outState);
  117. }
  118. @Override
  119. void loadAndShowTextPreview() {
  120. textLoadAsyncTask = new TextLoadAsyncTask(new WeakReference<>(mTextPreview));
  121. textLoadAsyncTask.execute(getFile().getStoragePath());
  122. }
  123. /**
  124. * Reads the file to preview and shows its contents. Too critical to be anonymous.
  125. */
  126. private class TextLoadAsyncTask extends AsyncTask<Object, Void, StringWriter> {
  127. private static final int PARAMS_LENGTH = 1;
  128. private final WeakReference<TextView> mTextViewReference;
  129. private TextLoadAsyncTask(WeakReference<TextView> textView) {
  130. mTextViewReference = textView;
  131. }
  132. @Override
  133. protected void onPreExecute() {
  134. // not used at the moment
  135. }
  136. @Override
  137. protected StringWriter doInBackground(Object... params) {
  138. if (params.length != PARAMS_LENGTH) {
  139. throw new IllegalArgumentException("The parameter to " + TextLoadAsyncTask.class.getName()
  140. + " must be (1) the file location");
  141. }
  142. String location = (String) params[0];
  143. Scanner scanner = null;
  144. StringWriter source = new StringWriter();
  145. BufferedWriter bufferedWriter = new BufferedWriter(source);
  146. Reader reader = null;
  147. try {
  148. File file = new File(location);
  149. reader = ReaderFactory.createReaderFromFile(file);
  150. scanner = new Scanner(reader);
  151. while (scanner.hasNextLine()) {
  152. bufferedWriter.append(scanner.nextLine());
  153. if (scanner.hasNextLine()) {
  154. bufferedWriter.append("\n");
  155. }
  156. }
  157. bufferedWriter.close();
  158. IOException exc = scanner.ioException();
  159. if (exc != null) {
  160. throw exc;
  161. }
  162. } catch (IOException e) {
  163. Log_OC.e(TAG, e.getMessage(), e);
  164. finish();
  165. } finally {
  166. if (reader != null) {
  167. try {
  168. reader.close();
  169. } catch (IOException e) {
  170. Log_OC.e(TAG, e.getMessage(), e);
  171. finish();
  172. }
  173. }
  174. if (scanner != null) {
  175. scanner.close();
  176. }
  177. }
  178. return source;
  179. }
  180. @Override
  181. protected void onPostExecute(final StringWriter stringWriter) {
  182. final TextView textView = mTextViewReference.get();
  183. if (textView != null) {
  184. mOriginalText = stringWriter.toString();
  185. mSearchView.setOnQueryTextListener(PreviewTextFileFragment.this);
  186. setText(textView, mOriginalText, getFile(), requireActivity());
  187. if (mSearchOpen) {
  188. mSearchView.setQuery(mSearchQuery, true);
  189. }
  190. textView.setVisibility(View.VISIBLE);
  191. }
  192. if (mMultiView != null) {
  193. mMultiView.setVisibility(View.GONE);
  194. }
  195. }
  196. }
  197. /**
  198. * {@inheritDoc}
  199. */
  200. @Override
  201. public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
  202. super.onCreateOptionsMenu(menu, inflater);
  203. inflater.inflate(R.menu.item_file, menu);
  204. MenuItem menuItem = menu.findItem(R.id.action_search);
  205. menuItem.setVisible(true);
  206. mSearchView = (SearchView) MenuItemCompat.getActionView(menuItem);
  207. mSearchView.setMaxWidth(Integer.MAX_VALUE);
  208. if (mSearchOpen) {
  209. mSearchView.setIconified(false);
  210. mSearchView.setQuery(mSearchQuery, false);
  211. mSearchView.clearFocus();
  212. }
  213. }
  214. /**
  215. * {@inheritDoc}
  216. */
  217. @Override
  218. public void onPrepareOptionsMenu(@NotNull Menu menu) {
  219. super.onPrepareOptionsMenu(menu);
  220. if (containerActivity.getStorageManager() != null) {
  221. Account currentAccount = containerActivity.getStorageManager().getAccount();
  222. FileMenuFilter mf = new FileMenuFilter(
  223. getFile(),
  224. currentAccount,
  225. containerActivity,
  226. getActivity(),
  227. false,
  228. deviceInfo,
  229. accountManager.getUser()
  230. );
  231. mf.filter(menu,
  232. true,
  233. accountManager.isMediaStreamingSupported(currentAccount));
  234. }
  235. // additional restriction for this fragment
  236. FileMenuFilter.hideMenuItems(
  237. menu.findItem(R.id.action_rename_file),
  238. menu.findItem(R.id.action_select_all),
  239. menu.findItem(R.id.action_move),
  240. menu.findItem(R.id.action_download_file),
  241. menu.findItem(R.id.action_sync_file),
  242. menu.findItem(R.id.action_sync_account),
  243. menu.findItem(R.id.action_favorite),
  244. menu.findItem(R.id.action_unset_favorite)
  245. );
  246. Boolean dualPane = getResources().getBoolean(R.bool.large_land_layout);
  247. if (!dualPane) {
  248. FileMenuFilter.hideMenuItems(menu.findItem(R.id.action_switch_view),
  249. menu.findItem(R.id.action_sort)
  250. );
  251. }
  252. if (getFile().isSharedWithMe() && !getFile().canReshare()) {
  253. FileMenuFilter.hideMenuItem(menu.findItem(R.id.action_send_share_file));
  254. }
  255. }
  256. /**
  257. * {@inheritDoc}
  258. */
  259. @Override
  260. public boolean onOptionsItemSelected(MenuItem item) {
  261. switch (item.getItemId()) {
  262. case R.id.action_send_share_file: {
  263. if (getFile().isSharedWithMe() && !getFile().canReshare()) {
  264. DisplayUtils.showSnackMessage(getView(), R.string.resharing_is_not_allowed);
  265. } else {
  266. containerActivity.getFileOperationsHelper().sendShareFile(getFile());
  267. }
  268. return true;
  269. }
  270. case R.id.action_open_file_with: {
  271. openFile();
  272. return true;
  273. }
  274. case R.id.action_remove_file: {
  275. RemoveFilesDialogFragment dialog = RemoveFilesDialogFragment.newInstance(getFile());
  276. dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
  277. return true;
  278. }
  279. case R.id.action_see_details: {
  280. seeDetails();
  281. return true;
  282. }
  283. case R.id.action_sync_file: {
  284. containerActivity.getFileOperationsHelper().syncFile(getFile());
  285. return true;
  286. }
  287. default:
  288. return super.onOptionsItemSelected(item);
  289. }
  290. }
  291. /**
  292. * Update the file of the fragment with file value
  293. *
  294. * @param file The new file to set
  295. */
  296. public void updateFile(OCFile file) {
  297. setFile(file);
  298. }
  299. private void seeDetails() {
  300. containerActivity.showDetails(getFile());
  301. }
  302. /**
  303. * Opens the previewed file with an external application.
  304. */
  305. private void openFile() {
  306. containerActivity.getFileOperationsHelper().openFile(getFile());
  307. finish();
  308. }
  309. /**
  310. * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewTextFileFragment} to be previewed.
  311. *
  312. * @param file File to test if can be previewed.
  313. * @return 'True' if the file can be handled by the fragment.
  314. */
  315. public static boolean canBePreviewed(OCFile file) {
  316. final List<String> unsupportedTypes = new LinkedList<>();
  317. unsupportedTypes.add("text/richtext");
  318. unsupportedTypes.add("text/rtf");
  319. unsupportedTypes.add("text/calendar");
  320. unsupportedTypes.add("text/vnd.abc");
  321. unsupportedTypes.add("text/vnd.fmi.flexstor");
  322. unsupportedTypes.add("text/vnd.rn-realtext");
  323. unsupportedTypes.add("text/vnd.wap.wml");
  324. unsupportedTypes.add("text/vnd.wap.wmlscript");
  325. return file != null && file.isDown() && MimeTypeUtil.isText(file) &&
  326. !unsupportedTypes.contains(file.getMimeType()) &&
  327. !unsupportedTypes.contains(MimeTypeUtil.getMimeTypeFromPath(file.getRemotePath()));
  328. }
  329. @Override
  330. public void onStop() {
  331. super.onStop();
  332. Log_OC.e(TAG, "onStop");
  333. if (textLoadAsyncTask != null) {
  334. textLoadAsyncTask.cancel(true);
  335. }
  336. }
  337. }