Browse Source

【UI替换】编辑工具 - 添加背景OC转Swift

lizhe 1 year ago
parent
commit
85be5ead2e

+ 1 - 1
PDF Office/PDF Master/Class/PDFTools/Background/Model/KMBackgroundModel.swift

@@ -28,7 +28,7 @@ import Cocoa
     
     var pagesString: String = ""
     
-    var backgroundID: String = ""
+    var backgroundID: String = KMBackgroundManager.defaultManager.fetchAvailableName()
     
     var image: NSImage!
     

+ 1 - 0
PDF Office/PDF Master/Class/PDFTools/Background/New/KMBackgroundWindowController.swift

@@ -15,6 +15,7 @@ class KMBackgroundWindowController: KMBaseWindowController {
         
         // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
         
+        addBackgroundView.pdfDocument = self.pdfDocument
         addBackgroundView.cancelAction = { [unowned self] view in
             cancelAction?(self)
         }

+ 755 - 5
PDF Office/PDF Master/Class/PDFTools/Background/New/View/KMAddBackgroundView.swift

@@ -7,22 +7,540 @@
 
 import Cocoa
 
+enum KMBackgroundManagerType: Int {
+    case add = 0
+    case edit
+    case use
+}
+
+typealias KMAddBackgroundViewOperateCallBack = (_ background: KMBackgroundModel, _ countType: Int) -> ()
 typealias KMAddBackgroundViewBatchAction = (_ view: KMAddBackgroundView, _ files: [KMFileAttribute]) -> Void
 typealias KMAddBackgroundViewCancelAction = (_ view: KMAddBackgroundView) -> Void
 
-
-class KMAddBackgroundView: KMBaseXibView {
+class KMAddBackgroundView: KMBaseXibView, NSComboBoxDelegate {
+    
+    @IBOutlet weak var pdfView: KMWatermarkPDFView!
+    @IBOutlet weak var previousButton: NSButton!
+    @IBOutlet weak var nextButton: NSButton!
+    @IBOutlet weak var currentPageIndexTextField: NSTextField!
+    @IBOutlet weak var totalPageCountlabel: NSTextField!
+    
+    @IBOutlet weak var typeBox: NSBox!
+    @IBOutlet weak var colorButton: NSButton!
+    @IBOutlet weak var colorWell: NSColorWell!
+    @IBOutlet weak var fileButton: NSButton!
+    
+    @IBOutlet weak var filePathLabel: NSTextField!
+    @IBOutlet weak var browseButton: NSButton!
+    @IBOutlet weak var ratioLabel: NSTextField!
+    @IBOutlet weak var ratioTextField: NSTextField!
+    @IBOutlet weak var ratioStepper: NSStepper!
+    
+    @IBOutlet weak var appearanceBox: NSBox!
+    @IBOutlet weak var angleLabel: NSTextField!
+    @IBOutlet weak var angleTextField: NSTextField!
+    @IBOutlet weak var angleStepper: NSStepper!
+    @IBOutlet weak var left45IndicateView: KMAngleIndicateView!
+    @IBOutlet weak var horizontalIndicateView: KMAngleIndicateView!
+    @IBOutlet weak var right45IndicateView: KMAngleIndicateView!
+    @IBOutlet weak var alphaLabel: NSTextField!
+    @IBOutlet weak var alphaSlider: NSSlider!
+    @IBOutlet weak var alphaTextField: NSTextField!
+    @IBOutlet weak var alphaStepper: NSStepper!
+    @IBOutlet weak var postionView: KMPostionIndicateView!
+    @IBOutlet weak var verticalGapLabel: NSTextField!
+    @IBOutlet weak var verticalGapTextField: NSTextField!
+    @IBOutlet weak var verticalStepper: NSStepper!
+    @IBOutlet weak var horizontalGapLabel: NSTextField!
+    @IBOutlet weak var horizontalGapTextField: NSTextField!
+    @IBOutlet weak var horizontalStepper: NSStepper!
+    @IBOutlet weak var pageRangeComboBox: NSComboBox!
+    @IBOutlet weak var pageRangeLabel: NSTextField!
+    
+    @IBOutlet weak var saveToTemplateButton: NSButton!
+    @IBOutlet weak var templateNameLabel: NSTextField!
+    @IBOutlet weak var templateNameTextField: NSTextField!
+    
     @IBOutlet weak var doneButton: NSButton!
     @IBOutlet weak var cancelButton: NSButton!
     @IBOutlet weak var batchButton: NSButton!
     
+    var background: KMBackgroundModel = KMBackgroundModel()
+    var originalBackground: KMBackgroundModel = KMBackgroundModel()
+    var filePath: String = Bundle.main.path(forResource: "Quick Start Guide", ofType: "pdf") ?? ""
+    var password: String = ""
+    var type: KMBackgroundManagerType = .add
+    var pdfDocument: CPDFDocument? {
+        didSet {
+            self.reloadData()
+        }
+    }
+    var backgroundType: KMBackgroundType!
+    
+    
+    var initialID: String!
+    var currentType: Int!
+    
     var cancelAction: KMAddBackgroundViewCancelAction?
     var batchAction: KMAddBackgroundViewCancelAction?
+    var operateCallBack: KMAddBackgroundViewOperateCallBack?
+
+    var onlyManagerTemplate: Bool = false
+
+    // MARK: - Dealloc
+
+    deinit {
+        NotificationCenter.default.removeObserver(self)
+    }
+
+    // MARK: - Init Methods
+
+    convenience init?(baseFile filePath: String, background backgroundObject: KMBackgroundModel, password: String, type: KMBackgroundManagerType, fileType countType: Int) {
+        self.init()
+        self.filePath = filePath
+        self.password = password
+        self.background = backgroundObject
+        self.originalBackground = backgroundObject
+        self.initialID = backgroundObject.backgroundID
+        self.type = type
+        self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.filePath))
+
+        if pdfDocument!.isLocked {
+            pdfDocument!.unlock(withPassword: password)
+        }
+
+        if pdfDocument!.isLocked {
+            return nil
+        }
+    }
+
+    override func setup() {
+        pdfView.background = background
+        pdfView.document = pdfDocument
+        pdfView.autoScales = true
+//        pdfView.documentView?.enclosingScrollView?.hasVerticalScroller = false
+//        pdfView.documentView?.enclosingScrollView?.hasHorizontalScroller = false
+
+        for i in 0..<3 {
+            for j in 0..<3 {
+                if i == Int(background.horizontalMode) && j == Int(background.verticalMode) {
+                    postionView.style = KMPositionIndicateViewStyle(rawValue: i + 3 * j)!
+                }
+            }
+        }
+
+        postionView.styleChangedCallBack = { [weak self] in
+            guard let self = self else { return }
+            self.background.horizontalMode = self.postionView.style.rawValue % 3
+            self.background.verticalMode = self.postionView.style.rawValue / 3
+            self.pdfView.needsDisplay = true
+            if self.filePathLabel.stringValue.count > 0 {
+                self.doneButton.isEnabled = true
+            }
+        }
+
+        currentPageIndexTextField.stringValue = "1"
+//        let numberFormatter = currentPageIndexTextField.formatter as! NumberFormatter
+//        numberFormatter.maximum = NSNumber(value: pdfDocument.pageCount)
+        
+
+        left45IndicateView.style = .left45
+        left45IndicateView.touchCallBack = { [weak self] in
+            guard let self = self else { return }
+            self.background.rotation = 45
+            self.angleStepper.doubleValue = 45
+            self.angleTextField.stringValue = "\(45)"
+            self.checkAngle()
+            if self.filePathLabel.stringValue.count > 0 {
+                self.doneButton.isEnabled = true
+            }
+            self.pdfView.needsDisplay = true
+        }
+
+        horizontalIndicateView.style = .horizontal
+        horizontalIndicateView.touchCallBack = { [weak self] in
+            guard let self = self else { return }
+            self.background.rotation = 0
+            self.angleStepper.doubleValue = 0
+            self.angleTextField.stringValue = "\(0)"
+            self.checkAngle()
+            if self.filePathLabel.stringValue.count > 0 {
+                self.doneButton.isEnabled = true
+            }
+            self.pdfView.needsDisplay = true
+        }
+
+        right45IndicateView.style = .right45
+        right45IndicateView.touchCallBack = { [weak self] in
+            guard let self = self else { return }
+            self.background.rotation = -45
+            self.angleStepper.doubleValue = -45
+            self.angleTextField.stringValue = "\(-45)"
+            self.checkAngle()
+            if self.filePathLabel.stringValue.count > 0 {
+                self.doneButton.isEnabled = true
+            }
+            self.pdfView.needsDisplay = true
+        }
+
+        checkAngle()
+
+        typeBox.titleFont = NSFont.systemFont(ofSize: 13)
+
+        colorWell.color = background.color ?? NSColor.red
+        templateNameTextField.stringValue = background.backgroundID
+
+        appearanceBox.titleFont = NSFont.systemFont(ofSize: 13)
+
+        if !onlyManagerTemplate {
+            saveToTemplateButton.isEnabled = false
+        }
+
+        if type == .use {
+            saveToTemplateButton.isHidden = true
+            saveToTemplateButton.state = .off
+        } else {
+            saveToTemplateButton.isHidden = false
+            saveToTemplateButton.state = .on
+        }
+
+        pageRangeComboBox.removeAllItems()
+        pageRangeComboBox.addItems(withObjectValues: [
+            NSLocalizedString("All Pages", comment: ""),
+            NSLocalizedString("Odd Pages Only", comment: ""),
+            NSLocalizedString("Even Pages Only", comment: ""),
+            NSLocalizedString("e.g. 1,3-5,10", comment: "")
+        ])
+        pageRangeComboBox.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
+        pageRangeComboBox.delegate = nil
+        pageRangeComboBox.selectItem(at: 0)
+        pageRangeComboBox.isEditable = false
+        pageRangeComboBox.delegate = self
+    }
+    
+    override func addNotification() {
+        NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification), name: NSNotification.Name("PDFViewPageChangedNotification"), object: self.pdfView)
+    }
+    override func updateLanguage() {
+        typeBox.title = NSLocalizedString("Source", comment: "")
+
+        colorButton.title = NSLocalizedString("Color", comment: "")
+        fileButton.title = NSLocalizedString("File", comment: "")
+        browseButton.title = NSLocalizedString("Choose...", comment: "")
+        ratioLabel.stringValue = "\(NSLocalizedString("Ratio", comment: "")):"
+
+        appearanceBox.title = NSLocalizedString("Appearance", comment: "")
+        angleLabel.stringValue = "\(NSLocalizedString("Rotation", comment: "")):"
+        alphaLabel.stringValue = "\(NSLocalizedString("Opacity", comment: "")):"
+        pageRangeLabel.stringValue = "\(NSLocalizedString("Page Range", comment: "")):"
+        horizontalGapLabel.stringValue = "X:"
+        verticalGapLabel.stringValue = "Y:"
+        
+        saveToTemplateButton.title = NSLocalizedString("Add to Template", comment: "")
+    }
+
+    private func checkAngle() {
+        left45IndicateView.isSelcted = false
+        horizontalIndicateView.isSelcted = false
+        right45IndicateView.isSelcted = false
+
+        if background.rotation == -45 {
+            right45IndicateView.isSelcted = true
+        } else if background.rotation == 0 {
+            horizontalIndicateView.isSelcted = true
+        } else if background.rotation == 45 {
+            left45IndicateView.isSelcted = true
+        }
+    }
+
+    override func reloadData() {
+        guard let pdfDocument = pdfDocument else { return }
+        
+        totalPageCountlabel.stringValue = "/ \(pdfDocument.pageCount)"
+        
+        filePathLabel.stringValue = background.imagePath
+        filePathLabel.placeholderString = NSLocalizedString("Select a File", comment: "")
+        angleStepper.doubleValue = Double(-background.rotation)
+        angleTextField.stringValue = "\(angleStepper.doubleValue)"
+        alphaSlider.doubleValue = background.opacity
+        alphaStepper.doubleValue = background.opacity
+        let opacity = round(background.opacity * 100) / 100
+        alphaTextField.stringValue = "\(Int(opacity * 100))%"
+        ratioStepper.doubleValue = background.scale
+        ratioTextField.stringValue = "\(Int(background.scale * 100))%"
+        if currentType == 0 {
+            changeTypeBoxState(true)
+        } else {
+            changeTypeBoxState(false)
+        }
+        pageRangeComboBox.delegate = nil
+        switch background.pageRangeType {
+        case .all:
+            pageRangeComboBox.isEditable = false
+            pageRangeComboBox.selectItem(at: 0)
+        case .odd:
+            pageRangeComboBox.isEditable = false
+            pageRangeComboBox.selectItem(at: 1)
+        case .even:
+            pageRangeComboBox.isEditable = false
+            pageRangeComboBox.selectItem(at: 2)
+        case .other:
+            pageRangeComboBox.isEditable = true
+            pageRangeComboBox.selectItem(at: 3)
+            pageRangeComboBox.stringValue = background.pagesString 
+            window?.makeFirstResponder(pageRangeComboBox)
+        }
+        pageRangeComboBox.delegate = self
+        verticalStepper.doubleValue = background.verticalSpace
+        verticalGapTextField.stringValue = "\(verticalStepper.doubleValue)"
+        horizontalStepper.doubleValue = background.horizontalSpace
+        horizontalGapTextField.stringValue = "\(horizontalStepper.doubleValue)"
+    }
+
+    private func changeTypeBoxState(_ isColor: Bool) {
+        if isColor {
+            currentType = 0
+            colorButton.state = .on
+            colorWell.isEnabled = true
+            fileButton.state = .off
+            browseButton.isEnabled = false
+            ratioTextField.isEnabled = false
+            ratioStepper.isEnabled = false
+            background.color = colorWell.color
+            background.type = .color
+            background.scale = 1
+            doneButton.isEnabled = true
+        } else {
+            currentType = 1
+            colorButton.state = .off
+            colorWell.isEnabled = false
+            fileButton.state = .on
+            browseButton.isEnabled = true
+            ratioTextField.isEnabled = true
+            ratioStepper.isEnabled = true
+            background.color = nil
+            background.type = .file
+            background.scale = ratioStepper.doubleValue
+            doneButton.isEnabled = filePathLabel.stringValue.count > 0
+        }
+        pdfView.needsDisplay = true
+    }
+
+    // Other methods...
     
