Welcome to mirror list, hosted at ThFree Co, Russian Federation.

NCScan.swift « ScanDocument « iOSClient - github.com/nextcloud/ios.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0a1e4c863744c60239677df5dab43e36500be002 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//
//  NCScan.swift
//  Nextcloud
//
//  Created by Marino Faggiana on 21/08/18.
//  Copyright (c) 2018 Marino Faggiana. All rights reserved.
//
//  Author Marino Faggiana <marino.faggiana@nextcloud.com>
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

import UIKit
import Photos
import EasyTipView

class NCScan: UIViewController, NCScanCellCellDelegate {

    @IBOutlet weak var collectionViewSource: UICollectionView!
    @IBOutlet weak var collectionViewDestination: UICollectionView!
    @IBOutlet weak var cancel: UIBarButtonItem!
    @IBOutlet weak var save: UIBarButtonItem!
    @IBOutlet weak var add: UIButton!
    @IBOutlet weak var transferDown: UIButton!
    @IBOutlet weak var labelTitlePDFzone: UILabel!
    @IBOutlet weak var segmentControlFilter: UISegmentedControl!

    // Data Source for collectionViewSource
    internal var itemsSource: [String] = []

    // Data Source for collectionViewDestination
    internal var imagesDestination: [UIImage] = []
    internal var itemsDestination: [String] = []

    internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!

    private var tipView: EasyTipView?

    enum TypeFilter {
        case original
        case grayScale
        case bn
    }
    internal var filter: TypeFilter = TypeFilter.original

    // MARK: - View Life Cycle

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .secondarySystemGroupedBackground
        navigationItem.title = NSLocalizedString("_scanned_images_", comment: "")

        collectionViewSource.dragInteractionEnabled = true
        collectionViewSource.dragDelegate = self
        collectionViewSource.dropDelegate = self
        collectionViewSource.backgroundColor = .secondarySystemGroupedBackground

        collectionViewDestination.dragInteractionEnabled = true
        collectionViewDestination.dropDelegate = self
        collectionViewDestination.dragDelegate = self
        collectionViewDestination.reorderingCadence = .fast // default value - .immediate
        collectionViewDestination.backgroundColor = .secondarySystemGroupedBackground

        cancel.title = NSLocalizedString("_cancel_", comment: "")
        save.title = NSLocalizedString("_save_", comment: "")

        labelTitlePDFzone.text = NSLocalizedString("_scan_label_document_zone_", comment: "")
        labelTitlePDFzone.backgroundColor = .systemGray6
        labelTitlePDFzone.textColor = .label

        segmentControlFilter.setTitle(NSLocalizedString("_filter_original_", comment: ""), forSegmentAt: 0)
        segmentControlFilter.setTitle(NSLocalizedString("_filter_grayscale_", comment: ""), forSegmentAt: 1)
        segmentControlFilter.setTitle(NSLocalizedString("_filter_bn_", comment: ""), forSegmentAt: 2)

