MWPhoto.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // This file is based on third party code, see below for the original author
  2. // and original license.
  3. // Modifications are (c) by Threema GmbH and licensed under the AGPLv3.
  4. //
  5. // MWPhoto.m
  6. // MWPhotoBrowser
  7. //
  8. // Created by Michael Waterfall on 17/10/2010.
  9. // Copyright 2010 d3i. All rights reserved.
  10. //
  11. #import <SDWebImage/SDWebImageDecoder.h>
  12. #import <SDWebImage/SDWebImageManager.h>
  13. #import <SDWebImage/SDWebImageOperation.h>
  14. #import <AssetsLibrary/AssetsLibrary.h>
  15. #import "MWPhoto.h"
  16. #import "MWPhotoBrowser.h"
  17. @interface MWPhoto () {
  18. BOOL _loadingInProgress;
  19. id <SDWebImageOperation> _webImageOperation;
  20. PHImageRequestID _assetRequestID;
  21. PHImageRequestID _assetVideoRequestID;
  22. }
  23. @property (nonatomic, strong) UIImage *image;
  24. @property (nonatomic, strong) NSURL *photoURL;
  25. @property (nonatomic, strong) PHAsset *asset;
  26. @property (nonatomic) CGSize assetTargetSize;
  27. - (void)imageLoadingComplete;
  28. @end
  29. @implementation MWPhoto
  30. @synthesize underlyingImage = _underlyingImage; // synth property from protocol
  31. #pragma mark - Class Methods
  32. + (MWPhoto *)photoWithImage:(UIImage *)image {
  33. return [[MWPhoto alloc] initWithImage:image];
  34. }
  35. + (MWPhoto *)photoWithURL:(NSURL *)url {
  36. return [[MWPhoto alloc] initWithURL:url];
  37. }
  38. + (MWPhoto *)photoWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
  39. return [[MWPhoto alloc] initWithAsset:asset targetSize:targetSize];
  40. }
  41. + (MWPhoto *)videoWithURL:(NSURL *)url {
  42. return [[MWPhoto alloc] initWithVideoURL:url];
  43. }
  44. #pragma mark - Init
  45. - (id)init {
  46. if ((self = [super init])) {
  47. self.emptyImage = YES;
  48. [self setup];
  49. }
  50. return self;
  51. }
  52. - (id)initWithImage:(UIImage *)image {
  53. if ((self = [super init])) {
  54. self.image = image;
  55. [self setup];
  56. }
  57. return self;
  58. }
  59. - (id)initWithURL:(NSURL *)url {
  60. if ((self = [super init])) {
  61. self.photoURL = url;
  62. [self setup];
  63. }
  64. return self;
  65. }
  66. - (id)initWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
  67. if ((self = [super init])) {
  68. self.asset = asset;
  69. self.assetTargetSize = targetSize;
  70. self.isVideo = asset.mediaType == PHAssetMediaTypeVideo;
  71. [self setup];
  72. }
  73. return self;
  74. }
  75. - (id)initWithVideoURL:(NSURL *)url {
  76. if ((self = [super init])) {
  77. self.videoURL = url;
  78. self.isVideo = YES;
  79. self.emptyImage = YES;
  80. [self setup];
  81. }
  82. return self;
  83. }
  84. - (void)setup {
  85. _assetRequestID = PHInvalidImageRequestID;
  86. _assetVideoRequestID = PHInvalidImageRequestID;
  87. }
  88. - (void)dealloc {
  89. [self cancelAnyLoading];
  90. }
  91. #pragma mark - Video
  92. - (void)setVideoURL:(NSURL *)videoURL {
  93. _videoURL = videoURL;
  94. self.isVideo = YES;
  95. }
  96. - (void)getVideoURL:(void (^)(NSURL *url))completion {
  97. if (_videoURL) {
  98. completion(_videoURL);
  99. } else if (_asset && _asset.mediaType == PHAssetMediaTypeVideo) {
  100. [self cancelVideoRequest]; // Cancel any existing
  101. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  102. options.networkAccessAllowed = YES;
  103. typeof(self) __weak weakSelf = self;
  104. _assetVideoRequestID = [[PHImageManager defaultManager] requestAVAssetForVideo:_asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  105. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ // Testing
  106. typeof(self) strongSelf = weakSelf;
  107. if (!strongSelf) return;
  108. strongSelf->_assetVideoRequestID = PHInvalidImageRequestID;
  109. if ([asset isKindOfClass:[AVURLAsset class]]) {
  110. completion(((AVURLAsset *)asset).URL);
  111. } else {
  112. completion(nil);
  113. }
  114. }];
  115. }
  116. }
  117. #pragma mark - MWPhoto Protocol Methods
  118. - (UIImage *)underlyingImage {
  119. return _underlyingImage;
  120. }
  121. - (void)loadUnderlyingImageAndNotify {
  122. NSAssert([[NSThread currentThread] isMainThread], @"This method must be called on the main thread.");
  123. if (_loadingInProgress) return;
  124. _loadingInProgress = YES;
  125. @try {
  126. if (self.underlyingImage) {
  127. [self imageLoadingComplete];
  128. } else {
  129. [self performLoadUnderlyingImageAndNotify];
  130. }
  131. }
  132. @catch (NSException *exception) {
  133. self.underlyingImage = nil;
  134. _loadingInProgress = NO;
  135. [self imageLoadingComplete];
  136. }
  137. @finally {
  138. }
  139. }
  140. // Set the underlyingImage
  141. - (void)performLoadUnderlyingImageAndNotify {
  142. // Get underlying image
  143. if (_image) {
  144. // We have UIImage!
  145. self.underlyingImage = _image;
  146. [self imageLoadingComplete];
  147. } else if (_photoURL) {
  148. // Check what type of url it is
  149. if ([[[_photoURL scheme] lowercaseString] isEqualToString:@"assets-library"]) {
  150. // Load from assets library
  151. [self _performLoadUnderlyingImageAndNotifyWithAssetsLibraryURL: _photoURL];
  152. } else if ([_photoURL isFileReferenceURL]) {
  153. // Load from local file async
  154. [self _performLoadUnderlyingImageAndNotifyWithLocalFileURL: _photoURL];
  155. } else {
  156. // Load async from web (using SDWebImage)
  157. [self _performLoadUnderlyingImageAndNotifyWithWebURL: _photoURL];
  158. }
  159. } else if (_asset) {
  160. // Load from photos asset
  161. [self _performLoadUnderlyingImageAndNotifyWithAsset: _asset targetSize:_assetTargetSize];
  162. } else {
  163. // Image is empty
  164. [self imageLoadingComplete];
  165. }
  166. }
  167. // Load from local file
  168. - (void)_performLoadUnderlyingImageAndNotifyWithWebURL:(NSURL *)url {
  169. @try {
  170. SDWebImageManager *manager = [SDWebImageManager sharedManager];
  171. _webImageOperation = [manager downloadImageWithURL:url
  172. options:0
  173. progress:^(NSInteger receivedSize, NSInteger expectedSize) {
  174. if (expectedSize > 0) {
  175. float progress = receivedSize / (float)expectedSize;
  176. NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
  177. [NSNumber numberWithFloat:progress], @"progress",
  178. self, @"photo", nil];
  179. [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_PROGRESS_NOTIFICATION object:dict];
  180. }
  181. }
  182. completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
  183. if (error) {
  184. MWLog(@"SDWebImage failed to download image: %@", error);
  185. }
  186. _webImageOperation = nil;
  187. self.underlyingImage = image;
  188. dispatch_async(dispatch_get_main_queue(), ^{
  189. [self imageLoadingComplete];
  190. });
  191. }];
  192. } @catch (NSException *e) {
  193. MWLog(@"Photo from web: %@", e);
  194. _webImageOperation = nil;
  195. [self imageLoadingComplete];
  196. }
  197. }
  198. // Load from local file
  199. - (void)_performLoadUnderlyingImageAndNotifyWithLocalFileURL:(NSURL *)url {
  200. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  201. @autoreleasepool {
  202. @try {
  203. self.underlyingImage = [UIImage imageWithContentsOfFile:url.path];
  204. if (!_underlyingImage) {
  205. MWLog(@"Error loading photo from path: %@", url.path);
  206. }
  207. } @finally {
  208. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  209. }
  210. }
  211. });
  212. }
  213. // Load from asset library async
  214. - (void)_performLoadUnderlyingImageAndNotifyWithAssetsLibraryURL:(NSURL *)url {
  215. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  216. @autoreleasepool {
  217. @try {
  218. ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
  219. [assetslibrary assetForURL:url
  220. resultBlock:^(ALAsset *asset){
  221. ALAssetRepresentation *rep = [asset defaultRepresentation];
  222. CGImageRef iref = [rep fullScreenImage];
  223. if (iref) {
  224. self.underlyingImage = [UIImage imageWithCGImage:iref];
  225. }
  226. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  227. }
  228. failureBlock:^(NSError *error) {
  229. self.underlyingImage = nil;
  230. MWLog(@"Photo from asset library error: %@",error);
  231. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  232. }];
  233. } @catch (NSException *e) {
  234. MWLog(@"Photo from asset library error: %@", e);
  235. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  236. }
  237. }
  238. });
  239. }
  240. // Load from photos library
  241. - (void)_performLoadUnderlyingImageAndNotifyWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
  242. PHImageManager *imageManager = [PHImageManager defaultManager];
  243. PHImageRequestOptions *options = [PHImageRequestOptions new];
  244. options.networkAccessAllowed = YES;
  245. options.resizeMode = PHImageRequestOptionsResizeModeFast;
  246. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  247. options.synchronous = false;
  248. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  249. NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
  250. [NSNumber numberWithDouble: progress], @"progress",
  251. self, @"photo", nil];
  252. [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_PROGRESS_NOTIFICATION object:dict];
  253. };
  254. _assetRequestID = [imageManager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
  255. dispatch_async(dispatch_get_main_queue(), ^{
  256. self.underlyingImage = result;
  257. [self imageLoadingComplete];
  258. });
  259. }];
  260. }
  261. // Release if we can get it again from path or url
  262. - (void)unloadUnderlyingImage {
  263. _loadingInProgress = NO;
  264. self.underlyingImage = nil;
  265. }
  266. - (void)imageLoadingComplete {
  267. NSAssert([[NSThread currentThread] isMainThread], @"This method must be called on the main thread.");
  268. // Complete so notify
  269. _loadingInProgress = NO;
  270. // Notify on next run loop
  271. [self performSelector:@selector(postCompleteNotification) withObject:nil afterDelay:0];
  272. }
  273. - (void)postCompleteNotification {
  274. [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_LOADING_DID_END_NOTIFICATION
  275. object:self];
  276. }
  277. - (void)cancelAnyLoading {
  278. if (_webImageOperation != nil) {
  279. [_webImageOperation cancel];
  280. _loadingInProgress = NO;
  281. }
  282. [self cancelImageRequest];
  283. [self cancelVideoRequest];
  284. }
  285. - (void)cancelImageRequest {
  286. if (_assetRequestID != PHInvalidImageRequestID) {
  287. [[PHImageManager defaultManager] cancelImageRequest:_assetRequestID];
  288. _assetRequestID = PHInvalidImageRequestID;
  289. }
  290. }
  291. - (void)cancelVideoRequest {
  292. if (_assetVideoRequestID != PHInvalidImageRequestID) {
  293. [[PHImageManager defaultManager] cancelImageRequest:_assetVideoRequestID];
  294. _assetVideoRequestID = PHInvalidImageRequestID;
  295. }
  296. }
  297. /***** BEGIN THREEMA MODIFICATION: add function *********/
  298. -(BOOL)showControls {
  299. return YES;
  300. }
  301. - (NSString *)accessibilityLabelForContent {
  302. return @"";
  303. }
  304. - (BOOL)canScaleImage {
  305. return YES;
  306. }
  307. /***** END THREEMA MODIFICATION: add function *********/
  308. @end