-    override func draw(_ dirtyRect: NSRect) {
-        super.draw(dirtyRect)
+    @objc func controlTextDidEndEditing(_ notification: Notification) {
+        guard let textField = notification.object as? NSTextField else { return }
+
+        switch textField {
+        case ratioTextField:
+            let formatter = textField.formatter as? NumberFormatter
+            if let floatValue = formatter?.number(from: textField.stringValue)?.floatValue {
+                ratioStepper.doubleValue = Double(floatValue)
+                background.scale = Double(floatValue)
+                pdfView.needsDisplay = true
+            }
+        case angleTextField:
+            if let integerValue = Int(textField.stringValue) {
+                background.rotation = -integerValue
+                angleStepper.doubleValue = Double(-background.rotation)
+                checkAngle()
+                pdfView.needsDisplay = true
+            }
+        case alphaTextField:
+            let formatter = textField.formatter as? NumberFormatter
+            if let floatValue = formatter?.number(from: textField.stringValue)?.floatValue {
+                alphaSlider.doubleValue = Double(floatValue)
+                alphaStepper.doubleValue = Double(floatValue)
+                background.opacity = Double(floatValue)
+                pdfView.needsDisplay = true
+            }
+        case pageRangeComboBox:
+            if pageRangeComboBox.indexOfSelectedItem == -1 {
+                if !checkPageRangeValidate(pageRangeComboBox.stringValue) {
+                    let alert = NSAlert()
+                    alert.alertStyle = .critical
+                    alert.messageText = "\(pdfDocument!.documentURL.lastPathComponent) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
+                    alert.runModal()
+                    window?.makeFirstResponder(pageRangeComboBox)
+                    return
+                } else {
+                    background.pagesString = pageRangeComboBox.stringValue
+                    pdfView.needsDisplay = true
+                }
+            }
+        case verticalGapTextField:
+            if let integerValue = Int(verticalGapTextField.stringValue) {
+                background.verticalSpace = CGFloat(integerValue)
+                verticalStepper.doubleValue = background.verticalSpace
+                pdfView.needsDisplay = true
+            }
+        case horizontalGapTextField:
+            if let integerValue = Int(horizontalGapTextField.stringValue) {
+                background.horizontalSpace = CGFloat(integerValue)
+                horizontalStepper.doubleValue = background.horizontalSpace
+                pdfView.needsDisplay = true
+            }
+        case currentPageIndexTextField:
+            if let pageIndex = Int(currentPageIndexTextField.stringValue), let page = pdfDocument!.page(at: UInt(pageIndex - 1)) {
+                pdfView.go(to: page)
+            }
+        default:
+            break
+        }
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
 
-        // Drawing code here.
+    @objc func comboBoxSelectionDidChange(_ notification: Notification) {
+        guard notification.object as? NSComboBox == pageRangeComboBox else { return }
+
+        pageRangeComboBox.isEditable = false
+        switch pageRangeComboBox.indexOfSelectedItem {
+        case 0:
+            background.pageRangeType = .all
+        case 1:
+            background.pageRangeType = .odd
+        case 2:
+            background.pageRangeType = .even
+        default:
+            background.pageRangeType = .other
+            pageRangeComboBox.stringValue = ""
+            pageRangeComboBox.isEditable = true
+            window?.makeFirstResponder(pageRangeComboBox)
+        }
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
+
+    func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
+        let fileAttribute = KMFileAttribute()
+        fileAttribute.filePath = pdfDocument!.documentURL.path
+        fileAttribute.bAllPage = false
+        fileAttribute.pagesString = pageRangeComboBox.stringValue
+
+        return fileAttribute.fetchSelectPages().count != 0
+    }
+
+    func saveAsPDF(with background: KMBackgroundModel, to path: String, autoOpen: Bool) {
+        DispatchQueue.global(qos: .default).async { [unowned self] in
+            var filePath = self.pdfDocument!.documentURL?.path
+            let password = self.password
+            if filePath == nil {
+                let writeSuccess = self.pdfDocument!.write(to: URL(fileURLWithPath: kNewDocumentTempSavePath(NSLocalizedString("Untitled", comment: ""))))
+                if writeSuccess {
+                    self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: kNewDocumentTempSavePath(NSLocalizedString("Untitled", comment: ""))))!
+                    filePath = self.pdfDocument!.documentURL?.path
+                }
+            }
+
+            let document = CPDFDocument(url: URL(fileURLWithPath: filePath!))!
+            document.unlock(withPassword: password)
+            
+
+            let tBackground: CPDFBackground = document.background()
+            tBackground.opacity = background.opacity
+            tBackground.scale = background.scale
+            tBackground.rotation = CGFloat(-background.rotation)
+            tBackground.horizontalAlignment = UInt(background.horizontalMode)
+            tBackground.verticalAlignment = UInt(background.verticalMode)
+            tBackground.xOffset = background.horizontalSpace
+            tBackground.yOffset = background.verticalSpace
+
+            if let color = background.color {
+                tBackground.color = color
+                tBackground.type = .color
+            } else if background.imagePath.count != 0 {
+                let image = NSImage(contentsOfFile: background.imagePath)!
+                tBackground.setImage(image)
+                tBackground.type = .image
+            }
+
+            if background.pagesString.count != 0 {
+                tBackground.pageString = background.pagesString
+            } else {
+                let pageString = "0-\(document.pageCount - 1)"
+                tBackground.pageString = pageString
+            }
+
+            tBackground.update()
+
+            // Save to temporary path
+            let documentPath = NSTemporaryDirectory()
+            let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
+            try? FileManager.default.removeItem(atPath: tempPath)
+
+            let result = document.write(to: URL(fileURLWithPath: tempPath))
+            if result {
+                if FileManager.default.fileExists(atPath: path) {
+                    try? FileManager.default.removeItem(atPath: path)
+                }
+                try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
+            } else {
+                try? FileManager.default.removeItem(atPath: tempPath)
+            }
+
+            if result {
+                DispatchQueue.main.async {
+                    let needSave = self.saveToTemplateButton.state == .on
+                    if needSave {
+                        if self.checkPageRangeValidate(self.pageRangeComboBox.stringValue) && self.pageRangeComboBox.indexOfSelectedItem == -1 {
+                            self.background.pagesString = self.pageRangeComboBox.stringValue
+                        }
+                        KMBackgroundManager.defaultManager.addTemplate(model: self.background)
+                        NotificationCenter.default.post(name: NSNotification.Name("KMBatchOperateWatermarksNotification"), object: self)
+                    }
+                    self.cancelAction?(self)
+                    if autoOpen {
+                        NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { _, _, _ in }
+                    } else {
+                        NSWorkspace.shared.selectFile(path, inFileViewerRootedAtPath: "")
+                    }
+                }
+            }
+        }
+    }
+    
+    func kNewDocumentTempSavePath(_ fileName: String) -> String {
+        let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
+        let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
+        let append2 = append1!.stringByAppendingPathComponent(String(format: "%@", fileName))
+        return append2
+    }
+
+    func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
+        let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("addImageAnnotation")
+        if !FileManager.default.fileExists(atPath: addImageAnnotation) {
+            try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
+        }
+
+        let data = image.tiffRepresentation!
+        let imageRep = NSBitmapImageRep(data: data)!
+        imageRep.size = image.size
+        var imageData: Data?
+
+        if path.lowercased() == "png" {
+            imageData = imageRep.representation(using: .png, properties: [:])
+        } else {
+            imageData = imageRep.representation(using: .jpeg, properties: [:])
+        }
+
+        let rPath = (addImageAnnotation as NSString).appendingPathComponent(tagString() + ".png")
+        return ((try? imageData?.write(to: URL(fileURLWithPath: rPath), options: .atomic)) == nil)
+    }
+
+    func tagString() -> String {
+        let dateFormatter = DateFormatter()
+        dateFormatter.dateFormat = "yyMMddHHmmss"
+        return String(format: "%@%04d", dateFormatter.string(from: Date()), arc4random() % 10000)
+    }
+
+    // ... (remaining methods)
+    @objc func pageChangeNotification(notification: NSNotification) {
+        self.currentPageIndexTextField.stringValue = self.pdfView.currentPage().label;
     }
 }
 
