UIHelper.java

  1package eu.siacs.conversations.utils;
  2
  3import java.io.FileNotFoundException;
  4import java.text.SimpleDateFormat;
  5import java.util.ArrayList;
  6import java.util.Date;
  7import java.util.List;
  8import java.util.Locale;
  9
 10import eu.siacs.conversations.R;
 11import eu.siacs.conversations.entities.Account;
 12import eu.siacs.conversations.entities.Contact;
 13import eu.siacs.conversations.entities.Conversation;
 14import eu.siacs.conversations.entities.Message;
 15import eu.siacs.conversations.entities.MucOptions.User;
 16import eu.siacs.conversations.ui.ConversationActivity;
 17import eu.siacs.conversations.ui.ManageAccountActivity;
 18
 19import android.app.Activity;
 20import android.app.AlertDialog;
 21import android.app.Notification;
 22import android.app.NotificationManager;
 23import android.app.PendingIntent;
 24import android.content.Context;
 25import android.content.DialogInterface;
 26import android.content.DialogInterface.OnClickListener;
 27import android.content.Intent;
 28import android.content.SharedPreferences;
 29import android.graphics.Bitmap;
 30import android.graphics.BitmapFactory;
 31import android.graphics.Canvas;
 32import android.graphics.Paint;
 33import android.graphics.Rect;
 34import android.graphics.Typeface;
 35import android.net.Uri;
 36import android.preference.PreferenceManager;
 37import android.provider.ContactsContract.Contacts;
 38import android.support.v4.app.NotificationCompat;
 39import android.support.v4.app.TaskStackBuilder;
 40import android.text.Html;
 41import android.util.DisplayMetrics;
 42import android.view.LayoutInflater;
 43import android.view.View;
 44import android.widget.LinearLayout;
 45import android.widget.QuickContactBadge;
 46import android.widget.TextView;
 47
 48public class UIHelper {
 49	private static final int BG_COLOR = 0xFF181818;
 50	private static final int FG_COLOR = 0xFFE5E5E5;
 51	private static final int TRANSPARENT = 0x00000000;
 52
 53	public static String readableTimeDifference(long time) {
 54		if (time == 0) {
 55			return "just now";
 56		}
 57		Date date = new Date(time);
 58		long difference = (System.currentTimeMillis() - time) / 1000;
 59		if (difference < 60) {
 60			return "just now";
 61		} else if (difference < 60 * 10) {
 62			return difference / 60 + " min ago";
 63		} else if (difference < 60 * 60 * 24) {
 64			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm",Locale.US);
 65			return sdf.format(date);
 66		} else {
 67			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd",Locale.US);
 68			return sdf.format(date);
 69		}
 70	}
 71
 72	public static int getRealPx(int dp, Context context) {
 73		final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
 74		return ((int) (dp * metrics.density));
 75	}
 76
 77	private static int getNameColor(String name) {
 78		int holoColors[] = { 0xFF1da9da, 0xFFb368d9, 0xFF83b600, 0xFFffa713,
 79				0xFFe92727 };
 80		int color = holoColors[Math.abs(name.toLowerCase(Locale.getDefault()).hashCode()) % holoColors.length];
 81		return color;
 82	}
 83
 84	private static Bitmap getUnknownContactPicture(String[] names, int size, int bgColor, int fgColor) {
 85		int tiles = (names.length > 4)? 4 :
 86					(names.length < 1)? 1 :
 87						names.length;
 88		Bitmap bitmap = Bitmap
 89				.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 90		Canvas canvas = new Canvas(bitmap);
 91
 92		String[] letters = new String[tiles];
 93		int[] colors = new int[tiles];
 94		if (names.length < 1) {
 95			letters[0] = "?";
 96			colors[0] = 0xFFe92727;
 97		} else {
 98			for(int i = 0; i < tiles; ++i) {
 99				letters[i] = (names[i].length() > 0) ?
100						names[i].substring(0, 1).toUpperCase(Locale.US) : " ";
101				colors[i] = getNameColor(names[i]);
102			}
103
104			if (names.length > 4) {
105				letters[3] = "\u2026"; // Unicode ellipsis
106				colors[3] = 0xFF444444;
107			}
108		}
109		Paint textPaint = new Paint(), tilePaint = new Paint();
110		textPaint.setColor(fgColor);
111		textPaint.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
112		Rect rect, left, right, topLeft, bottomLeft, topRight, bottomRight;
113		float width;
114
115		switch(tiles) {
116			case 1:
117				bitmap.eraseColor(colors[0]);
118
119				textPaint.setTextSize((float) (size * 0.8));
120				textPaint.setAntiAlias(true);
121				rect = new Rect();
122				textPaint.getTextBounds(letters[0], 0, 1, rect);
123				width = textPaint.measureText(letters[0]);
124				canvas.drawText(letters[0], (size / 2) - (width / 2), (size / 2)
125						+ (rect.height() / 2), textPaint);
126				break;
127
128			case 2:
129				bitmap.eraseColor(bgColor);
130
131				tilePaint.setColor(colors[0]);
132				left = new Rect(0, 0, (size/2)-1, size);
133				canvas.drawRect(left, tilePaint);
134
135				tilePaint.setColor(colors[1]);
136				right = new Rect((size/2)+1, 0, size, size);
137				canvas.drawRect(right, tilePaint);
138
139				textPaint.setTextSize((float) (size * 0.8*0.5));
140				textPaint.setAntiAlias(true);
141				rect = new Rect();
142				textPaint.getTextBounds(letters[0], 0, 1, rect);
143				width = textPaint.measureText(letters[0]);
144				canvas.drawText(letters[0], (size / 4) - (width / 2), (size / 2)
145						+ (rect.height() / 2), textPaint);
146				textPaint.getTextBounds(letters[1], 0, 1, rect);
147				width = textPaint.measureText(letters[1]);
148				canvas.drawText(letters[1], (3 * size / 4) - (width / 2), (size / 2)
149						+ (rect.height() / 2), textPaint);
150				break;
151
152			case 3:
153				bitmap.eraseColor(bgColor);
154
155				tilePaint.setColor(colors[0]);
156				left = new Rect(0, 0, (size/2)-1, size);
157				canvas.drawRect(left, tilePaint);
158
159				tilePaint.setColor(colors[1]);
160				topRight = new Rect((size/2)+1, 0, size, (size/2 - 1));
161				canvas.drawRect(topRight, tilePaint);
162
163				tilePaint.setColor(colors[2]);
164				bottomRight = new Rect((size/2)+1, (size/2 + 1), size, size);
165				canvas.drawRect(bottomRight, tilePaint);
166
167				textPaint.setTextSize((float) (size * 0.8*0.5));
168				textPaint.setAntiAlias(true);
169				rect = new Rect();
170
171				textPaint.getTextBounds(letters[0], 0, 1, rect);
172				width = textPaint.measureText(letters[0]);
173				canvas.drawText(letters[0], (size / 4) - (width / 2), (size / 2)
174						+ (rect.height() / 2), textPaint);
175
176				textPaint.getTextBounds(letters[1], 0, 1, rect);
177				width = textPaint.measureText(letters[1]);
178				canvas.drawText(letters[1], (3 * size / 4) - (width / 2), (size / 4)
179						+ (rect.height() / 2), textPaint);
180
181				textPaint.getTextBounds(letters[2], 0, 1, rect);
182				width = textPaint.measureText(letters[2]);
183				canvas.drawText(letters[2], (3 * size / 4) - (width / 2), (3* size / 4)
184						+ (rect.height() / 2), textPaint);
185				break;
186
187			case 4:
188				bitmap.eraseColor(bgColor);
189
190				tilePaint.setColor(colors[0]);
191				topLeft = new Rect(0, 0, (size/2)-1, (size/2)-1);
192				canvas.drawRect(topLeft, tilePaint);
193
194				tilePaint.setColor(colors[1]);
195				bottomLeft = new Rect(0, (size/2)+1, (size/2)-1, size);
196				canvas.drawRect(bottomLeft, tilePaint);
197
198				tilePaint.setColor(colors[2]);
199				topRight = new Rect((size/2)+1, 0, size, (size/2 - 1));
200				canvas.drawRect(topRight, tilePaint);
201
202				tilePaint.setColor(colors[3]);
203				bottomRight = new Rect((size/2)+1, (size/2 + 1), size, size);
204				canvas.drawRect(bottomRight, tilePaint);
205
206				textPaint.setTextSize((float) (size * 0.8*0.5));
207				textPaint.setAntiAlias(true);
208				rect = new Rect();
209
210				textPaint.getTextBounds(letters[0], 0, 1, rect);
211				width = textPaint.measureText(letters[0]);
212				canvas.drawText(letters[0], (size / 4) - (width / 2), (size / 4)
213						+ (rect.height() / 2), textPaint);
214
215				textPaint.getTextBounds(letters[1], 0, 1, rect);
216				width = textPaint.measureText(letters[1]);
217				canvas.drawText(letters[1], (size / 4) - (width / 2), (3* size / 4)
218						+ (rect.height() / 2), textPaint);
219
220				textPaint.getTextBounds(letters[2], 0, 1, rect);
221				width = textPaint.measureText(letters[2]);
222				canvas.drawText(letters[2], (3 * size / 4) - (width / 2), (size / 4)
223						+ (rect.height() / 2), textPaint);
224
225				textPaint.getTextBounds(letters[3], 0, 1, rect);
226				width = textPaint.measureText(letters[3]);
227				canvas.drawText(letters[3], (3 * size / 4) - (width / 2), (3* size / 4)
228						+ (rect.height() / 2), textPaint);
229				break;
230		}
231		return bitmap;
232	}
233	
234	private static Bitmap getMucContactPicture(Conversation conversation, int size, int bgColor, int fgColor) {
235		List<User> members = conversation.getMucOptions().getUsers();
236		if (members.size() == 0) {
237			return getUnknownContactPicture(new String[]{conversation.getName(false)}, size, bgColor, fgColor);
238		}
239		String[] names = new String[members.size()+1];
240		names[0] = conversation.getMucOptions().getNick();
241		for(int i = 0; i < members.size(); ++i) {
242			names[i+1] = members.get(i).getName();
243		}
244
245		return getUnknownContactPicture(names, size, bgColor, fgColor);
246	}
247
248	public static Bitmap getContactPicture(Conversation conversation, int dpSize, Context context, boolean notification) {
249		if(conversation.getMode() == Conversation.MODE_SINGLE) {
250			if (conversation.getContact() != null){
251				return getContactPicture(conversation.getContact(), dpSize,
252						context, notification);
253			} else {
254				return getContactPicture(conversation.getName(false), dpSize,
255						context, notification);
256			}
257		} else{
258			int fgColor = UIHelper.FG_COLOR,
259				bgColor = (notification) ?
260					UIHelper.BG_COLOR : UIHelper.TRANSPARENT;
261
262			return getMucContactPicture(conversation, getRealPx(dpSize, context),
263					bgColor, fgColor);
264		}
265	}
266
267	public static Bitmap getContactPicture(Contact contact, int dpSize, Context context, boolean notification) {
268		String uri = contact.getProfilePhoto();
269		if (uri==null) {
270			return getContactPicture(contact.getDisplayName(), dpSize,
271					context, notification);
272		}
273		try {
274			Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver()
275					.openInputStream(Uri.parse(uri)));
276			return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context),
277					getRealPx(dpSize, context), false);
278		} catch (FileNotFoundException e) {
279			return getContactPicture(contact.getDisplayName(), dpSize,
280					context, notification);
281		}
282	}
283
284	public static Bitmap getContactPicture(String name, int dpSize, Context context, boolean notification) {
285		int fgColor = UIHelper.FG_COLOR,
286			bgColor = (notification) ?
287				UIHelper.BG_COLOR : UIHelper.TRANSPARENT;
288
289		return getUnknownContactPicture(new String[]{name}, getRealPx(dpSize, context),
290				bgColor, fgColor);
291	}
292
293	public static void showErrorNotification(Context context, List<Account> accounts) {
294		NotificationManager mNotificationManager = (NotificationManager) context
295				.getSystemService(Context.NOTIFICATION_SERVICE);
296		List<Account> accountsWproblems = new ArrayList<Account>();
297		for(Account account : accounts) {
298			if (account.hasErrorStatus()) {
299				accountsWproblems.add(account);
300			}
301		}
302		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
303		if (accountsWproblems.size() == 0) {
304			mNotificationManager.cancel(1111);
305			return;
306		} else if (accountsWproblems.size() == 1) {
307			mBuilder.setContentTitle(context.getString(R.string.problem_connecting_to_account));
308			mBuilder.setContentText(accountsWproblems.get(0).getJid());
309		} else {
310			mBuilder.setContentTitle(context.getString(R.string.problem_connecting_to_accounts));
311			mBuilder.setContentText(context.getString(R.string.touch_to_fix));
312		}
313		mBuilder.setOngoing(true);
314		mBuilder.setLights(0xffffffff, 2000, 4000);
315		mBuilder.setSmallIcon(R.drawable.notification);
316		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
317		stackBuilder.addParentStack(ConversationActivity.class);
318
319		Intent manageAccountsIntent = new Intent(context,
320				ManageAccountActivity.class);
321		stackBuilder.addNextIntent(manageAccountsIntent);
322
323		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
324				0, PendingIntent.FLAG_UPDATE_CURRENT);
325		
326		mBuilder.setContentIntent(resultPendingIntent);
327		Notification notification = mBuilder.build();
328		mNotificationManager.notify(1111, notification);
329	}
330
331	public static void updateNotification(Context context,
332			List<Conversation> conversations, Conversation currentCon, boolean notify) {
333		NotificationManager mNotificationManager = (NotificationManager) context
334				.getSystemService(Context.NOTIFICATION_SERVICE);
335		
336		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
337		boolean useSubject = preferences.getBoolean("use_subject_in_muc", true);
338		boolean showNofifications = preferences.getBoolean("show_notification",true);
339		boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
340		boolean alwaysNotify = preferences.getBoolean("notify_in_conversation_when_highlighted", false);
341
342		if (!showNofifications) {
343			mNotificationManager.cancel(2342);
344			return;
345		}
346		
347		String targetUuid = "";
348		
349		if ((currentCon != null) &&(currentCon.getMode() == Conversation.MODE_MULTI)&&(!alwaysNotify)) {
350			String nick = currentCon.getMucOptions().getNick();
351			notify = currentCon.getLatestMessage().getBody().contains(nick);
352		}
353		
354		List<Conversation> unread = new ArrayList<Conversation>();
355		for (Conversation conversation : conversations) {
356			if (conversation.getMode() == Conversation.MODE_MULTI) {
357				if ((!conversation.isRead())&&((wasHighlighted(conversation)||(alwaysNotify)))) {
358					unread.add(conversation);
359				}
360			} else {
361				if (!conversation.isRead()) {
362					unread.add(conversation);
363				}
364			}
365		}
366		String ringtone = preferences.getString("notification_ringtone", null);
367
368		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
369				context);
370		if (unread.size() == 0) {
371			mNotificationManager.cancel(2342);
372			return;
373		} else if (unread.size() == 1) {
374			Conversation conversation = unread.get(0);
375			targetUuid = conversation.getUuid();
376			mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation, 64,
377							context, true));
378			mBuilder.setContentTitle(conversation.getName(useSubject));
379			if (notify) {
380				mBuilder.setTicker(conversation.getLatestMessage().getReadableBody(context));
381			}
382			StringBuilder bigText = new StringBuilder();
383			List<Message> messages = conversation.getMessages();
384			String firstLine = "";
385			for (int i = messages.size() - 1; i >= 0; --i) {
386				if (!messages.get(i).isRead()) {
387					if (i == messages.size() - 1) {
388						firstLine = messages.get(i).getReadableBody(context);
389						bigText.append(firstLine);
390					} else {
391						firstLine = messages.get(i).getReadableBody(context);
392						bigText.insert(0, firstLine + "\n");
393					}
394				} else {
395					break;
396				}
397			}
398			mBuilder.setContentText(firstLine);
399			mBuilder.setStyle(new NotificationCompat.BigTextStyle()
400					.bigText(bigText.toString()));
401		} else {
402			NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
403			style.setBigContentTitle(unread.size() + " unread Conversations");
404			StringBuilder names = new StringBuilder();
405			for (int i = 0; i < unread.size(); ++i) {
406				targetUuid = unread.get(i).getUuid();
407				if (i < unread.size() - 1) {
408					names.append(unread.get(i).getName(useSubject) + ", ");
409				} else {
410					names.append(unread.get(i).getName(useSubject));
411				}
412				style.addLine(Html.fromHtml("<b>" + unread.get(i).getName(useSubject)
413						+ "</b> " + unread.get(i).getLatestMessage().getReadableBody(context)));
414			}
415			mBuilder.setContentTitle(unread.size() + " unread Conversations");
416			mBuilder.setContentText(names.toString());
417			mBuilder.setStyle(style);
418		}
419		if ((currentCon!=null)&&(notify)) {
420			targetUuid=currentCon.getUuid();
421		}
422		if (unread.size() != 0) {
423			mBuilder.setSmallIcon(R.drawable.notification);
424			if (notify) {
425				if (vibrate) {
426					int dat = 70;
427					long[] pattern = {0,3*dat,dat,dat};
428					mBuilder.setVibrate(pattern);
429				}
430				mBuilder.setLights(0xffffffff, 2000, 4000);
431				if (ringtone != null) {
432					mBuilder.setSound(Uri.parse(ringtone));
433				}
434			}
435
436			TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
437			stackBuilder.addParentStack(ConversationActivity.class);
438
439			Intent viewConversationIntent = new Intent(context,
440					ConversationActivity.class);
441			viewConversationIntent.setAction(Intent.ACTION_VIEW);
442			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
443					targetUuid);
444			viewConversationIntent
445					.setType(ConversationActivity.VIEW_CONVERSATION);
446			
447			stackBuilder.addNextIntent(viewConversationIntent);
448
449			PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
450					0, PendingIntent.FLAG_UPDATE_CURRENT);
451			
452			mBuilder.setContentIntent(resultPendingIntent);
453			Notification notification = mBuilder.build();
454			mNotificationManager.notify(2342, notification);
455		}
456	}
457	
458	private static boolean wasHighlighted(Conversation conversation) {
459		List<Message> messages = conversation.getMessages();
460		String nick = conversation.getMucOptions().getNick();
461		for(int i = messages.size() - 1; i >= 0; --i) {
462			if (messages.get(i).isRead()) {
463				break;
464			} else {
465				if (messages.get(i).getBody().contains(nick)) {
466					return true;
467				}
468			}
469		}
470		return false;
471	}
472
473	public static void prepareContactBadge(final Activity activity,
474			QuickContactBadge badge, final Contact contact, Context context) {
475		if (contact.getSystemAccount() != null) {
476			String[] systemAccount = contact.getSystemAccount().split("#");
477			long id = Long.parseLong(systemAccount[0]);
478			badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
479		}
480		badge.setImageBitmap(UIHelper.getContactPicture(contact, 72, context, false));
481	}
482
483	public static AlertDialog getVerifyFingerprintDialog(
484			final ConversationActivity activity,
485			final Conversation conversation, final LinearLayout msg) {
486		final Contact contact = conversation.getContact();
487		final Account account = conversation.getAccount();
488
489		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
490		builder.setTitle("Verify fingerprint");
491		LayoutInflater inflater = activity.getLayoutInflater();
492		View view = inflater.inflate(R.layout.dialog_verify_otr, null);
493		TextView jid = (TextView) view.findViewById(R.id.verify_otr_jid);
494		TextView fingerprint = (TextView) view
495				.findViewById(R.id.verify_otr_fingerprint);
496		TextView yourprint = (TextView) view
497				.findViewById(R.id.verify_otr_yourprint);
498
499		jid.setText(contact.getJid());
500		fingerprint.setText(conversation.getOtrFingerprint());
501		yourprint.setText(account.getOtrFingerprint());
502		builder.setNegativeButton("Cancel", null);
503		builder.setPositiveButton("Verify", new OnClickListener() {
504
505			@Override
506			public void onClick(DialogInterface dialog, int which) {
507				contact.addOtrFingerprint(conversation.getOtrFingerprint());
508				msg.setVisibility(View.GONE);
509				activity.xmppConnectionService.updateContact(contact);
510			}
511		});
512		builder.setView(view);
513		return builder.create();
514	}
515
516	public static Bitmap getSelfContactPicture(Account account, int size, boolean showPhoneSelfContactPicture, Context context) {
517		if (showPhoneSelfContactPicture) {
518			Uri selfiUri = PhoneHelper.getSefliUri(context);
519			if (selfiUri != null) {
520				try {
521					return BitmapFactory.decodeStream(context
522							.getContentResolver().openInputStream(selfiUri));
523				} catch (FileNotFoundException e) {
524					return getContactPicture(account.getJid(), size, context, false);
525				}
526			}
527			return getContactPicture(account.getJid(), size, context, false);
528		} else {
529			return getContactPicture(account.getJid(), size, context, false);
530		}
531	}
532}