MWPhotoBrowser.m 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. //
  2. // MWPhotoBrowser.m
  3. // MWPhotoBrowser
  4. //
  5. // Created by Michael Waterfall on 14/10/2010.
  6. // Copyright 2010 d3i. All rights reserved.
  7. //
  8. #import <QuartzCore/QuartzCore.h>
  9. #import "MWCommon.h"
  10. #import "MWPhotoBrowser.h"
  11. #import "MWPhotoBrowserPrivate.h"
  12. #import "UIImage+MWPhotoBrowser.h"
  13. #ifdef CUSTOM_BUILD
  14. #import "CustomSwift.h"
  15. #else
  16. #import "Nextcloud-Swift.h"
  17. #endif
  18. #define PADDING 10
  19. #pragma clang diagnostic ignored "-Wundeclared-selector"
  20. static void * MWVideoPlayerObservation = &MWVideoPlayerObservation;
  21. @implementation MWPhotoBrowser
  22. #pragma mark - Init
  23. - (id)init {
  24. if ((self = [super init])) {
  25. [self _initialisation];
  26. }
  27. return self;
  28. }
  29. - (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
  30. if ((self = [self init])) {
  31. _delegate = delegate;
  32. }
  33. return self;
  34. }
  35. - (id)initWithPhotos:(NSArray *)photosArray {
  36. if ((self = [self init])) {
  37. _fixedPhotosArray = photosArray;
  38. }
  39. return self;
  40. }
  41. - (id)initWithCoder:(NSCoder *)decoder {
  42. if ((self = [super initWithCoder:decoder])) {
  43. [self _initialisation];
  44. }
  45. return self;
  46. }
  47. - (void)_initialisation {
  48. // Defaults
  49. NSNumber *isVCBasedStatusBarAppearanceNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
  50. if (isVCBasedStatusBarAppearanceNum) {
  51. _isVCBasedStatusBarAppearance = isVCBasedStatusBarAppearanceNum.boolValue;
  52. } else {
  53. _isVCBasedStatusBarAppearance = YES; // default
  54. }
  55. self.hidesBottomBarWhenPushed = YES;
  56. _hasBelongedToViewController = NO;
  57. _photoCount = NSNotFound;
  58. _previousLayoutBounds = CGRectZero;
  59. _currentPageIndex = 0;
  60. _previousPageIndex = NSUIntegerMax;
  61. _displayActionButton = YES;
  62. _displayShareButton = YES;
  63. _displayDeleteButton = YES;
  64. _displayNavArrows = NO;
  65. _zoomPhotosToFill = YES;
  66. _performingLayout = NO; // Reset on view did appear
  67. _rotating = NO;
  68. _viewIsActive = NO;
  69. _enableGrid = YES;
  70. _startOnGrid = NO;
  71. _enableSwipeToDismiss = YES;
  72. _delayToHideElements = 5;
  73. _visiblePages = [[NSMutableSet alloc] init];
  74. _recycledPages = [[NSMutableSet alloc] init];
  75. _photos = [[NSMutableArray alloc] init];
  76. _thumbPhotos = [[NSMutableArray alloc] init];
  77. _currentGridContentOffset = CGPointMake(0, CGFLOAT_MAX);
  78. _didSavePreviousStateOfNavBar = NO;
  79. self.automaticallyAdjustsScrollViewInsets = NO;
  80. // Listen for MWPhoto notifications
  81. [[NSNotificationCenter defaultCenter] addObserver:self
  82. selector:@selector(handleMWPhotoLoadingDidEndNotification:)
  83. name:MWPHOTO_LOADING_DID_END_NOTIFICATION
  84. object:nil];
  85. }
  86. - (void)dealloc {
  87. [self clearCurrentVideo];
  88. _pagingScrollView.delegate = nil;
  89. [[NSNotificationCenter defaultCenter] removeObserver:self];
  90. [self releaseAllUnderlyingPhotos:NO];
  91. }
  92. - (void)releaseAllUnderlyingPhotos:(BOOL)preserveCurrent {
  93. // Create a copy in case this array is modified while we are looping through
  94. // Release photos
  95. NSArray *copy = [_photos copy];
  96. for (id p in copy) {
  97. if (p != [NSNull null]) {
  98. if (preserveCurrent && p == [self photoAtIndex:self.currentIndex]) {
  99. continue; // skip current
  100. }
  101. [p unloadUnderlyingImage];
  102. }
  103. }
  104. // Release thumbs
  105. copy = [_thumbPhotos copy];
  106. for (id p in copy) {
  107. if (p != [NSNull null]) {
  108. [p unloadUnderlyingImage];
  109. }
  110. }
  111. }
  112. - (void)didReceiveMemoryWarning {
  113. // Release any cached data, images, etc that aren't in use.
  114. [self releaseAllUnderlyingPhotos:YES];
  115. [_recycledPages removeAllObjects];
  116. // Releases the view if it doesn't have a superview.
  117. [super didReceiveMemoryWarning];
  118. }
  119. #pragma mark - View Loading
  120. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  121. - (void)viewDidLoad {
  122. // Validate grid settings
  123. if (_startOnGrid) _enableGrid = YES;
  124. if (_enableGrid) {
  125. _enableGrid = [_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)];
  126. }
  127. if (!_enableGrid) _startOnGrid = NO;
  128. // View
  129. self.view.backgroundColor = [UIColor whiteColor]; //TWS
  130. self.view.clipsToBounds = YES;
  131. // Setup paging scrolling view
  132. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  133. _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
  134. _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  135. _pagingScrollView.pagingEnabled = YES;
  136. _pagingScrollView.delegate = self;
  137. _pagingScrollView.showsHorizontalScrollIndicator = NO;
  138. _pagingScrollView.showsVerticalScrollIndicator = NO;
  139. _pagingScrollView.backgroundColor = [UIColor whiteColor]; //TWS
  140. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  141. [self.view addSubview:_pagingScrollView];
  142. // Toolbar
  143. _toolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]]];
  144. _toolbar.tintColor = [NCColorBrand sharedInstance].tabBarText; //TWS
  145. _toolbar.barTintColor = [NCColorBrand sharedInstance].tabBar;
  146. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  147. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsCompact];
  148. _toolbar.barStyle = UIBarStyleDefault; //TWS
  149. _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
  150. // Toolbar Items
  151. if (self.displayNavArrows) {
  152. NSString *arrowPathFormat = @"UIBarButtonItemArrow%@";
  153. UIImage *previousButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Left"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  154. UIImage *nextButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Right"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  155. _previousButton = [[UIBarButtonItem alloc] initWithImage:previousButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoPreviousPage)];
  156. _nextButton = [[UIBarButtonItem alloc] initWithImage:nextButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextPage)];
  157. }
  158. //TWS
  159. if (self.displayDeleteButton) {
  160. _deleteButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  161. }
  162. if (self.displayActionButton) {
  163. _actionButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionButtonPressed:)];
  164. }
  165. if (self.displayShareButton) {
  166. _shareButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetShare"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  167. }
  168. // Update
  169. [self reloadData];
  170. // Swipe to dismiss
  171. if (_enableSwipeToDismiss) {
  172. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doneButtonPressed:)];
  173. swipeGesture.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
  174. [self.view addGestureRecognizer:swipeGesture];
  175. }
  176. // Super
  177. [super viewDidLoad];
  178. }
  179. - (void)performLayout {
  180. // Setup
  181. _performingLayout = YES;
  182. NSUInteger numberOfPhotos = [self numberOfPhotos];
  183. // Setup pages
  184. [_visiblePages removeAllObjects];
  185. [_recycledPages removeAllObjects];
  186. // Navigation buttons
  187. if ([self.navigationController.viewControllers objectAtIndex:0] == self) {
  188. // We're first on stack so show done button
  189. _doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];
  190. // Set appearance
  191. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  192. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsCompact];
  193. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  194. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsCompact];
  195. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
  196. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
  197. self.navigationItem.rightBarButtonItem = _doneButton;
  198. }
  199. // color
  200. self.navigationController.navigationBar.barTintColor = [NCColorBrand sharedInstance].navigationBar;
  201. self.navigationController.navigationBar.tintColor = [NCColorBrand sharedInstance].navigationBarText;
  202. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCColorBrand sharedInstance].navigationBarText}];
  203. // Toolbar items
  204. BOOL hasItems = NO;
  205. UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  206. fixedSpace.width = 32; // To balance action button
  207. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  208. fixedSpaceMini.width = 25; // To balance action button
  209. UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  210. NSMutableArray *items = [[NSMutableArray alloc] init];
  211. // Left button - Grid
  212. if (_enableGrid) {
  213. hasItems = YES;
  214. [items addObject:[[UIBarButtonItem alloc] initWithImage:[UIImage imageForResourcePath:@"UIBarButtonItemGrid" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] style:UIBarButtonItemStylePlain target:self action:@selector(showGridAnimated)]];
  215. } else {
  216. [items addObject:fixedSpace];
  217. }
  218. // Middle - Nav
  219. if (_previousButton && _nextButton && numberOfPhotos > 1) {
  220. hasItems = YES;
  221. [items addObject:flexSpace];
  222. [items addObject:_previousButton];
  223. [items addObject:flexSpace];
  224. [items addObject:_nextButton];
  225. [items addObject:flexSpace];
  226. } else {
  227. [items addObject:flexSpace];
  228. }
  229. // Right - Action
  230. if (_actionButton && !(!hasItems && !self.navigationItem.rightBarButtonItem)) {
  231. if (_deleteButton) {
  232. [items addObject:_deleteButton];
  233. [items addObject:fixedSpaceMini];
  234. }
  235. if (_shareButton) {
  236. [items addObject:_shareButton];
  237. [items addObject:fixedSpaceMini];
  238. }
  239. [items addObject:_actionButton];
  240. } else {
  241. // We're not showing the toolbar so try and show in top right
  242. if (_actionButton)
  243. self.navigationItem.rightBarButtonItem = _actionButton;
  244. [items addObject:fixedSpace];
  245. }
  246. // Toolbar visibility
  247. [_toolbar setItems:items];
  248. BOOL hideToolbar = YES;
  249. for (UIBarButtonItem* item in _toolbar.items) {
  250. if (item != fixedSpace && item != flexSpace) {
  251. hideToolbar = NO;
  252. break;
  253. }
  254. }
  255. if (hideToolbar) {
  256. [_toolbar removeFromSuperview];
  257. } else {
  258. [self.view addSubview:_toolbar];
  259. }
  260. // Update nav
  261. [self updateNavigation];
  262. // Content offset
  263. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
  264. [self tilePages];
  265. _performingLayout = NO;
  266. }
  267. // Release any retained subviews of the main view.
  268. - (void)viewDidUnload {
  269. _currentPageIndex = 0;
  270. _pagingScrollView = nil;
  271. _visiblePages = nil;
  272. _recycledPages = nil;
  273. _toolbar = nil;
  274. _previousButton = nil;
  275. _nextButton = nil;
  276. _progressHUD = nil;
  277. [super viewDidUnload];
  278. }
  279. - (BOOL)presentingViewControllerPrefersStatusBarHidden {
  280. UIViewController *presenting = self.presentingViewController;
  281. if (presenting) {
  282. if ([presenting isKindOfClass:[UINavigationController class]]) {
  283. presenting = [(UINavigationController *)presenting topViewController];
  284. }
  285. } else {
  286. // We're in a navigation controller so get previous one!
  287. if (self.navigationController && self.navigationController.viewControllers.count > 1) {
  288. presenting = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
  289. }
  290. }
  291. if (presenting) {
  292. return [presenting prefersStatusBarHidden];
  293. } else {
  294. return NO;
  295. }
  296. }
  297. #pragma mark - Appearance
  298. - (void)viewWillAppear:(BOOL)animated {
  299. // Super
  300. [super viewWillAppear:animated];
  301. // Status bar
  302. if (!_viewHasAppearedInitially) {
  303. _leaveStatusBarAlone = [self presentingViewControllerPrefersStatusBarHidden];
  304. // Check if status bar is hidden on first appear, and if so then ignore it
  305. if (CGRectEqualToRect([[UIApplication sharedApplication] statusBarFrame], CGRectZero)) {
  306. _leaveStatusBarAlone = YES;
  307. }
  308. }
  309. // Nav Bar Appearance iPAD
  310. if (self.traitCollection.horizontalSizeClass != UIUserInterfaceSizeClassCompact) {
  311. // ----- TWS ----- //
  312. self.navigationItem.hidesBackButton = YES;
  313. self.navigationController.topViewController.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem;
  314. self.splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  315. }
  316. // Update UI
  317. [self hideControlsAfterDelay];
  318. // Initial appearance
  319. if (!_viewHasAppearedInitially) {
  320. if (_startOnGrid) {
  321. [self showGrid:NO];
  322. }
  323. }
  324. // If rotation occured while we're presenting a modal
  325. // and the index changed, make sure we show the right one now
  326. if (_currentPageIndex != _pageIndexBeforeRotation) {
  327. [self jumpToPageAtIndex:_pageIndexBeforeRotation animated:NO];
  328. }
  329. // Layaout
  330. [self.view setNeedsLayout];
  331. }
  332. - (void)viewDidAppear:(BOOL)animated {
  333. [super viewDidAppear:animated];
  334. _viewIsActive = YES;
  335. // Autoplay if first is video
  336. if (!_viewHasAppearedInitially) {
  337. if (_autoPlayOnAppear) {
  338. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  339. if ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo) {
  340. [self playVideoAtIndex:_currentPageIndex];
  341. }
  342. }
  343. }
  344. _viewHasAppearedInitially = YES;
  345. }
  346. - (void)viewWillDisappear:(BOOL)animated {
  347. // Detect if rotation occurs while we're presenting a modal
  348. _pageIndexBeforeRotation = _currentPageIndex;
  349. // Check that we're being popped for good
  350. if ([self.navigationController.viewControllers objectAtIndex:0] != self &&
  351. ![self.navigationController.viewControllers containsObject:self]) {
  352. // State
  353. _viewIsActive = NO;
  354. }
  355. // Controls
  356. [self.navigationController.navigationBar.layer removeAllAnimations]; // Stop all animations on nav bar
  357. [NSObject cancelPreviousPerformRequestsWithTarget:self]; // Cancel any pending toggles from taps
  358. [self setControlsHidden:NO animated:NO permanent:YES];
  359. // Super
  360. [super viewWillDisappear:animated];
  361. }
  362. - (void)willMoveToParentViewController:(UIViewController *)parent {
  363. if (parent && _hasBelongedToViewController) {
  364. [NSException raise:@"MWPhotoBrowser Instance Reuse" format:@"MWPhotoBrowser instances cannot be reused."];
  365. }
  366. }
  367. - (void)didMoveToParentViewController:(UIViewController *)parent {
  368. if (!parent) _hasBelongedToViewController = YES;
  369. }
  370. #pragma mark - Layout
  371. - (void)viewWillLayoutSubviews {
  372. [super viewWillLayoutSubviews];
  373. [self layoutVisiblePages];
  374. }
  375. - (void)layoutVisiblePages {
  376. // Flag
  377. _performingLayout = YES;
  378. // Toolbar
  379. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  380. // Remember index
  381. NSUInteger indexPriorToLayout = _currentPageIndex;
  382. // Get paging scroll view frame to determine if anything needs changing
  383. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  384. // Frame needs changing
  385. if (!_skipNextPagingScrollViewPositioning) {
  386. _pagingScrollView.frame = pagingScrollViewFrame;
  387. }
  388. _skipNextPagingScrollViewPositioning = NO;
  389. // Recalculate contentSize based on current orientation
  390. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  391. // Adjust frames and configuration of each visible page
  392. for (MWZoomingScrollView *page in _visiblePages) {
  393. NSUInteger index = page.index;
  394. page.frame = [self frameForPageAtIndex:index];
  395. if (page.captionView) {
  396. page.captionView.frame = [self frameForCaptionView:page.captionView atIndex:index];
  397. }
  398. if (page.selectedButton) {
  399. page.selectedButton.frame = [self frameForSelectedButton:page.selectedButton atIndex:index];
  400. }
  401. if (page.playButton) {
  402. page.playButton.frame = [self frameForPlayButton:page.playButton atIndex:index];
  403. }
  404. // Adjust scales if bounds has changed since last time
  405. if (!CGRectEqualToRect(_previousLayoutBounds, self.view.bounds)) {
  406. // Update zooms for new bounds
  407. [page setMaxMinZoomScalesForCurrentBounds];
  408. _previousLayoutBounds = self.view.bounds;
  409. }
  410. }
  411. // Adjust video loading indicator if it's visible
  412. [self positionVideoLoadingIndicator];
  413. // Adjust contentOffset to preserve page location based on values collected prior to location
  414. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:indexPriorToLayout];
  415. [self didStartViewingPageAtIndex:_currentPageIndex]; // initial
  416. // Reset
  417. _currentPageIndex = indexPriorToLayout;
  418. _performingLayout = NO;
  419. }
  420. #pragma mark - Rotation
  421. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  422. return YES;
  423. }
  424. #if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
  425. - (NSUInteger)supportedInterfaceOrientations
  426. #else
  427. - (UIInterfaceOrientationMask)supportedInterfaceOrientations
  428. #endif
  429. {
  430. return UIInterfaceOrientationMaskPortrait;
  431. }
  432. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  433. // Remember page index before rotation
  434. _pageIndexBeforeRotation = _currentPageIndex;
  435. _rotating = YES;
  436. // In iOS 7 the nav bar gets shown after rotation, but might as well do this for everything!
  437. if ([self areControlsHidden]) {
  438. // Force hidden
  439. self.navigationController.navigationBarHidden = YES;
  440. }
  441. }
  442. - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  443. // Perform layout
  444. _currentPageIndex = _pageIndexBeforeRotation;
  445. // Delay control holding
  446. [self hideControlsAfterDelay];
  447. // Layout
  448. [self layoutVisiblePages];
  449. }
  450. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
  451. _rotating = NO;
  452. // Ensure nav bar isn't re-displayed
  453. if ([self areControlsHidden]) {
  454. self.navigationController.navigationBarHidden = NO;
  455. self.navigationController.navigationBar.alpha = 0;
  456. }
  457. }
  458. #pragma mark - Data
  459. - (NSUInteger)currentIndex {
  460. return _currentPageIndex;
  461. }
  462. - (void)reloadData {
  463. // Reset
  464. _photoCount = NSNotFound;
  465. // Get data
  466. NSUInteger numberOfPhotos = [self numberOfPhotos];
  467. [self releaseAllUnderlyingPhotos:YES];
  468. [_photos removeAllObjects];
  469. [_thumbPhotos removeAllObjects];
  470. for (int i = 0; i < numberOfPhotos; i++) {
  471. [_photos addObject:[NSNull null]];
  472. [_thumbPhotos addObject:[NSNull null]];
  473. }
  474. // Update current page index
  475. if (numberOfPhotos > 0) {
  476. _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1));
  477. } else {
  478. _currentPageIndex = 0;
  479. }
  480. // Update layout
  481. if ([self isViewLoaded]) {
  482. while (_pagingScrollView.subviews.count) {
  483. [[_pagingScrollView.subviews lastObject] removeFromSuperview];
  484. }
  485. [self performLayout];
  486. [self.view setNeedsLayout];
  487. }
  488. _toolbar.hidden = (_gridController ? true : false);
  489. _toolbar.alpha = (_gridController ? 0 : 1);
  490. //TWS
  491. if (!_gridController) {
  492. self.navigationController.navigationBar.hidden = (_gridController ? true : false);
  493. self.navigationController.navigationBar.alpha = (_gridController ? 0 : 1);
  494. }
  495. //TWS Update grid if it's presented
  496. [_gridController.collectionView reloadData];
  497. }
  498. - (void)reloadDataGridAtIndex:(NSArray *)indexPaths
  499. {
  500. [_gridController.collectionView reloadItemsAtIndexPaths:indexPaths];
  501. }
  502. //TWS
  503. - (BOOL)isGridReload:(NSUInteger)index
  504. {
  505. if (_gridController) {
  506. return [_gridController visibleGridIndexPath:index];
  507. } else return NO;
  508. }
  509. - (NSUInteger)numberOfPhotos {
  510. if (_photoCount == NSNotFound) {
  511. if ([_delegate respondsToSelector:@selector(numberOfPhotosInPhotoBrowser:)]) {
  512. _photoCount = [_delegate numberOfPhotosInPhotoBrowser:self];
  513. } else if (_fixedPhotosArray) {
  514. _photoCount = _fixedPhotosArray.count;
  515. }
  516. }
  517. if (_photoCount == NSNotFound) _photoCount = 0;
  518. return _photoCount;
  519. }
  520. - (id<MWPhoto>)photoAtIndex:(NSUInteger)index {
  521. id <MWPhoto> photo = nil;
  522. if (index < _photos.count) {
  523. if ([_photos objectAtIndex:index] == [NSNull null]) {
  524. if ([_delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:)]) {
  525. photo = [_delegate photoBrowser:self photoAtIndex:index];
  526. } else if (_fixedPhotosArray && index < _fixedPhotosArray.count) {
  527. photo = [_fixedPhotosArray objectAtIndex:index];
  528. }
  529. if (photo) [_photos replaceObjectAtIndex:index withObject:photo];
  530. } else {
  531. photo = [_photos objectAtIndex:index];
  532. }
  533. }
  534. return photo;
  535. }
  536. - (id<MWPhoto>)thumbPhotoAtIndex:(NSUInteger)index {
  537. id <MWPhoto> photo = nil;
  538. if (index < _thumbPhotos.count) {
  539. if ([_thumbPhotos objectAtIndex:index] == [NSNull null]) {
  540. if ([_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)]) {
  541. photo = [_delegate photoBrowser:self thumbPhotoAtIndex:index];
  542. }
  543. if (photo) [_thumbPhotos replaceObjectAtIndex:index withObject:photo];
  544. } else {
  545. photo = [_thumbPhotos objectAtIndex:index];
  546. }
  547. }
  548. return photo;
  549. }
  550. - (MWCaptionView *)captionViewForPhotoAtIndex:(NSUInteger)index {
  551. MWCaptionView *captionView = nil;
  552. if ([_delegate respondsToSelector:@selector(photoBrowser:captionViewForPhotoAtIndex:)]) {
  553. captionView = [_delegate photoBrowser:self captionViewForPhotoAtIndex:index];
  554. } else {
  555. id <MWPhoto> photo = [self photoAtIndex:index];
  556. if ([photo respondsToSelector:@selector(caption)]) {
  557. if ([photo caption]) captionView = [[MWCaptionView alloc] initWithPhoto:photo];
  558. }
  559. }
  560. captionView.alpha = [self areControlsHidden] ? 0 : 1; // Initial alpha
  561. return captionView;
  562. }
  563. - (BOOL)photoIsSelectedAtIndex:(NSUInteger)index {
  564. BOOL value = NO;
  565. if (_displaySelectionButtons) {
  566. if ([self.delegate respondsToSelector:@selector(photoBrowser:isPhotoSelectedAtIndex:)]) {
  567. value = [self.delegate photoBrowser:self isPhotoSelectedAtIndex:index];
  568. }
  569. }
  570. return value;
  571. }
  572. - (void)setPhotoSelected:(BOOL)selected atIndex:(NSUInteger)index {
  573. if (_displaySelectionButtons) {
  574. if ([self.delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:selectedChanged:)]) {
  575. [self.delegate photoBrowser:self photoAtIndex:index selectedChanged:selected];
  576. }
  577. }
  578. }
  579. - (UIImage *)imageForPhoto:(id<MWPhoto>)photo {
  580. if (photo) {
  581. // Get image or obtain in background
  582. if ([photo underlyingImage]) {
  583. return [photo underlyingImage];
  584. } else {
  585. [photo loadUnderlyingImageAndNotify];
  586. }
  587. }
  588. return nil;
  589. }
  590. - (void)loadAdjacentPhotosIfNecessary:(id<MWPhoto>)photo
  591. {
  592. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  593. if (page) {
  594. // If page is current page then initiate loading of previous and next pages
  595. NSUInteger pageIndex = page.index;
  596. if (_currentPageIndex == pageIndex) {
  597. if (pageIndex > 0) {
  598. // Preload index - 1
  599. id <MWPhoto> photo = [self photoAtIndex:pageIndex-1];
  600. if (![photo underlyingImage]) {
  601. [photo loadUnderlyingImageAndNotify];
  602. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex-1);
  603. }
  604. }
  605. if (pageIndex < [self numberOfPhotos] - 1) {
  606. // Preload index + 1
  607. id <MWPhoto> photo = [self photoAtIndex:pageIndex+1];
  608. if (![photo underlyingImage]) {
  609. [photo loadUnderlyingImageAndNotify];
  610. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex+1);
  611. }
  612. }
  613. }
  614. }
  615. }
  616. #pragma mark - MWPhoto Loading Notification
  617. - (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification {
  618. id <MWPhoto> photo = [notification object];
  619. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  620. if (page) {
  621. if ([photo underlyingImage]) {
  622. // Successful load
  623. [page displayImage];
  624. [self loadAdjacentPhotosIfNecessary:photo];
  625. } else {
  626. // Failed to load
  627. [page displayImageFailure];
  628. }
  629. // Update nav
  630. [self updateNavigation];
  631. }
  632. }
  633. #pragma mark - Paging
  634. - (void)tilePages {
  635. // Calculate which pages should be visible
  636. // Ignore padding as paging bounces encroach on that
  637. // and lead to false page loads
  638. CGRect visibleBounds = _pagingScrollView.bounds;
  639. NSInteger iFirstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
  640. NSInteger iLastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
  641. if (iFirstIndex < 0) iFirstIndex = 0;
  642. if (iFirstIndex > [self numberOfPhotos] - 1) iFirstIndex = [self numberOfPhotos] - 1;
  643. if (iLastIndex < 0) iLastIndex = 0;
  644. if (iLastIndex > [self numberOfPhotos] - 1) iLastIndex = [self numberOfPhotos] - 1;
  645. // Recycle no longer needed pages
  646. NSInteger pageIndex;
  647. for (MWZoomingScrollView *page in _visiblePages) {
  648. pageIndex = page.index;
  649. if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
  650. [_recycledPages addObject:page];
  651. [page.captionView removeFromSuperview];
  652. [page.selectedButton removeFromSuperview];
  653. [page.playButton removeFromSuperview];
  654. [page prepareForReuse];
  655. [page removeFromSuperview];
  656. MWLog(@"Removed page at index %lu", (unsigned long)pageIndex);
  657. }
  658. }
  659. [_visiblePages minusSet:_recycledPages];
  660. while (_recycledPages.count > 2) // Only keep 2 recycled pages
  661. [_recycledPages removeObject:[_recycledPages anyObject]];
  662. // Add missing pages
  663. for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
  664. if (![self isDisplayingPageForIndex:index]) {
  665. // Add new page
  666. MWZoomingScrollView *page = [self dequeueRecycledPage];
  667. if (!page) {
  668. page = [[MWZoomingScrollView alloc] initWithPhotoBrowser:self];
  669. }
  670. [_visiblePages addObject:page];
  671. [self configurePage:page forIndex:index];
  672. [_pagingScrollView addSubview:page];
  673. MWLog(@"Added page at index %lu", (unsigned long)index);
  674. // Add caption
  675. MWCaptionView *captionView = [self captionViewForPhotoAtIndex:index];
  676. if (captionView) {
  677. captionView.frame = [self frameForCaptionView:captionView atIndex:index];
  678. [_pagingScrollView addSubview:captionView];
  679. page.captionView = captionView;
  680. }
  681. // Add play button if needed
  682. if (page.displayingVideo) {
  683. UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
  684. [playButton setImage:[UIImage imageForResourcePath:@"PlayButtonOverlayLarge" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  685. [playButton setImage:[UIImage imageForResourcePath:@"PlayButtonOverlayLargeTap" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateHighlighted];
  686. [playButton addTarget:self action:@selector(playButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  687. [playButton sizeToFit];
  688. playButton.frame = [self frameForPlayButton:playButton atIndex:index];
  689. [_pagingScrollView addSubview:playButton];
  690. page.playButton = playButton;
  691. }
  692. // Add selected button
  693. if (self.displaySelectionButtons) {
  694. UIButton *selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
  695. [selectedButton setImage:[UIImage imageForResourcePath:@"ImageSelectedOff" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  696. UIImage *selectedOnImage;
  697. if (self.customImageSelectedIconName) {
  698. selectedOnImage = [UIImage imageNamed:self.customImageSelectedIconName];
  699. } else {
  700. selectedOnImage = [UIImage imageForResourcePath:@"ImageSelectedOn" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  701. }
  702. [selectedButton setImage:selectedOnImage forState:UIControlStateSelected];
  703. [selectedButton sizeToFit];
  704. selectedButton.adjustsImageWhenHighlighted = NO;
  705. [selectedButton addTarget:self action:@selector(selectedButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  706. selectedButton.frame = [self frameForSelectedButton:selectedButton atIndex:index];
  707. [_pagingScrollView addSubview:selectedButton];
  708. page.selectedButton = selectedButton;
  709. selectedButton.selected = [self photoIsSelectedAtIndex:index];
  710. }
  711. }
  712. }
  713. }
  714. - (void)updateVisiblePageStates {
  715. NSSet *copy = [_visiblePages copy];
  716. for (MWZoomingScrollView *page in copy) {
  717. // Update selection
  718. page.selectedButton.selected = [self photoIsSelectedAtIndex:page.index];
  719. }
  720. }
  721. - (BOOL)isDisplayingPageForIndex:(NSUInteger)index {
  722. for (MWZoomingScrollView *page in _visiblePages)
  723. if (page.index == index) return YES;
  724. return NO;
  725. }
  726. - (MWZoomingScrollView *)pageDisplayedAtIndex:(NSUInteger)index {
  727. MWZoomingScrollView *thePage = nil;
  728. for (MWZoomingScrollView *page in _visiblePages) {
  729. if (page.index == index) {
  730. thePage = page; break;
  731. }
  732. }
  733. return thePage;
  734. }
  735. - (MWZoomingScrollView *)pageDisplayingPhoto:(id<MWPhoto>)photo {
  736. MWZoomingScrollView *thePage = nil;
  737. for (MWZoomingScrollView *page in _visiblePages) {
  738. if (page.photo == photo) {
  739. thePage = page; break;
  740. }
  741. }
  742. return thePage;
  743. }
  744. - (void)configurePage:(MWZoomingScrollView *)page forIndex:(NSUInteger)index {
  745. page.frame = [self frameForPageAtIndex:index];
  746. page.index = index;
  747. page.photo = [self photoAtIndex:index];
  748. }
  749. - (MWZoomingScrollView *)dequeueRecycledPage {
  750. MWZoomingScrollView *page = [_recycledPages anyObject];
  751. if (page) {
  752. [_recycledPages removeObject:page];
  753. }
  754. return page;
  755. }
  756. // Handle page changes
  757. - (void)didStartViewingPageAtIndex:(NSUInteger)index {
  758. // Handle 0 photos
  759. if (![self numberOfPhotos]) {
  760. // Show controls
  761. [self setControlsHidden:NO animated:YES permanent:YES];
  762. return;
  763. }
  764. // Handle video on page change
  765. if (!_rotating || index != _currentVideoIndex) {
  766. [self clearCurrentVideo];
  767. }
  768. // Release images further away than +/-1
  769. NSUInteger i;
  770. if (index > 0) {
  771. // Release anything < index - 1
  772. for (i = 0; i < index-1; i++) {
  773. id photo = [_photos objectAtIndex:i];
  774. if (photo != [NSNull null]) {
  775. [photo unloadUnderlyingImage];
  776. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  777. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  778. }
  779. }
  780. }
  781. if (index < [self numberOfPhotos] - 1) {
  782. // Release anything > index + 1
  783. for (i = index + 2; i < _photos.count; i++) {
  784. id photo = [_photos objectAtIndex:i];
  785. if (photo != [NSNull null]) {
  786. [photo unloadUnderlyingImage];
  787. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  788. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  789. }
  790. }
  791. }
  792. // Load adjacent images if needed and the photo is already
  793. // loaded. Also called after photo has been loaded in background
  794. id <MWPhoto> currentPhoto = [self photoAtIndex:index];
  795. if ([currentPhoto underlyingImage]) {
  796. // photo loaded so load ajacent now
  797. [self loadAdjacentPhotosIfNecessary:currentPhoto];
  798. }
  799. // Notify delegate
  800. if (index != _previousPageIndex) {
  801. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  802. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  803. _previousPageIndex = index;
  804. } else {
  805. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  806. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  807. }
  808. // Update nav
  809. [self updateNavigation];
  810. }
  811. #pragma mark - Frame Calculations
  812. - (CGRect)frameForPagingScrollView {
  813. CGRect frame = self.view.bounds;// [[UIScreen mainScreen] bounds];
  814. frame.origin.x -= PADDING;
  815. frame.size.width += (2 * PADDING);
  816. return CGRectIntegral(frame);
  817. }
  818. - (CGRect)frameForPageAtIndex:(NSUInteger)index {
  819. // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
  820. // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
  821. // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
  822. // because it has a rotation transform applied.
  823. CGRect bounds = _pagingScrollView.bounds;
  824. CGRect pageFrame = bounds;
  825. pageFrame.size.width -= (2 * PADDING);
  826. pageFrame.origin.x = (bounds.size.width * index) + PADDING;
  827. return CGRectIntegral(pageFrame);
  828. }
  829. - (CGSize)contentSizeForPagingScrollView {
  830. // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
  831. CGRect bounds = _pagingScrollView.bounds;
  832. return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height);
  833. }
  834. - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index {
  835. CGFloat pageWidth = _pagingScrollView.bounds.size.width;
  836. CGFloat newOffset = index * pageWidth;
  837. return CGPointMake(newOffset, 0);
  838. }
  839. - (CGRect)frameForToolbarAtOrientation:(UIInterfaceOrientation)orientation {
  840. CGFloat height = 49; //TWS
  841. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone &&
  842. UIInterfaceOrientationIsLandscape(orientation)) height = 49; //32
  843. return CGRectIntegral(CGRectMake(0, self.view.bounds.size.height - height, self.view.bounds.size.width, height));
  844. }
  845. - (CGRect)frameForCaptionView:(MWCaptionView *)captionView atIndex:(NSUInteger)index {
  846. CGRect pageFrame = [self frameForPageAtIndex:index];
  847. CGSize captionSize = [captionView sizeThatFits:CGSizeMake(pageFrame.size.width, 0)];
  848. CGRect captionFrame = CGRectMake(pageFrame.origin.x,
  849. pageFrame.size.height - captionSize.height - (_toolbar.superview?_toolbar.frame.size.height:0),
  850. pageFrame.size.width,
  851. captionSize.height);
  852. return CGRectIntegral(captionFrame);
  853. }
  854. - (CGRect)frameForSelectedButton:(UIButton *)selectedButton atIndex:(NSUInteger)index {
  855. CGRect pageFrame = [self frameForPageAtIndex:index];
  856. CGFloat padding = 20;
  857. CGFloat yOffset = 0;
  858. if (![self areControlsHidden]) {
  859. UINavigationBar *navBar = self.navigationController.navigationBar;
  860. yOffset = navBar.frame.origin.y + navBar.frame.size.height;
  861. }
  862. CGRect selectedButtonFrame = CGRectMake(pageFrame.origin.x + pageFrame.size.width - selectedButton.frame.size.width - padding,
  863. padding + yOffset,
  864. selectedButton.frame.size.width,
  865. selectedButton.frame.size.height);
  866. return CGRectIntegral(selectedButtonFrame);
  867. }
  868. - (CGRect)frameForPlayButton:(UIButton *)playButton atIndex:(NSUInteger)index {
  869. CGRect pageFrame = [self frameForPageAtIndex:index];
  870. return CGRectMake(floorf(CGRectGetMidX(pageFrame) - playButton.frame.size.width / 2),
  871. floorf(CGRectGetMidY(pageFrame) - playButton.frame.size.height / 2),
  872. playButton.frame.size.width,
  873. playButton.frame.size.height);
  874. }
  875. #pragma mark - UIScrollView Delegate
  876. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  877. // Checks
  878. if (!_viewIsActive || _performingLayout || _rotating) return;
  879. // Tile pages
  880. [self tilePages];
  881. // Calculate current page
  882. CGRect visibleBounds = _pagingScrollView.bounds;
  883. NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)));
  884. if (index < 0) index = 0;
  885. if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1;
  886. NSUInteger previousCurrentPage = _currentPageIndex;
  887. _currentPageIndex = index;
  888. if (_currentPageIndex != previousCurrentPage) {
  889. [self didStartViewingPageAtIndex:index];
  890. }
  891. }
  892. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  893. // Hide controls when dragging begins
  894. [self setControlsHidden:YES animated:YES permanent:NO];
  895. }
  896. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  897. // Update nav when page changes
  898. [self updateNavigation];
  899. }
  900. #pragma mark - Navigation
  901. - (void)updateNavigation {
  902. // Title
  903. NSUInteger numberOfPhotos = [self numberOfPhotos];
  904. if (_gridController) {
  905. if (_gridController.selectionMode) {
  906. self.title = NSLocalizedString(@"Select Photos", nil);
  907. } else {
  908. NSString *photosText;
  909. if (numberOfPhotos == 1) {
  910. photosText = NSLocalizedString(@"photo", @"Used in the context: '1 photo'");
  911. } else {
  912. photosText = NSLocalizedString(@"photos", @"Used in the context: '3 photos'");
  913. }
  914. self.title = [NSString stringWithFormat:@"%lu %@", (unsigned long)numberOfPhotos, photosText];
  915. }
  916. } else if (numberOfPhotos > 1) {
  917. if ([_delegate respondsToSelector:@selector(photoBrowser:titleForPhotoAtIndex:)]) {
  918. self.title = [_delegate photoBrowser:self titleForPhotoAtIndex:_currentPageIndex];
  919. } else {
  920. self.title = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)(_currentPageIndex+1), NSLocalizedString(@"of", @"Used in the context: 'Showing 1 of 3 items'"), (unsigned long)numberOfPhotos];
  921. }
  922. } else {
  923. self.title = nil;
  924. }
  925. // Buttons
  926. _previousButton.enabled = (_currentPageIndex > 0);
  927. _nextButton.enabled = (_currentPageIndex < numberOfPhotos - 1);
  928. //TWS Disable action button if there is no image or it's a video
  929. /*
  930. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  931. if ([photo underlyingImage] == nil || ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo)) {
  932. _actionButton.enabled = NO;
  933. _actionButton.tintColor = [UIColor clearColor]; // Tint to hide button
  934. } else {
  935. _actionButton.enabled = YES;
  936. _actionButton.tintColor = nil;
  937. }
  938. */
  939. }
  940. - (void)jumpToPageAtIndex:(NSUInteger)index animated:(BOOL)animated {
  941. // Change page
  942. if (index < [self numberOfPhotos]) {
  943. CGRect pageFrame = [self frameForPageAtIndex:index];
  944. [_pagingScrollView setContentOffset:CGPointMake(pageFrame.origin.x - PADDING, 0) animated:animated];
  945. [self updateNavigation];
  946. }
  947. // Update timer to give more time
  948. [self hideControlsAfterDelay];
  949. }
  950. - (void)gotoPreviousPage {
  951. [self showPreviousPhotoAnimated:NO];
  952. }
  953. - (void)gotoNextPage {
  954. [self showNextPhotoAnimated:NO];
  955. }
  956. - (void)showPreviousPhotoAnimated:(BOOL)animated {
  957. [self jumpToPageAtIndex:_currentPageIndex-1 animated:animated];
  958. }
  959. - (void)showNextPhotoAnimated:(BOOL)animated {
  960. [self jumpToPageAtIndex:_currentPageIndex+1 animated:animated];
  961. }
  962. #pragma mark - Interactions
  963. - (void)selectedButtonTapped:(id)sender {
  964. UIButton *selectedButton = (UIButton *)sender;
  965. selectedButton.selected = !selectedButton.selected;
  966. NSUInteger index = NSUIntegerMax;
  967. for (MWZoomingScrollView *page in _visiblePages) {
  968. if (page.selectedButton == selectedButton) {
  969. index = page.index;
  970. break;
  971. }
  972. }
  973. if (index != NSUIntegerMax) {
  974. [self setPhotoSelected:selectedButton.selected atIndex:index];
  975. }
  976. }
  977. - (void)playButtonTapped:(id)sender {
  978. UIButton *playButton = (UIButton *)sender;
  979. NSUInteger index = NSUIntegerMax;
  980. for (MWZoomingScrollView *page in _visiblePages) {
  981. if (page.playButton == playButton) {
  982. index = page.index;
  983. break;
  984. }
  985. }
  986. if (index != NSUIntegerMax) {
  987. if (!_currentVideoPlayerViewController) {
  988. [self playVideoAtIndex:index];
  989. }
  990. }
  991. }
  992. #pragma mark - Video
  993. - (void)playVideoAtIndex:(NSUInteger)index {
  994. id photo = [self photoAtIndex:index];
  995. if ([photo respondsToSelector:@selector(getVideoURL:)]) {
  996. // Valid for playing
  997. _currentVideoIndex = index;
  998. [self clearCurrentVideo];
  999. [self setVideoLoadingIndicatorVisible:YES atPageIndex:index];
  1000. // Get video and play
  1001. [photo getVideoURL:^(NSURL *url) {
  1002. if (url) {
  1003. dispatch_async(dispatch_get_main_queue(), ^{
  1004. [self _playVideo:url atPhotoIndex:index];
  1005. });
  1006. } else {
  1007. [self setVideoLoadingIndicatorVisible:NO atPageIndex:index];
  1008. }
  1009. }];
  1010. }
  1011. }
  1012. - (void)_playVideo:(NSURL *)videoURL atPhotoIndex:(NSUInteger)index {
  1013. // Setup player
  1014. _currentVideoPlayerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
  1015. [_currentVideoPlayerViewController.moviePlayer prepareToPlay];
  1016. _currentVideoPlayerViewController.moviePlayer.shouldAutoplay = YES;
  1017. _currentVideoPlayerViewController.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
  1018. _currentVideoPlayerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  1019. // Remove the movie player view controller from the "playback did finish" notification observers
  1020. // Observe ourselves so we can get it to use the crossfade transition
  1021. [[NSNotificationCenter defaultCenter] removeObserver:_currentVideoPlayerViewController
  1022. name:MPMoviePlayerPlaybackDidFinishNotification
  1023. object:_currentVideoPlayerViewController.moviePlayer];
  1024. [[NSNotificationCenter defaultCenter] addObserver:self
  1025. selector:@selector(videoFinishedCallback:)
  1026. name:MPMoviePlayerPlaybackDidFinishNotification
  1027. object:_currentVideoPlayerViewController.moviePlayer];
  1028. // Show
  1029. [self presentViewController:_currentVideoPlayerViewController animated:YES completion:nil];
  1030. }
  1031. - (void)videoFinishedCallback:(NSNotification*)notification {
  1032. // Remove observer
  1033. [[NSNotificationCenter defaultCenter] removeObserver:self
  1034. name:MPMoviePlayerPlaybackDidFinishNotification
  1035. object:_currentVideoPlayerViewController.moviePlayer];
  1036. // Clear up
  1037. [self clearCurrentVideo];
  1038. //TWS
  1039. [[NSNotificationCenter defaultCenter] postNotificationName:@"closePhotoBrowser" object:nil];
  1040. // Dismiss
  1041. BOOL error = [[[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue] == MPMovieFinishReasonPlaybackError;
  1042. if (error) {
  1043. // Error occured so dismiss with a delay incase error was immediate and we need to wait to dismiss the VC
  1044. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1045. [self dismissViewControllerAnimated:YES completion:nil];
  1046. });
  1047. } else {
  1048. [self dismissViewControllerAnimated:YES completion:nil];
  1049. }
  1050. }
  1051. - (void)clearCurrentVideo {
  1052. if (!_currentVideoPlayerViewController) return;
  1053. [_currentVideoLoadingIndicator removeFromSuperview];
  1054. _currentVideoPlayerViewController = nil;
  1055. _currentVideoLoadingIndicator = nil;
  1056. _currentVideoIndex = NSUIntegerMax;
  1057. }
  1058. - (void)setVideoLoadingIndicatorVisible:(BOOL)visible atPageIndex:(NSUInteger)pageIndex {
  1059. if (_currentVideoLoadingIndicator && !visible) {
  1060. [_currentVideoLoadingIndicator removeFromSuperview];
  1061. _currentVideoLoadingIndicator = nil;
  1062. } else if (!_currentVideoLoadingIndicator && visible) {
  1063. _currentVideoLoadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectZero];
  1064. [_currentVideoLoadingIndicator sizeToFit];
  1065. [_currentVideoLoadingIndicator startAnimating];
  1066. [_pagingScrollView addSubview:_currentVideoLoadingIndicator];
  1067. [self positionVideoLoadingIndicator];
  1068. }
  1069. }
  1070. - (void)positionVideoLoadingIndicator {
  1071. if (_currentVideoLoadingIndicator && _currentVideoIndex != NSUIntegerMax) {
  1072. CGRect frame = [self frameForPageAtIndex:_currentVideoIndex];
  1073. _currentVideoLoadingIndicator.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
  1074. }
  1075. }
  1076. #pragma mark - Grid
  1077. - (BOOL)isGridController {
  1078. return (_gridController ? true : false);
  1079. }
  1080. - (void)showGridAnimated {
  1081. [self showGrid:YES];
  1082. }
  1083. - (void)showGrid:(BOOL)animated {
  1084. if (_gridController) return;
  1085. // Init grid controller
  1086. _gridController = [[MWGridViewController alloc] init];
  1087. _gridController.initialContentOffset = _currentGridContentOffset;
  1088. _gridController.browser = self;
  1089. _gridController.selectionMode = _displaySelectionButtons;
  1090. _gridController.view.frame = self.view.bounds;
  1091. _gridController.view.frame = CGRectOffset(_gridController.view.frame, 0, (self.startOnGrid ? -1 : 1) * self.view.bounds.size.height);
  1092. // Stop specific layout being triggered
  1093. _skipNextPagingScrollViewPositioning = YES;
  1094. // Add as a child view controller
  1095. [self addChildViewController:_gridController];
  1096. [self.view addSubview:_gridController.view];
  1097. // Perform any adjustments
  1098. [_gridController.view layoutIfNeeded];
  1099. [_gridController adjustOffsetsAsRequired];
  1100. // Hide action button on nav bar if it exists
  1101. if (self.navigationItem.rightBarButtonItem == _actionButton) {
  1102. _gridPreviousRightNavItem = _actionButton;
  1103. [self.navigationItem setRightBarButtonItem:nil animated:YES];
  1104. } else {
  1105. _gridPreviousRightNavItem = nil;
  1106. }
  1107. // Update
  1108. [self updateNavigation];
  1109. [self setControlsHidden:NO animated:YES permanent:YES];
  1110. // Animate grid in and photo scroller out
  1111. [_gridController willMoveToParentViewController:self];
  1112. [UIView animateWithDuration:animated ? 0.3 : 0 animations:^(void) {
  1113. _gridController.view.frame = self.view.bounds;
  1114. CGRect newPagingFrame = [self frameForPagingScrollView];
  1115. newPagingFrame = CGRectOffset(newPagingFrame, 0, (self.startOnGrid ? 1 : -1) * newPagingFrame.size.height);
  1116. _pagingScrollView.frame = newPagingFrame;
  1117. } completion:^(BOOL finished) {
  1118. [_gridController didMoveToParentViewController:self];
  1119. }];
  1120. //TWS
  1121. if ([_delegate respondsToSelector:@selector(gridWillAppear:)]) {
  1122. // Call delegate method and let them dismiss us
  1123. [_delegate gridWillAppear:self];
  1124. }
  1125. }
  1126. - (void)hideGrid {
  1127. if (!_gridController) return;
  1128. // Remember previous content offset
  1129. _currentGridContentOffset = _gridController.collectionView.contentOffset;
  1130. // Restore action button if it was removed
  1131. if (_gridPreviousRightNavItem == _actionButton && _actionButton) {
  1132. [self.navigationItem setRightBarButtonItem:_gridPreviousRightNavItem animated:YES];
  1133. }
  1134. // Position prior to hide animation
  1135. CGRect newPagingFrame = [self frameForPagingScrollView];
  1136. newPagingFrame = CGRectOffset(newPagingFrame, 0, (self.startOnGrid ? 1 : -1) * newPagingFrame.size.height);
  1137. _pagingScrollView.frame = newPagingFrame;
  1138. // Remember and remove controller now so things can detect a nil grid controller
  1139. MWGridViewController *tmpGridController = _gridController;
  1140. _gridController = nil;
  1141. // Update
  1142. [self updateNavigation];
  1143. [self updateVisiblePageStates];
  1144. // Animate, hide grid and show paging scroll view
  1145. [UIView animateWithDuration:0.3 animations:^{
  1146. tmpGridController.view.frame = CGRectOffset(self.view.bounds, 0, (self.startOnGrid ? -1 : 1) * self.view.bounds.size.height);
  1147. _pagingScrollView.frame = [self frameForPagingScrollView];
  1148. } completion:^(BOOL finished) {
  1149. [tmpGridController willMoveToParentViewController:nil];
  1150. [tmpGridController.view removeFromSuperview];
  1151. [tmpGridController removeFromParentViewController];
  1152. [self setControlsHidden:NO animated:YES permanent:NO]; // retrigger timer
  1153. }];
  1154. //TWS
  1155. if ([_delegate respondsToSelector:@selector(gridWillDisappear:)]) {
  1156. // Call delegate method and let them dismiss us
  1157. [_delegate gridWillDisappear:self];
  1158. }
  1159. }
  1160. #pragma mark - Control Hiding / Showing
  1161. // If permanent then we don't set timers to hide again
  1162. // Fades all controls on iOS 5 & 6, and iOS 7 controls slide and fade
  1163. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent {
  1164. // Force visible
  1165. if (![self numberOfPhotos] || _gridController || _alwaysShowControls)
  1166. hidden = NO;
  1167. // Cancel any timers
  1168. [self cancelControlHiding];
  1169. // Animations & positions
  1170. CGFloat animatonOffset = 20;
  1171. CGFloat animationDuration = (animated ? 0.35 : 0);
  1172. // Status bar
  1173. if (!_leaveStatusBarAlone) {
  1174. // Hide status bar
  1175. if (!_isVCBasedStatusBarAppearance) {
  1176. //TWS Non-view controller based
  1177. //[[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:animated ? UIStatusBarAnimationSlide : UIStatusBarAnimationNone];
  1178. } else {
  1179. // View controller based so animate away
  1180. _statusBarShouldBeHidden = hidden;
  1181. //TWS
  1182. //[UIView animateWithDuration:animationDuration animations:^(void) {
  1183. // [self setNeedsStatusBarAppearanceUpdate];
  1184. //} completion:^(BOOL finished) {}];
  1185. }
  1186. }
  1187. // Toolbar, nav bar and captions
  1188. // Pre-appear animation positions for sliding
  1189. if ([self areControlsHidden] && !hidden && animated) {
  1190. // Toolbar
  1191. _toolbar.frame = CGRectOffset([self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]], 0, animatonOffset);
  1192. // Captions
  1193. for (MWZoomingScrollView *page in _visiblePages) {
  1194. if (page.captionView) {
  1195. MWCaptionView *v = page.captionView;
  1196. //TWS
  1197. id <MWPhoto> photo = [self photoAtIndex:self.currentIndex];
  1198. if (photo.caption) {
  1199. if ([photo caption]) v.label.text = photo.caption;
  1200. }
  1201. // Pass any index, all we're interested in is the Y
  1202. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1203. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1204. v.frame = CGRectOffset(captionFrame, 0, animatonOffset);
  1205. }
  1206. }
  1207. }
  1208. if ([_delegate respondsToSelector:@selector(setControlsHidden:animated:permanent:)]) {
  1209. [_delegate setControlsHidden:hidden animated:animated permanent:permanent];
  1210. }
  1211. [UIView animateWithDuration:animationDuration animations:^(void) {
  1212. CGFloat alpha = hidden ? 0 : 1;
  1213. // Nav bar slides up on it's own on iOS 7+
  1214. [self.navigationController.navigationBar setAlpha:alpha];
  1215. // Toolbar
  1216. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  1217. if (hidden) _toolbar.frame = CGRectOffset(_toolbar.frame, 0, animatonOffset);
  1218. _toolbar.alpha = alpha;
  1219. // Captions
  1220. for (MWZoomingScrollView *page in _visiblePages) {
  1221. if (page.captionView) {
  1222. MWCaptionView *v = page.captionView;
  1223. // Pass any index, all we're interested in is the Y
  1224. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1225. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1226. if (hidden) captionFrame = CGRectOffset(captionFrame, 0, animatonOffset);
  1227. v.frame = captionFrame;
  1228. v.alpha = alpha;
  1229. }
  1230. }
  1231. // Selected buttons
  1232. for (MWZoomingScrollView *page in _visiblePages) {
  1233. if (page.selectedButton) {
  1234. UIButton *v = page.selectedButton;
  1235. CGRect newFrame = [self frameForSelectedButton:v atIndex:0];
  1236. newFrame.origin.x = v.frame.origin.x;
  1237. v.frame = newFrame;
  1238. }
  1239. }
  1240. } completion:^(BOOL finished) {}];
  1241. // Control hiding timer
  1242. // Will cancel existing timer but only begin hiding if
  1243. // they are visible
  1244. if (!permanent) [self hideControlsAfterDelay];
  1245. }
  1246. - (BOOL)prefersStatusBarHidden {
  1247. if (!_leaveStatusBarAlone) {
  1248. return _statusBarShouldBeHidden;
  1249. } else {
  1250. return [self presentingViewControllerPrefersStatusBarHidden];
  1251. }
  1252. }
  1253. - (UIStatusBarStyle)preferredStatusBarStyle {
  1254. return UIStatusBarStyleLightContent;
  1255. }
  1256. - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
  1257. return UIStatusBarAnimationSlide;
  1258. }
  1259. - (void)cancelControlHiding {
  1260. // If a timer exists then cancel and release
  1261. if (_controlVisibilityTimer) {
  1262. [_controlVisibilityTimer invalidate];
  1263. _controlVisibilityTimer = nil;
  1264. }
  1265. }
  1266. // Enable/disable control visiblity timer
  1267. - (void)hideControlsAfterDelay {
  1268. if (![self areControlsHidden]) {
  1269. [self cancelControlHiding];
  1270. _controlVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:self.delayToHideElements target:self selector:@selector(hideControls) userInfo:nil repeats:NO];
  1271. }
  1272. }
  1273. - (BOOL)areControlsHidden {
  1274. return (_toolbar.alpha == 0);
  1275. }
  1276. - (void)hideControls { [self setControlsHidden:YES animated:YES permanent:NO]; }
  1277. - (void)showControls { [self setControlsHidden:NO animated:YES permanent:NO]; }
  1278. - (void)toggleControls { [self setControlsHidden:![self areControlsHidden] animated:YES permanent:NO]; }
  1279. #pragma mark - Properties
  1280. - (void)setCurrentPhotoIndex:(NSUInteger)index {
  1281. // Validate
  1282. NSUInteger photoCount = [self numberOfPhotos];
  1283. if (photoCount == 0) {
  1284. index = 0;
  1285. } else {
  1286. if (index >= photoCount)
  1287. index = [self numberOfPhotos]-1;
  1288. }
  1289. _currentPageIndex = index;
  1290. if ([self isViewLoaded]) {
  1291. [self jumpToPageAtIndex:index animated:NO];
  1292. if (!_viewIsActive)
  1293. [self tilePages]; // Force tiling if view is not visible
  1294. }
  1295. }
  1296. #pragma mark - Misc
  1297. - (void)doneButtonPressed:(id)sender {
  1298. // Only if we're modal and there's a done button
  1299. if (_doneButton) {
  1300. // See if we actually just want to show/hide grid
  1301. if (self.enableGrid) {
  1302. if (self.startOnGrid && !_gridController) {
  1303. [self showGrid:YES];
  1304. return;
  1305. } else if (!self.startOnGrid && _gridController) {
  1306. [self hideGrid];
  1307. return;
  1308. }
  1309. }
  1310. // Dismiss view controller
  1311. if ([_delegate respondsToSelector:@selector(photoBrowserDidFinishModalPresentation:)]) {
  1312. // Call delegate method and let them dismiss us
  1313. [_delegate photoBrowserDidFinishModalPresentation:self];
  1314. } else {
  1315. [self dismissViewControllerAnimated:YES completion:nil];
  1316. }
  1317. }
  1318. }
  1319. #pragma mark - Delete
  1320. - (void)deleteButtonPressed:(id)sender {
  1321. if ([self.delegate respondsToSelector:@selector(photoBrowser:deleteButtonPressedForPhotoAtIndex:deleteButton:)])
  1322. [self.delegate photoBrowser:self deleteButtonPressedForPhotoAtIndex:_currentPageIndex deleteButton:self.deleteButton];
  1323. }
  1324. #pragma mark - Share
  1325. - (void)shareButtonPressed:(id)sender {
  1326. if ([self.delegate respondsToSelector:@selector(photoBrowser:shareButtonPressedForPhotoAtIndex:)])
  1327. [self.delegate photoBrowser:self shareButtonPressedForPhotoAtIndex:_currentPageIndex];
  1328. }
  1329. #pragma mark - Actions
  1330. - (void)actionButtonPressed:(id)sender {
  1331. // Only react when image has loaded
  1332. id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
  1333. if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
  1334. // If they have defined a delegate method then just message them
  1335. if ([self.delegate respondsToSelector:@selector(photoBrowser:actionButtonPressedForPhotoAtIndex:)]) {
  1336. // Let delegate handle things
  1337. [self.delegate photoBrowser:self actionButtonPressedForPhotoAtIndex:_currentPageIndex];
  1338. } else {
  1339. // Show activity view controller
  1340. NSMutableArray *items = [NSMutableArray arrayWithObject:[photo underlyingImage]];
  1341. if (photo.caption) {
  1342. [items addObject:photo.caption];
  1343. }
  1344. self.activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
  1345. // Show
  1346. typeof(self) __weak weakSelf = self;
  1347. [self.activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  1348. weakSelf.activityViewController = nil;
  1349. [weakSelf hideControlsAfterDelay];
  1350. }];
  1351. // iOS 8 - Set the Anchor Point for the popover
  1352. if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8")) {
  1353. self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
  1354. }
  1355. [self presentViewController:self.activityViewController animated:YES completion:nil];
  1356. }
  1357. // Keep controls hidden
  1358. [self setControlsHidden:NO animated:YES permanent:YES];
  1359. }
  1360. }
  1361. @end