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(Context context, long time) {
 54		if (time == 0) {
 55			return context.getString(R.string.just_now);
 56		}
 57		Date date = new Date(time);
 58		long difference = (System.currentTimeMillis() - time) / 1000;
 59		if (difference < 60) {
 60			return context.getString(R.string.just_now);
 61		} else if (difference < 60 * 10) {
 62			return difference / 60 + " " + context.getString(R.string.minutes_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				return getContactPicture(conversation.getContact(), dpSize,
251						context, notification);
252		} else{
253			int fgColor = UIHelper.FG_COLOR,
254				bgColor = (notification) ?
255					UIHelper.BG_COLOR : UIHelper.TRANSPARENT;
256
257			return getMucContactPicture(conversation, getRealPx(dpSize, context),
258					bgColor, fgColor);
259		}
260	}
261
262	public static Bitmap getContactPicture(Contact contact, int dpSize, Context context, boolean notification) {
263		String uri = contact.getProfilePhoto();
264		if (uri==null) {
265			return getContactPicture(contact.getDisplayName(), dpSize,
266					context, notification);
267		}
268		try {
269			Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver()
270					.openInputStream(Uri.parse(uri)));
271			return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context),
272					getRealPx(dpSize, context), false);
273		} catch (FileNotFoundException e) {
274			return getContactPicture(contact.getDisplayName(), dpSize,
275					context, notification);
276		}
277	}
278
279	public static Bitmap getContactPicture(String name, int dpSize, Context context, boolean notification) {
280		int fgColor = UIHelper.FG_COLOR,
281			bgColor = (notification) ?
282				UIHelper.BG_COLOR : UIHelper.TRANSPARENT;
283
284		return getUnknownContactPicture(new String[]{name}, getRealPx(dpSize, context),
285				bgColor, fgColor);
286	}
287
288	public static void showErrorNotification(Context context, List<Account> accounts) {
289		NotificationManager mNotificationManager = (NotificationManager) context
290				.getSystemService(Context.NOTIFICATION_SERVICE);
291		List<Account> accountsWproblems = new ArrayList<Account>();
292		for(Account account : accounts) {
293			if (account.hasErrorStatus()) {
294				accountsWproblems.add(account);
295			}
296		}
297		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
298		if (accountsWproblems.size() == 0) {
299			mNotificationManager.cancel(1111);
300			return;
301		} else if (accountsWproblems.size() == 1) {
302			mBuilder.setContentTitle(context.getString(R.string.problem_connecting_to_account));
303			mBuilder.setContentText(accountsWproblems.get(0).getJid());
304		} else {
305			mBuilder.setContentTitle(context.getString(R.string.problem_connecting_to_accounts));
306			mBuilder.setContentText(context.getString(R.string.touch_to_fix));
307		}
308		mBuilder.setOngoing(true);
309		mBuilder.setLights(0xffffffff, 2000, 4000);
310		mBuilder.setSmallIcon(R.drawable.notification);
311		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
312		stackBuilder.addParentStack(ConversationActivity.class);
313
314		Intent manageAccountsIntent = new Intent(context,
315				ManageAccountActivity.class);
316		stackBuilder.addNextIntent(manageAccountsIntent);
317
318		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
319				0, PendingIntent.FLAG_UPDATE_CURRENT);
320		
321		mBuilder.setContentIntent(resultPendingIntent);
322		Notification notification = mBuilder.build();
323		mNotificationManager.notify(1111, notification);
324	}
325
326	public static void updateNotification(Context context,
327			List<Conversation> conversations, Conversation currentCon, boolean notify) {
328		NotificationManager mNotificationManager = (NotificationManager) context
329				.getSystemService(Context.NOTIFICATION_SERVICE);
330		
331		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
332		boolean useSubject = preferences.getBoolean("use_subject_in_muc", true);
333		boolean showNofifications = preferences.getBoolean("show_notification",true);
334		boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
335		boolean alwaysNotify = preferences.getBoolean("notify_in_conversation_when_highlighted", false);
336
337		if (!showNofifications) {
338			mNotificationManager.cancel(2342);
339			return;
340		}
341		
342		String targetUuid = "";
343		
344		if ((currentCon != null) &&(currentCon.getMode() == Conversation.MODE_MULTI)&&(!alwaysNotify)) {
345			String nick = currentCon.getMucOptions().getNick();
346			notify = currentCon.getLatestMessage().getBody().contains(nick);
347		}
348		
349		List<Conversation> unread = new ArrayList<Conversation>();
350		for (Conversation conversation : conversations) {
351			if (conversation.getMode() == Conversation.MODE_MULTI) {
352				if ((!conversation.isRead())&&((wasHighlighted(conversation)||(alwaysNotify)))) {
353					unread.add(conversation);
354				}
355			} else {
356				if (!conversation.isRead()) {
357					unread.add(conversation);
358				}
359			}
360		}
361		String ringtone = preferences.getString("notification_ringtone", null);
362
363		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
364				context);
365		if (unread.size() == 0) {
366			mNotificationManager.cancel(2342);
367			return;
368		} else if (unread.size() == 1) {
369			Conversation conversation = unread.get(0);
370			targetUuid = conversation.getUuid();
371			mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation, 64,
372							context, true));
373			mBuilder.setContentTitle(conversation.getName(useSubject));
374			if (notify) {
375				mBuilder.setTicker(conversation.getLatestMessage().getReadableBody(context));
376			}
377			StringBuilder bigText = new StringBuilder();
378			List<Message> messages = conversation.getMessages();
379			String firstLine = "";
380			for (int i = messages.size() - 1; i >= 0; --i) {
381				if (!messages.get(i).isRead()) {
382					if (i == messages.size() - 1) {
383						firstLine = messages.get(i).getReadableBody(context);
384						bigText.append(firstLine);
385					} else {
386						firstLine = messages.get(i).getReadableBody(context);
387						bigText.insert(0, firstLine + "\n");
388					}
389				} else {
390					break;
391				}
392			}
393			mBuilder.setContentText(firstLine);
394			mBuilder.setStyle(new NotificationCompat.BigTextStyle()
395					.bigText(bigText.toString()));
396		} else {
397			NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
398			style.setBigContentTitle(unread.size() + " " + context.getString(R.string.unread_conversations));
399			StringBuilder names = new StringBuilder();
400			for (int i = 0; i < unread.size(); ++i) {
401				targetUuid = unread.get(i).getUuid();
402				if (i < unread.size() - 1) {
403					names.append(unread.get(i).getName(useSubject) + ", ");
404				} else {
405					names.append(unread.get(i).getName(useSubject));
406				}
407				style.addLine(Html.fromHtml("<b>" + unread.get(i).getName(useSubject)
408						+ "</b> " + unread.get(i).getLatestMessage().getReadableBody(context)));
409			}
410			mBuilder.setContentTitle(unread.size() + " " + context.getString(R.string.unread_conversations));
411			mBuilder.setContentText(names.toString());
412			mBuilder.setStyle(style);
413		}
414		if ((currentCon!=null)&&(notify)) {
415			targetUuid=currentCon.getUuid();
416		}
417		if (unread.size() != 0) {
418			mBuilder.setSmallIcon(R.drawable.notification);
419			if (notify) {
420				if (vibrate) {
421					int dat = 70;
422					long[] pattern = {0,3*dat,dat,dat};
423					mBuilder.setVibrate(pattern);
424				}
425				mBuilder.setLights(0xffffffff, 2000, 4000);
426				if (ringtone != null) {
427					mBuilder.setSound(Uri.parse(ringtone));
428				}
429			}
430
431			TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
432			stackBuilder.addParentStack(ConversationActivity.class);
433
434			Intent viewConversationIntent = new Intent(context,
435					ConversationActivity.class);
436			viewConversationIntent.setAction(Intent.ACTION_VIEW);
437			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
438					targetUuid);
439			viewConversationIntent
440					.setType(ConversationActivity.VIEW_CONVERSATION);
441			
442			stackBuilder.addNextIntent(viewConversationIntent);
443
444			PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
445					0, PendingIntent.FLAG_UPDATE_CURRENT);
446			
447			mBuilder.setContentIntent(resultPendingIntent);
448			Notification notification = mBuilder.build();
449			mNotificationManager.notify(2342, notification);
450		}
451	}
452	
453	private static boolean wasHighlighted(Conversation conversation) {
454		List<Message> messages = conversation.getMessages();
455		String nick = conversation.getMucOptions().getNick();
456		for(int i = messages.size() - 1; i >= 0; --i) {
457			if (messages.get(i).isRead()) {
458				break;
459			} else {
460				if (messages.get(i).getBody().contains(nick)) {
461					return true;
462				}
463			}
464		}
465		return false;
466	}
467
468	public static void prepareContactBadge(final Activity activity,
469			QuickContactBadge badge, final Contact contact, Context context) {
470		if (contact.getSystemAccount() != null) {
471			String[] systemAccount = contact.getSystemAccount().split("#");
472			long id = Long.parseLong(systemAccount[0]);
473			badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
474		}
475		badge.setImageBitmap(UIHelper.getContactPicture(contact, 72, context, false));
476	}
477
478	public static AlertDialog getVerifyFingerprintDialog(
479			final ConversationActivity activity,
480			final Conversation conversation, final LinearLayout msg) {
481		final Contact contact = conversation.getContact();
482		final Account account = conversation.getAccount();
483
484		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
485		builder.setTitle("Verify fingerprint");
486		LayoutInflater inflater = activity.getLayoutInflater();
487		View view = inflater.inflate(R.layout.dialog_verify_otr, null);
488		TextView jid = (TextView) view.findViewById(R.id.verify_otr_jid);
489		TextView fingerprint = (TextView) view
490				.findViewById(R.id.verify_otr_fingerprint);
491		TextView yourprint = (TextView) view
492				.findViewById(R.id.verify_otr_yourprint);
493
494		jid.setText(contact.getJid());
495		fingerprint.setText(conversation.getOtrFingerprint());
496		yourprint.setText(account.getOtrFingerprint());
497		builder.setNegativeButton("Cancel", null);
498		builder.setPositiveButton("Verify", new OnClickListener() {
499
500			@Override
501			public void onClick(DialogInterface dialog, int which) {
502				contact.addOtrFingerprint(conversation.getOtrFingerprint());
503				msg.setVisibility(View.GONE);
504				//activity.xmppConnectionService.updateContact(contact);
505			}
506		});
507		builder.setView(view);
508		return builder.create();
509	}
510
511	public static Bitmap getSelfContactPicture(Account account, int size, boolean showPhoneSelfContactPicture, Context context) {
512		if (showPhoneSelfContactPicture) {
513			Uri selfiUri = PhoneHelper.getSefliUri(context);
514			if (selfiUri != null) {
515				try {
516					return BitmapFactory.decodeStream(context
517							.getContentResolver().openInputStream(selfiUri));
518				} catch (FileNotFoundException e) {
519					return getContactPicture(account.getJid(), size, context, false);
520				}
521			}
522			return getContactPicture(account.getJid(), size, context, false);
523		} else {
524			return getContactPicture(account.getJid(), size, context, false);
525		}
526	}
527}