        add.setImage(UIImage(named: "plus")?.image(color: .label, size: 25), for: .normal)
        transferDown.setImage(UIImage(named: "transferDown")?.image(color: .label, size: 25), for: .normal)

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
        collectionViewSource.addGestureRecognizer(longPressRecognizer)
        let longPressRecognizerPlus = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(recognizer:)))
        add.addGestureRecognizer(longPressRecognizerPlus)

        // TIP
        var preferences = EasyTipView.Preferences()
        preferences.drawing.foregroundColor = .white
        preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
        preferences.drawing.textAlignment = .left
        preferences.drawing.arrowPosition = .left
        preferences.drawing.cornerRadius = 10

        preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
        preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
        preferences.animating.showInitialAlpha = 0
        preferences.animating.showDuration = 1.5
        preferences.animating.dismissDuration = 1.5

        tipView = EasyTipView(text: NSLocalizedString("_tip_addcopyimage_", comment: ""), preferences: preferences, delegate: self)

        collectionViewSource.reloadData()
        collectionViewDestination.reloadData()

        loadImage()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        showTip()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        self.tipView?.dismiss()
        coordinator.animate(alongsideTransition: nil) { _ in
            self.showTip()
        }
    }

    // MARK: - Tip

    func showTip() {

        if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCScanAddImage) {
            self.tipView?.show(forView: add, withinSuperview: self.view)
        }
    }

    // MARK: -

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)

        add.setImage(UIImage(named: "plus")?.image(color: .label, size: 25), for: .normal)
        transferDown.setImage(UIImage(named: "transferDown")?.image(color: .label, size: 25), for: .normal)
    }

    override var canBecomeFirstResponder: Bool { return true }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(pasteImage) {
            return true
        }
        return false
    }

    @IBAction func cancelAction(sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func saveAction(sender: UIBarButtonItem) {

        if !imagesDestination.isEmpty {

            var images: [UIImage] = []
            let serverUrl = appDelegate.activeServerUrl

            for image in imagesDestination {
                images.append(filter(image: image)!)
            }

            let formViewController = NCCreateFormUploadScanDocument(serverUrl: serverUrl, arrayImages: images)
            self.navigationController?.pushViewController(formViewController, animated: true)
        }
    }

    @IBAction func add(sender: UIButton) {

        // TIP
        dismissTip()

        NCCreateScanDocument.shared.openScannerDocument(viewController: self)
    }

    @IBAction func transferDown(sender: UIButton) {

        for fileName in itemsSource {

            if !itemsDestination.contains(fileName) {

                let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName

                guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)), let image = UIImage(data: data) else { return }

                imagesDestination.append(image)
                itemsDestination.append(fileName)
            }
        }

        // Save button
        if imagesDestination.isEmpty {
            save.isEnabled = false
        } else {
            save.isEnabled = true
        }

        collectionViewDestination.reloadData()
    }

    @IBAction func indexChanged(_ sender: AnyObject) {

        switch segmentControlFilter.selectedSegmentIndex {
        case 0:
            filter = .original
        case 1:
            filter = .grayScale
        case 2:
            filter = .bn
        default:
            break
        }

        collectionViewDestination.reloadData()
    }

    func loadImage() {

        itemsSource.removeAll()

        do {
            let atPath = CCUtility.getDirectoryScan()!
            let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath)
            for fileName in directoryContents where fileName.first != "." {
                itemsSource.append(fileName)
            }
        } catch {
            print(error.localizedDescription)
        }

        itemsSource = itemsSource.sorted()

        collectionViewSource.reloadData()

        // Save button
        if imagesDestination.isEmpty {
            save.isEnabled = false
        } else {
            save.isEnabled = true
        }
    }

    func filter(image: UIImage) -> UIImage? {

        var inputContrast: Double = 0

        if filter == .original {
            return image
        }

        if filter == .grayScale {
            inputContrast = 1
        }

        if filter == .bn {
            inputContrast = 4
        }

        let ciImage = CIImage(image: image)!
        let imageFilter = ciImage.applyingFilter("CIColorControls", parameters: ["inputSaturation": 0, "inputContrast": inputContrast])

        let context: CIContext = CIContext(options: nil)
        let cgImage: CGImage = context.createCGImage(imageFilter, from: imageFilter.extent)!
        let image: UIImage = UIImage(cgImage: cgImage)
        return image
    }

    // destinationIndexPath: indexpath of the collection view where the user drops the element
    // collectionView: collectionView in which reordering needs to be done.

    func reorderItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {

        let items = coordinator.items

        if items.count == 1, let item = items.first, let sourceIndexPath = item.sourceIndexPath {

            var dIndexPath = destinationIndexPath

            if dIndexPath.row >= collectionView.numberOfItems(inSection: 0) {
                dIndexPath.row = collectionView.numberOfItems(inSection: 0) - 1
            }

            collectionView.performBatchUpdates({

                if collectionView === collectionViewDestination {

                    imagesDestination.remove(at: sourceIndexPath.row)
                    imagesDestination.insert((item.dragItem.localObject as? UIImage)!, at: dIndexPath.row)

                    let fileName = itemsDestination[sourceIndexPath.row]
                    itemsDestination.remove(at: sourceIndexPath.row)
                    itemsDestination.insert(fileName, at: dIndexPath.row)

                } else {

                    itemsSource.remove(at: sourceIndexPath.row)
                    itemsSource.insert((item.dragItem.localObject as? String)!, at: dIndexPath.row)
                }

                collectionView.deleteItems(at: [sourceIndexPath])
                collectionView.insertItems(at: [dIndexPath])
            })

            coordinator.drop(items.first!.dragItem, toItemAt: dIndexPath)
        }
    }

    func copyItems(coordinator: UICollectionViewDropCoordinator, destinationIndexPath: IndexPath, collectionView: UICollectionView) {
        collectionView.performBatchUpdates({

            var indexPaths: [IndexPath] = []

            for (index, item) in coordinator.items.enumerated() {

                let indexPath = IndexPath(row: destinationIndexPath.row + index, section: destinationIndexPath.section)

                if collectionView === collectionViewDestination {

                    let fileName = (item.dragItem.localObject as? String)!
                    let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName

                    guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)), let image = UIImage(data: data) else { return }

                    imagesDestination.insert(image, at: indexPath.row)
                    itemsDestination.insert(fileName, at: indexPath.row)

                } else {

                    // NOT PERMITTED
                    return
                }

                indexPaths.append(indexPath)
            }

            collectionView.insertItems(at: indexPaths)
        })
    }

    @objc func handleLongPressGesture(recognizer: UIGestureRecognizer) {

        if recognizer.state == UIGestureRecognizer.State.began {

            self.becomeFirstResponder()

            let pasteboard = UIPasteboard.general

            if let recognizerView = recognizer.view, let recognizerSuperView = recognizerView.superview, pasteboard.hasImages {

                UIMenuController.shared.menuItems = [UIMenuItem(title: "Paste", action: #selector(pasteImage))]
                UIMenuController.shared.setTargetRect(recognizerView.frame, in: recognizerSuperView)
                UIMenuController.shared.setMenuVisible(true, animated: true)
            }

            // TIP
            dismissTip()
        }
    }

    @objc func pasteImage() {

        let pasteboard = UIPasteboard.general

        if pasteboard.hasImages {

            guard let image = pasteboard.image?.fixedOrientation() else { return }

            let fileName = CCUtility.createFileName("scan.png", fileDate: Date(),
                                                    fileType: PHAssetMediaType.image,
                                                    keyFileName: NCGlobal.shared.keyFileNameMask,
                                                    keyFileNameType: NCGlobal.shared.keyFileNameType,
                                                    keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
                                                    forcedNewFileName: true)!
            let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName

            do {
                try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
            } catch {
                return
            }

            loadImage()
        }
    }

    func delete(with imageIndex: Int, sender: Any) {

        imagesDestination.remove(at: imageIndex)
        itemsDestination.remove(at: imageIndex)

        // Save button
        if imagesDestination.isEmpty {
            save.isEnabled = false
        } else {
            save.isEnabled = true
        }

        collectionViewDestination.reloadData()
    }

    func rotate(with imageIndex: Int, sender: Any) {

        let indexPath = IndexPath(row: imageIndex, section: 0)
        if let cell = collectionViewDestination.cellForItem(at: indexPath) as? NCScanCell {

            var image = imagesDestination[imageIndex]
            image = image.rotate(radians: .pi / 2)!
            imagesDestination[imageIndex] = image
            cell.customImageView.image = image
        }
    }
}

extension NCScan: EasyTipViewDelegate {

    // TIP
    func easyTipViewDidTap(_ tipView: EasyTipView) {
        NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCScanAddImage)
    }

    func easyTipViewDidDismiss(_ tipView: EasyTipView) { }

    func dismissTip() {
        NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCScanAddImage)
        self.tipView?.dismiss()
    }
}