added iOS source code
[wl-app.git] / iOS / Pods / FolioReaderKit / Source / FolioReaderQuoteShare.swift
1 //
2 //  FolioReaderQuoteShare.swift
3 //  FolioReaderKit
4 //
5 //  Created by Heberti Almeida on 8/11/16.
6 //  Copyright (c) 2016 Folio Reader. All rights reserved.
7 //
8
9 import UIKit
10
11 class FolioReaderQuoteShare: UIViewController {
12     var quoteText: String!
13     var filterImage: UIView!
14     var imageView: UIImageView!
15     var quoteLabel: UILabel!
16     var titleLabel: UILabel!
17     var authorLabel: UILabel!
18     var logoImageView: UIImageView!
19     var collectionView: UICollectionView!
20     let collectionViewLayout = UICollectionViewFlowLayout()
21     let itemSize: CGFloat = 90
22     var dataSource = [QuoteImage]()
23 //    let imagePicker = UIImagePickerController()
24     var selectedIndex = 0
25
26     fileprivate var book: FRBook
27     fileprivate var folioReader: FolioReader
28     fileprivate var readerConfig: FolioReaderConfig
29
30     // MARK: Init
31
32     init(initWithText shareText: String, readerConfig: FolioReaderConfig, folioReader: FolioReader, book: FRBook) {
33         self.folioReader = folioReader
34         self.readerConfig = readerConfig
35         self.quoteText = shareText.stripLineBreaks().stripHtml()
36         self.book = book
37
38         super.init(nibName: nil, bundle: Bundle.frameworkBundle())
39     }
40
41     required init?(coder aDecoder: NSCoder) {
42         fatalError("storyboards are incompatible with truth and beauty")
43     }
44
45     override func viewWillAppear(_ animated: Bool) {
46         super.viewWillAppear(animated)
47         setNeedsStatusBarAppearanceUpdate()
48     }
49
50     override func viewDidLoad() {
51         super.viewDidLoad()
52
53         self.setCloseButton(withConfiguration: self.readerConfig)
54         configureNavBar()
55
56         let titleAttrs = [NSAttributedStringKey.foregroundColor: self.readerConfig.tintColor]
57         let share = UIBarButtonItem(title: self.readerConfig.localizedShare, style: .plain, target: self, action: #selector(shareQuote(_:)))
58         share.setTitleTextAttributes(titleAttrs, for: UIControlState())
59         navigationItem.rightBarButtonItem = share
60
61         let isPad = (UIDevice.current.userInterfaceIdiom == .pad)
62         if (isPad == true) {
63             preferredContentSize = CGSize(width: 400, height: 600)
64         }
65         let screenBounds = (isPad == true ? preferredContentSize : UIScreen.main.bounds.size)
66
67         self.filterImage = UIView(frame: CGRect(x: 0, y: 0, width: screenBounds.width, height: screenBounds.width))
68         self.filterImage.backgroundColor = self.readerConfig.menuSeparatorColor
69         view.addSubview(self.filterImage)
70
71         imageView = UIImageView(frame: filterImage.bounds)
72         filterImage.addSubview(imageView)
73
74         quoteLabel = UILabel()
75         quoteLabel.text = quoteText
76         quoteLabel.textAlignment = .center
77         quoteLabel.font = UIFont(name: "Andada-Regular", size: 26)
78         quoteLabel.textColor = UIColor.white
79         quoteLabel.numberOfLines = 0
80         quoteLabel.baselineAdjustment = .alignCenters
81         quoteLabel.translatesAutoresizingMaskIntoConstraints = false
82         quoteLabel.adjustsFontSizeToFitWidth = true
83         quoteLabel.minimumScaleFactor = 0.3
84         quoteLabel.setContentCompressionResistancePriority(UILayoutPriority(100), for: .vertical)
85         filterImage.addSubview(quoteLabel)
86
87         var bookTitle = ""
88         var authorName = ""
89
90         if let title = self.book.title {
91             bookTitle = title
92         }
93
94         if let author = self.book.metadata.creators.first {
95             authorName = author.name
96         }
97
98         titleLabel = UILabel()
99         titleLabel.text = bookTitle
100         titleLabel.font = UIFont(name: "Lato-Bold", size: 15)
101         titleLabel.textAlignment = .center
102         titleLabel.textColor = UIColor.white
103         titleLabel.numberOfLines = 1
104         titleLabel.translatesAutoresizingMaskIntoConstraints = false
105         titleLabel.adjustsFontSizeToFitWidth = true
106         titleLabel.minimumScaleFactor = 0.8
107         titleLabel.setContentCompressionResistancePriority(UILayoutPriority(600), for: .vertical)
108         filterImage.addSubview(titleLabel)
109
110         // Attributed author
111         let attrs = [NSAttributedStringKey.font: UIFont(name: "Lato-Italic", size: 15)!]
112         let attributedString = NSMutableAttributedString(string:"\(self.readerConfig.localizedShareBy) ", attributes: attrs)
113
114         let attrs1 = [NSAttributedStringKey.font: UIFont(name: "Lato-Regular", size: 15)!]
115         let boldString = NSMutableAttributedString(string: authorName, attributes:attrs1)
116         attributedString.append(boldString)
117
118         authorLabel = UILabel()
119         authorLabel.attributedText = attributedString
120         authorLabel.textAlignment = .center
121         authorLabel.textColor = UIColor.white
122         authorLabel.numberOfLines = 1
123         authorLabel.translatesAutoresizingMaskIntoConstraints = false
124         authorLabel.adjustsFontSizeToFitWidth = true
125         authorLabel.minimumScaleFactor = 0.5
126         filterImage.addSubview(authorLabel)
127
128         let logoImage = self.readerConfig.quoteCustomLogoImage
129         let logoHeight = logoImage?.size.height ?? 0
130         logoImageView = UIImageView(image: logoImage)
131         logoImageView.contentMode = .center
132         logoImageView.translatesAutoresizingMaskIntoConstraints = false
133         filterImage.addSubview(logoImageView)
134
135         // Configure layout contraints
136         var constraints = [NSLayoutConstraint]()
137         let views = [
138             "quoteLabel": self.quoteLabel,
139             "titleLabel": self.titleLabel,
140             "authorLabel": self.authorLabel,
141             "logoImageView": self.logoImageView
142             ] as [String : Any]
143
144         NSLayoutConstraint.constraints(withVisualFormat: "V:|-40-[quoteLabel]-20-[titleLabel]", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
145         NSLayoutConstraint.constraints(withVisualFormat: "V:[titleLabel]-0-[authorLabel]", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
146         NSLayoutConstraint.constraints(withVisualFormat: "V:[authorLabel]-25-[logoImageView(\(Int(logoHeight)))]-18-|", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
147
148         NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[quoteLabel]-15-|", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
149         NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[titleLabel]-15-|", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
150         NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[authorLabel]-15-|", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
151         NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[logoImageView]-15-|", options: [], metrics: nil, views: views).forEach { constraints.append($0) }
152
153         filterImage.addConstraints(constraints)
154
155         // Layout
156         collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
157         collectionViewLayout.minimumLineSpacing = 15
158         collectionViewLayout.minimumInteritemSpacing = 0
159         collectionViewLayout.scrollDirection = .horizontal
160
161         let background = self.folioReader.isNight(self.readerConfig.nightModeBackground, UIColor.white)
162         view.backgroundColor = background
163
164         // CollectionView
165         let collectionFrame = CGRect(x: 0, y: filterImage.frame.height+15, width: screenBounds.width, height: itemSize)
166         collectionView = UICollectionView(frame: collectionFrame, collectionViewLayout: collectionViewLayout)
167         collectionView.delegate = self
168         collectionView.dataSource = self
169         collectionView.showsHorizontalScrollIndicator = false
170         collectionView.backgroundColor = background
171         collectionView.decelerationRate = UIScrollViewDecelerationRateFast
172         view.addSubview(collectionView)
173
174         if (UIDevice.current.userInterfaceIdiom == .phone) {
175             collectionView.autoresizingMask = [.flexibleWidth]
176         }
177
178         // Register cell classes
179         collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kReuseCellIdentifier)
180
181         // Create images
182         dataSource = self.readerConfig.quoteCustomBackgrounds
183         if (self.readerConfig.quotePreserveDefaultBackgrounds == true) {
184             createDefaultImages()
185         }
186
187         // Picker delegate
188 //        imagePicker.delegate = self
189
190         // Select first item
191         selectIndex(0)
192     }
193
194     func configureNavBar() {
195         let navBackground = self.folioReader.isNight(self.readerConfig.nightModeMenuBackground, UIColor.white)
196         let tintColor = self.readerConfig.tintColor
197         let navText = self.folioReader.isNight(UIColor.white, UIColor.black)
198         let font = UIFont(name: "Avenir-Light", size: 17)!
199         setTranslucentNavigation(false, color: navBackground, tintColor: tintColor, titleColor: navText, andFont: font)
200     }
201
202     func createDefaultImages() {
203         let color1 = QuoteImage(withColor: UIColor(rgba: "#FA7B67"))
204         let color2 = QuoteImage(withColor: UIColor(rgba: "#78CAB6"))
205         let color3 = QuoteImage(withColor: UIColor(rgba: "#71B630"))
206         let color4 = QuoteImage(withColor: UIColor(rgba: "#4D5B49"))
207         let color5 = QuoteImage(withColor: UIColor(rgba: "#959D92"), textColor: UIColor(rgba: "#4D5B49"))
208
209         var gradient = CAGradientLayer()
210         gradient.colors = [UIColor(rgba: "#2989C9").cgColor, UIColor(rgba: "#21B8C2").cgColor]
211         gradient.startPoint = CGPoint(x: 0, y: 1)
212         gradient.endPoint = CGPoint(x: 1, y: 0)
213         let gradient1 = QuoteImage(withGradient: gradient)
214
215         gradient = CAGradientLayer()
216         gradient.colors = [UIColor(rgba: "#FAD961").cgColor, UIColor(rgba: "#F76B1C").cgColor]
217         let gradient2 = QuoteImage(withGradient: gradient)
218
219         gradient = CAGradientLayer()
220         gradient.colors = [UIColor(rgba: "#B4EC51").cgColor, UIColor(rgba: "#429321").cgColor]
221         let gradient3 = QuoteImage(withGradient: gradient)
222
223         dataSource.append(contentsOf: [color1, color2, color3, color4, color5, gradient1, gradient2, gradient3])
224     }
225
226     func selectIndex(_ index: Int) {
227         let quoteImage = dataSource[index]
228         let row = index+1
229
230         filterImage.backgroundColor = quoteImage.backgroundColor
231         imageView.alpha = quoteImage.alpha
232
233         UIView.transition(with: filterImage, duration: 0.4, options: .transitionCrossDissolve, animations: {
234             self.imageView.image = quoteImage.image
235             self.quoteLabel.textColor = quoteImage.textColor
236             self.titleLabel.textColor = quoteImage.textColor
237             self.authorLabel.textColor = quoteImage.textColor
238             self.logoImageView.image = self.logoImageView.image?.imageTintColor(quoteImage.textColor)
239         }, completion: nil)
240
241         //
242         let prevSelectedIndex = selectedIndex
243         selectedIndex = row
244
245         guard prevSelectedIndex != selectedIndex else { return }
246
247         collectionView.performBatchUpdates({
248             self.collectionView.reloadItems(at: [
249                 IndexPath(item: self.selectedIndex, section: 0),
250                 IndexPath(item: prevSelectedIndex, section: 0)
251                 ])
252         }, completion: nil)
253     }
254
255     // MARK: Share
256
257     @objc func shareQuote(_ sender: UIBarButtonItem) {
258         var subject = self.readerConfig.localizedShareHighlightSubject
259         var text = ""
260         var bookTitle = ""
261         var authorName = ""
262         var shareItems = [AnyObject]()
263
264         // Get book title
265         if let title = self.book.title {
266             bookTitle = title
267             subject += " “\(title)”"
268         }
269
270         // Get author name
271         if let author = self.book.metadata.creators.first {
272             authorName = author.name
273         }
274
275         text = "\(bookTitle) \n\(self.readerConfig.localizedShareBy) \(authorName)"
276
277         let imageQuote = UIImage.imageWithView(filterImage)
278         shareItems.append(imageQuote)
279
280         if let bookShareLink = self.readerConfig.localizedShareWebLink {
281             text += "\n\(bookShareLink.absoluteString)"
282         }
283
284         let act = FolioReaderSharingProvider(subject: subject, text: text)
285         shareItems.insert(act, at: 0)
286
287         let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
288         activityViewController.excludedActivityTypes = [UIActivityType.print, UIActivityType.postToVimeo]
289
290         // Pop style on iPad
291         if let actv = activityViewController.popoverPresentationController {
292             actv.barButtonItem = sender
293         }
294
295         present(activityViewController, animated: true, completion: nil)
296     }
297
298     // MARK: Status Bar
299
300     override var preferredStatusBarStyle : UIStatusBarStyle {
301         return self.folioReader.isNight(.lightContent, .default)
302     }
303
304     override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
305         return .portrait
306     }
307
308     override var shouldAutorotate : Bool {
309         return false
310     }
311 }
312
313 // MARK: UICollectionViewDataSource
314
315 extension FolioReaderQuoteShare: UICollectionViewDataSource {
316     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
317         return dataSource.count + 1
318     }
319
320     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
321         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kReuseCellIdentifier, for: indexPath)
322         let imageView: UIImageView!
323         let tag = 9999
324
325         cell.backgroundColor = UIColor.clear
326         cell.contentView.backgroundColor = UIColor.clear
327         cell.contentView.layer.borderWidth = 1
328
329         if let view = cell.contentView.viewWithTag(tag) as? UIImageView {
330             imageView = view
331         } else {
332             imageView = UIImageView(frame: cell.bounds)
333             imageView.tag = tag
334             cell.contentView.addSubview(imageView)
335         }
336
337         // Camera
338         guard ((indexPath as NSIndexPath).row > 0) else {
339
340             // Image color
341             let normalColor = UIColor(white: 0.5, alpha: 0.7)
342             let camera = UIImage(readerImageNamed: "icon-camera")
343             let dash = UIImage(readerImageNamed: "border-dashed-pattern")
344             let cameraNormal = camera?.imageTintColor(normalColor)
345
346             imageView.contentMode = .center
347             imageView.image = cameraNormal
348             if let dashNormal = dash?.imageTintColor(normalColor) {
349                 cell.contentView.layer.borderColor = UIColor(patternImage: dashNormal).cgColor
350             }
351             return cell
352         }
353
354         if (selectedIndex == (indexPath as NSIndexPath).row) {
355             cell.contentView.layer.borderColor = self.readerConfig.tintColor.cgColor
356             cell.contentView.layer.borderWidth = 3
357         } else {
358             cell.contentView.layer.borderColor = UIColor(white: 0.5, alpha: 0.2).cgColor
359         }
360
361         let quoteImage = dataSource[(indexPath as NSIndexPath).row-1]
362         imageView.image = quoteImage.image
363         imageView.alpha = quoteImage.alpha
364         imageView.contentMode = .scaleAspectFit
365         cell.contentView.backgroundColor = quoteImage.backgroundColor
366         return cell
367     }
368
369     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
370         return CGSize(width: itemSize, height: itemSize)
371     }
372 }
373
374 // MARK: UICollectionViewDelegate
375
376 extension FolioReaderQuoteShare: UICollectionViewDelegate {
377     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
378
379         guard (indexPath as NSIndexPath).row > 0 else {
380             let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
381
382             let takePhoto = UIAlertAction(title: self.readerConfig.localizedTakePhoto, style: .default, handler: { (action) -> Void in
383 //                self.imagePicker.sourceType = .camera
384 //                self.imagePicker.allowsEditing = true
385 //                self.present(self.imagePicker, animated: true, completion: nil)
386             })
387
388             let existingPhoto = UIAlertAction(title: self.readerConfig.localizedChooseExisting, style: .default) { (action) -> Void in
389 //                self.imagePicker.sourceType = .photoLibrary
390 //                self.imagePicker.allowsEditing = true
391 //                self.present(self.imagePicker, animated: true, completion: nil)
392             }
393
394             let cancel = UIAlertAction(title: self.readerConfig.localizedCancel, style: .cancel, handler: nil)
395
396             alertController.addAction(takePhoto)
397             alertController.addAction(existingPhoto)
398             alertController.addAction(cancel)
399
400             present(alertController, animated: true, completion: nil)
401             return
402         }
403
404         selectIndex((indexPath as NSIndexPath).row-1)
405     }
406 }
407
408 // MARK: ImagePicker delegate
409
410 //extension FolioReaderQuoteShare: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
411 //    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
412 //        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
413 //
414 //            let quoteImage = QuoteImage(withImage: image, alpha: 0.6, backgroundColor: UIColor.black)
415 //
416 //            collectionView.performBatchUpdates({
417 //                self.dataSource.insert(quoteImage, at: 0)
418 //                self.collectionView.insertItems(at: [IndexPath(item: 1, section: 0)])
419 //                self.collectionView.reloadItems(at: [IndexPath(item: self.selectedIndex, section: 0)])
420 //            }, completion: { (finished) in
421 //                self.selectIndex(0)
422 //            })
423 //        }
424 //
425 //        self.dismiss(animated: true, completion: nil)
426 //    }
427 //}