@@ -41,4 +559,236 @@ extension KMAddBackgroundView {
         callBack(self)
     }
     
+    @IBAction func buttonClicked_SwitchBackgroundType(_ sender: Any) {
+        changeTypeBoxState(sender as? NSObject == colorButton)
+    }
+
+    @IBAction func colorWellChanged(_ sender: NSColorWell) {
+        background.color = sender.color
+        pdfView.needsDisplay = true
+    }
+
+    @IBAction func radioStepperAction(_ sender: NSStepper) {
+        ratioTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
+        background.scale = sender.doubleValue
+        pdfView.needsDisplay = true
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
+
+    @IBAction func angleStepperAction(_ sender: NSStepper) {
+        angleTextField.stringValue = "\(sender.doubleValue)"
+        background.rotation = Int(sender.doubleValue)
+        checkAngle()
+        pdfView.needsDisplay = true
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
+
+    @IBAction func alphaSliderAction(_ sender: NSSlider) {
+        background.opacity = sender.doubleValue
+        alphaStepper.doubleValue = sender.doubleValue
+        alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+        pdfView.needsDisplay = true
+    }
+
+    @IBAction func verticalStepperAction(_ sender: NSStepper) {
+        verticalGapTextField.stringValue = "\(sender.doubleValue)"
+        background.verticalSpace = sender.doubleValue
+        pdfView.needsDisplay = true
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
+
+    @IBAction func horizentalStepperAction(_ sender: NSStepper) {
+        horizontalGapTextField.stringValue = "\(sender.doubleValue)"
+        background.horizontalSpace = sender.doubleValue
+        pdfView.needsDisplay = true
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
+
+    @IBAction func alphaSteperAction(_ sender: NSStepper) {
+        alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
+        background.opacity = sender.doubleValue
+        alphaStepper.doubleValue = sender.doubleValue
+        pdfView.needsDisplay = true
+
+        if filePathLabel.stringValue.count > 0 {
+            doneButton.isEnabled = true
+        }
+    }
+
+    @IBAction func goPrevious(_ sender: Any) {
+        if pdfView.canGoToPreviousPage() {
+            pdfView.goToPreviousPage(nil)
+        }
+        let index = pdfDocument!.index(for: pdfView.currentPage())
+        currentPageIndexTextField.stringValue = "\(index + 1)"
+    }
+
+    @IBAction func goNext(_ sender: Any) {
+        if pdfView.canGoToNextPage() {
+            pdfView.goToNextPage(nil)
+        }
+
+        let index = pdfDocument!.index(for: pdfView.currentPage())
+        currentPageIndexTextField.stringValue = "\(index + 1)"
+    }
+
+    @IBAction func buttonClicked_BrowserFile(_ sender: Any) {
+        let openPanel = NSOpenPanel()
+        openPanel.canChooseDirectories = false
+        openPanel.canChooseFiles = true
+        openPanel.allowsMultipleSelection = false
+        openPanel.allowedFileTypes = ["jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "pdf"]
+
+        openPanel.beginSheetModal(for: window!) { (result) in
+            if result == .OK {
+                guard let url = openPanel.url else { return }
+                let filePath: NSString = url.path as NSString
+
+                if filePath.pathExtension.lowercased() == "pdf" {
+                    let pdf = CPDFDocument(url: url)
+                    if pdf?.isEncrypted == true {
+                        return
+                    }
+                }
+
+                if let image = NSImage(contentsOfFile: url.path), !self.isDamageImage(image, imagePath: url.path) {
+                    self.filePathLabel.stringValue = url.path
+                    self.doneButton.isEnabled = true
+                    self.background.imagePath = url.path
+                    self.background.backgroundID = url.path.lastPathComponent.deletingPathExtension
+                    self.templateNameTextField.stringValue = url.path.lastPathComponent.deletingPathExtension
+                    self.pdfView.needsDisplay = true
+                }
+            }
+        }
+    }
+
+    // ... (remaining IBActions)
+
+    @IBAction func buttonClicked_Batch(_ sender: Any) {
+        if background.type == .color {
+            background.imagePath = ""
+        } else {
+            background.color = nil
+            if background.image == nil {
+                return
+            }
+        }
+
+        if templateNameTextField.stringValue.count < 1 {
+            background.backgroundID = initialID
+        } else {
+            background.backgroundID = templateNameTextField.stringValue
+        }
+
+        let needSave = saveToTemplateButton.state == .on
+        if needSave {
+            KMBackgroundManager.defaultManager.addTemplate(model: background)
+        }
+
+        operateCallBack?(background, currentType)
+    }
+
+    @IBAction func buttonClicked_Done(_ sender: Any) {
+        guard let pdfDocument = pdfDocument else { return }
+        if background.type == .color {
+            background.imagePath = ""
+        } else {
+            background.color = nil
+            if background.image == nil {
+                return
+            }
+        }
+
+        if templateNameTextField.stringValue.isEmpty {
+            background.backgroundID = initialID
+        } else {
+            background.backgroundID = templateNameTextField.stringValue
+        }
+
+        // Avoid showing the page range alert twice
+        if checkPageRangeValidate(pageRangeComboBox.stringValue) {
+            background.pagesString = pageRangeComboBox.stringValue
+            pdfView.needsDisplay = true
+            window?.makeFirstResponder(self)
+        }
+
+        let needSave = saveToTemplateButton.state == .on
+        var pages = [Int]()
+
+        switch pageRangeComboBox.indexOfSelectedItem {
+        case 0:
+            pages = Array(0..<Int(pdfDocument.pageCount))
+        case 1:
+            pages = Array(stride(from: 0, to: Int(pdfDocument.pageCount), by: 2))
+        case 2:
+            pages = Array(stride(from: 1, to: Int(pdfDocument.pageCount), by: 2))
+        default:
+            let fileAttribute = KMFileAttribute()
+            fileAttribute.filePath = pdfDocument.documentURL?.path ?? ""
+            fileAttribute.bAllPage = false
+            fileAttribute.pagesString = pageRangeComboBox.stringValue
+
+            let selectPages = fileAttribute.fetchSelectPages()
+            if selectPages.count != 0 {
+                pages = selectPages.map { $0.intValue - 1 }
+            } else {
+                let alert = NSAlert()
+                alert.alertStyle = .critical
+                alert.messageText = "\(fileAttribute.filePath.lastPathComponent) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
+                alert.runModal()
+                return
+            }
+        }
+
+        background.pagesString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
+
+        switch type {
+        case .add:
+            if needSave {
+                if checkPageRangeValidate(pageRangeComboBox.stringValue) && pageRangeComboBox.indexOfSelectedItem == -1 {
+                    background.pagesString = pageRangeComboBox.stringValue
+                }
+                KMBackgroundManager.defaultManager.addTemplate(model: background)
+            }
+            operateCallBack?(background, currentType)
+        case .edit:
+            if needSave {
+                if checkPageRangeValidate(pageRangeComboBox.stringValue) && pageRangeComboBox.indexOfSelectedItem == -1 {
+                    background.pagesString = pageRangeComboBox.stringValue
+                }
+                originalBackground = (background.copy() as? KMBackgroundModel)!
+//                KMBackgroundManager.defaultManager.store()
+            }
+            operateCallBack?(originalBackground, currentType)
+        case .use:
+            let fileName = "\(pdfDocument.documentURL?.lastPathComponent ?? NSLocalizedString("Untitled", comment: ""))_Background"
+            let savePanelAccessoryViewController = KMSavePanelAccessoryController()
+            let savePanel = NSSavePanel()
+            savePanel.nameFieldStringValue = fileName
+            savePanel.allowedFileTypes = ["pdf"]
+            savePanel.accessoryView = savePanelAccessoryViewController.view
+            savePanel.beginSheetModal(for: window!) { result in
+                if result == .OK {
+                    self.saveAsPDF(with: self.background, to: savePanel.url?.path ?? "", autoOpen: savePanelAccessoryViewController.openAutomaticButton.state == .on ? true : false)
+                }
+            }
+        }
+    }
 }

+ 42 - 5
PDF Office/PDF Master/Class/PDFTools/Background/New/View/KMAddBackgroundView.xib

@@ -9,9 +9,46 @@
     <objects>
         <customObject id="-2" userLabel="File's Owner" customClass="KMAddBackgroundView" customModule="PDF_Master" customModuleProvider="target">
             <connections>
+                <outlet property="alphaLabel" destination="xZ8-fz-ItF" id="ssl-se-XyJ"/>
+                <outlet property="alphaSlider" destination="qgx-tW-Cch" id="VqX-0L-S1g"/>
+                <outlet property="alphaStepper" destination="sVe-7U-Sr3" id="zN2-EL-GKp"/>
+                <outlet property="alphaTextField" destination="Yw0-0L-CLB" id="sp3-PY-96b"/>
+                <outlet property="angleLabel" destination="rm6-4f-1Wl" id="0i7-Pe-t6G"/>
+                <outlet property="angleStepper" destination="ZfX-mo-ogH" id="Uyb-Jg-VxJ"/>
+                <outlet property="angleTextField" destination="VpQ-rd-1lb" id="OWW-eu-o3x"/>
+                <outlet property="appearanceBox" destination="uVG-9U-es7" id="7sE-cP-ePn"/>
                 <outlet property="batchButton" destination="dCQ-Gq-Cst" id="1eZ-79-CVg"/>
+                <outlet property="browseButton" destination="Jmd-Ox-rOL" id="v6O-kM-C4N"/>
                 <outlet property="cancelButton" destination="D5H-CW-WxN" id="Ajv-hT-unV"/>
+                <outlet property="colorButton" destination="uJE-UR-TcB" id="xkS-R2-x51"/>
+                <outlet property="colorWell" destination="ZXz-PO-D6F" id="Rmy-Wd-tWy"/>
+                <outlet property="currentPageIndexTextField" destination="auI-8C-JAb" id="Ktp-6M-Eg1"/>
                 <outlet property="doneButton" destination="V6K-Pu-pZ6" id="aPK-KL-17b"/>
+                <outlet property="fileButton" destination="e5H-Ra-5M6" id="Mbz-tw-Wfg"/>
+                <outlet property="filePathLabel" destination="KJc-ko-3Kw" id="fc0-Gg-mo6"/>
+                <outlet property="horizontalGapLabel" destination="PVJ-QE-OSa" id="bpj-Gp-MR6"/>
+                <outlet property="horizontalGapTextField" destination="TN8-0T-3ni" id="n49-mw-eZe"/>
+                <outlet property="horizontalIndicateView" destination="BBR-fQ-n2l" id="eqX-iP-e9C"/>
+                <outlet property="horizontalStepper" destination="RYW-E6-8Ph" id="EOa-hN-XUy"/>
+                <outlet property="left45IndicateView" destination="Qbj-dr-1LX" id="4fr-xK-aQn"/>
+                <outlet property="nextButton" destination="grh-Kn-g1l" id="Egi-VL-H66"/>
+                <outlet property="pageRangeComboBox" destination="hai-eI-TEB" id="dFL-UU-N2P"/>
+                <outlet property="pageRangeLabel" destination="RTe-5d-eUd" id="61M-07-pJ0"/>
+                <outlet property="pdfView" destination="afp-IL-Bkr" id="2qc-GJ-H1Z"/>
+                <outlet property="postionView" destination="plG-s5-sBd" id="yGP-bI-iwv"/>
+                <outlet property="previousButton" destination="K9f-us-FkG" id="YcK-gX-UxV"/>
+                <outlet property="ratioLabel" destination="FdJ-Mo-ixe" id="ofc-1s-aXB"/>
+                <outlet property="ratioStepper" destination="Lzl-LX-D6c" id="JJI-rl-MKj"/>
+                <outlet property="ratioTextField" destination="IHa-Le-PQB" id="RRa-h6-Qmg"/>
+                <outlet property="right45IndicateView" destination="nic-kL-H4J" id="ZeI-wT-SnW"/>
+                <outlet property="saveToTemplateButton" destination="tLK-st-rLL" id="eMa-My-PLP"/>
+                <outlet property="templateNameLabel" destination="SAP-r8-yOW" id="7vt-Ra-mcA"/>
+                <outlet property="templateNameTextField" destination="pkF-sT-JBT" id="DBi-KK-IuB"/>
+                <outlet property="totalPageCountlabel" destination="W2y-dS-mSh" id="pQJ-WM-APk"/>
+                <outlet property="typeBox" destination="wuk-f8-DLJ" id="1eY-nw-3LW"/>
+                <outlet property="verticalGapLabel" destination="WNU-SS-y7q" id="eXM-1Z-KDC"/>
+                <outlet property="verticalGapTextField" destination="h7e-Zv-9g0" id="bT4-Z8-yDI"/>
+                <outlet property="verticalStepper" destination="FK4-eP-ZsW" id="PZr-ri-YY7"/>
             </connections>
         </customObject>
         <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
@@ -23,7 +60,7 @@
                 <view translatesAutoresizingMaskIntoConstraints="NO" id="rxq-as-8Qd">
                     <rect key="frame" x="0.0" y="0.0" width="992" height="565"/>
                     <subviews>
-                        <pdfView autoresizesSubviews="NO" wantsLayer="YES" displayMode="singlePage" displaysPageBreaks="NO" translatesAutoresizingMaskIntoConstraints="NO" id="afp-IL-Bkr" customClass="KMWatermarkPDFView">
+                        <pdfView autoresizesSubviews="NO" wantsLayer="YES" displayMode="singlePage" displaysPageBreaks="NO" translatesAutoresizingMaskIntoConstraints="NO" id="afp-IL-Bkr" customClass="KMWatermarkPDFView" customModule="PDF_Master" customModuleProvider="target">
                             <rect key="frame" x="40" y="219" width="240" height="310"/>
                             <constraints>
                                 <constraint firstAttribute="height" constant="310" id="3F8-3R-L32"/>
@@ -226,7 +263,7 @@
                                         <rect key="frame" x="298" y="43" width="19" height="28"/>
                                         <stepperCell key="cell" continuous="YES" alignment="left" increment="0.01" maxValue="1" id="Oaa-8F-8y4"/>
                                     </stepper>
-                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="plG-s5-sBd" customClass="KMPostionIndicateView">
+                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="plG-s5-sBd" customClass="KMPostionIndicateView" customModule="PDF_Master" customModuleProvider="target">
                                         <rect key="frame" x="366" y="20" width="80" height="80"/>
                                         <constraints>
                                             <constraint firstAttribute="height" constant="80" id="Vzf-gu-lfR"/>
@@ -308,21 +345,21 @@
                                             <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                                         </textFieldCell>
                                     </textField>
-                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="Qbj-dr-1LX" customClass="KMAngleIndicateView">
+                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="Qbj-dr-1LX" customClass="KMAngleIndicateView" customModule="PDF_Master" customModuleProvider="target">
                                         <rect key="frame" x="230" y="77" width="20" height="28"/>
                                         <constraints>
                                             <constraint firstAttribute="height" constant="28" id="YcK-XO-cVB"/>
                                             <constraint firstAttribute="width" constant="20" id="v4N-2u-Oi4"/>
                                         </constraints>
                                     </customView>
-                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="nic-kL-H4J" customClass="KMAngleIndicateView">
+                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="nic-kL-H4J" customClass="KMAngleIndicateView" customModule="PDF_Master" customModuleProvider="target">
                                         <rect key="frame" x="294" y="77" width="20" height="28"/>
                                         <constraints>
                                             <constraint firstAttribute="height" constant="28" id="8fk-3T-ax0"/>
                                             <constraint firstAttribute="width" constant="20" id="Xj5-yz-db5"/>
                                         </constraints>
                                     </customView>
-                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="BBR-fQ-n2l" customClass="KMAngleIndicateView">
+                                    <customView translatesAutoresizingMaskIntoConstraints="NO" id="BBR-fQ-n2l" customClass="KMAngleIndicateView" customModule="PDF_Master" customModuleProvider="target">
                                         <rect key="frame" x="262" y="77" width="20" height="28"/>
                                         <constraints>
                                             <constraint firstAttribute="width" constant="20" id="9aZ-hm-Pdw"/>

+ 14 - 0
PDF Office/PDF Master/Class/PDFTools/Background/tool/KMBackgroundManager.swift

@@ -377,4 +377,18 @@ class KMBackgroundManager: NSObject {
         
         return result
     }
+    
+    func fetchAvailableName() -> String {
+        var availableIndex = 0
+        
+        for item in datas {
+            if item.backgroundID.hasPrefix("Background") {
+                if let index = Int(item.backgroundID.dropFirst("Background".count)), index >= availableIndex {
+                    availableIndex = index + 1
+                }
+            }
+        }
+        
+        return "Background\(availableIndex)"
+    }
 }

+ 3 - 3
PDF Office/PDF Master/Class/PDFTools/Watermark/Controller/KMWatermarkViewController.swift

@@ -151,10 +151,10 @@ class KMWatermarkViewController: KMWatermarkAdjectivePreViewBaseController {
             let preView: KMWatermarkPDFView = self.preView as! KMWatermarkPDFView
             let templateModel: KMWatermarkTemplateModel = model as! KMWatermarkTemplateModel
             if (templateModel.isSelected) {
-                preView.watermarkModel = model
+                preView.watermark = model
                 self.topBarView.isCanApply(can: true)
             } else {
-                preView.watermarkModel = nil
+                preView.watermark = KMWatermarkModel()
                 self.topBarView.isCanApply(can: false)
             }
             
@@ -196,7 +196,7 @@ class KMWatermarkViewController: KMWatermarkAdjectivePreViewBaseController {
         self.topBarView.isCanApply(can: true)
         
         let preView: KMWatermarkPDFView = self.preView as! KMWatermarkPDFView
-        preView.watermarkModel = self.createWatermarkTemplate()
+        preView.watermark = self.createWatermarkTemplate()
         preView.setNeedsDisplay(preView.bounds)
         
         let createController = KMWatermarkPropertyCreateController()

+ 3 - 3
PDF Office/PDF Master/Class/PDFTools/Watermark/Controller/KMWatermarkViewController.xib

@@ -1,12 +1,12 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
+<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="22155" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
     <dependencies>
         <deployment identifier="macosx"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="22155"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
     </dependencies>
     <objects>
-        <customObject id="-2" userLabel="File's Owner" customClass="KMWatermarkViewController" customModule="PDF_Office" customModuleProvider="target">
+        <customObject id="-2" userLabel="File's Owner" customClass="KMWatermarkViewController" customModule="PDF_Master" customModuleProvider="target">
             <connections>
                 <outlet property="view" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/>
             </connections>

+ 58 - 58
PDF Office/PDF Master/Class/PDFTools/Watermark/View/KMWatermarkPDFView.swift

@@ -9,19 +9,19 @@ import Cocoa
 
 class KMWatermarkPDFView: CPDFView {
     
-    var watermarkModel: KMWatermarkModel!
+//    var watermarkModel: KMWatermarkModel!
     
-    var watermark: KMWatermarkModel?
-    var background: KMBackgroundObject?
-    var headerFooter: KMHeaderFooterObject?
+    var watermark: KMWatermarkModel = KMWatermarkModel()
+    var background: KMBackgroundModel = KMBackgroundModel()
+    var headerFooter: KMHeaderFooterModel = KMHeaderFooterModel()
     
     override func draw(_ page: CPDFPage!, to context: CGContext!) {
-        if (self.watermarkModel == nil) {
+        if (self.watermark == nil) {
             super.draw(page, to: context)
             return 
         }
         
-        if (self.watermarkModel.isFront) {
+        if (self.watermark.isFront) {
             super.draw(page, to: context)
             
             if (self.needDraw(page)) {
@@ -37,11 +37,11 @@ class KMWatermarkPDFView: CPDFView {
     }
     
     func needDraw(_ page: CPDFPage) -> Bool {
-        if (self.watermarkModel == nil) {
+        if (self.watermark == nil) {
             return true
         }
         
-        if (self.watermarkModel.pageRangeType.rawValue == 0) {
+        if (self.watermark.pageRangeType.rawValue == 0) {
             return true
         }
 //        else if (self.watermarkModel.pageRangeType == 1) {
@@ -51,18 +51,18 @@ class KMWatermarkPDFView: CPDFView {
 //                return false
 //            }
 //        }
-        else if (self.watermarkModel.pageRangeType == .odd) {
+        else if (self.watermark.pageRangeType == .odd) {
             let index: Int = Int(self.document.index(for: page))
             return (index % 2 == 0)
-        } else if (self.watermarkModel.pageRangeType == .even) {
+        } else if (self.watermark.pageRangeType == .even) {
             let index: Int = Int(self.document.index(for: page))
             return (index % 2 == 1)
-        } else if (self.watermarkModel.pageRangeType == .other) {
-            if (self.watermarkModel.pagesString.isEmpty) {
+        } else if (self.watermark.pageRangeType == .other) {
+            if (self.watermark.pagesString.isEmpty) {
                 return false
             }
             
-            let array = self.watermarkModel.pagesString.components(separatedBy: ",")
+            let array = self.watermark.pagesString.components(separatedBy: ",")
             let index: Int = Int(self.document.index(for: page))
             if (!array.contains("\(index+1)")) {
                 return false
@@ -95,14 +95,14 @@ class KMWatermarkPDFView: CPDFView {
 //            }
 //        }
         
-        if (!self.watermarkModel.text.isEmpty) {
-            var font = self.watermarkModel.textFont
+        if (!self.watermark.text.isEmpty) {
+            var font = self.watermark.textFont
             if (font == nil) {
 //                font = NSFont(name: "Helvetica", size: 48)
             }
             
             var color = NSColor.black
-            if (self.watermarkModel.textColor != nil) {
+            if (self.watermark.textColor != nil) {
 //                color = self.watermarkModel.textColor
             }
             
@@ -110,157 +110,157 @@ class KMWatermarkPDFView: CPDFView {
             var green: CGFloat = 0
             var blue: CGFloat = 0
             color.usingColorSpaceName(NSColorSpaceName.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: nil)
-            color = NSColor(red: red, green: green, blue: blue, alpha: self.watermarkModel.opacity)
+            color = NSColor(red: red, green: green, blue: blue, alpha: self.watermark.opacity)
             
             var size = NSZeroSize
             let style = NSMutableParagraphStyle()
-            style.alignment = self.watermarkModel.textAligement
+            style.alignment = self.watermark.textAligement
             style.lineBreakMode = .byCharWrapping
             let dict = [NSAttributedString.Key.paragraphStyle : style,
                         NSAttributedString.Key.foregroundColor : color,
                         NSAttributedString.Key.font : font] as [NSAttributedString.Key : Any]
-            size = self.watermarkModel.text.boundingRect(with: NSSize(width: 1000, height: 1000), options: NSString.DrawingOptions(rawValue: 3), attributes: dict).size
+            size = self.watermark.text.boundingRect(with: NSSize(width: 1000, height: 1000), options: NSString.DrawingOptions(rawValue: 3), attributes: dict).size
             
-            let radian: CGFloat = self.watermarkModel.rotation*(Double.pi/180.0)
+            let radian: CGFloat = self.watermark.rotation*(Double.pi/180.0)
             let t: CGAffineTransform = CGAffineTransform(rotationAngle: radian)
             var rect:CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
             
-            if (self.watermarkModel.isTilePage) {
+            if (self.watermark.isTilePage) {
                 context.translateBy(x: w * 0.5, y: h * 0.5)
                 context.concatenate(t)
                 context.translateBy(x: -(w/2),  y: -(h/2))
                 
-                let verticalWidth: CGFloat = size.width + self.watermarkModel.tileHorizontalSpace
-                let horizontalHeight: CGFloat = size.height + self.watermarkModel.tileVerticalSpace
-                let line: Int = Int(((new_h-self.watermarkModel.tileVerticalSpace)/horizontalHeight)+1)
-                let row: Int = Int(((new_w-self.watermarkModel.tileHorizontalSpace)/verticalWidth)+1)
+                let verticalWidth: CGFloat = size.width + self.watermark.tileHorizontalSpace
+                let horizontalHeight: CGFloat = size.height + self.watermark.tileVerticalSpace
+                let line: Int = Int(((new_h-self.watermark.tileVerticalSpace)/horizontalHeight)+1)
+                let row: Int = Int(((new_w-self.watermark.tileHorizontalSpace)/verticalWidth)+1)
                 
-                let point: CGPoint = CGPoint(x: w*0.5-size.width*0.5+self.watermarkModel.horizontalSpace, y: h*0.5-size.height*0.5+self.watermarkModel.verticalSpace)
+                let point: CGPoint = CGPoint(x: w*0.5-size.width*0.5+self.watermark.horizontalSpace, y: h*0.5-size.height*0.5+self.watermark.verticalSpace)
                 for i in 0 ..< line {
                     for j in 0 ..< row {
-                        self.watermarkModel.text.draw(in: NSRect(x: point.x+CGFloat(j)*verticalWidth, y: point.y+CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
+                        self.watermark.text.draw(in: NSRect(x: point.x+CGFloat(j)*verticalWidth, y: point.y+CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
                     }
                 }
                 
                 for i in 1 ..< line {
                     for j in 0 ..< row {
-                        self.watermarkModel.text.draw(in: NSRect(x: point.x+CGFloat(j)*verticalWidth, y: point.y-CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
+                        self.watermark.text.draw(in: NSRect(x: point.x+CGFloat(j)*verticalWidth, y: point.y-CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
                     }
                 }
                 
                 for i in 0 ..< line {
                     for j in 1 ..< row {
-                        self.watermarkModel.text.draw(in: NSRect(x: point.x-CGFloat(j)*verticalWidth, y: point.y+CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
+                        self.watermark.text.draw(in: NSRect(x: point.x-CGFloat(j)*verticalWidth, y: point.y+CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
                     }
                 }
                 
                 for i in 1 ..< line {
                     for j in 1 ..< row {
-                        self.watermarkModel.text.draw(in: NSRect(x: point.x-CGFloat(j)*verticalWidth, y: point.y-CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
+                        self.watermark.text.draw(in: NSRect(x: point.x-CGFloat(j)*verticalWidth, y: point.y-CGFloat(i)*horizontalHeight, width: size.width, height: size.height), withAttributes: dict)
                     }
                 }
             } else {
-                if (self.watermarkModel.verticalMode == 0) {
+                if (self.watermark.verticalMode == 0) {
                     rect.origin.y = pageBounds.size.height-rect.size.height
-                } else if (self.watermarkModel.verticalMode == 1) {
+                } else if (self.watermark.verticalMode == 1) {
                     rect.origin.y = (pageBounds.size.height-rect.size.height) * 0.5
                 } else {
                     rect.origin.y = 0
                 }
                 
-                if (self.watermarkModel.horizontalMode == 0) {
+                if (self.watermark.horizontalMode == 0) {
                     rect.origin.x = 0
-                } else if (self.watermarkModel.horizontalMode == 1) {
+                } else if (self.watermark.horizontalMode == 1) {
                     rect.origin.x = (pageBounds.size.width-rect.size.width) * 0.5
                 } else {
                     rect.origin.x = pageBounds.size.width-rect.size.width
                 }
                 
-                rect.origin.x += self.watermarkModel.horizontalSpace
-                rect.origin.y += self.watermarkModel.verticalSpace
+                rect.origin.x += self.watermark.horizontalSpace
+                rect.origin.y += self.watermark.verticalSpace
                 
                 let contextCenter = CGPoint(x: rect.midX, y: rect.midY)
                 context.translateBy(x: contextCenter.x, y: contextCenter.y)
                 context.rotate(by: radian)
                 context.translateBy(x: -contextCenter.x, y: -contextCenter.y)
                 
-                self.watermarkModel.text.draw(in: rect, withAttributes: dict)
+                self.watermark.text.draw(in: rect, withAttributes: dict)
             }
-        } else if (self.watermarkModel.image != nil) {
-            let tiffData = self.watermarkModel.image.tiffRepresentation
+        } else if (self.watermark.image != nil) {
+            let tiffData = self.watermark.image.tiffRepresentation
             let bitmap: NSBitmapImageRep!
             bitmap = NSBitmapImageRep(data: tiffData!)
             let ciImage = CIImage(bitmapImageRep: bitmap)
             var size: NSSize = (ciImage?.extent.size)!
-            size.width *= self.watermarkModel.scale
-            size.height *= self.watermarkModel.scale
+            size.width *= self.watermark.scale
+            size.height *= self.watermark.scale
             
-            let radian = self.watermarkModel.rotation * (Double.pi / 180.0)
+            let radian = self.watermark.rotation * (Double.pi / 180.0)
             let t: CGAffineTransform = CGAffineTransform(rotationAngle: radian)
             var rect = NSMakeRect(0, 0, size.width, size.height)
-            if (self.watermarkModel.isTilePage) {
+            if (self.watermark.isTilePage) {
                 context.translateBy(x: w/2,y: h/2)
                 context.concatenate(t)
                 context.translateBy(x: -(w/2),  y: -(h/2))
                 
-                let verticalWidth: CGFloat = size.width + self.watermarkModel.tileHorizontalSpace
-                let horizontalHeight: CGFloat = size.height + self.watermarkModel.tileVerticalSpace
-                let line: Int = Int((new_h - self.watermarkModel.tileVerticalSpace)/horizontalHeight + 1)
-                let row: Int = Int((new_w - self.watermarkModel.tileHorizontalSpace) / verticalWidth + 1)
+                let verticalWidth: CGFloat = size.width + self.watermark.tileHorizontalSpace
+                let horizontalHeight: CGFloat = size.height + self.watermark.tileVerticalSpace
+                let line: Int = Int((new_h - self.watermark.tileVerticalSpace)/horizontalHeight + 1)
+                let row: Int = Int((new_w - self.watermark.tileHorizontalSpace) / verticalWidth + 1)
                 let point = NSPoint(x: w/2 - size.width/2, y: h/2 - size.height/2)
                 for i in 0 ..< (line/2+1) {
                     for j in 0 ..< row {
                         let area = CGRect(x: point.x  + CGFloat(j) * verticalWidth, y: point.y + CGFloat(i)*horizontalHeight, width: size.width, height: size.height)
-                        self.watermarkModel.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermarkModel.opacity)
+                        self.watermark.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermark.opacity)
                     }
                 }
                 
                 for i in 1 ..< (line/2+1) {
                     for j in 0 ..< row {
                         let area = CGRect(x: point.x  + CGFloat(j) * verticalWidth, y: point.y - CGFloat(i)*horizontalHeight, width: size.width, height: size.height)
-                        self.watermarkModel.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermarkModel.opacity)
+                        self.watermark.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermark.opacity)
                     }
                 }
                 
                 for i in 0 ..< (line/2+1) {
                     for j in 1 ..< row {
                         let area = CGRect(x: point.x  - CGFloat(j) * verticalWidth, y: point.y + CGFloat(i)*horizontalHeight, width: size.width, height: size.height)
-                        self.watermarkModel.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermarkModel.opacity)
+                        self.watermark.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermark.opacity)
                     }
                 }
                 
                 for i in 1 ..< (line/2+1) {
                     for j in 1 ..< row {
                         let area = CGRect(x: point.x  - CGFloat(j) * verticalWidth, y: point.y - CGFloat(i)*horizontalHeight, width: size.width, height: size.height)
-                        self.watermarkModel.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermarkModel.opacity)
+                        self.watermark.image.draw(in: area, from: NSZeroRect, operation: .overlay, fraction: self.watermark.opacity)
                     }
                 }
             } else {
-                if (self.watermarkModel.verticalMode == 0) {
+                if (self.watermark.verticalMode == 0) {
                     rect.origin.y = pageBounds.size.height-rect.size.height
-                } else if (self.watermarkModel.verticalMode == 1) {
+                } else if (self.watermark.verticalMode == 1) {
                     rect.origin.y = (pageBounds.size.height-rect.size.height) * 0.5
                 } else {
                     rect.origin.y = 0
                 }
                 
-                if (self.watermarkModel.horizontalMode == 0) {
+                if (self.watermark.horizontalMode == 0) {
                     rect.origin.x = 0
-                } else if (self.watermarkModel.horizontalMode == 1) {
+                } else if (self.watermark.horizontalMode == 1) {
                     rect.origin.x = (pageBounds.size.width-rect.size.width) * 0.5
                 } else {
                     rect.origin.x = pageBounds.size.width-rect.size.width
                 }
                 
-                rect.origin.x += self.watermarkModel.horizontalSpace
-                rect.origin.y += self.watermarkModel.verticalSpace
+                rect.origin.x += self.watermark.horizontalSpace
+                rect.origin.y += self.watermark.verticalSpace
                 
                 let contextCenter = CGPoint(x: rect.midX, y: rect.midY)
                 context.translateBy(x: contextCenter.x, y: contextCenter.y)
                 context.rotate(by: radian)
                 context.translateBy(x: -contextCenter.x, y: -contextCenter.y)
                 
-                self.watermarkModel.image.draw(in: rect, from: NSZeroRect, operation: .overlay, fraction: self.watermarkModel.opacity)
+                self.watermark.image.draw(in: rect, from: NSZeroRect, operation: .overlay, fraction: self.watermark.opacity)
             }
         }
         NSGraphicsContext.restoreGraphicsState()

+ 2 - 2
PDF Office/PDF Master/Class/PDFWindowController/Side/LeftSide/Annotation/KMAnnotationViewController.swift

@@ -134,8 +134,8 @@ class KMAnnotationViewController: KMSideViewController {
 //MARK: Data
 extension KMAnnotationViewController {
     @objc public func reloadData() {
-        self.reloadAnnotation()
-        self.annotationSort(sortArray: [])
+//        self.reloadAnnotation()
+//        self.annotationSort(sortArray: [])
     }
     
     func reloadAnnotation() {

+ 2 - 2
PDF Office/PDF Master/Class/PDFWindowController/Side/LeftSide/Annotation/KMAnnotationViewController.xib

@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="22146" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
+<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="22155" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
     <dependencies>
         <deployment identifier="macosx"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="22146"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="22155"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
     </dependencies>
     <objects>

+ 1 - 0
PDF Office/PDF Master/Class/PDFWindowController/ViewController/KMMainViewController+Action.swift

@@ -3358,6 +3358,7 @@ extension KMMainViewController : KMMainToolbarControllerDelegate {
             } else if type == .background {
                 let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
                 self.currentWindowController = controller
+                controller.pdfDocument = self.document
                 
                 controller.cancelAction = { [unowned self] controller in
                     self.view.window?.endSheet((self.currentWindowController.window)!)