MWPhotoBrowser.m 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073
  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. // MWPhotoBrowser.m
  6. // MWPhotoBrowser
  7. //
  8. // Created by Michael Waterfall on 14/10/2010.
  9. // Copyright 2010 d3i. All rights reserved.
  10. //
  11. #import <QuartzCore/QuartzCore.h>
  12. #import "MWCommon.h"
  13. #import "MWPhotoBrowser.h"
  14. #import "MWPhotoBrowserPrivate.h"
  15. #import "SDImageCache.h"
  16. #import "UIImage+MWPhotoBrowser.h"
  17. ///***** BEGIN THREEMA MODIFICATION: Add AppGroup and utils *********/
  18. #import "TTOpenInAppActivity.h"
  19. #import "ForwardURLActivity.h"
  20. #import "ForwardMultipleURLActivity.h"
  21. #import "AppGroup.h"
  22. #import "Utils.h"
  23. #import "ChatViewHeader.h"
  24. #import "Threema-Swift.h"
  25. #import "ActivityUtil.h"
  26. #import "ContactGroupPickerViewController.h"
  27. #import "FeatureMaskChecker.h"
  28. ///***** END THREEMA MODIFICATION: Add AppGroup and utils *********/
  29. #define PADDING 10
  30. static void * MWVideoPlayerObservation = &MWVideoPlayerObservation;
  31. ///***** BEGIN THREEMA MODIFICATION: Add delegates *********/
  32. @interface MWPhotoBrowser () <ModalNavigationControllerDelegate, ContactGroupPickerDelegate>
  33. @end
  34. ///***** END THREEMA MODIFICATION: Add delegates *********/
  35. @implementation MWPhotoBrowser
  36. #pragma mark - Init
  37. - (id)init {
  38. if ((self = [super init])) {
  39. [self _initialisation];
  40. }
  41. return self;
  42. }
  43. - (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
  44. if ((self = [self init])) {
  45. _delegate = delegate;
  46. }
  47. return self;
  48. }
  49. - (id)initWithPhotos:(NSArray *)photosArray {
  50. if ((self = [self init])) {
  51. _fixedPhotosArray = photosArray;
  52. }
  53. return self;
  54. }
  55. - (id)initWithCoder:(NSCoder *)decoder {
  56. if ((self = [super initWithCoder:decoder])) {
  57. [self _initialisation];
  58. }
  59. return self;
  60. }
  61. - (void)_initialisation {
  62. // Defaults
  63. NSNumber *isVCBasedStatusBarAppearanceNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
  64. if (isVCBasedStatusBarAppearanceNum) {
  65. _isVCBasedStatusBarAppearance = isVCBasedStatusBarAppearanceNum.boolValue;
  66. } else {
  67. _isVCBasedStatusBarAppearance = YES; // default
  68. }
  69. self.hidesBottomBarWhenPushed = YES;
  70. _hasBelongedToViewController = NO;
  71. _photoCount = NSNotFound;
  72. _previousLayoutBounds = CGRectZero;
  73. _currentPageIndex = 0;
  74. _previousPageIndex = NSUIntegerMax;
  75. _currentVideoIndex = NSUIntegerMax;
  76. _displayActionButton = YES;
  77. _displayNavArrows = NO;
  78. _zoomPhotosToFill = YES;
  79. _performingLayout = NO; // Reset on view did appear
  80. _rotating = NO;
  81. _viewIsActive = NO;
  82. _enableGrid = YES;
  83. _startOnGrid = NO;
  84. _enableSwipeToDismiss = YES;
  85. _delayToHideElements = 5;
  86. ///***** BEGIN THREEMA MODIFICATION: don't hide controll when voiceover is running *********/
  87. if (UIAccessibilityIsVoiceOverRunning()) {
  88. _alwaysShowControls = YES;
  89. } else {
  90. _alwaysShowControls = NO;
  91. }
  92. ///***** END THREEMA MODIFICATION: don't hide controll when voiceover is running *********/
  93. _visiblePages = [[NSMutableSet alloc] init];
  94. _recycledPages = [[NSMutableSet alloc] init];
  95. _photos = [[NSMutableArray alloc] init];
  96. _thumbPhotos = [[NSMutableArray alloc] init];
  97. ///***** BEGIN THREEMA MODIFICATION: iOS 11 *********/
  98. // _currentGridContentOffset = CGPointMake(0, CGFLOAT_MAX);
  99. if (@available(iOS 11.0, *)) {
  100. } else {
  101. _currentGridContentOffset = CGPointMake(0, CGFLOAT_MAX);
  102. }
  103. ///***** END THREEMA MODIFICATION: iOS 11 *********/
  104. _didSavePreviousStateOfNavBar = NO;
  105. _testCount = 0;
  106. self.automaticallyAdjustsScrollViewInsets = NO;
  107. // Listen for MWPhoto notifications
  108. [[NSNotificationCenter defaultCenter] addObserver:self
  109. selector:@selector(handleMWPhotoLoadingDidEndNotification:)
  110. name:MWPHOTO_LOADING_DID_END_NOTIFICATION
  111. object:nil];
  112. /***** BEGIN THREEMA MODIFICATION: listen for application foreground/background events to fix status bar *********/
  113. [[NSNotificationCenter defaultCenter] addObserver:self
  114. selector:@selector(applicationWillEnterForeground:)
  115. name:UIApplicationWillEnterForegroundNotification
  116. object:nil];
  117. [[NSNotificationCenter defaultCenter] addObserver:self
  118. selector:@selector(applicationDidEnterBackground:)
  119. name:UIApplicationDidEnterBackgroundNotification
  120. object:nil];
  121. /***** END THREEMA MODIFICATION: listen for application foreground/background events to fix status bar *********/
  122. }
  123. - (void)dealloc {
  124. [self clearCurrentVideo: true];
  125. _pagingScrollView.delegate = nil;
  126. [[NSNotificationCenter defaultCenter] removeObserver:self];
  127. [self releaseAllUnderlyingPhotos:NO];
  128. [[SDImageCache sharedImageCache] clearMemory]; // clear memory
  129. }
  130. - (void)releaseAllUnderlyingPhotos:(BOOL)preserveCurrent {
  131. // Create a copy in case this array is modified while we are looping through
  132. // Release photos
  133. NSArray *copy = [_photos copy];
  134. for (id p in copy) {
  135. if (p != [NSNull null]) {
  136. if (preserveCurrent && p == [self photoAtIndex:self.currentIndex]) {
  137. continue; // skip current
  138. }
  139. [p unloadUnderlyingImage];
  140. }
  141. }
  142. // Release thumbs
  143. copy = [_thumbPhotos copy];
  144. for (id p in copy) {
  145. if (p != [NSNull null]) {
  146. [p unloadUnderlyingImage];
  147. }
  148. }
  149. }
  150. - (void)didReceiveMemoryWarning {
  151. // Release any cached data, images, etc that aren't in use.
  152. [self releaseAllUnderlyingPhotos:YES];
  153. [_recycledPages removeAllObjects];
  154. // Releases the view if it doesn't have a superview.
  155. [super didReceiveMemoryWarning];
  156. }
  157. #pragma mark - View Loading
  158. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  159. - (void)viewDidLoad {
  160. // Validate grid settings
  161. if (_startOnGrid) _enableGrid = YES;
  162. if (_enableGrid) {
  163. _enableGrid = [_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)];
  164. }
  165. if (!_enableGrid) _startOnGrid = NO;
  166. // View
  167. self.view.backgroundColor = [UIColor blackColor];
  168. self.view.clipsToBounds = YES;
  169. // Setup paging scrolling view
  170. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  171. _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
  172. _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  173. _pagingScrollView.pagingEnabled = YES;
  174. _pagingScrollView.delegate = self;
  175. _pagingScrollView.showsHorizontalScrollIndicator = NO;
  176. _pagingScrollView.showsVerticalScrollIndicator = NO;
  177. _pagingScrollView.backgroundColor = [UIColor blackColor];
  178. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  179. [self.view addSubview:_pagingScrollView];
  180. // Toolbar
  181. _toolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]]];
  182. _toolbar.tintColor = [UIColor whiteColor];
  183. _toolbar.barTintColor = nil;
  184. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  185. [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsCompact];
  186. _toolbar.barStyle = UIBarStyleBlackTranslucent;
  187. _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
  188. // Toolbar
  189. _gridToolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]]];
  190. _gridToolbar.tintColor = [UIColor whiteColor];
  191. _gridToolbar.barTintColor = nil;
  192. [_gridToolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  193. [_gridToolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsCompact];
  194. _gridToolbar.barStyle = UIBarStyleBlackTranslucent;
  195. _gridToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
  196. // Toolbar Items
  197. if (self.displayNavArrows) {
  198. NSString *arrowPathFormat = @"MWPhotoBrowser.bundle/UIBarButtonItemArrow%@";
  199. UIImage *previousButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Left"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  200. UIImage *nextButtonImage = [UIImage imageForResourcePath:[NSString stringWithFormat:arrowPathFormat, @"Right"] ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  201. _previousButton = [[UIBarButtonItem alloc] initWithImage:previousButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoPreviousPage)];
  202. _nextButton = [[UIBarButtonItem alloc] initWithImage:nextButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextPage)];
  203. }
  204. if (self.displayActionButton) {
  205. _actionButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionButtonPressed:)];
  206. _actionMultipleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionMultipleButtonPressed:)];
  207. }
  208. /***** BEGIN THREEMA MODIFICATION: add delete button *********/
  209. if (self.displayDeleteButton) {
  210. _deleteSingleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  211. _deleteMultipleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteMultipleButtonPressed:)];
  212. }
  213. /***** END THREEMA MODIFICATION: add delete button *********/
  214. // Update
  215. [self reloadData: true];
  216. // Swipe to dismiss
  217. if (_enableSwipeToDismiss) {
  218. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doneButtonPressed:)];
  219. swipeGesture.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
  220. [self.view addGestureRecognizer:swipeGesture];
  221. }
  222. // Super
  223. [super viewDidLoad];
  224. }
  225. - (void)performLayout {
  226. // Setup
  227. _performingLayout = YES;
  228. NSUInteger numberOfPhotos = [self numberOfPhotos];
  229. // Setup pages
  230. [_visiblePages removeAllObjects];
  231. [_recycledPages removeAllObjects];
  232. // Navigation buttons
  233. if ([self.navigationController.viewControllers objectAtIndex:0] == self || self.navigationController == nil) {
  234. // We're first on stack so show done button
  235. _doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];
  236. // Set appearance
  237. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  238. [_doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsCompact];
  239. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  240. [_doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsCompact];
  241. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
  242. [_doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
  243. /***** BEGIN THREEMA MODIFICATION: 'done' on left *********/
  244. self.navigationItem.leftBarButtonItem = _doneButton;
  245. /***** END THREEMA MODIFICATION: 'done' on left *********/
  246. } else {
  247. // We're not first so show back button
  248. UIViewController *previousViewController = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
  249. NSString *backButtonTitle = previousViewController.navigationItem.backBarButtonItem ? previousViewController.navigationItem.backBarButtonItem.title : previousViewController.title;
  250. UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:backButtonTitle style:UIBarButtonItemStylePlain target:nil action:nil];
  251. // Appearance
  252. [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
  253. [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsCompact];
  254. [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
  255. [newBackButton setBackButtonBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsCompact];
  256. [newBackButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
  257. [newBackButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
  258. _previousViewControllerBackButton = previousViewController.navigationItem.backBarButtonItem; // remember previous
  259. previousViewController.navigationItem.backBarButtonItem = newBackButton;
  260. }
  261. // Toolbar items
  262. BOOL hasItems = NO;
  263. UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  264. fixedSpace.width = 32; // To balance action button
  265. UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  266. NSMutableArray *items = [[NSMutableArray alloc] init];
  267. // Left button - Grid
  268. if (_enableGrid) {
  269. hasItems = YES;
  270. ///***** BEGIN THREEMA MODIFICATION: don't hide controll when voiceover is running *********/
  271. UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageForResourcePath:@"MWPhotoBrowser.bundle/UIBarButtonItemGrid" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] style:UIBarButtonItemStylePlain target:self action:@selector(showGridAnimated)];
  272. item.accessibilityLabel = NSLocalizedString(@"media_overview", nil);
  273. [items addObject:item];
  274. ///***** END THREEMA MODIFICATION: don't hide controll when voiceover is running *********/
  275. } else {
  276. [items addObject:fixedSpace];
  277. }
  278. // Middle - Nav
  279. if (_previousButton && _nextButton && numberOfPhotos > 1) {
  280. hasItems = YES;
  281. [items addObject:flexSpace];
  282. [items addObject:_previousButton];
  283. [items addObject:flexSpace];
  284. /***** BEGIN THREEMA MODIFICATION: add delete single button *********/
  285. if (_deleteSingleButton) {
  286. [items addObject:_deleteSingleButton];
  287. [items addObject:flexSpace];
  288. }
  289. /***** END THREEMA MODIFICATION: add delete single button *********/
  290. [items addObject:_nextButton];
  291. [items addObject:flexSpace];
  292. } else {
  293. [items addObject:flexSpace];
  294. /***** BEGIN THREEMA MODIFICATION: add delete single button *********/
  295. if (_deleteSingleButton) {
  296. [items addObject:_deleteSingleButton];
  297. [items addObject:flexSpace];
  298. }
  299. /***** END THREEMA MODIFICATION: add delete single button *********/
  300. }
  301. // Right - Action
  302. if (_actionButton && !(!hasItems && !self.navigationItem.rightBarButtonItem)) {
  303. [items addObject:_actionButton];
  304. } else {
  305. // We're not showing the toolbar so try and show in top right
  306. if (_actionButton)
  307. self.navigationItem.rightBarButtonItem = _actionButton;
  308. [items addObject:fixedSpace];
  309. }
  310. // Toolbar visibility
  311. [_toolbar setItems:items];
  312. BOOL hideToolbar = YES;
  313. for (UIBarButtonItem* item in _toolbar.items) {
  314. if (item != fixedSpace && item != flexSpace) {
  315. hideToolbar = NO;
  316. break;
  317. }
  318. }
  319. if (hideToolbar) {
  320. [_toolbar removeFromSuperview];
  321. } else {
  322. [self.view addSubview:_toolbar];
  323. }
  324. ///***** BEGIN THREEMA MODIFICATION: Add grid toolbar *********/
  325. // Grid toolbar items
  326. NSMutableArray *gridItems = [[NSMutableArray alloc] init];
  327. // Left button - Delete multiple
  328. if (_deleteMultipleButton) {
  329. [gridItems addObject:_deleteMultipleButton];
  330. } else {
  331. [gridItems addObject:fixedSpace];
  332. }
  333. // Middle - empty
  334. [gridItems addObject:flexSpace];
  335. // Right - Action
  336. if (_actionMultipleButton) {
  337. [gridItems addObject:_actionMultipleButton];
  338. } else {
  339. [gridItems addObject:fixedSpace];
  340. }
  341. // GridToolbar visibility
  342. [_gridToolbar setItems:gridItems];
  343. [_gridToolbar removeFromSuperview];
  344. ///***** END THREEMA MODIFICATION: Add grid toolbar *********/
  345. // Update nav
  346. [self updateNavigation];
  347. // Content offset
  348. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
  349. [self tilePages];
  350. _performingLayout = NO;
  351. }
  352. - (BOOL)presentingViewControllerPrefersStatusBarHidden {
  353. UIViewController *presenting = self.presentingViewController;
  354. if (presenting) {
  355. if ([presenting isKindOfClass:[UINavigationController class]]) {
  356. presenting = [(UINavigationController *)presenting topViewController];
  357. }
  358. } else {
  359. // We're in a navigation controller so get previous one!
  360. if (self.navigationController && self.navigationController.viewControllers.count > 1) {
  361. presenting = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
  362. }
  363. }
  364. if (presenting) {
  365. return [presenting prefersStatusBarHidden];
  366. } else {
  367. return NO;
  368. }
  369. }
  370. #pragma mark - Appearance
  371. - (void)viewWillAppear:(BOOL)animated {
  372. // Super
  373. [super viewWillAppear:animated];
  374. // Status bar
  375. if (!_viewHasAppearedInitially) {
  376. _leaveStatusBarAlone = [self presentingViewControllerPrefersStatusBarHidden];
  377. // Check if status bar is hidden on first appear, and if so then ignore it
  378. if (CGRectEqualToRect([[UIApplication sharedApplication] statusBarFrame], CGRectZero)) {
  379. _leaveStatusBarAlone = YES;
  380. }
  381. }
  382. // Set style
  383. if (!_leaveStatusBarAlone && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  384. _previousStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle];
  385. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:animated];
  386. }
  387. // Navigation bar appearance
  388. if (!_viewIsActive && [self.navigationController.viewControllers objectAtIndex:0] != self) {
  389. [self storePreviousNavBarAppearance];
  390. }
  391. [self setNavBarAppearance:animated];
  392. // Update UI
  393. [self hideControlsAfterDelay];
  394. // Initial appearance
  395. if (!_viewHasAppearedInitially) {
  396. if (_startOnGrid) {
  397. [self showGrid:NO];
  398. }
  399. }
  400. // If rotation occured while we're presenting a modal
  401. // and the index changed, make sure we show the right one now
  402. if (_currentPageIndex != _pageIndexBeforeRotation) {
  403. [self jumpToPageAtIndex:_pageIndexBeforeRotation animated:NO];
  404. }
  405. // Layout
  406. /***** BEGIN THREEMA MODIFICATION: ios 11 bugfix *********/
  407. if (@available(iOS 11.0, *)) {
  408. [self layoutVisiblePages];
  409. }
  410. /***** END THREEMA MODIFICATION: ios 11 bu gfix *********/
  411. [self.view setNeedsLayout];
  412. }
  413. - (void)viewDidAppear:(BOOL)animated {
  414. [super viewDidAppear:animated];
  415. _viewIsActive = YES;
  416. // Autoplay if first is video
  417. if (!_viewHasAppearedInitially) {
  418. if (_autoPlayOnAppear) {
  419. MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  420. if ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo) {
  421. [self playVideoAtIndex:_currentPageIndex];
  422. }
  423. }
  424. }
  425. _viewHasAppearedInitially = YES;
  426. }
  427. /***** BEGIN THREEMA MODIFICATION: show controls/status bar when moving into background to avoid iOS 8 back button bug *********/
  428. - (void)applicationDidEnterBackground:(NSNotification*)notification {
  429. [self setControlsHidden:NO animated:NO permanent:YES];
  430. }
  431. - (void)applicationWillEnterForeground:(NSNotification*)notification {
  432. [self hideControlsAfterDelay];
  433. }
  434. /***** END THREEMA MODIFICATION: show controls/status bar when moving into background to avoid iOS 8 back button bug *********/
  435. - (void)viewWillDisappear:(BOOL)animated {
  436. // Detect if rotation occurs while we're presenting a modal
  437. _pageIndexBeforeRotation = _currentPageIndex;
  438. // Check that we're disappearing for good
  439. // self.isMovingFromParentViewController just doesn't work, ever. Or self.isBeingDismissed
  440. if ((_doneButton && self.navigationController.isBeingDismissed) ||
  441. ([self.navigationController.viewControllers objectAtIndex:0] != self && ![self.navigationController.viewControllers containsObject:self])) {
  442. // State
  443. _viewIsActive = NO;
  444. [self clearCurrentVideo: true]; // Clear current playing video
  445. // Bar state / appearance
  446. [self restorePreviousNavBarAppearance:animated];
  447. }
  448. // Controls
  449. [self.navigationController.navigationBar.layer removeAllAnimations]; // Stop all animations on nav bar
  450. [NSObject cancelPreviousPerformRequestsWithTarget:self]; // Cancel any pending toggles from taps
  451. [self setControlsHidden:NO animated:NO permanent:YES];
  452. // Status bar
  453. if (!_leaveStatusBarAlone && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  454. [[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle animated:animated];
  455. }
  456. // Super
  457. [super viewWillDisappear:animated];
  458. }
  459. ///***** BEGIN THREEMA MODIFICATION: show controls/status bar when moving into background to avoid iOS 8 back button bug *********/
  460. //- (void)applicationDidEnterBackground:(NSNotification*)notification {
  461. // [self setControlsHidden:NO animated:NO permanent:YES];
  462. //}
  463. //
  464. //- (void)applicationWillEnterForeground:(NSNotification*)notification {
  465. // [self hideControlsAfterDelay];
  466. //}
  467. ///***** END THREEMA MODIFICATION: show controls/status bar when moving into background to avoid iOS 8 back button bug *********/
  468. - (void)willMoveToParentViewController:(UIViewController *)parent {
  469. if (parent && _hasBelongedToViewController) {
  470. [NSException raise:@"MWPhotoBrowser Instance Reuse" format:@"MWPhotoBrowser instances cannot be reused."];
  471. }
  472. }
  473. - (void)didMoveToParentViewController:(UIViewController *)parent {
  474. if (!parent) _hasBelongedToViewController = YES;
  475. }
  476. #pragma mark - Nav Bar Appearance
  477. - (void)setNavBarAppearance:(BOOL)animated {
  478. [self.navigationController setNavigationBarHidden:NO animated:animated];
  479. UINavigationBar *navBar = self.navigationController.navigationBar;
  480. navBar.tintColor = [UIColor whiteColor];
  481. navBar.barTintColor = nil;
  482. navBar.shadowImage = nil;
  483. navBar.translucent = YES;
  484. navBar.barStyle = UIBarStyleBlackTranslucent;
  485. [navBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
  486. [navBar setBackgroundImage:nil forBarMetrics:UIBarMetricsCompact];
  487. /***** BEGIN THREEMA MODIFICATION: adapt to own style *********/
  488. [Colors updateNavigationBar: navBar];
  489. /***** END THREEMA MODIFICATION *********/
  490. }
  491. - (void)storePreviousNavBarAppearance {
  492. _didSavePreviousStateOfNavBar = YES;
  493. _previousNavBarBarTintColor = self.navigationController.navigationBar.barTintColor;
  494. _previousNavBarTranslucent = self.navigationController.navigationBar.translucent;
  495. _previousNavBarTintColor = self.navigationController.navigationBar.tintColor;
  496. _previousNavBarHidden = self.navigationController.navigationBarHidden;
  497. _previousNavBarStyle = self.navigationController.navigationBar.barStyle;
  498. _previousNavigationBarBackgroundImageDefault = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
  499. _previousNavigationBarBackgroundImageLandscapePhone = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsCompact];
  500. }
  501. - (void)restorePreviousNavBarAppearance:(BOOL)animated {
  502. if (_didSavePreviousStateOfNavBar) {
  503. [self.navigationController setNavigationBarHidden:_previousNavBarHidden animated:animated];
  504. UINavigationBar *navBar = self.navigationController.navigationBar;
  505. navBar.tintColor = _previousNavBarTintColor;
  506. navBar.translucent = _previousNavBarTranslucent;
  507. navBar.barTintColor = _previousNavBarBarTintColor;
  508. navBar.barStyle = _previousNavBarStyle;
  509. [navBar setBackgroundImage:_previousNavigationBarBackgroundImageDefault forBarMetrics:UIBarMetricsDefault];
  510. [navBar setBackgroundImage:_previousNavigationBarBackgroundImageLandscapePhone forBarMetrics:UIBarMetricsCompact];
  511. // Restore back button if we need to
  512. if (_previousViewControllerBackButton) {
  513. UIViewController *previousViewController = [self.navigationController topViewController]; // We've disappeared so previous is now top
  514. previousViewController.navigationItem.backBarButtonItem = _previousViewControllerBackButton;
  515. _previousViewControllerBackButton = nil;
  516. }
  517. }
  518. }
  519. #pragma mark - Layout
  520. - (void)viewWillLayoutSubviews {
  521. [super viewWillLayoutSubviews];
  522. /***** BEGIN THREEMA MODIFICATION: ios 11 bugfix *********/
  523. if (@available(iOS 11.0, *)) {
  524. // do nothing
  525. } else {
  526. [self layoutVisiblePages];
  527. }
  528. /***** END THREEMA MODIFICATION: ios 11 bugfix *********/
  529. }
  530. - (void)layoutVisiblePages {
  531. // Flag
  532. _performingLayout = YES;
  533. // Toolbar
  534. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  535. _gridToolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  536. // Remember index
  537. NSUInteger indexPriorToLayout = _currentPageIndex;
  538. // Get paging scroll view frame to determine if anything needs changing
  539. CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
  540. // Frame needs changing
  541. if (!_skipNextPagingScrollViewPositioning) {
  542. _pagingScrollView.frame = pagingScrollViewFrame;
  543. }
  544. _skipNextPagingScrollViewPositioning = NO;
  545. // Recalculate contentSize based on current orientation
  546. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  547. // Adjust frames and configuration of each visible page
  548. for (MWZoomingScrollView *page in _visiblePages) {
  549. NSUInteger index = page.index;
  550. page.frame = [self frameForPageAtIndex:index];
  551. if (page.captionView) {
  552. page.captionView.frame = [self frameForCaptionView:page.captionView atIndex:index];
  553. }
  554. if (page.selectedButton) {
  555. page.selectedButton.frame = [self frameForSelectedButton:page.selectedButton atIndex:index];
  556. }
  557. if (page.playButton) {
  558. page.playButton.frame = [self frameForPlayButton:page.playButton atIndex:index];
  559. }
  560. // Adjust scales if bounds has changed since last time
  561. if (!CGRectEqualToRect(_previousLayoutBounds, self.view.bounds)) {
  562. // Update zooms for new bounds
  563. [page setMaxMinZoomScalesForCurrentBounds];
  564. _previousLayoutBounds = self.view.bounds;
  565. }
  566. }
  567. // Adjust video loading indicator if it's visible
  568. [self positionVideoLoadingIndicator];
  569. // Adjust contentOffset to preserve page location based on values collected prior to location
  570. _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:indexPriorToLayout];
  571. [self didStartViewingPageAtIndex:_currentPageIndex]; // initial
  572. // Reset
  573. _currentPageIndex = indexPriorToLayout;
  574. _performingLayout = NO;
  575. }
  576. #pragma mark - Rotation
  577. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  578. return YES;
  579. }
  580. - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
  581. return UIInterfaceOrientationMaskAll;
  582. }
  583. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  584. // Remember page index before rotation
  585. _pageIndexBeforeRotation = _currentPageIndex;
  586. _rotating = YES;
  587. // In iOS 7 the nav bar gets shown after rotation, but might as well do this for everything!
  588. if ([self areControlsHidden]) {
  589. // Force hidden
  590. self.navigationController.navigationBarHidden = YES;
  591. }
  592. }
  593. - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
  594. // Perform layout
  595. _currentPageIndex = _pageIndexBeforeRotation;
  596. // Delay control holding
  597. [self hideControlsAfterDelay];
  598. // Layout
  599. [self layoutVisiblePages];
  600. /***** BEGIN THREEMA MODIFICATION: refresh status bar visibility when rotating on iOS 8.0 *********/
  601. [self setNeedsStatusBarAppearanceUpdate];
  602. /***** END THREEMA MODIFICATION: refresh status bar visibility when rotating on iOS 8.0 *********/
  603. }
  604. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
  605. _rotating = NO;
  606. // Ensure nav bar isn't re-displayed
  607. if ([self areControlsHidden]) {
  608. self.navigationController.navigationBarHidden = NO;
  609. self.navigationController.navigationBar.alpha = 0;
  610. }
  611. }
  612. #pragma mark - Data
  613. - (NSUInteger)currentIndex {
  614. return _currentPageIndex;
  615. }
  616. /***** BEGIN THREEMA MODIFICATION: update for delete files *********/
  617. - (void)reloadData:(BOOL)updateLayout {
  618. // Reset
  619. _photoCount = NSNotFound;
  620. // Get data
  621. NSUInteger numberOfPhotos = [self numberOfPhotos];
  622. [self releaseAllUnderlyingPhotos:YES];
  623. [_photos removeAllObjects];
  624. [_thumbPhotos removeAllObjects];
  625. for (int i = 0; i < numberOfPhotos; i++) {
  626. [_photos addObject:[NSNull null]];
  627. [_thumbPhotos addObject:[NSNull null]];
  628. }
  629. // Update current page index
  630. if (numberOfPhotos > 0) {
  631. _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1));
  632. } else {
  633. _currentPageIndex = 0;
  634. }
  635. if (_gridController) {
  636. _toolbar.alpha = 0.0;
  637. }
  638. // Update layout
  639. if ([self isViewLoaded] && updateLayout) {
  640. _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
  641. while (_pagingScrollView.subviews.count) {
  642. [[_pagingScrollView.subviews lastObject] removeFromSuperview];
  643. }
  644. [self performLayout];
  645. [self.view setNeedsLayout];
  646. }
  647. }
  648. /***** END THREEMA MODIFICATION: update for delete files *********/
  649. - (NSUInteger)numberOfPhotos {
  650. if (_photoCount == NSNotFound) {
  651. if ([_delegate respondsToSelector:@selector(numberOfPhotosInPhotoBrowser:)]) {
  652. _photoCount = [_delegate numberOfPhotosInPhotoBrowser:self];
  653. } else if (_fixedPhotosArray) {
  654. _photoCount = _fixedPhotosArray.count;
  655. }
  656. }
  657. if (_photoCount == NSNotFound) _photoCount = 0;
  658. return _photoCount;
  659. }
  660. - (id<MWPhoto>)photoAtIndex:(NSUInteger)index {
  661. id <MWPhoto> photo = nil;
  662. if (index < _photos.count) {
  663. if ([_photos objectAtIndex:index] == [NSNull null]) {
  664. if ([_delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:)]) {
  665. photo = [_delegate photoBrowser:self photoAtIndex:index];
  666. } else if (_fixedPhotosArray && index < _fixedPhotosArray.count) {
  667. photo = [_fixedPhotosArray objectAtIndex:index];
  668. }
  669. if (photo) [_photos replaceObjectAtIndex:index withObject:photo];
  670. } else {
  671. photo = [_photos objectAtIndex:index];
  672. }
  673. }
  674. return photo;
  675. }
  676. - (id<MWPhoto>)thumbPhotoAtIndex:(NSUInteger)index {
  677. id <MWPhoto> photo = nil;
  678. if (index < _thumbPhotos.count) {
  679. if ([_thumbPhotos objectAtIndex:index] == [NSNull null]) {
  680. if ([_delegate respondsToSelector:@selector(photoBrowser:thumbPhotoAtIndex:)]) {
  681. photo = [_delegate photoBrowser:self thumbPhotoAtIndex:index];
  682. }
  683. if (photo) [_thumbPhotos replaceObjectAtIndex:index withObject:photo];
  684. } else {
  685. photo = [_thumbPhotos objectAtIndex:index];
  686. }
  687. }
  688. return photo;
  689. }
  690. - (MWCaptionView *)captionViewForPhotoAtIndex:(NSUInteger)index {
  691. MWCaptionView *captionView = nil;
  692. if ([_delegate respondsToSelector:@selector(photoBrowser:captionViewForPhotoAtIndex:)]) {
  693. captionView = [_delegate photoBrowser:self captionViewForPhotoAtIndex:index];
  694. } else {
  695. id <MWPhoto> photo = [self photoAtIndex:index];
  696. if ([photo respondsToSelector:@selector(caption)]) {
  697. if ([photo caption]) captionView = [[MWCaptionView alloc] initWithPhoto:photo];
  698. }
  699. }
  700. captionView.alpha = [self areControlsHidden] ? 0 : 1; // Initial alpha
  701. return captionView;
  702. }
  703. - (BOOL)photoIsSelectedAtIndex:(NSUInteger)index {
  704. BOOL value = NO;
  705. if (_displaySelectionButtons) {
  706. if ([self.delegate respondsToSelector:@selector(photoBrowser:isPhotoSelectedAtIndex:)]) {
  707. value = [self.delegate photoBrowser:self isPhotoSelectedAtIndex:index];
  708. }
  709. }
  710. return value;
  711. }
  712. - (void)setPhotoSelected:(BOOL)selected atIndex:(NSUInteger)index {
  713. if (_displaySelectionButtons) {
  714. if ([self.delegate respondsToSelector:@selector(photoBrowser:photoAtIndex:selectedChanged:)]) {
  715. [self.delegate photoBrowser:self photoAtIndex:index selectedChanged:selected];
  716. }
  717. if ([self.delegate respondsToSelector:@selector(mediaSelectionCount)]) {
  718. NSUInteger selectionCount = [((ChatViewHeader *)self.delegate) mediaSelectionCount];
  719. _deleteMultipleButton.enabled = selectionCount > 0;
  720. _actionMultipleButton.enabled = selectionCount > 0;
  721. }
  722. }
  723. }
  724. - (UIImage *)imageForPhoto:(id<MWPhoto>)photo {
  725. if (photo) {
  726. // Get image or obtain in background
  727. if ([photo underlyingImage]) {
  728. return [photo underlyingImage];
  729. } else {
  730. [photo loadUnderlyingImageAndNotify];
  731. }
  732. }
  733. return nil;
  734. }
  735. - (void)loadAdjacentPhotosIfNecessary:(id<MWPhoto>)photo {
  736. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  737. if (page) {
  738. // If page is current page then initiate loading of previous and next pages
  739. NSUInteger pageIndex = page.index;
  740. if (_currentPageIndex == pageIndex) {
  741. if (pageIndex > 0) {
  742. // Preload index - 1
  743. id <MWPhoto> photo = [self photoAtIndex:pageIndex-1];
  744. if (![photo underlyingImage]) {
  745. [photo loadUnderlyingImageAndNotify];
  746. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex-1);
  747. }
  748. }
  749. if (pageIndex < [self numberOfPhotos] - 1) {
  750. // Preload index + 1
  751. id <MWPhoto> photo = [self photoAtIndex:pageIndex+1];
  752. if (![photo underlyingImage]) {
  753. [photo loadUnderlyingImageAndNotify];
  754. MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex+1);
  755. }
  756. }
  757. }
  758. }
  759. }
  760. #pragma mark - MWPhoto Loading Notification
  761. - (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification {
  762. id <MWPhoto> photo = [notification object];
  763. MWZoomingScrollView *page = [self pageDisplayingPhoto:photo];
  764. if (page) {
  765. if ([photo underlyingImage]) {
  766. // Successful load
  767. [page displayImage];
  768. [self loadAdjacentPhotosIfNecessary:photo];
  769. } else {
  770. // Failed to load
  771. [page displayImageFailure];
  772. }
  773. // Update nav
  774. [self updateNavigation];
  775. }
  776. }
  777. #pragma mark - Paging
  778. - (void)tilePages {
  779. // Calculate which pages should be visible
  780. // Ignore padding as paging bounces encroach on that
  781. // and lead to false page loads
  782. CGRect visibleBounds = _pagingScrollView.bounds;
  783. NSInteger iFirstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
  784. NSInteger iLastIndex = (NSInteger)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
  785. if (iFirstIndex < 0) iFirstIndex = 0;
  786. if (iFirstIndex > [self numberOfPhotos] - 1) iFirstIndex = [self numberOfPhotos] - 1;
  787. if (iLastIndex < 0) iLastIndex = 0;
  788. if (iLastIndex > [self numberOfPhotos] - 1) iLastIndex = [self numberOfPhotos] - 1;
  789. // // Recycle no longer needed pages
  790. NSInteger pageIndex;
  791. for (MWZoomingScrollView *page in _visiblePages) {
  792. pageIndex = page.index;
  793. if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
  794. [_recycledPages addObject:page];
  795. [page.captionView removeFromSuperview];
  796. [page.selectedButton removeFromSuperview];
  797. [page.playButton removeFromSuperview];
  798. [page prepareForReuse];
  799. [page removeFromSuperview];
  800. MWLog(@"Removed page at index %lu", (unsigned long)pageIndex);
  801. }
  802. }
  803. [_visiblePages minusSet:_recycledPages];
  804. while (_recycledPages.count > 2) // Only keep 2 recycled pages
  805. [_recycledPages removeObject:[_recycledPages anyObject]];
  806. // Add missing pages
  807. for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
  808. if (![self isDisplayingPageForIndex:index]) {
  809. // Add new page
  810. MWZoomingScrollView *page = [self dequeueRecycledPage];
  811. if (!page) {
  812. page = [[MWZoomingScrollView alloc] initWithPhotoBrowser:self];
  813. }
  814. [_visiblePages addObject:page];
  815. [self configurePage:page forIndex:index];
  816. [_pagingScrollView addSubview:page];
  817. MWLog(@"Added page at index %lu", (unsigned long)index);
  818. // Add caption
  819. MWCaptionView *captionView = [self captionViewForPhotoAtIndex:index];
  820. if (captionView) {
  821. captionView.frame = [self frameForCaptionView:captionView atIndex:index];
  822. [_pagingScrollView addSubview:captionView];
  823. page.captionView = captionView;
  824. }
  825. // Add play button if needed
  826. if (page.displayingVideo) {
  827. UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
  828. [playButton setImage:[UIImage imageForResourcePath:@"MWPhotoBrowser.bundle/PlayButtonOverlayLarge" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  829. [playButton setImage:[UIImage imageForResourcePath:@"MWPhotoBrowser.bundle/PlayButtonOverlayLargeTap" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateHighlighted];
  830. [playButton addTarget:self action:@selector(playButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  831. [playButton sizeToFit];
  832. playButton.frame = [self frameForPlayButton:playButton atIndex:index];
  833. [_pagingScrollView addSubview:playButton];
  834. page.playButton = playButton;
  835. }
  836. // Add selected button
  837. if (self.displaySelectionButtons) {
  838. UIButton *selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
  839. [selectedButton setImage:[UIImage imageForResourcePath:@"MWPhotoBrowser.bundle/ImageSelectedOff" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]] forState:UIControlStateNormal];
  840. UIImage *selectedOnImage;
  841. if (self.customImageSelectedIcon) {
  842. ///***** BEGIN THREEMA MODIFICATION: use image instead of name *********/
  843. selectedOnImage = self.customImageSelectedIcon;
  844. ///***** END THREEMA MODIFICATION: use image instead of name *********/
  845. } else {
  846. selectedOnImage = [UIImage imageForResourcePath:@"MWPhotoBrowser.bundle/ImageSelectedOn" ofType:@"png" inBundle:[NSBundle bundleForClass:[self class]]];
  847. }
  848. [selectedButton setImage:selectedOnImage forState:UIControlStateSelected];
  849. [selectedButton sizeToFit];
  850. selectedButton.adjustsImageWhenHighlighted = NO;
  851. [selectedButton addTarget:self action:@selector(selectedButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
  852. selectedButton.frame = [self frameForSelectedButton:selectedButton atIndex:index];
  853. [_pagingScrollView addSubview:selectedButton];
  854. page.selectedButton = selectedButton;
  855. selectedButton.selected = [self photoIsSelectedAtIndex:index];
  856. /***** BEGIN THREEMA MODIFICATION: *********/
  857. selectedButton.accessibilityLabel = NSLocalizedString(@"mwphotobrowser_select", nil);
  858. /***** END THREEMA MODIFICATION: *********/
  859. }
  860. }
  861. }
  862. }
  863. - (void)updateVisiblePageStates {
  864. NSSet *copy = [_visiblePages copy];
  865. for (MWZoomingScrollView *page in copy) {
  866. // Update selection
  867. page.selectedButton.selected = [self photoIsSelectedAtIndex:page.index];
  868. }
  869. }
  870. - (BOOL)isDisplayingPageForIndex:(NSUInteger)index {
  871. for (MWZoomingScrollView *page in _visiblePages)
  872. if (page.index == index) return YES;
  873. return NO;
  874. }
  875. - (MWZoomingScrollView *)pageDisplayedAtIndex:(NSUInteger)index {
  876. MWZoomingScrollView *thePage = nil;
  877. for (MWZoomingScrollView *page in _visiblePages) {
  878. if (page.index == index) {
  879. thePage = page; break;
  880. }
  881. }
  882. return thePage;
  883. }
  884. - (MWZoomingScrollView *)pageDisplayingPhoto:(id<MWPhoto>)photo {
  885. MWZoomingScrollView *thePage = nil;
  886. for (MWZoomingScrollView *page in _visiblePages) {
  887. if (page.photo == photo) {
  888. thePage = page; break;
  889. }
  890. }
  891. return thePage;
  892. }
  893. - (void)configurePage:(MWZoomingScrollView *)page forIndex:(NSUInteger)index {
  894. page.frame = [self frameForPageAtIndex:index];
  895. page.index = index;
  896. page.photo = [self photoAtIndex:index];
  897. }
  898. - (MWZoomingScrollView *)dequeueRecycledPage {
  899. MWZoomingScrollView *page = [_recycledPages anyObject];
  900. if (page) {
  901. [_recycledPages removeObject:page];
  902. }
  903. return page;
  904. }
  905. // Handle page changes
  906. - (void)didStartViewingPageAtIndex:(NSUInteger)index {
  907. // Handle 0 photos
  908. if (![self numberOfPhotos]) {
  909. // Show controls
  910. [self setControlsHidden:NO animated:YES permanent:YES];
  911. return;
  912. }
  913. // Handle video on page change
  914. if (!_rotating && index != _currentVideoIndex) {
  915. [self clearCurrentVideo: true];
  916. }
  917. // Release images further away than +/-1
  918. NSUInteger i;
  919. if (index > 0) {
  920. // Release anything < index - 1
  921. for (i = 0; i < index-1; i++) {
  922. id photo = [_photos objectAtIndex:i];
  923. if (photo != [NSNull null]) {
  924. [photo unloadUnderlyingImage];
  925. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  926. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  927. }
  928. }
  929. }
  930. if (index < [self numberOfPhotos] - 1) {
  931. // Release anything > index + 1
  932. for (i = index + 2; i < _photos.count; i++) {
  933. id photo = [_photos objectAtIndex:i];
  934. if (photo != [NSNull null]) {
  935. [photo unloadUnderlyingImage];
  936. [_photos replaceObjectAtIndex:i withObject:[NSNull null]];
  937. MWLog(@"Released underlying image at index %lu", (unsigned long)i);
  938. }
  939. }
  940. }
  941. // Load adjacent images if needed and the photo is already
  942. // loaded. Also called after photo has been loaded in background
  943. id <MWPhoto> currentPhoto = [self photoAtIndex:index];
  944. if ([currentPhoto underlyingImage]) {
  945. // photo loaded so load ajacent now
  946. [self loadAdjacentPhotosIfNecessary:currentPhoto];
  947. }
  948. /***** BEGIN THREEMA MODIFICATION: always show controls for video *********/
  949. if ([currentPhoto showControls] && !_peeking) {
  950. [self setControlsHidden:NO animated:YES permanent:YES];
  951. } else {
  952. [self hideControlsAfterDelay];
  953. }
  954. /***** END THREEMA MODIFICATION: always show controls for video *********/
  955. // Notify delegate
  956. if (index != _previousPageIndex) {
  957. if ([_delegate respondsToSelector:@selector(photoBrowser:didDisplayPhotoAtIndex:)])
  958. [_delegate photoBrowser:self didDisplayPhotoAtIndex:index];
  959. _previousPageIndex = index;
  960. }
  961. // Update nav
  962. [self updateNavigation];
  963. }
  964. #pragma mark - Frame Calculations
  965. - (CGRect)frameForPagingScrollView {
  966. CGRect frame = self.view.bounds;// [[UIScreen mainScreen] bounds];
  967. frame.origin.x -= PADDING;
  968. frame.size.width += (2 * PADDING);
  969. return CGRectIntegral(frame);
  970. }
  971. - (CGRect)frameForPageAtIndex:(NSUInteger)index {
  972. // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
  973. // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
  974. // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
  975. // because it has a rotation transform applied.
  976. CGRect bounds = _pagingScrollView.bounds;
  977. CGRect pageFrame = bounds;
  978. pageFrame.size.width -= (2 * PADDING);
  979. pageFrame.origin.x = (bounds.size.width * index) + PADDING;
  980. return CGRectIntegral(pageFrame);
  981. }
  982. - (CGSize)contentSizeForPagingScrollView {
  983. // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
  984. CGRect bounds = _pagingScrollView.bounds;
  985. return CGSizeMake(bounds.size.width * [self numberOfPhotos], bounds.size.height);
  986. }
  987. - (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index {
  988. CGFloat pageWidth = _pagingScrollView.bounds.size.width;
  989. CGFloat newOffset = index * pageWidth;
  990. return CGPointMake(newOffset, 0);
  991. }
  992. - (CGRect)frameForToolbarAtOrientation:(UIInterfaceOrientation)orientation {
  993. CGFloat height = 44;
  994. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone &&
  995. UIInterfaceOrientationIsLandscape(orientation)) height = 32;
  996. CGFloat adjust = 0;
  997. if (@available(iOS 11.0, *)) {
  998. //Account for possible notch
  999. UIEdgeInsets safeArea = [[UIApplication sharedApplication] keyWindow].safeAreaInsets;
  1000. adjust = safeArea.bottom;
  1001. }
  1002. return CGRectIntegral(CGRectMake(0, self.view.bounds.size.height - height - adjust, self.view.bounds.size.width, height));
  1003. }
  1004. - (CGRect)frameForCaptionView:(MWCaptionView *)captionView atIndex:(NSUInteger)index {
  1005. CGRect pageFrame = [self frameForPageAtIndex:index];
  1006. CGSize captionSize = [captionView sizeThatFits:CGSizeMake(pageFrame.size.width, 0)];
  1007. CGRect toolBarRect = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  1008. CGRect captionFrame = CGRectMake(pageFrame.origin.x,
  1009. toolBarRect.origin.y - captionSize.height,
  1010. pageFrame.size.width,
  1011. captionSize.height);
  1012. return CGRectIntegral(captionFrame);
  1013. }
  1014. - (CGRect)frameForSelectedButton:(UIButton *)selectedButton atIndex:(NSUInteger)index {
  1015. CGRect pageFrame = [self frameForPageAtIndex:index];
  1016. CGFloat padding = 20;
  1017. CGFloat yOffset = 0;
  1018. if (![self areControlsHidden]) {
  1019. UINavigationBar *navBar = self.navigationController.navigationBar;
  1020. yOffset = navBar.frame.origin.y + navBar.frame.size.height;
  1021. }
  1022. /***** BEGIN THREEMA MODIFICATION: change button to bottom right instead of top right *********/
  1023. CGRect selectedButtonFrame = CGRectMake(pageFrame.origin.x + pageFrame.size.width - selectedButton.frame.size.width - padding,
  1024. pageFrame.origin.y + pageFrame.size.height - selectedButton.frame.size.height - padding,
  1025. selectedButton.frame.size.width,
  1026. selectedButton.frame.size.height);
  1027. /***** END THREEMA MODIFICATION: change button to bottom right instead of top right *********/
  1028. return CGRectIntegral(selectedButtonFrame);
  1029. }
  1030. - (CGRect)frameForPlayButton:(UIButton *)playButton atIndex:(NSUInteger)index {
  1031. CGRect pageFrame = [self frameForPageAtIndex:index];
  1032. return CGRectMake(floorf(CGRectGetMidX(pageFrame) - playButton.frame.size.width / 2),
  1033. floorf(CGRectGetMidY(pageFrame) - playButton.frame.size.height / 2),
  1034. playButton.frame.size.width,
  1035. playButton.frame.size.height);
  1036. }
  1037. #pragma mark - UIScrollView Delegate
  1038. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  1039. // Checks
  1040. if (!_viewIsActive || _performingLayout || _rotating) return;
  1041. // Tile pages
  1042. [self tilePages];
  1043. // Calculate current page
  1044. CGRect visibleBounds = _pagingScrollView.bounds;
  1045. NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)));
  1046. if (index < 0) index = 0;
  1047. if (index > [self numberOfPhotos] - 1) index = [self numberOfPhotos] - 1;
  1048. NSUInteger previousCurrentPage = _currentPageIndex;
  1049. _currentPageIndex = index;
  1050. if (_currentPageIndex != previousCurrentPage) {
  1051. [self didStartViewingPageAtIndex:index];
  1052. }
  1053. }
  1054. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  1055. // Hide controls when dragging begins
  1056. [self setControlsHidden:YES animated:YES permanent:NO];
  1057. }
  1058. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  1059. // Update nav when page changes
  1060. [self updateNavigation];
  1061. }
  1062. #pragma mark - Navigation
  1063. - (void)updateNavigation {
  1064. // Title
  1065. NSUInteger numberOfPhotos = [self numberOfPhotos];
  1066. if (_gridController) {
  1067. if (_gridController.selectionMode) {
  1068. self.title = NSLocalizedString(@"Select Photos", nil);
  1069. } else {
  1070. NSString *photosText;
  1071. if (numberOfPhotos == 1) {
  1072. photosText = NSLocalizedString(@"photo", @"Used in the context: '1 photo'");
  1073. } else {
  1074. photosText = NSLocalizedString(@"photos", @"Used in the context: '3 photos'");
  1075. }
  1076. self.title = [NSString stringWithFormat:@"%lu %@", (unsigned long)numberOfPhotos, photosText];
  1077. }
  1078. } else if (numberOfPhotos > 1) {
  1079. if ([_delegate respondsToSelector:@selector(photoBrowser:titleForPhotoAtIndex:)]) {
  1080. self.title = [_delegate photoBrowser:self titleForPhotoAtIndex:_currentPageIndex];
  1081. } else {
  1082. self.title = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)(_currentPageIndex+1), NSLocalizedString(@"of", @"Used in the context: 'Showing 1 of 3 items'"), (unsigned long)numberOfPhotos];
  1083. }
  1084. } else {
  1085. self.title = nil;
  1086. }
  1087. // Buttons
  1088. _previousButton.enabled = (_currentPageIndex > 0);
  1089. _nextButton.enabled = (_currentPageIndex < numberOfPhotos - 1);
  1090. // // Disable action button if there is no image or it's a video
  1091. // MWPhoto *photo = [self photoAtIndex:_currentPageIndex];
  1092. // if ([photo underlyingImage] == nil || ([photo respondsToSelector:@selector(isVideo)] && photo.isVideo)) {
  1093. // _actionButton.enabled = NO;
  1094. // _actionButton.tintColor = [UIColor clearColor]; // Tint to hide button
  1095. // } else {
  1096. // _actionButton.enabled = YES;
  1097. // _actionButton.tintColor = nil;
  1098. // }
  1099. }
  1100. - (void)jumpToPageAtIndex:(NSUInteger)index animated:(BOOL)animated {
  1101. // Change page
  1102. if (index < [self numberOfPhotos]) {
  1103. CGRect pageFrame = [self frameForPageAtIndex:index];
  1104. [_pagingScrollView setContentOffset:CGPointMake(pageFrame.origin.x - PADDING, 0) animated:animated];
  1105. [self updateNavigation];
  1106. }
  1107. // Update timer to give more time
  1108. [self hideControlsAfterDelay];
  1109. }
  1110. - (void)gotoPreviousPage {
  1111. [self showPreviousPhotoAnimated:NO];
  1112. }
  1113. - (void)gotoNextPage {
  1114. [self showNextPhotoAnimated:NO];
  1115. }
  1116. - (void)showPreviousPhotoAnimated:(BOOL)animated {
  1117. [self jumpToPageAtIndex:_currentPageIndex-1 animated:animated];
  1118. }
  1119. - (void)showNextPhotoAnimated:(BOOL)animated {
  1120. [self jumpToPageAtIndex:_currentPageIndex+1 animated:animated];
  1121. }
  1122. #pragma mark - Interactions
  1123. - (void)selectedButtonTapped:(id)sender {
  1124. UIButton *selectedButton = (UIButton *)sender;
  1125. selectedButton.selected = !selectedButton.selected;
  1126. NSUInteger index = NSUIntegerMax;
  1127. for (MWZoomingScrollView *page in _visiblePages) {
  1128. if (page.selectedButton == selectedButton) {
  1129. index = page.index;
  1130. break;
  1131. }
  1132. }
  1133. if (index != NSUIntegerMax) {
  1134. [self setPhotoSelected:selectedButton.selected atIndex:index];
  1135. }
  1136. }
  1137. - (void)playButtonTapped:(id)sender {
  1138. // Ignore if we're already playing a video
  1139. if (_currentVideoIndex != NSUIntegerMax) {
  1140. return;
  1141. }
  1142. NSUInteger index = [self indexForPlayButton:sender];
  1143. if (index != NSUIntegerMax) {
  1144. if (!_currentVideoPlayerViewController) {
  1145. [self playVideoAtIndex:index];
  1146. }
  1147. }
  1148. }
  1149. - (NSUInteger)indexForPlayButton:(UIView *)playButton {
  1150. NSUInteger index = NSUIntegerMax;
  1151. for (MWZoomingScrollView *page in _visiblePages) {
  1152. if (page.playButton == playButton) {
  1153. index = page.index;
  1154. break;
  1155. }
  1156. }
  1157. return index;
  1158. }
  1159. #pragma mark - Video
  1160. - (void)playVideoAtIndex:(NSUInteger)index {
  1161. id photo = [self photoAtIndex:index];
  1162. if ([photo respondsToSelector:@selector(getVideoURL:)]) {
  1163. // Valid for playing
  1164. [self clearCurrentVideo: true];
  1165. _currentVideoIndex = index;
  1166. [self setVideoLoadingIndicatorVisible:YES atPageIndex:index];
  1167. ///***** BEGIN THREEMA MODIFICATION: ignore mute switch *********/
  1168. NSInteger state = [[VoIPCallStateManager shared] currentCallState];
  1169. if (state == CallStateIdle) {
  1170. _prevAudioCategory = [[AVAudioSession sharedInstance] category];
  1171. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  1172. }
  1173. ///***** END THREEMA MODIFICATION: ignore mute switch *********/
  1174. // Get video and play
  1175. typeof(self) __weak weakSelf = self;
  1176. [photo getVideoURL:^(NSURL *url) {
  1177. dispatch_async(dispatch_get_main_queue(), ^{
  1178. // If the video is not playing anymore then bail
  1179. typeof(self) strongSelf = weakSelf;
  1180. if (!strongSelf) return;
  1181. if (strongSelf->_currentVideoIndex != index || !strongSelf->_viewIsActive) {
  1182. return;
  1183. }
  1184. if (url) {
  1185. [weakSelf _playVideo:url atPhotoIndex:index];
  1186. } else {
  1187. [weakSelf setVideoLoadingIndicatorVisible:NO atPageIndex:index];
  1188. }
  1189. });
  1190. }];
  1191. }
  1192. }
  1193. - (void)_playVideo:(NSURL *)videoURL atPhotoIndex:(NSUInteger)index {
  1194. AVPlayer *player = [AVPlayer playerWithURL:videoURL];
  1195. _currentVideoPlayerViewController = [AVPlayerViewController new];
  1196. _currentVideoPlayerViewController.player = player;
  1197. ///***** BEGIN THREEMA MODIFICATION: ignore mute switch *********/
  1198. _currentVideoPlayerViewController.delegate = self;
  1199. ///***** END THREEMA MODIFICATION: ignore mute switch *********/
  1200. [self presentViewController:_currentVideoPlayerViewController animated:YES completion:^{
  1201. [_currentVideoPlayerViewController.player play];
  1202. [self clearCurrentVideo: false];
  1203. }];
  1204. }
  1205. ///***** BEGIN THREEMA MODIFICATION: reset audio *********/
  1206. - (void)clearCurrentVideo:(BOOL)audioFree {
  1207. [_currentVideoLoadingIndicator removeFromSuperview];
  1208. _currentVideoPlayerViewController = nil;
  1209. _currentVideoLoadingIndicator = nil;
  1210. [[self pageDisplayedAtIndex:_currentVideoIndex] playButton].hidden = NO;
  1211. _currentVideoIndex = NSUIntegerMax;
  1212. NSInteger state = [[VoIPCallStateManager shared] currentCallState];
  1213. if (audioFree == true && state == CallStateIdle) {
  1214. [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
  1215. }
  1216. }
  1217. ///***** END THREEMA MODIFICATION: reset audio *********/
  1218. - (void)setVideoLoadingIndicatorVisible:(BOOL)visible atPageIndex:(NSUInteger)pageIndex {
  1219. if (_currentVideoLoadingIndicator && !visible) {
  1220. [_currentVideoLoadingIndicator removeFromSuperview];
  1221. _currentVideoLoadingIndicator = nil;
  1222. [[self pageDisplayedAtIndex:pageIndex] playButton].hidden = NO;
  1223. } else if (!_currentVideoLoadingIndicator && visible) {
  1224. _currentVideoLoadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectZero];
  1225. [_currentVideoLoadingIndicator sizeToFit];
  1226. [_currentVideoLoadingIndicator startAnimating];
  1227. [_pagingScrollView addSubview:_currentVideoLoadingIndicator];
  1228. [self positionVideoLoadingIndicator];
  1229. [[self pageDisplayedAtIndex:pageIndex] playButton].hidden = YES;
  1230. }
  1231. }
  1232. - (void)positionVideoLoadingIndicator {
  1233. if (_currentVideoLoadingIndicator && _currentVideoIndex != NSUIntegerMax) {
  1234. CGRect frame = [self frameForPageAtIndex:_currentVideoIndex];
  1235. _currentVideoLoadingIndicator.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
  1236. }
  1237. }
  1238. #pragma mark - Grid
  1239. - (void)showGridAnimated {
  1240. [self showGrid:YES];
  1241. }
  1242. - (void)showGrid:(BOOL)animated {
  1243. if (_gridController) return;
  1244. // Clear video
  1245. [self clearCurrentVideo: true];
  1246. // Init grid controller
  1247. _gridController = [[MWGridViewController alloc] init];
  1248. ///***** BEGIN THREEMA MODIFICATION: iOS 11 *********/
  1249. // _gridController.initialContentOffset = _currentGridContentOffset;
  1250. if (@available(iOS 11.0, *)) {
  1251. } else {
  1252. _gridController.initialContentOffset = _currentGridContentOffset;
  1253. }
  1254. ///***** END THREEMA MODIFICATION: iOS 11 *********/
  1255. /***** BEGIN THREEMA MODIFICATION: add select button *********/
  1256. _selectButton = [[UIBarButtonItem alloc] initWithTitle:[BundleUtil localizedStringForKey:@"mwphotobrowser_select"] style:UIBarButtonItemStylePlain target:self action:@selector(selectButtonPressed:)];
  1257. _selectButton.enabled = [self numberOfPhotos] > 0;
  1258. self.navigationItem.rightBarButtonItem = _selectButton;
  1259. /***** END THREEMA MODIFICATION: add select button *********/
  1260. _gridController.browser = self;
  1261. _gridController.selectionMode = _displaySelectionButtons;
  1262. _gridController.view.frame = self.view.bounds;
  1263. _gridController.view.frame = CGRectOffset(_gridController.view.frame, 0, (self.startOnGrid ? -1 : 1) * self.view.bounds.size.height);
  1264. // Stop specific layout being triggered
  1265. _skipNextPagingScrollViewPositioning = YES;
  1266. // Add as a child view controller
  1267. [self addChildViewController:_gridController];
  1268. [self.view addSubview:_gridController.view];
  1269. // Perform any adjustments
  1270. [_gridController.view layoutIfNeeded];
  1271. [_gridController adjustOffsetsAsRequired];
  1272. // Hide action button on nav bar if it exists
  1273. if (self.navigationItem.rightBarButtonItem == _actionButton) {
  1274. _gridPreviousRightNavItem = _actionButton;
  1275. [self.navigationItem setRightBarButtonItem:nil animated:YES];
  1276. } else {
  1277. _gridPreviousRightNavItem = nil;
  1278. }
  1279. // Update
  1280. [self updateNavigation];
  1281. [self setControlsHidden:NO animated:YES permanent:YES];
  1282. // Animate grid in and photo scroller out
  1283. [_gridController willMoveToParentViewController:self];
  1284. [UIView animateWithDuration:animated ? 0.3 : 0 animations:^(void) {
  1285. _gridController.view.frame = self.view.bounds;
  1286. CGRect newPagingFrame = [self frameForPagingScrollView];
  1287. newPagingFrame = CGRectOffset(newPagingFrame, 0, (self.startOnGrid ? 1 : -1) * newPagingFrame.size.height);
  1288. _pagingScrollView.frame = newPagingFrame;
  1289. } completion:^(BOOL finished) {
  1290. [_gridController didMoveToParentViewController:self];
  1291. }];
  1292. }
  1293. - (void)hideGrid {
  1294. if (!_gridController) return;
  1295. ///***** BEGIN THREEMA MODIFICATION: iOS 11 *********/
  1296. // Remember previous content offset
  1297. // _currentGridContentOffset = _gridController.collectionView.contentOffset;
  1298. if (@available(iOS 11.0, *)) {
  1299. } else {
  1300. // Remember previous content offset
  1301. _currentGridContentOffset = _gridController.collectionView.contentOffset;
  1302. }
  1303. ///***** END THREEMA MODIFICATION: iOS 11 *********/
  1304. /***** BEGIN THREEMA MODIFICATION: add select button *********/
  1305. self.navigationItem.rightBarButtonItem = nil;
  1306. /***** END THREEMA MODIFICATION: add select button *********/
  1307. // Restore action button if it was removed
  1308. if (_gridPreviousRightNavItem == _actionButton && _actionButton) {
  1309. [self.navigationItem setRightBarButtonItem:_gridPreviousRightNavItem animated:YES];
  1310. }
  1311. // Position prior to hide animation
  1312. CGRect newPagingFrame = [self frameForPagingScrollView];
  1313. newPagingFrame = CGRectOffset(newPagingFrame, 0, (self.startOnGrid ? 1 : -1) * newPagingFrame.size.height);
  1314. _pagingScrollView.frame = newPagingFrame;
  1315. // Remember and remove controller now so things can detect a nil grid controller
  1316. MWGridViewController *tmpGridController = _gridController;
  1317. _gridController = nil;
  1318. // Update
  1319. [self updateNavigation];
  1320. [self updateVisiblePageStates];
  1321. // Animate, hide grid and show paging scroll view
  1322. [UIView animateWithDuration:0.3 animations:^{
  1323. tmpGridController.view.frame = CGRectOffset(self.view.bounds, 0, (self.startOnGrid ? -1 : 1) * self.view.bounds.size.height);
  1324. _pagingScrollView.frame = [self frameForPagingScrollView];
  1325. } completion:^(BOOL finished) {
  1326. [tmpGridController willMoveToParentViewController:nil];
  1327. [tmpGridController.view removeFromSuperview];
  1328. [tmpGridController removeFromParentViewController];
  1329. [self setControlsHidden:NO animated:YES permanent:NO]; // retrigger timer
  1330. }];
  1331. }
  1332. #pragma mark - Control Hiding / Showing
  1333. // If permanent then we don't set timers to hide again
  1334. // Fades all controls on iOS 5 & 6, and iOS 7 controls slide and fade
  1335. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent {
  1336. // Force visible
  1337. if (![self numberOfPhotos] || _gridController || _alwaysShowControls)
  1338. hidden = NO;
  1339. // Cancel any timers
  1340. [self cancelControlHiding];
  1341. // Animations & positions
  1342. CGFloat animatonOffset = 20;
  1343. CGFloat animationDuration = (animated ? 0.35 : 0);
  1344. // Status bar
  1345. if (!_leaveStatusBarAlone) {
  1346. // Hide status bar
  1347. if (!_isVCBasedStatusBarAppearance) {
  1348. // Non-view controller based
  1349. [[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:animated ? UIStatusBarAnimationSlide : UIStatusBarAnimationNone];
  1350. } else {
  1351. // View controller based so animate away
  1352. _statusBarShouldBeHidden = hidden;
  1353. [UIView animateWithDuration:animationDuration animations:^(void) {
  1354. [self setNeedsStatusBarAppearanceUpdate];
  1355. } completion:^(BOOL finished) {}];
  1356. }
  1357. }
  1358. // Toolbar, nav bar and captions
  1359. // Pre-appear animation positions for sliding
  1360. if ([self areControlsHidden] && !hidden && animated) {
  1361. // Toolbar
  1362. _toolbar.frame = CGRectOffset([self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]], 0, animatonOffset);
  1363. _gridToolbar.frame = CGRectOffset([self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]], 0, animatonOffset);
  1364. // Captions
  1365. for (MWZoomingScrollView *page in _visiblePages) {
  1366. if (page.captionView) {
  1367. MWCaptionView *v = page.captionView;
  1368. // Pass any index, all we're interested in is the Y
  1369. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1370. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1371. v.frame = CGRectOffset(captionFrame, 0, animatonOffset);
  1372. }
  1373. }
  1374. }
  1375. [UIView animateWithDuration:animationDuration animations:^(void) {
  1376. CGFloat alpha = hidden ? 0 : 1;
  1377. // Nav bar slides up on it's own on iOS 7+
  1378. [self.navigationController.navigationBar setAlpha:alpha];
  1379. // Toolbar
  1380. _toolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  1381. _gridToolbar.frame = [self frameForToolbarAtOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
  1382. if (hidden) _toolbar.frame = CGRectOffset(_toolbar.frame, 0, animatonOffset);
  1383. _toolbar.alpha = alpha;
  1384. // Captions
  1385. for (MWZoomingScrollView *page in _visiblePages) {
  1386. if (page.captionView) {
  1387. MWCaptionView *v = page.captionView;
  1388. // Pass any index, all we're interested in is the Y
  1389. CGRect captionFrame = [self frameForCaptionView:v atIndex:0];
  1390. captionFrame.origin.x = v.frame.origin.x; // Reset X
  1391. if (hidden) captionFrame = CGRectOffset(captionFrame, 0, animatonOffset);
  1392. v.frame = captionFrame;
  1393. v.alpha = alpha;
  1394. }
  1395. }
  1396. // Selected buttons
  1397. for (MWZoomingScrollView *page in _visiblePages) {
  1398. if (page.selectedButton) {
  1399. UIButton *v = page.selectedButton;
  1400. CGRect newFrame = [self frameForSelectedButton:v atIndex:0];
  1401. newFrame.origin.x = v.frame.origin.x;
  1402. v.frame = newFrame;
  1403. }
  1404. }
  1405. } completion:^(BOOL finished) {}];
  1406. // Control hiding timer
  1407. // Will cancel existing timer but only begin hiding if
  1408. // they are visible
  1409. if (!permanent) [self hideControlsAfterDelay];
  1410. }
  1411. - (BOOL)prefersStatusBarHidden {
  1412. /***** BEGIN THREEMA MODIFICATION: always hide status bar in landscape mode on iOS 8.0 *********/
  1413. if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
  1414. return YES;
  1415. }
  1416. /***** END THREEMA MODIFICATION: always hide status bar in landscape mode on iOS 8.0 *********/
  1417. if (!_leaveStatusBarAlone) {
  1418. return _statusBarShouldBeHidden;
  1419. } else {
  1420. return [self presentingViewControllerPrefersStatusBarHidden];
  1421. }
  1422. }
  1423. - (UIStatusBarStyle)preferredStatusBarStyle {
  1424. return UIStatusBarStyleLightContent;
  1425. }
  1426. - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
  1427. return UIStatusBarAnimationSlide;
  1428. }
  1429. - (void)cancelControlHiding {
  1430. // If a timer exists then cancel and release
  1431. if (_controlVisibilityTimer) {
  1432. [_controlVisibilityTimer invalidate];
  1433. _controlVisibilityTimer = nil;
  1434. }
  1435. }
  1436. // Enable/disable control visiblity timer
  1437. - (void)hideControlsAfterDelay {
  1438. if (![self areControlsHidden]) {
  1439. [self cancelControlHiding];
  1440. _controlVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:self.delayToHideElements target:self selector:@selector(hideControls) userInfo:nil repeats:NO];
  1441. }
  1442. }
  1443. - (BOOL)areControlsHidden { return (_toolbar.alpha == 0); }
  1444. - (void)hideControls { [self setControlsHidden:YES animated:YES permanent:NO]; }
  1445. - (void)showControls { [self setControlsHidden:NO animated:YES permanent:NO]; }
  1446. - (void)toggleControls { [self setControlsHidden:![self areControlsHidden] animated:YES permanent:NO]; }
  1447. #pragma mark - Properties
  1448. - (void)setCurrentPhotoIndex:(NSUInteger)index {
  1449. // Validate
  1450. NSUInteger photoCount = [self numberOfPhotos];
  1451. if (photoCount == 0) {
  1452. index = 0;
  1453. } else {
  1454. if (index >= photoCount)
  1455. index = [self numberOfPhotos]-1;
  1456. }
  1457. _currentPageIndex = index;
  1458. if ([self isViewLoaded]) {
  1459. [self jumpToPageAtIndex:index animated:NO];
  1460. if (!_viewIsActive)
  1461. [self tilePages]; // Force tiling if view is not visible
  1462. }
  1463. }
  1464. #pragma mark - Misc
  1465. - (void)doneButtonPressed:(id)sender {
  1466. // Only if we're modal and there's a done button
  1467. if (_doneButton) {
  1468. // Dismiss view controller
  1469. if ([_delegate respondsToSelector:@selector(photoBrowserDidFinishModalPresentation:)]) {
  1470. // Call delegate method and let them dismiss us
  1471. [_delegate photoBrowserDidFinishModalPresentation:self];
  1472. } else {
  1473. [self dismissViewControllerAnimated:YES completion:nil];
  1474. }
  1475. }
  1476. }
  1477. #pragma mark - Actions
  1478. - (void)actionButtonPressed:(id)sender {
  1479. // Only react when image has loaded
  1480. id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
  1481. if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
  1482. // If they have defined a delegate method then just message them
  1483. if ([self.delegate respondsToSelector:@selector(photoBrowser:actionButtonPressedForPhotoAtIndex:)]) {
  1484. // Let delegate handle things
  1485. [self.delegate photoBrowser:self actionButtonPressedForPhotoAtIndex:_currentPageIndex];
  1486. } else {
  1487. // Share current photo
  1488. [self shareMedia:photo];
  1489. }
  1490. // Keep controls hidden
  1491. [self setControlsHidden:NO animated:YES permanent:YES];
  1492. }
  1493. }
  1494. /***** BEGIN THREEMA MODIFICATION: add delete button *********/
  1495. - (void)deleteButtonPressed:(id)sender {
  1496. if ([self numberOfPhotos] > 0) {
  1497. if ([self.delegate respondsToSelector:@selector(photoBrowser:deleteButton:pressedForPhotoAtIndex:)]) {
  1498. [self.delegate photoBrowser:self deleteButton:_deleteSingleButton pressedForPhotoAtIndex:_currentPageIndex];
  1499. }
  1500. }
  1501. }
  1502. - (void)selectButtonPressed:(id)sender {
  1503. if (!self.displaySelectionButtons) {
  1504. self.displaySelectionButtons = YES;
  1505. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[BundleUtil localizedStringForKey:@"mwphotobrowser_select_all"] style:UIBarButtonItemStylePlain target:self action:@selector(selectAllButtonPressed:)];
  1506. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(selectButtonPressed:)];
  1507. _deleteMultipleButton.enabled = false;
  1508. _actionMultipleButton.enabled = false;
  1509. [self.view addSubview:_gridToolbar];
  1510. } else {
  1511. self.displaySelectionButtons = NO;
  1512. self.navigationItem.leftBarButtonItem = _doneButton;
  1513. self.navigationItem.rightBarButtonItem = _selectButton;
  1514. [_gridToolbar removeFromSuperview];
  1515. }
  1516. if ([self.delegate respondsToSelector:@selector(photoBrowserResetSelection:)]) {
  1517. [self.delegate photoBrowserResetSelection:self];
  1518. }
  1519. [_gridController setSelectionMode:self.displaySelectionButtons];
  1520. [[_gridController collectionView] reloadData];
  1521. }
  1522. - (void)selectAllButtonPressed:(id)sender {
  1523. if ([self.delegate respondsToSelector:@selector(photoBrowserSelectAll:)]) {
  1524. [self.delegate photoBrowserSelectAll:self];
  1525. }
  1526. [_gridController setSelectionMode:self.displaySelectionButtons];
  1527. [[_gridController collectionView] reloadData];
  1528. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[BundleUtil localizedStringForKey:@"mwphotobrowser_deselect_all"] style:UIBarButtonItemStylePlain target:self action:@selector(deselectAllButtonPressed:)];
  1529. _deleteMultipleButton.enabled = true;
  1530. _actionMultipleButton.enabled = true;
  1531. }
  1532. - (void)deselectAllButtonPressed:(id)sender {
  1533. if ([self.delegate respondsToSelector:@selector(photoBrowserResetSelection:)]) {
  1534. [self.delegate photoBrowserResetSelection:self];
  1535. }
  1536. [_gridController setSelectionMode:self.displaySelectionButtons];
  1537. [[_gridController collectionView] reloadData];
  1538. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[BundleUtil localizedStringForKey:@"mwphotobrowser_select_all"] style:UIBarButtonItemStylePlain target:self action:@selector(selectAllButtonPressed:)];
  1539. _deleteMultipleButton.enabled = false;
  1540. _actionMultipleButton.enabled = false;
  1541. }
  1542. - (void)deleteMultipleButtonPressed:(id)sender {
  1543. if ([self numberOfPhotos] > 0) {
  1544. NSString *actionTitle;
  1545. NSUInteger selectionCount = [((ChatViewHeader *)self.delegate) mediaSelectionCount];
  1546. if (selectionCount == 0) {
  1547. /* clear all */
  1548. actionTitle = NSLocalizedString(@"media_delete_all_confirm", nil);
  1549. } else {
  1550. actionTitle = NSLocalizedString(@"media_delete_selected_confirm", nil);
  1551. }
  1552. UIAlertController *deleteActionSheet = [UIAlertController alertControllerWithTitle:actionTitle message:nil preferredStyle:UIAlertControllerStyleAlert];
  1553. [deleteActionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"delete", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {
  1554. [self showProgressHUDWithMessage:[NSString stringWithFormat:@"%@...", NSLocalizedString(@"delete", "")]];
  1555. if ([self.delegate respondsToSelector:@selector(photoBrowser:deleteButton:)]) {
  1556. [self.delegate photoBrowser:self deleteButton:_deleteMultipleButton];
  1557. [self reloadData:YES];
  1558. [self updateNavigation];
  1559. }
  1560. }]];
  1561. [deleteActionSheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
  1562. deleteActionSheet.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItem;
  1563. [self presentViewController:deleteActionSheet animated:YES completion:nil];
  1564. }
  1565. }
  1566. - (void)actionMultipleButtonPressed:(id)sender {
  1567. MDMSetup *mdmSetup = [[MDMSetup alloc] initWithSetup:false];
  1568. if ([mdmSetup disableShareMedia] == true) {
  1569. // do nothing
  1570. } else {
  1571. NSSet *selectedPhotosIndexes = [((ChatViewHeader *)self.delegate) mediaPhotoSelection];
  1572. NSMutableArray *allSelectedPhotos = [NSMutableArray new];
  1573. [selectedPhotosIndexes enumerateObjectsUsingBlock:^(NSNumber *index, BOOL * _Nonnull stop) {
  1574. MWPhoto *photo = [self photoAtIndex:[index unsignedIntegerValue]];
  1575. NSURL *photoUrl = [photo urlForExportData:[index stringValue]];
  1576. if (photoUrl != nil) {
  1577. [allSelectedPhotos addObject:photoUrl];
  1578. }
  1579. }];
  1580. if (allSelectedPhotos.count == 0) {
  1581. return;
  1582. }
  1583. TTOpenInAppActivity *openInAppActivity = [[TTOpenInAppActivity alloc] initWithView:self.view andBarButtonItem:_actionButton];
  1584. ForwardMultipleURLActivity *forwardUrlActivity = [[ForwardMultipleURLActivity alloc] init];
  1585. self.activityViewController = [ActivityUtil activityViewControllerWithActivityItems:allSelectedPhotos applicationActivities:@[forwardUrlActivity, openInAppActivity]];
  1586. // Show
  1587. typeof(self) __weak weakSelf = self;
  1588. // iOS 8 - Set the Anchor Point for the popover
  1589. self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
  1590. NSUserDefaults *defaults = [AppGroup userDefaults];
  1591. [defaults setDouble:[Utils systemUptime] forKey:@"UIActivityViewControllerOpenTime"];
  1592. [defaults synchronize];
  1593. [self.activityViewController setCompletionWithItemsHandler:^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
  1594. weakSelf.activityViewController = nil;
  1595. [weakSelf hideControlsAfterDelay];
  1596. [weakSelf hideProgressHUD:YES];
  1597. NSUserDefaults *defaults = [AppGroup userDefaults];
  1598. [defaults removeObjectForKey:@"UIActivityViewControllerOpenTime"];
  1599. }];
  1600. [self presentViewController:self.activityViewController animated:YES completion:nil];
  1601. }
  1602. }
  1603. - (void)finishedDeleteMedia {
  1604. [self selectButtonPressed:nil];
  1605. [self hideProgressHUD:true];
  1606. [self reloadData:false];
  1607. }
  1608. /***** END THREEMA MODIFICATION: add delete button *********/
  1609. #pragma mark - Action Progress
  1610. - (MBProgressHUD *)progressHUD {
  1611. if (!_progressHUD) {
  1612. _progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
  1613. _progressHUD.minSize = CGSizeMake(120, 120);
  1614. _progressHUD.minShowTime = 1;
  1615. [self.view addSubview:_progressHUD];
  1616. }
  1617. return _progressHUD;
  1618. }
  1619. - (void)showProgressHUDWithMessage:(NSString *)message {
  1620. self.progressHUD.label.text = message;
  1621. self.progressHUD.mode = MBProgressHUDModeIndeterminate;
  1622. [self.progressHUD showAnimated:YES];
  1623. self.navigationController.navigationBar.userInteractionEnabled = NO;
  1624. }
  1625. - (void)hideProgressHUD:(BOOL)animated {
  1626. [self.progressHUD hideAnimated:animated];
  1627. self.navigationController.navigationBar.userInteractionEnabled = YES;
  1628. }
  1629. - (void)showProgressHUDCompleteMessage:(NSString *)message {
  1630. if (message) {
  1631. if (self.progressHUD.isHidden) [self.progressHUD showAnimated:YES];
  1632. self.progressHUD.label.text = message;
  1633. self.progressHUD.mode = MBProgressHUDModeCustomView;
  1634. [self.progressHUD hideAnimated:YES afterDelay:1.5];
  1635. } else {
  1636. [self.progressHUD hideAnimated:YES];
  1637. }
  1638. self.navigationController.navigationBar.userInteractionEnabled = YES;
  1639. }
  1640. /***** BEGIN THREEMA MODIFICATION: add peeking *********/
  1641. - (BOOL)peeking {
  1642. return _peeking;
  1643. }
  1644. - (void)setPeeking:(BOOL)peeking {
  1645. _peeking = peeking;
  1646. [self setControlsHidden:peeking animated:!peeking permanent:NO];
  1647. }
  1648. /***** END THREEMA MODIFICATION: add peeking *********/
  1649. ///***** BEGIN THREEMA MODIFICATION: ignore mute switch *********/
  1650. #pragma mark - AVPlayerViewControllerDelegate
  1651. - (void)playerViewControllerWillBeginDismissalTransition:(AVPlayerViewController *)playerViewController {
  1652. NSInteger state = [[VoIPCallStateManager shared] currentCallState];
  1653. if (state == CallStateIdle) {
  1654. [[AVAudioSession sharedInstance] setCategory:_prevAudioCategory error:nil];
  1655. }
  1656. }
  1657. ///***** END THREEMA MODIFICATION: ignore mute switch *********/
  1658. - (void)shareMedia:(MWPhoto *)item {
  1659. /***** BEGIN THREEMA MODIFICATION: use TTOpenInAppActivity, ForwardURLActivity, MDM share restriction *********/
  1660. MDMSetup *mdmSetup = [[MDMSetup alloc] initWithSetup:false];
  1661. if ([mdmSetup disableShareMedia] == true) {
  1662. ModalNavigationController *navigationController = [ContactGroupPickerViewController pickerFromStoryboardWithDelegate:self];
  1663. ContactGroupPickerViewController *picker = (ContactGroupPickerViewController *)navigationController.topViewController;
  1664. picker.enableMulitSelection = true;
  1665. picker.enableTextInput = true;
  1666. picker.submitOnSelect = false;
  1667. [self presentViewController:navigationController animated:YES completion:nil];
  1668. } else {
  1669. NSURL *photoUrl = [item urlForExportData:@"file"];
  1670. if (photoUrl == nil) {
  1671. [self setControlsHidden:NO animated:YES permanent:YES];
  1672. return;
  1673. }
  1674. NSArray *items = [NSArray arrayWithObject: photoUrl];
  1675. TTOpenInAppActivity *openInAppActivity = [[TTOpenInAppActivity alloc] initWithView:self.view andBarButtonItem:_actionButton];
  1676. ForwardURLActivity *forwardUrlActivity = [[ForwardURLActivity alloc] init];
  1677. self.activityViewController = [ActivityUtil activityViewControllerWithActivityItems:items applicationActivities:@[forwardUrlActivity, openInAppActivity]];
  1678. openInAppActivity.superViewController = self.activityViewController;
  1679. // Show
  1680. typeof(self) __weak weakSelf = self;
  1681. // iOS 8 - Set the Anchor Point for the popover
  1682. self.activityViewController.popoverPresentationController.barButtonItem = _actionButton;
  1683. NSUserDefaults *defaults = [AppGroup userDefaults];
  1684. [defaults setDouble:[Utils systemUptime] forKey:@"UIActivityViewControllerOpenTime"];
  1685. [defaults synchronize];
  1686. [self.activityViewController setCompletionWithItemsHandler:^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
  1687. // Fix: iOS 13 close modal view after save image to photos
  1688. if (@available(iOS 13.0, *)) {
  1689. if (activityType == UIActivityTypeSaveToCameraRoll && completed){
  1690. // do nothing
  1691. } else {
  1692. [weakSelf dismissViewControllerAnimated:NO completion:nil];
  1693. }
  1694. }
  1695. weakSelf.activityViewController = nil;
  1696. [weakSelf hideControlsAfterDelay];
  1697. [weakSelf hideProgressHUD:YES];
  1698. NSUserDefaults *defaults = [AppGroup userDefaults];
  1699. [defaults removeObjectForKey:@"UIActivityViewControllerOpenTime"];
  1700. }];
  1701. // Fix: iOS 13 close modal view after save image to photos
  1702. UIViewController *fakeVC=[[UIViewController alloc] init];
  1703. if (@available(iOS 13.0, *)) {
  1704. [self presentViewController:fakeVC animated:NO completion:^{
  1705. [fakeVC presentViewController:self.activityViewController animated:YES completion:nil];
  1706. }];
  1707. } else {
  1708. [self presentViewController:self.activityViewController animated:YES completion:nil];
  1709. }
  1710. }
  1711. ///***** END THREEMA MODIFICATION: use TTOpenInAppActivity, ForwardURLActivity, MDM share restriction *********/
  1712. }
  1713. - (void)showAlert:(NSString *)title message:(NSString *)message {
  1714. ///***** BEGIN THREEMA MODIFICATION: Use own AlertController *********/
  1715. [UIAlertTemplate showAlertWithOwner:self title:title message:message actionOk:nil];
  1716. ///***** END THREEMA MODIFICATION: Use own AlertController *********/
  1717. }
  1718. ///***** BEGIN THREEMA MODIFICATION: ContactGroupPickerDelegate *********/
  1719. #pragma mark - Contact picker delegate
  1720. - (void)contactPicker:(ContactGroupPickerViewController*)contactPicker didPickConversations:(NSSet *)conversations renderType:(NSNumber *)renderType sendAsFile:(BOOL)sendAsFile {
  1721. FeatureMaskChecker *featureMaskChecker = [[FeatureMaskChecker alloc] init];
  1722. id <MWPhoto> photo = [self photoAtIndex:_currentPageIndex];
  1723. if ([self numberOfPhotos] > 0 && [photo underlyingImage]) {
  1724. NSString *filename = [FileUtility getTemporarySendableFileNameWithBase:@"image"];
  1725. NSURL *photoUrl = [photo urlForExportData:filename];
  1726. [featureMaskChecker checkFileTransferFor:conversations presentAlarmOn:contactPicker onSuccess:^{
  1727. for (Conversation *conversation in conversations) {
  1728. [URLSender sendUrl:photoUrl asFile:sendAsFile caption:contactPicker.additionalTextToSend conversation:conversation];
  1729. }
  1730. [contactPicker dismissViewControllerAnimated:YES completion:nil];
  1731. } onFailure:^{
  1732. [contactPicker dismissViewControllerAnimated:YES completion:nil];
  1733. }];
  1734. } else {
  1735. [contactPicker dismissViewControllerAnimated:YES completion:nil];
  1736. }
  1737. }
  1738. - (void)contactPickerDidCancel:(ContactGroupPickerViewController*)contactPicker {
  1739. [contactPicker dismissViewControllerAnimated:YES completion:nil];
  1740. }
  1741. ///***** END THREEMA MODIFICATION: ContactGroupPickerDelegate *********/
  1742. @end