SearchActivity.java

  1/*
  2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
  3 *
  4 * Redistribution and use in source and binary forms, with or without modification,
  5 * are permitted provided that the following conditions are met:
  6 *
  7 * 1. Redistributions of source code must retain the above copyright notice, this
  8 * list of conditions and the following disclaimer.
  9 *
 10 * 2. Redistributions in binary form must reproduce the above copyright notice,
 11 * this list of conditions and the following disclaimer in the documentation and/or
 12 * other materials provided with the distribution.
 13 *
 14 * 3. Neither the name of the copyright holder nor the names of its contributors
 15 * may be used to endorse or promote products derived from this software without
 16 * specific prior written permission.
 17 *
 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 28 */
 29
 30package eu.siacs.conversations.ui;
 31
 32import android.databinding.DataBindingUtil;
 33import android.os.Bundle;
 34import android.support.v7.widget.Toolbar;
 35import android.text.Editable;
 36import android.text.InputType;
 37import android.text.TextWatcher;
 38import android.util.Log;
 39import android.view.ContextMenu;
 40import android.view.Menu;
 41import android.view.MenuItem;
 42import android.view.View;
 43import android.widget.AdapterView;
 44import android.widget.EditText;
 45
 46import java.lang.ref.WeakReference;
 47import java.util.ArrayList;
 48import java.util.List;
 49
 50import eu.siacs.conversations.Config;
 51import eu.siacs.conversations.R;
 52import eu.siacs.conversations.databinding.ActivitySearchBinding;
 53import eu.siacs.conversations.entities.Contact;
 54import eu.siacs.conversations.entities.Conversation;
 55import eu.siacs.conversations.entities.Conversational;
 56import eu.siacs.conversations.entities.Message;
 57import eu.siacs.conversations.entities.StubConversation;
 58import eu.siacs.conversations.services.MessageSearchTask;
 59import eu.siacs.conversations.ui.adapter.MessageAdapter;
 60import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 61import eu.siacs.conversations.ui.util.ChangeWatcher;
 62import eu.siacs.conversations.ui.util.Color;
 63import eu.siacs.conversations.ui.util.DateSeparator;
 64import eu.siacs.conversations.ui.util.Drawable;
 65import eu.siacs.conversations.ui.util.ListViewUtils;
 66import eu.siacs.conversations.ui.util.PendingItem;
 67import eu.siacs.conversations.ui.util.ShareUtil;
 68import eu.siacs.conversations.utils.FtsUtils;
 69import eu.siacs.conversations.utils.MessageUtils;
 70
 71import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard;
 72import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.showKeyboard;
 73
 74public class SearchActivity extends XmppActivity implements TextWatcher, OnSearchResultsAvailable, MessageAdapter.OnContactPictureClicked {
 75
 76	private static final String EXTRA_SEARCH_TERM = "search-term";
 77
 78	private ActivitySearchBinding binding;
 79	private MessageAdapter messageListAdapter;
 80	private final List<Message> messages = new ArrayList<>();
 81	private WeakReference<Message> selectedMessageReference = new WeakReference<>(null);
 82	private final ChangeWatcher<List<String>> currentSearch = new ChangeWatcher<>();
 83	private final PendingItem<String> pendingSearchTerm = new PendingItem<>();
 84	private final PendingItem<List<String>> pendingSearch = new PendingItem<>();
 85
 86	@Override
 87	public void onCreate(final Bundle bundle) {
 88		final String searchTerm = bundle == null ? null : bundle.getString(EXTRA_SEARCH_TERM);
 89		if (searchTerm != null) {
 90			pendingSearchTerm.push(searchTerm);
 91		}
 92		super.onCreate(bundle);
 93		this.binding = DataBindingUtil.setContentView(this, R.layout.activity_search);
 94		setSupportActionBar((Toolbar) this.binding.toolbar);
 95		configureActionBar(getSupportActionBar());
 96		this.messageListAdapter = new MessageAdapter(this, this.messages);
 97		this.messageListAdapter.setOnContactPictureClicked(this);
 98		this.binding.searchResults.setAdapter(messageListAdapter);
 99		registerForContextMenu(this.binding.searchResults);
100	}
101
102	@Override
103	public boolean onCreateOptionsMenu(final Menu menu) {
104		getMenuInflater().inflate(R.menu.activity_search, menu);
105		final MenuItem searchActionMenuItem = menu.findItem(R.id.action_search);
106		final EditText searchField = searchActionMenuItem.getActionView().findViewById(R.id.search_field);
107		final String term = pendingSearchTerm.pop();
108		if (term != null) {
109			searchField.append(term);
110			List<String> searchTerm = FtsUtils.parse(term);
111			if (xmppConnectionService != null) {
112				if (currentSearch.watch(searchTerm)) {
113					xmppConnectionService.search(searchTerm, this);
114				}
115			} else {
116				pendingSearch.push(searchTerm);
117			}
118		}
119		searchField.addTextChangedListener(this);
120		searchField.setHint(R.string.search_messages);
121		searchField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
122		if (term == null) {
123			showKeyboard(searchField);
124		}
125		return super.onCreateOptionsMenu(menu);
126	}
127
128	@Override
129	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
130		AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
131		final Message message = this.messages.get(acmi.position);
132		this.selectedMessageReference = new WeakReference<>(message);
133		getMenuInflater().inflate(R.menu.search_result_context, menu);
134		MenuItem copy = menu.findItem(R.id.copy_message);
135		MenuItem quote = menu.findItem(R.id.quote_message);
136		MenuItem copyUrl = menu.findItem(R.id.copy_url);
137		if (message.isGeoUri()) {
138			copy.setVisible(false);
139			quote.setVisible(false);
140		} else {
141			copyUrl.setVisible(false);
142		}
143		super.onCreateContextMenu(menu, v, menuInfo);
144	}
145
146	@Override
147	public boolean onOptionsItemSelected(MenuItem item) {
148		if (item.getItemId() == android.R.id.home) {
149			hideSoftKeyboard(this);
150		}
151		return super.onOptionsItemSelected(item);
152	}
153
154	@Override
155	public boolean onContextItemSelected(MenuItem item) {
156		final Message message = selectedMessageReference.get();
157		if (message != null) {
158			switch (item.getItemId()) {
159				case R.id.open_conversation:
160					switchToConversation(wrap(message.getConversation()));
161					break;
162				case R.id.share_with:
163					ShareUtil.share(this, message);
164					break;
165				case R.id.copy_message:
166					ShareUtil.copyToClipboard(this, message);
167					break;
168				case R.id.copy_url:
169					ShareUtil.copyUrlToClipboard(this, message);
170					break;
171				case R.id.quote_message:
172					quote(message);
173					break;
174			}
175		}
176		return super.onContextItemSelected(item);
177	}
178
179	@Override
180	public void onSaveInstanceState(Bundle bundle) {
181		List<String> term = currentSearch.get();
182		if (term != null && term.size() > 0) {
183			bundle.putString(EXTRA_SEARCH_TERM,FtsUtils.toUserEnteredString(term));
184		}
185		super.onSaveInstanceState(bundle);
186	}
187
188	private void quote(Message message) {
189		switchToConversationAndQuote(wrap(message.getConversation()), MessageUtils.prepareQuote(message));
190	}
191
192	private Conversation wrap(Conversational conversational) {
193		if (conversational instanceof Conversation) {
194			return (Conversation) conversational;
195		} else {
196			return xmppConnectionService.findOrCreateConversation(conversational.getAccount(),
197					conversational.getJid(),
198					conversational.getMode() == Conversational.MODE_MULTI,
199					true,
200					true);
201		}
202	}
203
204	@Override
205	protected void refreshUiReal() {
206
207	}
208
209	@Override
210	void onBackendConnected() {
211		final List<String> searchTerm = pendingSearch.pop();
212		if (searchTerm != null && currentSearch.watch(searchTerm)) {
213			xmppConnectionService.search(searchTerm, this);
214		}
215	}
216
217	private void changeBackground(boolean hasSearch, boolean hasResults) {
218		if (hasSearch) {
219			if (hasResults) {
220				binding.searchResults.setBackgroundColor(Color.get(this, R.attr.color_background_secondary));
221			} else {
222				binding.searchResults.setBackground(Drawable.get(this, R.attr.activity_background_no_results));
223			}
224		} else {
225			binding.searchResults.setBackground(Drawable.get(this, R.attr.activity_background_search));
226		}
227	}
228
229	@Override
230	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
231
232	}
233
234	@Override
235	public void onTextChanged(CharSequence s, int start, int before, int count) {
236
237	}
238
239	@Override
240	public void afterTextChanged(Editable s) {
241		final List<String> term = FtsUtils.parse(s.toString().trim());
242		if (!currentSearch.watch(term)) {
243			return;
244		}
245		if (term.size() > 0) {
246			xmppConnectionService.search(term, this);
247		} else {
248			MessageSearchTask.cancelRunningTasks();
249			this.messages.clear();
250			messageListAdapter.setHighlightedTerm(null);
251			messageListAdapter.notifyDataSetChanged();
252			changeBackground(false, false);
253		}
254	}
255
256	@Override
257	public void onSearchResultsAvailable(List<String> term, List<Message> messages) {
258		runOnUiThread(() -> {
259			this.messages.clear();
260			messageListAdapter.setHighlightedTerm(term);
261			DateSeparator.addAll(messages);
262			this.messages.addAll(messages);
263			messageListAdapter.notifyDataSetChanged();
264			changeBackground(true, messages.size() > 0);
265			ListViewUtils.scrollToBottom(this.binding.searchResults);
266		});
267	}
268
269	@Override
270	public void onContactPictureClicked(Message message) {
271		String fingerprint;
272		if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
273			fingerprint = "pgp";
274		} else {
275			fingerprint = message.getFingerprint();
276		}
277		if (message.getStatus() == Message.STATUS_RECEIVED) {
278			final Contact contact = message.getContact();
279			if (contact != null) {
280				if (contact.isSelf()) {
281					switchToAccount(message.getConversation().getAccount(), fingerprint);
282				} else {
283					switchToContactDetails(contact, fingerprint);
284				}
285			}
286		} else {
287			switchToAccount(message.getConversation().getAccount(), fingerprint);
288		}
289	}
290}