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.FrameLayout;
  32. import android.widget.TextView;
  33. import com.nextcloud.client.account.User;
  34. import com.nextcloud.client.account.UserAccountManager;
  35. import com.owncloud.android.R;
  36. import com.owncloud.android.datamodel.OCFile;
  37. import com.owncloud.android.files.FileMenuFilter;
  38. import com.owncloud.android.lib.common.utils.Log_OC;
  39. import com.owncloud.android.ui.activity.FileDisplayActivity;
  40. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  41. import com.owncloud.android.ui.dialog.RemoveFilesDialogFragment;
  42. import com.owncloud.android.utils.DisplayUtils;
  43. import com.owncloud.android.utils.MimeTypeUtil;
  44. import org.mozilla.universalchardet.ReaderFactory;
  45. import java.io.BufferedWriter;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.io.Reader;
  49. import java.io.StringWriter;
  50. import java.lang.ref.WeakReference;
  51. import java.util.LinkedList;
  52. import java.util.List;
  53. import java.util.Scanner;
  54. import javax.inject.Inject;
  55. import androidx.annotation.NonNull;
  56. import androidx.appcompat.widget.SearchView;
  57. import androidx.core.view.MenuItemCompat;
  58. public class PreviewTextFileFragment extends PreviewTextFragment {
  59. private static final String EXTRA_FILE = "FILE";
  60. private static final String EXTRA_ACCOUNT = "ACCOUNT";
  61. private static final String TAG = PreviewTextFileFragment.class.getSimpleName();
  62. private TextLoadAsyncTask textLoadAsyncTask;
  63. private Account account;
  64. @Inject UserAccountManager accountManager;
  65. /**
  66. * Creates an empty fragment for previews.
  67. * <p>
  68. * MUST BE KEPT: the system uses it when tries to re-instantiate a fragment automatically (for instance, when the
  69. * device is turned a aside).
  70. * <p>
  71. * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
  72. */
  73. public PreviewTextFileFragment() {
  74. super();
  75. account = null;
  76. }
  77. /**
  78. * {@inheritDoc}
  79. */
  80. @Override
  81. public void onCreate(Bundle savedInstanceState) {
  82. super.onCreate(savedInstanceState);
  83. setHasOptionsMenu(true);
  84. OCFile file = getFile();
  85. Bundle args = getArguments();
  86. if (file == null) {
  87. file = args.getParcelable(FileDisplayActivity.EXTRA_FILE);
  88. }
  89. if (account == null) {
  90. account = args.getParcelable(FileDisplayActivity.EXTRA_ACCOUNT);
  91. }
  92. if (args.containsKey(FileDisplayActivity.EXTRA_SEARCH_QUERY)) {
  93. searchQuery = args.getString(FileDisplayActivity.EXTRA_SEARCH_QUERY);
  94. }
  95. searchOpen = args.getBoolean(FileDisplayActivity.EXTRA_SEARCH, false);
  96. if (savedInstanceState == null) {
  97. if (file == null) {
  98. throw new IllegalStateException("Instanced with a NULL OCFile");
  99. }
  100. if (account == null) {
  101. throw new IllegalStateException("Instanced with a NULL ownCloud Account");
  102. }
  103. } else {
  104. file = savedInstanceState.getParcelable(EXTRA_FILE);
  105. account = savedInstanceState.getParcelable(EXTRA_ACCOUNT);
  106. }
  107. handler = new Handler();
  108. setFile(file);
  109. }
  110. /**
  111. * {@inheritDoc}
  112. */
  113. @Override
  114. public void onSaveInstanceState(@NonNull Bundle outState) {
  115. outState.putParcelable(PreviewTextFileFragment.EXTRA_FILE, getFile());
  116. outState.putParcelable(PreviewTextFileFragment.EXTRA_ACCOUNT, account);
  117. super.onSaveInstanceState(outState);
  118. }
  119. @Override
  120. void loadAndShowTextPreview() {
  121. textLoadAsyncTask = new TextLoadAsyncTask(new WeakReference<>(binding.textPreview),
  122. new WeakReference<>(binding.emptyListProgress));
  123. textLoadAsyncTask.execute(getFile().getStoragePath());
  124. }
  125. /**
  126. * Reads the file to preview and shows its contents. Too critical to be anonymous.
  127. */
  128. private class TextLoadAsyncTask extends AsyncTask<Object, Void, StringWriter> {
  129. private static final int PARAMS_LENGTH = 1;
  130. private final WeakReference<TextView> textViewReference;
  131. private final WeakReference<FrameLayout> progressViewReference;
  132. private TextLoadAsyncTask(WeakReference<TextView> textView, WeakReference<FrameLayout> progressView) {
  133. textViewReference = textView;
  134. progressViewReference = progressView;
  135. }
  136. @Override
  137. protected void onPreExecute() {
  138. // not used at the moment
  139. }
  140. @Override
  141. protected StringWriter doInBackground(Object... params) {
  142. if (params.length != PARAMS_LENGTH) {
  143. throw new IllegalArgumentException("The parameter to " + TextLoadAsyncTask.class.getName()
  144. + " must be (1) the file location");
  145. }
  146. String location = (String) params[0];
  147. Scanner scanner = null;
  148. StringWriter source = new StringWriter();
  149. BufferedWriter bufferedWriter = new BufferedWriter(source);
  150. Reader reader = null;
  151. try {
  152. File file = new File(location);
  153. reader = ReaderFactory.createReaderFromFile(file);
  154. scanner = new Scanner(reader);
  155. while (scanner.hasNextLine()) {
  156. bufferedWriter.append(scanner.nextLine());
  157. if (scanner.hasNextLine()) {
  158. bufferedWriter.append("\n");
  159. }
  160. }
  161. bufferedWriter.close();
  162. IOException exc = scanner.ioException();
  163. if (exc != null) {
  164. throw exc;
  165. }
  166. } catch (IOException e) {
  167. Log_OC.e(TAG, e.getMessage(), e);
  168. finish();
  169. } finally {
  170. if (reader != null) {
  171. try {
  172. reader.close();
  173. } catch (IOException e) {
  174. Log_OC.e(TAG, e.getMessage(), e);
  175. finish();
  176. }
  177. }
  178. if (scanner != null) {
  179. scanner.close();
  180. }
  181. }
  182. return source;
  183. }
  184. @Override
  185. protected void onPostExecute(final StringWriter stringWriter) {
  186. final TextView textView = textViewReference.get();
  187. if (textView != null) {
  188. originalText = stringWriter.toString();
  189. setText(textView, originalText, getFile(), requireActivity());
  190. if (searchView != null) {
  191. searchView.setOnQueryTextListener(PreviewTextFileFragment.this);
  192. if (searchOpen) {
  193. searchView.setQuery(searchQuery, true);
  194. }
  195. }
  196. textView.setVisibility(View.VISIBLE);
  197. }
  198. final FrameLayout progress = progressViewReference.get();
  199. if (progress != null) {
  200. progress.setVisibility(View.GONE);
  201. }
  202. }
  203. }
  204. /**
  205. * {@inheritDoc}
  206. */
  207. @Override
  208. public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
  209. super.onCreateOptionsMenu(menu, inflater);
  210. inflater.inflate(R.menu.item_file, menu);
  211. MenuItem menuItem = menu.findItem(R.id.action_search);
  212. menuItem.setVisible(true);
  213. searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
  214. searchView.setMaxWidth(Integer.MAX_VALUE);
  215. if (searchOpen) {
  216. searchView.setIconified(false);
  217. searchView.setQuery(searchQuery, false);
  218. searchView.clearFocus();
  219. }
  220. }
  221. /**
  222. * {@inheritDoc}
  223. */
  224. @Override
  225. public void onPrepareOptionsMenu(@NonNull Menu menu) {
  226. super.onPrepareOptionsMenu(menu);
  227. if (containerActivity.getStorageManager() != null) {
  228. User user = accountManager.getUser();
  229. FileMenuFilter mf = new FileMenuFilter(
  230. getFile(),
  231. containerActivity,
  232. getActivity(),
  233. false,
  234. user
  235. );
  236. mf.filter(menu, true);
  237. }
  238. // additional restriction for this fragment
  239. FileMenuFilter.hideMenuItems(
  240. menu.findItem(R.id.action_rename_file),
  241. menu.findItem(R.id.action_select_all),
  242. menu.findItem(R.id.action_move),
  243. menu.findItem(R.id.action_download_file),
  244. menu.findItem(R.id.action_sync_file),
  245. menu.findItem(R.id.action_favorite),
  246. menu.findItem(R.id.action_unset_favorite)
  247. );
  248. if (getFile().isSharedWithMe() && !getFile().canReshare()) {
  249. FileMenuFilter.hideMenuItem(menu.findItem(R.id.action_send_share_file));
  250. }
  251. }
  252. /**
  253. * {@inheritDoc}
  254. */
  255. @Override
  256. public boolean onOptionsItemSelected(MenuItem item) {
  257. switch (item.getItemId()) {
  258. case R.id.action_send_share_file: {
  259. if (getFile().isSharedWithMe() && !getFile().canReshare()) {
  260. DisplayUtils.showSnackMessage(getView(), R.string.resharing_is_not_allowed);
  261. } else {
  262. containerActivity.getFileOperationsHelper().sendShareFile(getFile());
  263. }
  264. return true;
  265. }
  266. case R.id.action_open_file_with: {
  267. openFile();
  268. return true;
  269. }
  270. case R.id.action_remove_file: {
  271. RemoveFilesDialogFragment dialog = RemoveFilesDialogFragment.newInstance(getFile());
  272. dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
  273. return true;
  274. }
  275. case R.id.action_see_details: {
  276. seeDetails();
  277. return true;
  278. }
  279. case R.id.action_sync_file: {
  280. containerActivity.getFileOperationsHelper().syncFile(getFile());
  281. return true;
  282. }
  283. case R.id.action_edit:
  284. containerActivity.getFileOperationsHelper().openFileWithTextEditor(getFile(), getContext());
  285. return true;
  286. default:
  287. return super.onOptionsItemSelected(item);
  288. }
  289. }
  290. /**
  291. * Update the file of the fragment with file value
  292. *
  293. * @param file The new file to set
  294. */
  295. public void updateFile(OCFile file) {
  296. setFile(file);
  297. }
  298. private void seeDetails() {
  299. containerActivity.showDetails(getFile());
  300. }
  301. /**
  302. * Opens the previewed file with an external application.
  303. */
  304. private void openFile() {
  305. containerActivity.getFileOperationsHelper().openFile(getFile());
  306. finish();
  307. }
  308. /**
  309. * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewTextFileFragment} to be previewed.
  310. *
  311. * @param file File to test if can be previewed.
  312. * @return 'True' if the file can be handled by the fragment.
  313. */
  314. public static boolean canBePreviewed(OCFile file) {
  315. final List<String> unsupportedTypes = new LinkedList<>();
  316. unsupportedTypes.add("text/richtext");
  317. unsupportedTypes.add("text/rtf");
  318. unsupportedTypes.add("text/calendar");
  319. unsupportedTypes.add("text/vnd.abc");
  320. unsupportedTypes.add("text/vnd.fmi.flexstor");
  321. unsupportedTypes.add("text/vnd.rn-realtext");
  322. unsupportedTypes.add("text/vnd.wap.wml");
  323. unsupportedTypes.add("text/vnd.wap.wmlscript");
  324. unsupportedTypes.add("text/html");
  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. }