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		showKeyboard(searchField);
123		return super.onCreateOptionsMenu(menu);
124	}
125
126	@Override
127	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
128		AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
129		final Message message = this.messages.get(acmi.position);
130		this.selectedMessageReference = new WeakReference<>(message);
131		getMenuInflater().inflate(R.menu.search_result_context, menu);
132		MenuItem copy = menu.findItem(R.id.copy_message);
133		MenuItem quote = menu.findItem(R.id.quote_message);
134		MenuItem copyUrl = menu.findItem(R.id.copy_url);
135		if (message.isGeoUri()) {
136			copy.setVisible(false);
137			quote.setVisible(false);
138		} else {
139			copyUrl.setVisible(false);
140		}
141		super.onCreateContextMenu(menu, v, menuInfo);
142	}
143
144	@Override
145	public boolean onOptionsItemSelected(MenuItem item) {
146		if (item.getItemId() == android.R.id.home) {
147			hideSoftKeyboard(this);
148		}
149		return super.onOptionsItemSelected(item);
150	}
151
152	@Override
153	public boolean onContextItemSelected(MenuItem item) {
154		final Message message = selectedMessageReference.get();
155		if (message != null) {
156			switch (item.getItemId()) {
157				case R.id.open_conversation:
158					switchToConversation(wrap(message.getConversation()));
159					break;
160				case R.id.share_with:
161					ShareUtil.share(this, message);
162					break;
163				case R.id.copy_message:
164					ShareUtil.copyToClipboard(this, message);
165					break;
166				case R.id.copy_url:
167					ShareUtil.copyUrlToClipboard(this, message);
168					break;
169				case R.id.quote_message:
170					quote(message);
171					break;
172			}
173		}
174		return super.onContextItemSelected(item);
175	}
176
177	@Override
178	public void onSaveInstanceState(Bundle bundle) {
179		List<String> term = currentSearch.get();
180		if (term != null && term.size() > 0) {
181			bundle.putString(EXTRA_SEARCH_TERM,FtsUtils.toUserEnteredString(term));
182		}
183		super.onSaveInstanceState(bundle);
184	}
185
186	private void quote(Message message) {
187		switchToConversationAndQuote(wrap(message.getConversation()), MessageUtils.prepareQuote(message));
188	}
189
190	private Conversation wrap(Conversational conversational) {
191		if (conversational instanceof Conversation) {
192			return (Conversation) conversational;
193		} else {
194			return xmppConnectionService.findOrCreateConversation(conversational.getAccount(),
195					conversational.getJid(),
196					conversational.getMode() == Conversational.MODE_MULTI,
197					true,
198					true);
199		}
200	}
201
202	@Override
203	protected void refreshUiReal() {
204
205	}
206
207	@Override
208	void onBackendConnected() {
209		final List<String> searchTerm = pendingSearch.pop();
210		if (searchTerm != null && currentSearch.watch(searchTerm)) {
211			xmppConnectionService.search(searchTerm, this);
212		}
213	}
214
215	private void changeBackground(boolean hasSearch, boolean hasResults) {
216		if (hasSearch) {
217			if (hasResults) {
218				binding.searchResults.setBackgroundColor(Color.get(this, R.attr.color_background_secondary));
219			} else {
220				binding.searchResults.setBackground(Drawable.get(this, R.attr.activity_background_no_results));
221			}
222		} else {
223			binding.searchResults.setBackground(Drawable.get(this, R.attr.activity_background_search));
224		}
225	}
226
227	@Override
228	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
229
230	}
231
232	@Override
233	public void onTextChanged(CharSequence s, int start, int before, int count) {
234
235	}
236
237	@Override
238	public void afterTextChanged(Editable s) {
239		final List<String> term = FtsUtils.parse(s.toString().trim());
240		if (!currentSearch.watch(term)) {
241			return;
242		}
243		if (term.size() > 0) {
244			xmppConnectionService.search(term, this);
245		} else {
246			MessageSearchTask.cancelRunningTasks();
247			this.messages.clear();
248			messageListAdapter.setHighlightedTerm(null);
249			messageListAdapter.notifyDataSetChanged();
250			changeBackground(false, false);
251		}
252	}
253
254	@Override
255	public void onSearchResultsAvailable(List<String> term, List<Message> messages) {
256		runOnUiThread(() -> {
257			this.messages.clear();
258			messageListAdapter.setHighlightedTerm(term);
259			DateSeparator.addAll(messages);
260			this.messages.addAll(messages);
261			messageListAdapter.notifyDataSetChanged();
262			changeBackground(true, messages.size() > 0);
263			ListViewUtils.scrollToBottom(this.binding.searchResults);
264		});
265	}
266
267	@Override
268	public void onContactPictureClicked(Message message) {
269		String fingerprint;
270		if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
271			fingerprint = "pgp";
272		} else {
273			fingerprint = message.getFingerprint();
274		}
275		if (message.getStatus() == Message.STATUS_RECEIVED) {
276			final Contact contact = message.getContact();
277			if (contact != null) {
278				if (contact.isSelf()) {
279					switchToAccount(message.getConversation().getAccount(), fingerprint);
280				} else {
281					switchToContactDetails(contact, fingerprint);
282				}
283			}
284		} else {
285			switchToAccount(message.getConversation().getAccount(), fingerprint);
286		}
287	}
288}