PreviewTextFileFragment.java 13 KB

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