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.content.Intent;
33import android.os.Bundle;
34import android.text.Editable;
35import android.text.InputType;
36import android.text.TextWatcher;
37import android.view.ContextMenu;
38import android.view.Menu;
39import android.view.MenuItem;
40import android.view.MotionEvent;
41import android.view.View;
42import android.widget.AdapterView;
43import android.widget.EditText;
44
45import androidx.databinding.DataBindingUtil;
46
47import com.google.common.base.Strings;
48
49import java.lang.ref.WeakReference;
50import java.util.ArrayList;
51import java.util.List;
52
53import eu.siacs.conversations.R;
54import eu.siacs.conversations.databinding.ActivitySearchBinding;
55import eu.siacs.conversations.entities.Contact;
56import eu.siacs.conversations.entities.Conversation;
57import eu.siacs.conversations.entities.Conversational;
58import eu.siacs.conversations.entities.Message;
59import eu.siacs.conversations.services.MessageSearchTask;
60import eu.siacs.conversations.ui.adapter.MessageAdapter;
61import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
62import eu.siacs.conversations.ui.util.ChangeWatcher;
63import eu.siacs.conversations.ui.util.DateSeparator;
64import eu.siacs.conversations.ui.util.ListViewUtils;
65import eu.siacs.conversations.ui.util.PendingItem;
66import eu.siacs.conversations.ui.util.ShareUtil;
67import eu.siacs.conversations.ui.util.StyledAttributes;
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 public static final String EXTRA_CONVERSATION_UUID = "uuid";
78
79 private ActivitySearchBinding binding;
80 private MessageAdapter messageListAdapter;
81 private final List<Message> messages = new ArrayList<>();
82 private WeakReference<Message> selectedMessageReference = new WeakReference<>(null);
83 private String uuid;
84 private final ChangeWatcher<List<String>> currentSearch = new ChangeWatcher<>();
85 private final PendingItem<String> pendingSearchTerm = new PendingItem<>();
86 private final PendingItem<List<String>> pendingSearch = new PendingItem<>();
87
88 @Override
89 public void onCreate(final Bundle bundle) {
90 final Intent intent = getIntent();
91 this.uuid = intent == null ? null : Strings.emptyToNull(intent.getStringExtra(EXTRA_CONVERSATION_UUID));
92 final String searchTerm = bundle == null ? null : bundle.getString(EXTRA_SEARCH_TERM);
93 if (searchTerm != null) {
94 pendingSearchTerm.push(searchTerm);
95 }
96 super.onCreate(bundle);
97 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_search);
98 setSupportActionBar(this.binding.toolbar);
99 configureActionBar(getSupportActionBar());
100 this.messageListAdapter = new MessageAdapter(this, this.messages, uuid == null);
101 this.messageListAdapter.setOnContactPictureClicked(this);
102 this.binding.searchResults.setAdapter(messageListAdapter);
103 registerForContextMenu(this.binding.searchResults);
104 }
105
106 @Override
107 public boolean onCreateOptionsMenu(final Menu menu) {
108 getMenuInflater().inflate(R.menu.activity_search, menu);
109 final MenuItem searchActionMenuItem = menu.findItem(R.id.action_search);
110 final EditText searchField = searchActionMenuItem.getActionView().findViewById(R.id.search_field);
111 final String term = pendingSearchTerm.pop();
112 if (term != null) {
113 searchField.append(term);
114 final List<String> searchTerm = FtsUtils.parse(term);
115 if (xmppConnectionService != null) {
116 if (currentSearch.watch(searchTerm)) {
117 xmppConnectionService.search(searchTerm, uuid, this);
118 }
119 } else {
120 pendingSearch.push(searchTerm);
121 }
122 }
123 searchField.addTextChangedListener(this);
124 searchField.setHint(R.string.search_messages);
125 searchField.setContentDescription(getString(R.string.search_messages));
126 searchField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
127 if (term == null) {
128 showKeyboard(searchField);
129 }
130 return super.onCreateOptionsMenu(menu);
131 }
132
133 @Override
134 public void onCreateContextMenu(final ContextMenu menu, final View v, ContextMenu.ContextMenuInfo menuInfo) {
135 v.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0));
136 AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
137 final Message message = this.messages.get(acmi.position);
138 this.selectedMessageReference = new WeakReference<>(message);
139 getMenuInflater().inflate(R.menu.search_result_context, menu);
140 MenuItem copy = menu.findItem(R.id.copy_message);
141 MenuItem quote = menu.findItem(R.id.quote_message);
142 MenuItem copyUrl = menu.findItem(R.id.copy_url);
143 if (message.isGeoUri()) {
144 copy.setVisible(false);
145 quote.setVisible(false);
146 } else {
147 copyUrl.setVisible(false);
148 }
149 super.onCreateContextMenu(menu, v, menuInfo);
150 }
151
152 @Override
153 public boolean onOptionsItemSelected(MenuItem item) {
154 if (item.getItemId() == android.R.id.home) {
155 hideSoftKeyboard(this);
156 }
157 return super.onOptionsItemSelected(item);
158 }
159
160 @Override
161 public boolean onContextItemSelected(MenuItem item) {
162 final Message message = selectedMessageReference.get();
163 if (message != null) {
164 switch (item.getItemId()) {
165 case R.id.open_conversation:
166 switchToConversation(wrap(message.getConversation()));
167 break;
168 case R.id.share_with:
169 ShareUtil.share(this, message);
170 break;
171 case R.id.copy_message:
172 ShareUtil.copyToClipboard(this, message);
173 break;
174 case R.id.copy_url:
175 ShareUtil.copyUrlToClipboard(this, message);
176 break;
177 case R.id.quote_message:
178 quote(message);
179 break;
180 }
181 }
182 return super.onContextItemSelected(item);
183 }
184
185 @Override
186 public void onSaveInstanceState(Bundle bundle) {
187 List<String> term = currentSearch.get();
188 if (term != null && term.size() > 0) {
189 bundle.putString(EXTRA_SEARCH_TERM,FtsUtils.toUserEnteredString(term));
190 }
191 super.onSaveInstanceState(bundle);
192 }
193
194 private void quote(Message message) {
195 switchToConversationAndQuote(wrap(message.getConversation()), MessageUtils.prepareQuote(message));
196 }
197
198 private Conversation wrap(Conversational conversational) {
199 if (conversational instanceof Conversation) {
200 return (Conversation) conversational;
201 } else {
202 return xmppConnectionService.findOrCreateConversation(conversational.getAccount(),
203 conversational.getJid(),
204 conversational.getMode() == Conversational.MODE_MULTI,
205 true,
206 true);
207 }
208 }
209
210 @Override
211 protected void refreshUiReal() {
212
213 }
214
215 @Override
216 void onBackendConnected() {
217 final List<String> searchTerm = pendingSearch.pop();
218 if (searchTerm != null && currentSearch.watch(searchTerm)) {
219 xmppConnectionService.search(searchTerm, uuid,this);
220 }
221 }
222
223 private void changeBackground(boolean hasSearch, boolean hasResults) {
224 if (hasSearch) {
225 if (hasResults) {
226 binding.searchResults.setBackgroundColor(StyledAttributes.getColor(this, R.attr.color_background_secondary));
227 } else {
228 binding.searchResults.setBackground(StyledAttributes.getDrawable(this, R.attr.activity_background_no_results));
229 }
230 } else {
231 binding.searchResults.setBackground(StyledAttributes.getDrawable(this, R.attr.activity_background_search));
232 }
233 }
234
235 @Override
236 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
237
238 }
239
240 @Override
241 public void onTextChanged(CharSequence s, int start, int before, int count) {
242
243 }
244
245 @Override
246 public void afterTextChanged(Editable s) {
247 final List<String> term = FtsUtils.parse(s.toString().trim());
248 if (!currentSearch.watch(term)) {
249 return;
250 }
251 if (term.size() > 0) {
252 xmppConnectionService.search(term, uuid,this);
253 } else {
254 MessageSearchTask.cancelRunningTasks();
255 this.messages.clear();
256 messageListAdapter.setHighlightedTerm(null);
257 messageListAdapter.notifyDataSetChanged();
258 changeBackground(false, false);
259 }
260 }
261
262 @Override
263 public void onSearchResultsAvailable(List<String> term, List<Message> messages) {
264 runOnUiThread(() -> {
265 this.messages.clear();
266 messageListAdapter.setHighlightedTerm(term);
267 DateSeparator.addAll(messages);
268 this.messages.addAll(messages);
269 messageListAdapter.notifyDataSetChanged();
270 changeBackground(true, messages.size() > 0);
271 ListViewUtils.scrollToBottom(this.binding.searchResults);
272 });
273 }
274
275 @Override
276 public void onContactPictureClicked(Message message) {
277 String fingerprint;
278 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
279 fingerprint = "pgp";
280 } else {
281 fingerprint = message.getFingerprint();
282 }
283 if (message.getStatus() == Message.STATUS_RECEIVED) {
284 final Contact contact = message.getContact();
285 if (contact != null) {
286 if (contact.isSelf()) {
287 switchToAccount(message.getConversation().getAccount(), fingerprint);
288 } else {
289 switchToContactDetails(contact, fingerprint);
290 }
291 }
292 } else {
293 switchToAccount(message.getConversation().getAccount(), fingerprint);
294 }
295 }
296}