AvatarMaker.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2014-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "AvatarMaker.h"
  21. #import "Contact.h"
  22. #import "Conversation.h"
  23. #import "ImageData.h"
  24. #import "UIImage+Mask.h"
  25. #import "UserSettings.h"
  26. #import "GatewayAvatarMaker.h"
  27. #import "BundleUtil.h"
  28. #import "UIImage+ColoredImage.h"
  29. #import "UIImage+Resize.h"
  30. static AvatarMaker *sharedInstance = nil;
  31. @interface AvatarMaker ()
  32. @property NSCache *avatarCache;
  33. @property NSCache *maskedImageCache;
  34. @property dispatch_queue_t dispatchQueue;
  35. @end
  36. @implementation AvatarMaker
  37. + (AvatarMaker*)sharedAvatarMaker {
  38. static dispatch_once_t pred;
  39. dispatch_once(&pred, ^{
  40. sharedInstance = [[AvatarMaker alloc] init];
  41. });
  42. return sharedInstance;
  43. }
  44. + (void)clearCache {
  45. [sharedInstance.avatarCache removeAllObjects];
  46. }
  47. + (UIImage *)avatarWithString:(NSString *)string size:(CGFloat)size {
  48. CGSize canvasSize = CGSizeMake(size, size);
  49. UIColor *fontColor = [Colors fontLight];
  50. UIFont *initialsFont = [UIFont fontWithName:@"Helvetica" size:0.4*size];
  51. UIGraphicsBeginImageContextWithOptions(canvasSize, NO, 1);
  52. CGContextRef context = UIGraphicsGetCurrentContext();
  53. UIGraphicsPushContext(context);
  54. /* Circle */
  55. CGFloat lineWidth = 0.018f * size;
  56. CGContextSetLineWidth(context, lineWidth);
  57. CGContextSetStrokeColorWithColor(context, fontColor.CGColor);
  58. CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
  59. CGRect circleRect = CGRectMake(0, 0, canvasSize.width, canvasSize.height);
  60. circleRect = CGRectInset(circleRect, lineWidth/2, lineWidth/2);
  61. CGContextFillEllipseInRect(context, circleRect);
  62. CGContextStrokeEllipseInRect(context, circleRect);
  63. /* Initials */
  64. if (string) {
  65. [fontColor set];
  66. CGSize textSize = [string sizeWithAttributes:@{NSFontAttributeName: initialsFont}];
  67. [string drawAtPoint:CGPointMake((canvasSize.width - textSize.width)/2, (canvasSize.height - textSize.height)/2) withAttributes:@{NSFontAttributeName: initialsFont, NSForegroundColorAttributeName: fontColor}];
  68. }
  69. UIGraphicsPopContext();
  70. UIImage *avatar = UIGraphicsGetImageFromCurrentImageContext();
  71. UIGraphicsEndImageContext();
  72. return avatar;
  73. }
  74. - (instancetype)init {
  75. self = [super init];
  76. if (self) {
  77. _avatarCache = [[NSCache alloc] init];
  78. _maskedImageCache = [[NSCache alloc] init];
  79. _dispatchQueue = dispatch_queue_create("ch.threema.AvatarMaker", NULL);
  80. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectImageChanged:) name:@"ThreemaContactImageChanged" object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectImageChanged:) name:@"ThreemaGroupConversationImageChanged" object:nil];
  83. }
  84. return self;
  85. }
  86. - (void)dealloc {
  87. [[NSNotificationCenter defaultCenter] removeObserver:self];
  88. }
  89. - (void)applicationDidReceiveMemoryWarning:(NSNotification*)notification {
  90. [_avatarCache removeAllObjects];
  91. [_maskedImageCache removeAllObjects];
  92. }
  93. - (void)clearCacheForProfilePicture {
  94. [sharedInstance.maskedImageCache removeObjectForKey:@"myProfilePicture"];
  95. [_maskedImageCache removeAllObjects];
  96. }
  97. - (void)managedObjectImageChanged:(NSNotification*)notification {
  98. NSManagedObject *managedObject = notification.object;
  99. [_maskedImageCache removeObjectForKey:managedObject.objectID];
  100. }
  101. - (void)avatarForContact:(Contact*)contact size:(CGFloat)size masked:(BOOL)masked onCompletion:(void (^)(UIImage *avatarImage))onCompletion {
  102. dispatch_async(_dispatchQueue, ^{
  103. UIImage *avatarImage = [self avatarForContact:contact size:size masked:masked];
  104. onCompletion(avatarImage);
  105. });
  106. }
  107. - (UIImage*)avatarForContact:(Contact*)contact size:(CGFloat)size masked:(BOOL)masked {
  108. return [self avatarForContact:contact size:size masked:masked scaled:YES];
  109. }
  110. - (UIImage*)avatarForContact:(Contact*)contact size:(CGFloat)size masked:(BOOL)masked scaled:(BOOL)scaled {
  111. /* If this contact has sent us an image, we'll use that and not make an avatar */
  112. CGFloat sizeScaled = size;
  113. if (scaled)
  114. sizeScaled = sizeScaled * [UIScreen mainScreen].scale;
  115. if (contact.contactImage != nil && [UserSettings sharedUserSettings].showProfilePictures) {
  116. if (contact.contactImage.data != nil) {
  117. UIImage *avatar;
  118. if (masked) {
  119. avatar = [self maskedImageForContact:contact ownImage:NO];
  120. } else {
  121. avatar = [UIImage imageWithData:contact.contactImage.data];
  122. }
  123. if (avatar != nil) {
  124. return [avatar resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(sizeScaled, sizeScaled) interpolationQuality:kCGInterpolationHigh];
  125. }
  126. }
  127. }
  128. /* If this contact has an image (but not from abRecord), we'll use that and not the received image */
  129. if (contact.imageData != nil && (contact.cnContactId == nil)) {
  130. UIImage *avatar;
  131. if (masked) {
  132. avatar = [self maskedImageForContact:contact ownImage:YES];
  133. } else {
  134. avatar = [UIImage imageWithData:contact.imageData];
  135. }
  136. if (avatar != nil) {
  137. return [avatar resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(sizeScaled, sizeScaled) interpolationQuality:kCGInterpolationHigh];
  138. }
  139. }
  140. /* If this contact has an image from abRecord, we'll use that and not a generic icon */
  141. if (contact.imageData != nil && contact.cnContactId != nil) {
  142. UIImage *avatar;
  143. if (masked) {
  144. avatar = [self maskedImageForContact:contact ownImage:YES];
  145. } else {
  146. avatar = [UIImage imageWithData:contact.imageData];
  147. }
  148. if (avatar != nil) {
  149. return [avatar resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(sizeScaled, sizeScaled) interpolationQuality:kCGInterpolationHigh];
  150. }
  151. }
  152. if (contact.isGatewayId) {
  153. UIImage *avatar = [BundleUtil imageNamed:@"Asterisk"];
  154. avatar = [avatar resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(sizeScaled, sizeScaled) interpolationQuality:kCGInterpolationHigh];
  155. return [avatar imageWithTint:[Colors fontLight]];
  156. }
  157. /* If there is no contact, then use a generic icon */
  158. if (contact == nil) {
  159. UIImage *avatar = [self unknownPersonImage];
  160. avatar = [avatar resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(sizeScaled, sizeScaled) interpolationQuality:kCGInterpolationHigh];
  161. return [avatar imageWithTint:[Colors fontLight]];
  162. }
  163. NSString *initials = [self initialsForContact:contact];
  164. /* check cache first */
  165. NSString *cacheKey = [NSString stringWithFormat:@"%@-%.0f", initials, sizeScaled];
  166. UIImage *cachedImage = [_avatarCache objectForKey:cacheKey];
  167. if (cachedImage != nil) {
  168. return cachedImage;
  169. }
  170. UIImage *avatar = [AvatarMaker avatarWithString:initials size:sizeScaled];
  171. /* Put in cache */
  172. [_avatarCache setObject:avatar forKey:cacheKey];
  173. return avatar;
  174. }
  175. - (void)avatarForConversation:(Conversation*)conversation size:(CGFloat)size masked:(BOOL)masked onCompletion:(void (^)(UIImage *avatarImage))onCompletion {
  176. dispatch_async(_dispatchQueue, ^{
  177. UIImage *avatarImage = [self avatarForConversation:conversation size:size masked:masked];
  178. onCompletion(avatarImage);
  179. });
  180. }
  181. - (UIImage*)avatarForConversation:(Conversation*)conversation size:(CGFloat)size masked:(BOOL)masked {
  182. return [self avatarForConversation:conversation size:size masked:masked scaled:YES];
  183. }
  184. - (UIImage*)avatarForConversation:(Conversation*)conversation size:(CGFloat)size masked:(BOOL)masked scaled:(BOOL)scaled {
  185. if (conversation.groupId == nil)
  186. return [self avatarForContact:conversation.contact size:size masked:masked];
  187. /* For groups, use the group image if available, or a default image otherwise */
  188. if (conversation.groupImage != nil) {
  189. UIImage *avatar;
  190. if (masked) {
  191. avatar = [self maskedImageForGroupConversation:conversation];
  192. } else {
  193. avatar = [UIImage imageWithData:conversation.groupImage.data];
  194. }
  195. if (scaled)
  196. size = size * [UIScreen mainScreen].scale;
  197. return [avatar resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(size, size) interpolationQuality:kCGInterpolationHigh];
  198. } else {
  199. UIImage *groupImage = [BundleUtil imageNamed:@"UnknownGroup"];
  200. if (scaled)
  201. size = size * [UIScreen mainScreen].scale;
  202. groupImage = [groupImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit bounds:CGSizeMake(size, size) interpolationQuality:kCGInterpolationHigh];
  203. return [groupImage imageWithTint:[Colors fontLight]];
  204. }
  205. }
  206. - (UIImage *)avatarForFirstName:(NSString *)firstName lastName:(NSString *)lastName size:(CGFloat)size {
  207. CGFloat sizeScaled = size * [UIScreen mainScreen].scale;;
  208. NSString *initials = nil;
  209. if (firstName.length > 0 && lastName.length > 0) {
  210. if ([UserSettings sharedUserSettings].displayOrderFirstName)
  211. initials = [NSString stringWithFormat:@"%@%@", [firstName substringToIndex:1], [lastName substringToIndex:1]];
  212. else
  213. initials = [NSString stringWithFormat:@"%@%@", [lastName substringToIndex:1], [firstName substringToIndex:1]];
  214. } else {
  215. return [self unknownPersonImage];
  216. }
  217. /* check cache first */
  218. NSString *cacheKey = [NSString stringWithFormat:@"%@-%.0f", initials, sizeScaled];
  219. UIImage *cachedImage = [_avatarCache objectForKey:cacheKey];
  220. if (cachedImage != nil) {
  221. return cachedImage;
  222. }
  223. UIImage *avatar = [AvatarMaker avatarWithString:initials size:sizeScaled];
  224. /* Put in cache */
  225. [_avatarCache setObject:avatar forKey:cacheKey];
  226. return avatar;
  227. }
  228. - (UIImage*)maskedProfilePicture:(UIImage *)image size:(CGFloat)size {
  229. if (image == nil) {
  230. return [self unknownPersonImage];
  231. }
  232. UIImage *maskedImage = [_maskedImageCache objectForKey:@"myProfilePicture"];
  233. if (maskedImage == nil) {
  234. maskedImage = [AvatarMaker maskImage:image];
  235. if (maskedImage) {
  236. [_maskedImageCache setObject:maskedImage forKey:@"myProfilePicture"];
  237. }
  238. }
  239. return maskedImage;
  240. }
  241. - (UIImage *)callBackgroundForContact:(Contact *)contact {
  242. /* If this contact has send us a image, we'll use that and not make an avatar */
  243. if (contact.contactImage != nil && [UserSettings sharedUserSettings].showProfilePictures) {
  244. return [UIImage imageWithData:contact.contactImage.data];
  245. }
  246. /* If this contact has an image (but not from abRecord), we'll use that and not the received image */
  247. if (contact.imageData != nil && contact.cnContactId == nil) {
  248. return [UIImage imageWithData:contact.imageData];
  249. }
  250. /* If this contact has an image from abRecord, we'll use that and not a generic icon */
  251. if (contact.imageData != nil && contact.cnContactId != nil) {
  252. return [UIImage imageWithData:contact.imageData];
  253. }
  254. NSString *initials = [self initialsForContact:contact];
  255. /* check cache first */
  256. NSString *cacheKey = [NSString stringWithFormat:@"%@-background", initials];
  257. UIImage *cachedImage = [_avatarCache objectForKey:cacheKey];
  258. if (cachedImage != nil) {
  259. return cachedImage;
  260. }
  261. UIImage *avatar = [AvatarMaker avatarWithString:initials size:[[UIScreen mainScreen] bounds].size.width];
  262. /* Put in cache */
  263. [_avatarCache setObject:avatar forKey:cacheKey];
  264. return avatar;
  265. }
  266. - (UIImage*)maskedImageForContact:(Contact*)contact ownImage:(BOOL)ownImage {
  267. if (ownImage) {
  268. return [self maskedImageForManagedObject:contact imageData:contact.imageData];
  269. }
  270. else {
  271. return [self maskedImageForManagedObject:contact imageData:contact.contactImage.data];
  272. }
  273. }
  274. - (UIImage*)maskedImageForGroupConversation:(Conversation*)conversation {
  275. return [self maskedImageForManagedObject:conversation imageData:conversation.groupImage.data];
  276. }
  277. - (UIImage*)maskedImageForManagedObject:(NSManagedObject*)managedObject imageData:(NSData*)imageData {
  278. if (imageData == nil) {
  279. return nil;
  280. }
  281. UIImage *maskedImage = [_maskedImageCache objectForKey:managedObject.objectID];
  282. if (maskedImage == nil) {
  283. maskedImage = [UIImage imageWithData:imageData];
  284. maskedImage = [AvatarMaker maskImage:maskedImage];
  285. if (maskedImage) {
  286. [_maskedImageCache setObject:maskedImage forKey:managedObject.objectID];
  287. }
  288. }
  289. return maskedImage;
  290. }
  291. + (UIImage *)maskImage:(UIImage *)image {
  292. UIImage *personMask = [BundleUtil imageNamed:@"PersonMask"];
  293. UIImage *maskedImage = [image maskWithImage:personMask];
  294. return maskedImage;
  295. }
  296. - (UIImage *)companyImage {
  297. return [[BundleUtil imageNamed:@"Asterisk"] imageWithTint:[Colors main]];
  298. }
  299. - (UIImage *)unknownPersonImage {
  300. return [[BundleUtil imageNamed:@"UnknownPerson"] imageWithTint:[Colors fontLight]];
  301. }
  302. - (NSString*)initialsForContact:(Contact*)contact {
  303. if (contact.firstName.length > 0 && contact.lastName.length > 0) {
  304. if ([UserSettings sharedUserSettings].displayOrderFirstName)
  305. return [NSString stringWithFormat:@"%@%@", [contact.firstName substringToIndex:1], [contact.lastName substringToIndex:1]];
  306. else
  307. return [NSString stringWithFormat:@"%@%@", [contact.lastName substringToIndex:1], [contact.firstName substringToIndex:1]];
  308. } else if (contact.displayName.length >= 2) {
  309. return [contact.displayName substringToIndex:2];
  310. } else {
  311. return @"-";
  312. }
  313. }
  314. - (BOOL)isDefaultAvatarForContact:(Contact *)contact {
  315. /* If this contact has send us a image, we'll use that and not make an avatar */
  316. if (contact.contactImage != nil && [UserSettings sharedUserSettings].showProfilePictures) {
  317. return false;
  318. }
  319. /* If this contact has an image (but not from abRecord), we'll use that and not the received image */
  320. if (contact.imageData != nil && contact.cnContactId == nil) {
  321. return false;
  322. }
  323. /* If this contact has an image from abRecord, we'll use that and not a generic icon */
  324. if (contact.imageData != nil && contact.cnContactId != nil) {
  325. return false;
  326. }
  327. return true;
  328. }
  329. @end