Просмотр исходного кода

Merge branches 'develop_PDFReaderProNew' and 'develop_PDFReaderProNew' of git.kdan.cc:Mac_PDF/PDF_Office into develop_PDFReaderProNew

liujiajie 1 год назад
Родитель
Сommit
14ecf3aecb
16 измененных файлов с 779 добавлено и 500 удалено
  1. 0 16
      PDF Office/PDF Master.xcodeproj/xcuserdata/kdanmobile.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
  2. 2 2
      PDF Office/PDF Master/Class/PDFTools/Print/Model/KMPrintPageModel.swift
  3. 2 2
      PDF Office/PDF Master/Class/PDFTools/Print/Presenter/KMPrintPresenter.swift
  4. 2 2
      PDF Office/PDF Master/Class/PDFTools/Print/View/ChooseView/View/View/DealPaper/KMPrintChoosePageSizeMultipageView.swift
  5. 2 2
      PDF Office/PDF Master/Class/PDFTools/Print/View/ChooseView/View/View/DealPaper/KMPrintChoosePageSizePamphletView.swift
  6. 1 4
      PDF Office/PDF Master/Class/PDFTools/Print/View/Preview/KMPrintPreviewView.swift
  7. 1 1
      PDF Office/PDF Master/Class/PDFTools/Print/View/Preview/KMPrintPreviewView.xib
  8. 8 0
      PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/KMPrintSettingView.swift
  9. 29 9
      PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/View/Multipage/KMPrintMultipageView.swift
  10. 198 0
      PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/View/Pamphlet/KMPrintPamphletView.swift
  11. 50 0
      PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/View/Pamphlet/KMPrintPamphletView.xib
  12. 57 6
      PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/ViewModel/KMPrintViewModel.swift
  13. 279 274
      PDF Office/PDF Master/Class/PDFTools/Snapshot/View/KMSnapshotPDFView.swift
  14. 135 180
      PDF Office/PDF Master/Class/PDFTools/Snapshot/Window/KMSnapshotWindowController.swift
  15. 13 1
      PDF Office/PDF Master/Class/PDFWindowController/Side/LeftSide/KMSegmentedControl.swift
  16. 0 1
      PDF Office/PDF Master/Class/PDFWindowController/ViewController/KMMainViewController.swift

+ 0 - 16
PDF Office/PDF Master.xcodeproj/xcuserdata/kdanmobile.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist

@@ -356,22 +356,6 @@
             landmarkType = "7">
          </BreakpointContent>
       </BreakpointProxy>
-      <BreakpointProxy
-         BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
-         <BreakpointContent
-            uuid = "E6699853-FF9B-462E-8EA1-E74734DC7310"
-            shouldBeEnabled = "Yes"
-            ignoreCount = "0"
-            continueAfterRunningActions = "No"
-            filePath = "PDF Master/Class/PDFTools/Snapshot/Window/KMSnapshotWindowController.swift"
-            startingColumnNumber = "9223372036854775807"
-            endingColumnNumber = "9223372036854775807"
-            startingLineNumber = "725"
-            endingLineNumber = "725"
-            landmarkName = "windowDidMiniaturize(_:)"
-            landmarkType = "7">
-         </BreakpointContent>
-      </BreakpointProxy>
       <BreakpointProxy
          BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
          <BreakpointContent

+ 2 - 2
PDF Office/PDF Master/Class/PDFTools/Print/Model/KMPrintPageModel.swift

@@ -90,6 +90,8 @@ enum KMPrintModelType {
 struct KMPrintPageOperation {
     var type: KMPrintModelType = .size
     var size: Size = Size()
+    var isAutoRotate: Bool = false //自动旋转
+    
     var poster: Poster = Poster()
     var multipage: Multipage = Multipage()
     var pamphlet: Pamphlet = Pamphlet()
@@ -178,7 +180,6 @@ struct KMPrintPageOperation {
     //多页模式参数内容
     struct Multipage {
         var orderType: Order = .horizontal
-        var isAutoRotate: Bool = false //自动旋转
         var lineSpacing: CGFloat = 30
         var columnsSpacing: CGFloat = 30
         var isBorder: Bool = false
@@ -206,7 +207,6 @@ struct KMPrintPageOperation {
         var pageIndex: Int = 1
         var toPageIndex: Int = 1
         var bookbindingType: BookbindingType = .left
-        var isAutoRotate: Bool = false //自动旋转
         
         enum PamphletType: String, CaseIterable {
             case doubleSided = "Double Sided" //双面

+ 2 - 2
PDF Office/PDF Master/Class/PDFTools/Print/Presenter/KMPrintPresenter.swift

@@ -610,9 +610,9 @@ extension KMPrintPresenter: KMPrintPresenterPage {
         var autoRotate = false
         switch pageModel.operation.type {
         case .multipage:
-            autoRotate = pageModel.operation.multipage.isAutoRotate
+            autoRotate = pageModel.operation.isAutoRotate
         case .pamphlet:
-            autoRotate = pageModel.operation.pamphlet.isAutoRotate
+            autoRotate = pageModel.operation.isAutoRotate
         default:
             autoRotate = false
         }

+ 2 - 2
PDF Office/PDF Master/Class/PDFTools/Print/View/ChooseView/View/View/DealPaper/KMPrintChoosePageSizeMultipageView.swift

@@ -65,14 +65,14 @@ class KMPrintChoosePageSizeMultipageView: KMBaseXibView {
 //        //
 //        self.pageOrderButton.selectItem(withTitle: self.outputData.orderType.rawValue)
         
-        self.autoRotateButton.state = (self.outputData.isAutoRotate == true) ? .on : .off
+//        self.autoRotateButton.state = (self.outputData.isAutoRotate == true) ? .on : .off
     }
 }
 
 protocol KMPrintChoosePageSizeMultipageViewAction {}
 extension KMPrintChoosePageSizeMultipageView: KMPrintChoosePageSizeMultipageViewAction {
     @IBAction func autoRotateAction(_ sender: NSButton) {
-        self.outputData.isAutoRotate = sender.state == .on ? true : false
+//        self.outputData.isAutoRotate = sender.state == .on ? true : false
         self.actionReloadData()
     }
     

+ 2 - 2
PDF Office/PDF Master/Class/PDFTools/Print/View/ChooseView/View/View/DealPaper/KMPrintChoosePageSizePamphletView.swift

@@ -61,7 +61,7 @@ class KMPrintChoosePageSizePamphletView: KMBaseXibView {
 
         self.bookbindingButton.selectItem(withTitle: self.outputData.bookbindingType.rawValue)
         
-        self.autoRotateButton.state = (self.outputData.isAutoRotate == true) ? .on : .off
+//        self.autoRotateButton.state = (self.outputData.isAutoRotate == true) ? .on : .off
         
         self.pageTextField.stringValue = self.outputData.pageIndex.description
         self.toPageTextField.stringValue = self.outputData.toPageIndex.description
@@ -82,7 +82,7 @@ extension KMPrintChoosePageSizePamphletView: KMPrintChoosePageSizePamphletViewAc
     }
     
     @IBAction func autoRotateAction(_ sender: NSButton) {
-        self.outputData.isAutoRotate = sender.state == .on ? true : false
+//        self.outputData.isAutoRotate = sender.state == .on ? true : false
         self.actionReloadData()
     }
     

+ 1 - 4
PDF Office/PDF Master/Class/PDFTools/Print/View/Preview/KMPrintPreviewView.swift

@@ -31,10 +31,7 @@ class KMPrintPreviewView: KMBaseXibView {
             self.previewView.document = PDFDocument(url: pdfDocument!.documentURL)
             self.previewView.autoScales = true
             self.previewView.displayMode = .singlePage
-            self.previewView.documentView?.enclosingScrollView?.hasVerticalScroller = false
-            self.previewView.documentView?.enclosingScrollView?.hasHorizontalScroller = false
-            self.previewView.enclosingScrollView?.hasHorizontalScroller = false
-            self.previewView.enclosingScrollView?.hasVerticalScroller = false
+            self.previewView.documentView?.enclosingScrollView?.scrollerStyle = .overlay
             if model?.page.operation.type == .poster {
                 
             } else {

+ 1 - 1
PDF Office/PDF Master/Class/PDFTools/Print/View/Preview/KMPrintPreviewView.xib

@@ -32,7 +32,7 @@
                         <customView translatesAutoresizingMaskIntoConstraints="NO" id="Uhc-ec-psZ">
                             <rect key="frame" x="0.0" y="60" width="180" height="248"/>
                             <subviews>
-                                <pdfView autoresizesSubviews="NO" wantsLayer="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Sws-Vc-u7D">
+                                <pdfView autoresizesSubviews="NO" wantsLayer="YES" displayMode="singlePage" translatesAutoresizingMaskIntoConstraints="NO" id="Sws-Vc-u7D">
                                     <rect key="frame" x="0.0" y="0.0" width="180" height="248"/>
                                 </pdfView>
                                 <customView translatesAutoresizingMaskIntoConstraints="NO" id="1lQ-Db-XbA" customClass="KMPrintPosterPreviewView" customModule="PDF_Master" customModuleProvider="target">

+ 8 - 0
PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/KMPrintSettingView.swift

@@ -49,6 +49,14 @@ class KMPrintSettingView: KMBaseXibView {
         multipageView.printSettingChangeAction = { [unowned self] view, model in
             self.printSettingChange?(self, model)
         }
+        
+        pamphletView.pageSettingChangeAction = { [unowned self] view, model in
+            self.pageSettingChange?(self, model)
+        }
+        
+        pamphletView.printSettingChangeAction = { [unowned self] view, model in
+            self.printSettingChange?(self, model)
+        }
     }
     
     override func reloadData() {

+ 29 - 9
PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/View/Multipage/KMPrintMultipageView.swift

@@ -260,7 +260,7 @@ extension KMPrintMultipageView {
     }
 
     @IBAction func buttonItemClickAutoRoate(_ sender: Any) {
-        self.viewModel.multipageAutoRotateChangeAction(isRotate: (autoRotaCheckButton.state == .on)) { success, model in
+        self.viewModel.autoRotateChangeAction(isRotate: (autoRotaCheckButton.state == .on)) { success, model in
             if success {
                 self.updatePDFView()
             }
@@ -336,15 +336,35 @@ extension KMPrintMultipageView {
     }
 
     @IBAction func comboBoxItemClickPageRange(_ sender: NSComboBox) {
-        if [0, 1, 2].contains(sender.indexOfSelectedItem) {
-            pageRangeComboBox.delegate = nil
-            window?.makeFirstResponder(self)
-            pageRangeComboBox.isEditable = false
+        var range: KMPrintPageRange = KMPrintPageRange()
+        if sender.indexOfSelectedItem == 0 ||
+            sender.indexOfSelectedItem == 1 ||
+            sender.indexOfSelectedItem == 2 {
+            if sender.indexOfSelectedItem == 0 {
+                range.type = .allPage
+            } else if sender.indexOfSelectedItem == 1 {
+                range.type = .oddPage
+            } else if sender.indexOfSelectedItem == 2 {
+                range.type = .evenPage
+            }
+            
+            sender.delegate = nil
+            sender.isEditable = false
         } else if sender.indexOfSelectedItem == 3 {
-            pageRangeComboBox.delegate = self
-            pageRangeComboBox.stringValue = ""
-            pageRangeComboBox.isEditable = true
-            window?.makeFirstResponder(pageRangeComboBox)
+            sender.delegate = self
+            sender.stringValue = ""
+            sender.isEditable = true
+            
+            window?.makeFirstResponder(sender)
+            
+            range.type = .custom
+            range.pageString = sender.stringValue
+        }
+        
+        self.viewModel.pageRangeAction(range: range) { success, model in
+            if success {
+                self.updatePDFView()
+            }
         }
     }
 

+ 198 - 0
PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/View/Pamphlet/KMPrintPamphletView.swift

@@ -102,4 +102,202 @@ class KMPrintPamphletView: KMBaseXibView, NSComboBoxDelegate {
         self.bookletSheetStartTextField.delegate = self
         self.bookletSheetEndTextField.delegate = self
     }
+    
+    override func reloadData() {
+        
+    }
+    
+    func updatePDFView(isPageChange: Bool = true) {
+        debugPrint("需要刷新PDFView")
+        self.reloadData()
+        if isPageChange {
+            self.pageSettingChangeAction?(self, self.viewModel.model)
+        } else {
+            self.printSettingChangeAction?(self, self.viewModel.model)
+        }
+    }
+}
+
+extension KMPrintPamphletView {
+    // Gap 步进器
+    @IBAction func bookletStepperClicked_PagesGap(_ sender: Any) {
+        let value: CGFloat = bookletPagesGapStepper.floatValue.cgFloat
+        self.viewModel.pamphletPagesGapChangeAction(value: value) { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        }
+    }
+
+    // 自动旋转
+    @IBAction func bookletButtonClicked_AutoRotatePage(_ sender: NSButton) {
+        
+        self.viewModel.autoRotateChangeAction(isRotate: sender.state == .on) { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        }
+    }
+
+    // 反转顺序
+    @IBAction func bookletButtonClicked_ReversePages(_ sender: NSButton) {
+        self.viewModel.printReverseAction(isSelect: sender.state == .on) { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        }
+    }
+
+    // PageRange ComboBox 点击
+    @IBAction func comboBoxClick_PageRanage(_ sender: NSComboBox) {
+        var range: KMPrintPageRange = KMPrintPageRange()
+        if sender.indexOfSelectedItem == 0 ||
+            sender.indexOfSelectedItem == 1 ||
+            sender.indexOfSelectedItem == 2 {
+            if sender.indexOfSelectedItem == 0 {
+                range.type = .allPage
+            } else if sender.indexOfSelectedItem == 1 {
+                range.type = .oddPage
+            } else if sender.indexOfSelectedItem == 2 {
+                range.type = .evenPage
+            }
+            
+            sender.delegate = nil
+            sender.isEditable = false
+        } else if sender.indexOfSelectedItem == 3 {
+            sender.delegate = self
+            sender.stringValue = ""
+            sender.isEditable = true
+            
+            window?.makeFirstResponder(sender)
+            
+            range.type = .custom
+            range.pageString = sender.stringValue
+        }
+        
+        self.viewModel.pageRangeAction(range: range) { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        }
+    }
+    
+    @IBAction func commentsAndFormsButtonAction(_ sender: NSComboBox) {
+        var type: KMPrintContentType = .document
+        if sender.indexOfSelectedItem == 0 {
+            type = .document
+        } else if sender.indexOfSelectedItem == 1 {
+            type = .documentAndMarkup
+        } else if sender.indexOfSelectedItem == 2 {
+            type = .documentAndStamp
+        }
+        
+        self.viewModel.printContentAction(type: type, completion: { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        })
+    }
+    
+    @IBAction func bindingButtonAction(_ sender: NSComboBox) {
+        let type: KMPrintPageOperation.Pamphlet.BookbindingType = KMPrintPageOperation.Pamphlet.BookbindingType(rawValue: sender.stringValue) ?? .left
+
+        self.viewModel.pamphletBindingChangeAction(type: type, completion: { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        })
+    }
+    
+    @IBAction func subsetButtonAction(_ sender: NSComboBox) {
+        let type: KMPrintPageOperation.Pamphlet.PamphletType = KMPrintPageOperation.Pamphlet.PamphletType(rawValue: sender.stringValue) ?? .doubleSided
+        
+        self.viewModel.pamphletSubsetChangeAction(type: type, completion: { success, model in
+            if success {
+                self.updatePDFView()
+            }
+        })
+    }
+    
+    @IBAction func pageSizeButtonAction(_ sender: NSComboBox) {
+        let type = KMPrintPaperInfo.KMPaperType(rawValue: sender.stringValue) ?? .A4
+        self.viewModel.printPaperTypeAction(type: type, completion: { success, model in
+            if success {
+                self.updatePDFView(isPageChange: false)
+            }
+        })
+    }
+    
+    @IBAction func unitButtonAction(_ sender: NSComboBox) {
+        var unit: KMPrintPaperInfoUnit = .mm
+        if sender.indexOfSelectedItem == 1 {
+            unit = .mm
+        } else if sender.indexOfSelectedItem == 0 {
+            unit = .cm
+        } else {
+            unit = .in
+        }
+        
+        self.viewModel.printUnitChangeAction(unit: unit) { success, model in
+            if success {
+                self.updatePDFView(isPageChange: false)
+            }
+        }
+    }
+    
+}
+
+extension KMPrintPamphletView {
+    @objc func controlTextDidChange(_ obj: Notification) {
+        guard let object = obj.object as? NSTextField else {
+            return
+        }
+
+        if object.isEqual(self.bookletSheetStartTextField) {
+            if let floatValue = Float(self.bookletSheetStartTextField.stringValue) {
+                let string = self.bookletSheetStartTextField.formatter?.string(for: NSNumber(value: floatValue)) ?? ""
+                self.bookletSheetStartTextField.stringValue = string
+            }
+        } else if object.isEqual(self.bookletSheetEndTextField) {
+            if let floatValue = Float(self.bookletSheetEndTextField.stringValue) {
+                let string = self.bookletSheetEndTextField.formatter?.string(for: NSNumber(value: floatValue)) ?? ""
+                self.bookletSheetEndTextField.stringValue = string
+            }
+        }
+    }
+
+    @objc func controlTextDidEndEditing(_ obj: Notification) {
+        guard let object = obj.object as? NSTextField else {
+            return
+        }
+
+        let string = object.stringValue
+
+        if object.isEqual(self.bookletPageGapTextField) {
+            if let floatValue = Float(string), floatValue <= 0 {
+                self.bookletPageGapTextField.stringValue = "0"
+                self.bookletPagesGapStepper.floatValue = floatValue
+                
+                self.viewModel.pamphletPagesGapChangeAction(value: floatValue.cgFloat) { success, model in
+                    if success {
+                        self.updatePDFView()
+                    }
+                }
+            }
+        } else if object.isEqual(self.bookletSheetStartTextField) {
+            self.viewModel.pamphletSheetBeginChangeAction(value: Int(bookletSheetStartTextField.stringValue) ?? 0) { success, model in
+                if success {
+                    self.updatePDFView()
+                }
+            }
+        } else if object.isEqual(self.bookletSheetEndTextField) {
+            self.viewModel.pamphletSheetEndChangeAction(value: Int(bookletSheetEndTextField.stringValue) ?? 0) { success, model in
+                if success {
+                    self.updatePDFView()
+                }
+            }
+        } else if object.isEqual(self.bookletPageRangeComboBox) {
+            
+        }
+    }
 }

+ 50 - 0
PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/View/Pamphlet/KMPrintPamphletView.xib

@@ -60,6 +60,9 @@
                         <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
                         <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                     </comboBoxCell>
+                    <connections>
+                        <action selector="unitButtonAction:" target="-2" id="bTQ-LG-aN2"/>
+                    </connections>
                 </comboBox>
                 <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="UMu-vN-WCE">
                     <rect key="frame" x="14" y="334" width="68" height="17"/>
@@ -83,6 +86,9 @@
                         <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
                         <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                     </comboBoxCell>
+                    <connections>
+                        <action selector="pageSizeButtonAction:" target="-2" id="53x-zW-nIL"/>
+                    </connections>
                 </comboBox>
                 <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="8PA-Nt-J57">
                     <rect key="frame" x="14" y="242" width="99" height="17"/>
@@ -122,6 +128,9 @@
                         <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
                         <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                     </comboBoxCell>
+                    <connections>
+                        <action selector="subsetButtonAction:" target="-2" id="TPJ-2B-CIC"/>
+                    </connections>
                 </comboBox>
                 <comboBox focusRingType="none" verticalHuggingPriority="750" allowsExpansionToolTips="YES" translatesAutoresizingMaskIntoConstraints="NO" id="pTG-Ps-mV4">
                     <rect key="frame" x="70" y="174" width="104" height="22"/>
@@ -134,6 +143,9 @@
                         <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
                         <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                     </comboBoxCell>
+                    <connections>
+                        <action selector="bindingButtonAction:" target="-2" id="Z71-ls-X4O"/>
+                    </connections>
                 </comboBox>
                 <textField focusRingType="none" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Anh-N3-yNf">
                     <rect key="frame" x="322" y="175" width="50" height="21"/>
@@ -168,6 +180,9 @@
                         <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
                         <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                     </comboBoxCell>
+                    <connections>
+                        <action selector="comboBoxClick_PageRanage:" target="-2" id="LwM-hl-hWd"/>
+                    </connections>
                 </comboBox>
                 <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="3qe-q8-N2W">
                     <rect key="frame" x="14" y="207" width="78" height="16"/>
@@ -209,6 +224,9 @@
                 <stepper horizontalHuggingPriority="750" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="x6b-Xn-y0s">
                     <rect key="frame" x="369" y="171" width="19" height="28"/>
                     <stepperCell key="cell" continuous="YES" alignment="left" increment="0.10000000000000001" maxValue="1000" doubleValue="1" id="gjW-ES-9bR"/>
+                    <connections>
+                        <action selector="bookletStepperClicked_PagesGap:" target="-2" id="4na-QN-FH4"/>
+                    </connections>
                 </stepper>
                 <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="IaC-Nu-0SW">
                     <rect key="frame" x="383" y="177" width="27" height="16"/>
@@ -224,6 +242,9 @@
                         <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
                         <font key="font" metaFont="system"/>
                     </buttonCell>
+                    <connections>
+                        <action selector="bookletButtonClicked_ReversePages:" target="-2" id="3tf-Mv-Y8k"/>
+                    </connections>
                 </button>
                 <comboBox focusRingType="none" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="QUM-ac-abF">
                     <rect key="frame" x="144" y="141" width="184" height="23"/>
@@ -235,6 +256,9 @@
                         <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
                         <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                     </comboBoxCell>
+                    <connections>
+                        <action selector="commentsAndFormsButtonAction:" target="-2" id="GnV-Z3-QRU"/>
+                    </connections>
                 </comboBox>
                 <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="749" translatesAutoresizingMaskIntoConstraints="NO" id="LiI-id-us0">
                     <rect key="frame" x="14" y="145" width="128" height="16"/>
@@ -250,6 +274,9 @@
                         <behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
                         <font key="font" metaFont="system"/>
                     </buttonCell>
+                    <connections>
+                        <action selector="bookletButtonClicked_AutoRotatePage:" target="-2" id="bCZ-rN-U2t"/>
+                    </connections>
                 </button>
                 <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="hus-Qh-0Hg">
                     <rect key="frame" x="229" y="302" width="11" height="16"/>
@@ -291,6 +318,29 @@
                         <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
                     </textFieldCell>
                 </textField>
+                <scrollView fixedFrame="YES" borderType="none" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" hasVerticalScroller="NO" usesPredominantAxisScrolling="NO" horizontalScrollElasticity="none" translatesAutoresizingMaskIntoConstraints="NO" id="WjR-xu-nig">
+                    <rect key="frame" x="202" y="314" width="183" height="96"/>
+                    <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
+                    <clipView key="contentView" drawsBackground="NO" id="gjt-dW-gr6">
+                        <rect key="frame" x="0.0" y="0.0" width="183" height="96"/>
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <subviews>
+                            <view id="rN9-Rb-JgQ">
+                                <rect key="frame" x="0.0" y="0.0" width="168" height="81"/>
+                                <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                            </view>
+                        </subviews>
+                        <color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.0" colorSpace="custom" customColorSpace="sRGB"/>
+                    </clipView>
+                    <scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" horizontal="YES" id="dd2-gY-3fN">
+                        <rect key="frame" x="-100" y="-100" width="183" height="15"/>
+                        <autoresizingMask key="autoresizingMask"/>
+                    </scroller>
+                    <scroller key="verticalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="NO" id="qlt-D0-xHe">
+                        <rect key="frame" x="-100" y="-100" width="15" height="81"/>
+                        <autoresizingMask key="autoresizingMask"/>
+                    </scroller>
+                </scrollView>
             </subviews>
             <constraints>
                 <constraint firstItem="8PA-Nt-J57" firstAttribute="leading" secondItem="vBR-Oh-oHi" secondAttribute="leading" id="0uq-Y4-lyt"/>

+ 57 - 6
PDF Office/PDF Master/Class/PDFTools/Print/View/PrintSettingView/ViewModel/KMPrintViewModel.swift

@@ -160,6 +160,12 @@ extension KMPrintViewModel {
         
         completion(true, model)
     }
+    
+    func autoRotateChangeAction(isRotate: Bool, completion: KMPrintViewModelCompletion) {
+        self.model.page.operation.isAutoRotate = isRotate
+        
+        completion(true, model)
+    }
 }
 
 //Poster
@@ -218,12 +224,6 @@ extension KMPrintViewModel {
         completion(true, model)
     }
     
-    func multipageAutoRotateChangeAction(isRotate: Bool, completion: KMPrintViewModelCompletion) {
-        self.model.page.operation.multipage.isAutoRotate = isRotate
-        
-        completion(true, model)
-    }
-    
     func multipageEdgeInsetChangeAction(edgeInset: NSEdgeInsets, completion: KMPrintViewModelCompletion) {
         self.model.paper.info.inset = edgeInset
         
@@ -261,3 +261,54 @@ extension KMPrintViewModel {
         completion(true, model)
     }
 }
+
+extension KMPrintViewModel {
+    
+    func pamphletPagesGapChangeAction(value: CGFloat, completion: KMPrintViewModelCompletion) {
+        
+    }
+    
+    func pamphletBindingChangeAction(type: KMPrintPageOperation.Pamphlet.BookbindingType , completion: KMPrintViewModelCompletion) {
+        if type == self.model.page.operation.pamphlet.bookbindingType {
+            completion(false, nil)
+            return
+        }
+        
+        self.model.page.operation.pamphlet.bookbindingType = type
+        
+        completion(true, model)
+    }
+    
+    func pamphletSubsetChangeAction(type: KMPrintPageOperation.Pamphlet.PamphletType , completion: KMPrintViewModelCompletion) {
+        if type == self.model.page.operation.pamphlet.type {
+            completion(false, nil)
+            return
+        }
+        
+        self.model.page.operation.pamphlet.type = type
+        
+        completion(true, model)
+    }
+    
+    func pamphletSheetBeginChangeAction(value: Int, completion: KMPrintViewModelCompletion)  {
+        if value == self.model.page.operation.pamphlet.pageIndex  {
+            completion(false, nil)
+            return
+        }
+        
+        self.model.page.operation.pamphlet.pageIndex = value
+        
+        completion(true, model)
+    }
+    
+    func pamphletSheetEndChangeAction(value: Int, completion: KMPrintViewModelCompletion)  {
+        if value == self.model.page.operation.pamphlet.toPageIndex  {
+            completion(false, nil)
+            return
+        }
+        
+        self.model.page.operation.pamphlet.toPageIndex = value
+        
+        completion(true, model)
+    }
+}

+ 279 - 274
PDF Office/PDF Master/Class/PDFTools/Snapshot/View/KMSnapshotPDFView.swift

@@ -14,12 +14,10 @@ class KMSnapshotPDFView: CPDFView {
         get {
             if (self._scalePopUpButton == nil) {
                 
-//                NSScrollView *scrollView = [self scrollView];
-                let scrollView = self.enclosingScrollView
+                let scrollView = self.documentView()
                 scrollView?.hasHorizontalScroller = true
                 
                 // create it
-//                scalePopUpButton = [[NSPopUpButton allocWithZone:[self zone]] initWithFrame:NSMakeRect(0.0, 0.0, 1.0, 1.0) pullsDown:NO];
                 let scalePopUpButton_ = NSPopUpButton(frame: NSMakeRect(0.0, 0.0, 1.0, 1.0), pullsDown: false)
                 scalePopUpButton_.cell?.controlSize = .small
                 self._scalePopUpButton = scalePopUpButton_
@@ -45,9 +43,7 @@ class KMSnapshotPDFView: CPDFView {
                 
                 // fill it
                 for i in 0 ..< numberOfDefaultItems {
-//                for (cnt = 0; cnt < numberOfDefaultItems; cnt++) {
                     label = Bundle.main.localizedString(forKey: self._SKDefaultScaleMenuLabels[i], value: "", table: "ZoomValues")
-//                    width = NSWidth([label boundingRectWithSize:size options:0 attributes:attrs]);
                     width = NSWidth(label.boundingRect(with: size, options: NSString.DrawingOptions(rawValue: 0), attributes: attrs))
                     if (width > maxWidth) {
                         maxWidth = width
@@ -67,7 +63,6 @@ class KMSnapshotPDFView: CPDFView {
                 // Make sure the popup is big enough to fit the largest cell
                 scalePopUpButton_.selectItem(at: maxIndex)
                 scalePopUpButton_.sizeToFit()
-//                [scalePopUpButton setFrameSize:];
                 scalePopUpButton_.setFrameSize(NSMakeSize(NSWidth(scalePopUpButton_.frame) - CONTROL_WIDTH_OFFSET, CONTROL_HEIGHT))
 //
 //                // select the appropriate item, adjusting the scaleFactor if necessary
@@ -105,6 +100,8 @@ class KMSnapshotPDFView: CPDFView {
     private let _SKMinDefaultScaleMenuFactor = 0.1
     private let _SKDefaultScaleMenuFactorsCount = 23
     
+    private let SKPDFContentViewChangedNotification = "SKPDFContentViewChangedNotification"
+    
     deinit {
         KMPrint("KMSnapshotPDFView deinit.")
         
@@ -123,84 +120,174 @@ class KMSnapshotPDFView: CPDFView {
         self._commonInitialization()
     }
     
+    override func layout() {
+        super.layout()
+        
+        let scrollView = self.documentView()
+        let clipView = scrollView?.contentView
+//        KMPrint(scrollView?.frame)
+//        KMPrint(clipView?.frame)
+        scrollView?.frame = self.bounds
+        
+    }
+    
     override func draw(_ dirtyRect: NSRect) {
         super.draw(dirtyRect)
 
         // Drawing code here.
     }
     
-
+    @objc func handlePDFViewFrameChangedNotification(_ notification: NSNotification) {
+        if self.autoFits {
+            let clipView = self.documentView().contentView
+            let clipRect = self.convert(clipView.visibleRect, from: clipView)
+            var rect = self.convert(self.autoFitRect, from: self.autoFitPage)
+            
+            let factor = fmin(NSWidth(clipRect) / NSWidth(rect), NSHeight(clipRect) / NSHeight(rect))
+            rect = self.convert(NSInsetRect(rect, 0.5 * (NSWidth(rect) - NSWidth(clipRect) / factor), 0.5 * (NSHeight(rect) - NSHeight(clipRect) / factor)), to: self.autoFitPage)
+            super.scaleFactor = factor * self.scaleFactor
+            self.go(to: rect, on: self.autoFitPage)
+        }
+    }
     
-    /*
-     #define SKPDFContentViewChangedNotification @"SKPDFContentViewChangedNotification"
-
-     - (void)handlePDFViewFrameChangedNotification:(NSNotification *)notification {
-         if ([self autoFits]) {
-             NSView *clipView = [[self scrollView] contentView];
-             NSRect clipRect = [self convertRect:[clipView visibleRect] fromView:clipView];
-             NSRect rect = [self convertRect:autoFitRect fromPage:autoFitPage];
-             CGFloat factor = fmin(NSWidth(clipRect) / NSWidth(rect), NSHeight(clipRect) / NSHeight(rect));
-             rect = [self convertRect:NSInsetRect(rect, 0.5 * (NSWidth(rect) - NSWidth(clipRect) / factor), 0.5 * (NSHeight(rect) - NSHeight(clipRect) / factor)) toPage:autoFitPage];
-             [super setScaleFactor:factor * [self scaleFactor]];
-             [self goToRect:rect onPage:autoFitPage];
-         }
-     }
-
-     - (void)handlePDFContentViewFrameChangedDelayedNotification:(NSNotification *)notification {
-         if ([self inLiveResize] == NO && [[self window] isZoomed] == NO)
-             [self resetAutoFitRectIfNeeded];
-     }
-
-     - (void)handlePDFContentViewFrameChangedNotification:(NSNotification *)notification {
-         if ([self inLiveResize] == NO && [[self window] isZoomed] == NO) {
-             NSNotification *note = [NSNotification notificationWithName:SKPDFContentViewChangedNotification object:self];
-             [[NSNotificationQueue defaultQueue] enqueueNotification:note postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName forModes:nil];
-         }
-     }
-
-     - (void)handlePDFViewScaleChangedNotification:(NSNotification *)notification {
-         if ([self autoFits] == NO)
-             [self setScaleFactor:fmax([self scaleFactor], SKMinDefaultScaleMenuFactor) adjustPopup:YES];
-     }
-     - (void)setAutoScales:(BOOL)newAuto {}
-
-     - (IBAction)zoomIn:(id)sender{
-         if([self autoFits]){
-             [super zoomIn:sender];
-             [self setAutoFits:NO adjustPopup:YES];
-         }else{
-             NSUInteger numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
-             NSUInteger i = [self lowerIndexForScaleFactor:[self scaleFactor]];
-             if (i < numberOfDefaultItems - 1) i++;
-             [self setScaleFactor:SKDefaultScaleMenuFactors[i]];
-         }
-     }
-
-     - (IBAction)zoomOut:(id)sender{
-         if([self autoFits]){
-             [super zoomOut:sender];
-             [self setAutoFits:NO adjustPopup:YES];
-         }else{
-             NSUInteger i = [self upperIndexForScaleFactor:[self scaleFactor]];
-             if (i > 1) i--;
-             [self setScaleFactor:SKDefaultScaleMenuFactors[i]];
-         }
-     }
+    @objc func handlePDFContentViewFrameChangedDelayedNotification(_ notification: NSNotification) {
+        if self.inLiveResize == false && (self.window?.isZoomed ?? false) == false {
+            self._resetAutoFitRectIfNeeded()
+        }
+    }
+    
+    @objc func handlePDFContentViewFrameChangedNotification(_ notification: NSNotification) {
+        if self.inLiveResize == false && (self.window?.isZoomed ?? false) == false {
+            let note = Notification(name: Notification.Name(SKPDFContentViewChangedNotification), object: self)
+            NotificationQueue.default.enqueue(note, postingStyle: .whenIdle, coalesceMask: .onName, forModes: nil)
+        }
+    }
+    
+    @objc func handlePDFViewScaleChangedNotification(_ notification: NSNotification) {
+        if self.autoFits == false {
+            self._setScaleFactor(fmax(self.scaleFactor, _SKMinDefaultScaleMenuFactor), adjustPopup: true)
+        }
+    }
+    
+    func setAutoScales() {
+        
+    }
+    
+    @IBAction override func zoomIn(_ sender: Any?) {
+        if self.autoFits {
+            super.zoomIn(sender)
+            self._setAutoFits(false, adjustPopup: true)
+        } else {
+            let numberOfDefaultItems = _SKDefaultScaleMenuFactorsCount
+            var i = self._lowerIndex(for: self.scaleFactor)
+            if i < numberOfDefaultItems-1 {
+               i += 1
+            }
+            self._setScaleFactor(_SKDefaultScaleMenuFactors[Int(i)])
+        }
+    }
+    
+    @IBAction override func zoomOut(_ sender: Any?) {
+        if self.autoFits {
+            super.zoomOut(sender)
+            self._setAutoFits(false, adjustPopup: true)
+        } else {
+            var i = self._upperIndex(for: self.scaleFactor)
+            if i > 1 {
+                i -= 1
+            }
+            self._setScaleFactor(_SKDefaultScaleMenuFactors[Int(i)])
+        }
+    }
+    
+    override var canZoomIn: Bool {
+        if super.canZoomIn == false {
+            return false
+        }
+        let numberOfDefaultItems = _SKDefaultScaleMenuFactorsCount
+        let i = self._lowerIndex(for: self.scaleFactor)
+        return i < numberOfDefaultItems - 1
+    }
+    
+    override var canZoomOut: Bool {
+        if super.canZoomOut == false {
+            return false
+        }
+        let i = self._upperIndex(for: self.scaleFactor)
+        return i > 1
+    }
+    
+    override func go(to page: CPDFPage!) {
+        super.go(to: page)
+        
+        self._resetAutoFitRectIfNeeded()
+    }
+    
+    @objc func doAutoFit(_ sender: Any?) {
+        self.autoFits = true
+    }
+    
+    @objc func doActualSize(_ sender: Any?) {
+        self.scaleFactor = 1.0
+    }
+    
+    override func menu(for event: NSEvent) -> NSMenu? {
+        let selectionActions: NSSet = NSSet(objects: ["copy:", "_searchInSpotlight:", "_searchInGoogle:", "_searchInDictionary:", "_revealSelection:"])
+        var menu = super.menu(for: event)
+        if menu == nil {
+            menu = NSMenu()
+        }
+        
+        menu?.insertItem(.separator(), at: 0)
+        menu?.insertItem(withTitle: KMLocalizedString("Print", "Menu item title"), action: #selector(menuItemClick_Print), target: self, at: 0)
 
-     - (BOOL)canZoomIn{
-         if ([super canZoomIn] == NO)
-             return NO;
-         NSUInteger numberOfDefaultItems = SKDefaultScaleMenuFactorsCount;
-         NSUInteger i = [self lowerIndexForScaleFactor:[self scaleFactor]];
-         return i < numberOfDefaultItems - 1;
-     }
+        var item = menu?.insertItem(withTitle: KMLocalizedString("Export", "Menu item title"), action: nil, target: self, at: 0)
+        let subMenu = NSMenu()
+         
+        subMenu.addItem(title: KMLocalizedString("PNG", "Menu item title"), action: #selector(menuItemClick_ExportPNG), target: self)
+        subMenu.addItem(title: KMLocalizedString("JPG", "Menu item title"), action: #selector(menuItemClick_ExportJPG), target: self)
+        subMenu.addItem(title: KMLocalizedString("PDF", "Menu item title"), action: #selector(menuItemClick_ExportPDF), target: self)
+        item?.submenu = subMenu
 
-     - (BOOL)canZoomOut{
-         if ([super canZoomOut] == NO)
-             return NO;
-         NSUInteger i = [self upperIndexForScaleFactor:[self scaleFactor]];
-         return i > 1;
-     }
+        menu?.insertItem(.separator(), at: 0)
+        menu?.insertItem(withTitle: KMLocalizedString("Copy", "Menu item title"), action: #selector(menuItemClick_Copy), target: self, at: 0)
+        
+//        [self setCurrentSelection:RUNNING_AFTER(10_11) ? [[[PDFSelection alloc] initWithDocument:[self document]] autorelease] : nil];
+        self.currentSelection = CPDFSelection(document: self.document)
+        if let _menu = menu {
+            while (_menu.numberOfItems > 0) {
+                if let item = _menu.item(at: 0), item.action != nil {
+                    if item.isSeparatorItem || self.validateMenuItem(item) == false || selectionActions.contains(NSStringFromSelector(item.action!)) {
+                        menu?.removeItem(at: 0)
+                    } else {
+                        break
+                    }
+                } else {
+                    break
+                }
+            }
+        }
+        
+        if let i = menu?.indexOfItem(withTarget: self, andAction: NSSelectorFromString("_setAutoSize:")), i != -1 {
+            menu?.item(at: i)?.action = #selector(doAutoFit)
+        }
+        if let i = menu?.indexOfItem(withTarget: self, andAction: NSSelectorFromString("_setActualSize:")), i != -1 {
+            menu?.item(at: i)?.action = #selector(doActualSize)
+            var item = menu?.insertItem(withTitle: KMLocalizedString("Physical Size", "Menu item title"), action: #selector(doPhysicalSize), target: self, at: i + 1)
+//            item?.keyEquivalentModifierMask = [.alternate]
+//            [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
+//            [item setAlternate:YES];
+            item?.isAlternate = true
+        }
+        
+        return menu
+    }
+    
+    @objc func doPhysicalSize(_ sender: Any?) {
+//        [self setPhysicalScaleFactor:1.0];
+    }
+    
+    /*
 
      - (BOOL)canGoBack {
          if ([self respondsToSelector:@selector(currentHistoryIndex)] && minHistoryIndex > 0)
@@ -209,23 +296,6 @@ class KMSnapshotPDFView: CPDFView {
              return [super canGoBack];
      }
 
-     - (void)goToPage:(PDFPage *)aPage {
-         [super goToPage:aPage];
-         [self resetAutoFitRectIfNeeded];
-     }
-
-     - (void)doAutoFit:(id)sender {
-         [self setAutoFits:YES];
-     }
-
-     - (void)doActualSize:(id)sender {
-         [self setScaleFactor:1.0];
-     }
-
-     - (void)doPhysicalSize:(id)sender {
-         [self setPhysicalScaleFactor:1.0];
-     }
-
      // we don't want to steal the printDocument: action from the responder chain
      - (void)printDocument:(id)sender{}
 
@@ -233,65 +303,6 @@ class KMSnapshotPDFView: CPDFView {
          return aSelector != @selector(printDocument:) && [super respondsToSelector:aSelector];
      }
 
-     - (NSMenu *)menuForEvent:(NSEvent *)theEvent {
-         static NSSet *selectionActions = nil;
-         if (selectionActions == nil)
-             selectionActions = [[NSSet alloc] initWithObjects:@"copy:", @"_searchInSpotlight:", @"_searchInGoogle:", @"_searchInDictionary:", @"_revealSelection:", nil];
-         NSMenu *menu = [super menuForEvent:theEvent];
-         
-         [menu insertItem:[NSMenuItem separatorItem] atIndex:0];
-         [menu insertItemWithTitle:NSLocalizedString(@"Print", @"Menu item title") action:@selector(menuItemClick_Print:) target:self atIndex:0];
-         
-        NSMenuItem * item = [menu insertItemWithTitle:NSLocalizedString(@"Export", @"Menu item title") action:nil target:self atIndex:0];
-         NSMenu *subMenu = [NSMenu menu];
-         
-         [subMenu addItemWithTitle:NSLocalizedString(@"PNG", @"Menu item title") action:@selector(menuItemClick_ExportPNG:) target:self];
-         [subMenu addItemWithTitle:NSLocalizedString(@"JPG", @"Menu item title") action:@selector(menuItemClick_ExportJPG:) target:self];
-         [subMenu addItemWithTitle:NSLocalizedString(@"PDF", @"Menu item title") action:@selector(menuItemClick_ExportPDF:) target:self];
-         item.submenu = subMenu;
-
-         [menu insertItem:[NSMenuItem separatorItem] atIndex:0];
-         [menu insertItemWithTitle:NSLocalizedString(@"Copy", @"Menu item title") action:@selector(menuItemClick_Copy:) target:self atIndex:0];
-         
-         [self setCurrentSelection:RUNNING_AFTER(10_11) ? [[[PDFSelection alloc] initWithDocument:[self document]] autorelease] : nil];
-         while ([menu numberOfItems]) {
-             NSMenuItem *item = [menu itemAtIndex:0];
-             if ([item isSeparatorItem] || [self validateMenuItem:item] == NO || [selectionActions containsObject:NSStringFromSelector([item action])])
-                 [menu removeItemAtIndex:0];
-             else
-                 break;
-         }
-         
-         NSInteger i = [menu indexOfItemWithTarget:self andAction:NSSelectorFromString(@"_setAutoSize:")];
-         if (i != -1)
-             [[menu itemAtIndex:i] setAction:@selector(doAutoFit:)];
-         i = [menu indexOfItemWithTarget:self andAction:NSSelectorFromString(@"_setActualSize:")];
-         if (i != -1) {
-             [[menu itemAtIndex:i] setAction:@selector(doActualSize:)];
-             NSMenuItem *item = [menu insertItemWithTitle:NSLocalizedString(@"Physical Size", @"Menu item title") action:@selector(doPhysicalSize:) target:self atIndex:i + 1];
-             [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
-             [item setAlternate:YES];
-         }
-         
-         return menu;
-     }
-
-     - (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
-         if ([menuItem action] == @selector(doAutoFit:)) {
-             [menuItem setState:[self autoFits] ? NSOnState : NSOffState];
-             return YES;
-         } else if ([menuItem action] == @selector(doActualSize:)) {
-             [menuItem setState:fabs([self scaleFactor] - 1.0) < 0.1 ? NSOnState : NSOffState];
-             return YES;
-         } else if ([menuItem action] == @selector(doPhysicalSize:)) {
-             [menuItem setState:([self autoScales] || fabs([self physicalScaleFactor] - 1.0 ) > 0.01) ? NSOffState : NSOnState];
-             return YES;
-         } else if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd]) {
-             return [super validateMenuItem:menuItem];
-         }
-         return YES;
-     }
-
      #pragma mark Gestures
 
      - (void)beginGestureWithEvent:(NSEvent *)theEvent {
@@ -340,52 +351,57 @@ class KMSnapshotPDFView: CPDFView {
          else
              [[NSCursor openHandCursor] set];
      }
-
-     - (NSImage *)thumbnailWithSize:(CGFloat)size {
-         NSView *clipView = [[[self documentView] enclosingScrollView] contentView];
-         NSRect bounds = [self convertRect:[clipView bounds] fromView:clipView];
-         NSBitmapImageRep *imageRep = [self bitmapImageRepForCachingDisplayInRect:bounds];
-         NSAffineTransform *transform = nil;
-         NSSize thumbnailSize = thumbnailSize = bounds.size;
-         CGFloat shadowBlurRadius = 0.0;
-         CGFloat shadowOffset = 0.0;
-         NSImage *image;
-         
-         [self cacheDisplayInRect:bounds toBitmapImageRep:imageRep];
-         
-         bounds.origin = NSZeroPoint;
-         
-         if (size > 0.0) {
-             shadowBlurRadius = round(size / 32.0);
-             shadowOffset = -ceil(shadowBlurRadius * 0.75);
-             if (NSHeight(bounds) > NSWidth(bounds))
-                 thumbnailSize = NSMakeSize(round((size - 2.0 * shadowBlurRadius) * NSWidth(bounds) / NSHeight(bounds) + 2.0 * shadowBlurRadius), size);
-             else
-                 thumbnailSize = NSMakeSize(size, round((size - 2.0 * shadowBlurRadius) * NSHeight(bounds) / NSWidth(bounds) + 2.0 * shadowBlurRadius));
-             transform = [NSAffineTransform transform];
-             [transform translateXBy:shadowBlurRadius yBy:shadowBlurRadius - shadowOffset];
-             [transform scaleXBy:(thumbnailSize.width - 2.0 * shadowBlurRadius) / NSWidth(bounds) yBy:(thumbnailSize.height - 2.0 * shadowBlurRadius) / NSHeight(bounds)];
-         }
-         
-         image = [[[NSImage alloc] initWithSize:thumbnailSize] autorelease];
-         
-         [image lockFocus];
-         [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
-         [transform concat];
-         [NSGraphicsContext saveGraphicsState];
-         [[PDFView defaultPageBackgroundColor] set];
-         if (shadowBlurRadius > 0.0)
-             [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5] blurRadius:shadowBlurRadius yOffset:shadowOffset];
-         NSRectFill(bounds);
-         [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationDefault];
-         [NSGraphicsContext restoreGraphicsState];
-         [imageRep drawInRect:bounds];
-         [image unlockFocus];
-         
-         return image;
-     }
      */
     
+    func thumbnailWithSize(_ size: CGFloat) -> NSImage? {
+//        NSView *clipView = [[[self documentView] enclosingScrollView] contentView];
+        let clipView = self.documentView().contentView
+        var bounds = self.convert(clipView.bounds, from: clipView)
+        guard let imageRep = self.bitmapImageRepForCachingDisplay(in: bounds) else {
+            return nil
+        }
+        var transform: NSAffineTransform?
+        var thumbnailSize = bounds.size
+        var shadowBlurRadius = 0.0
+        var shadowOffset = 0.0
+        var image: NSImage?
+        
+        self.cacheDisplay(in: bounds, to: imageRep)
+        
+        bounds.origin = .zero
+        
+        if (size > 0.0) {
+            shadowBlurRadius = round(size / 32.0)
+            shadowOffset = -ceil(shadowBlurRadius * 0.75)
+            if (NSHeight(bounds) > NSWidth(bounds)) {
+                thumbnailSize = NSMakeSize(round((size - 2.0 * shadowBlurRadius) * NSWidth(bounds) / NSHeight(bounds) + 2.0 * shadowBlurRadius), size)
+            } else {
+                thumbnailSize = NSMakeSize(size, round((size - 2.0 * shadowBlurRadius) * NSHeight(bounds) / NSWidth(bounds) + 2.0 * shadowBlurRadius))
+            }
+            transform = NSAffineTransform()
+            transform?.translateX(by: shadowBlurRadius, yBy: shadowBlurRadius - shadowOffset)
+            transform?.scaleX(by: (thumbnailSize.width - 2.0 * shadowBlurRadius) / NSWidth(bounds), yBy: (thumbnailSize.height - 2.0 * shadowBlurRadius) / NSHeight(bounds))
+        }
+        
+        image = NSImage(size: thumbnailSize)
+        
+        image?.lockFocus()
+        NSGraphicsContext.current?.imageInterpolation = .high
+        transform?.concat()
+        NSGraphicsContext.saveGraphicsState()
+//        [[PDFView defaultPageBackgroundColor] set];
+//        if (shadowBlurRadius > 0.0) {
+//            [NSShadow setShadowWithColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5] blurRadius:shadowBlurRadius yOffset:shadowOffset];
+//        }
+        __NSRectFill(bounds)
+        NSGraphicsContext.current?.imageInterpolation = .default
+        NSGraphicsContext.restoreGraphicsState()
+        imageRep.draw(in: bounds)
+        image?.unlockFocus()
+        
+        return image
+    }
+    
     func resetHistory() {
 //        if ([self respondsToSelector:@selector(currentHistoryIndex)])
 //            minHistoryIndex = [self currentHistoryIndex];
@@ -395,7 +411,7 @@ class KMSnapshotPDFView: CPDFView {
     }
     
     // MARK: - Menu
-    func menuItemClick_Print(_ sender: AnyObject?) {
+    @objc func menuItemClick_Print(_ sender: AnyObject?) {
 //        NSImage * image = [self thumbnailWithSize:0.0];
 //
 //        PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
@@ -413,78 +429,52 @@ class KMSnapshotPDFView: CPDFView {
 //        [printOperation runOperationModalForWindow:self.window delegate:self didRunSelector:nil contextInfo:NULL];
     }
     
-    func menuItemClick_ExportPDF(_ sender: NSMenuItem) {
-//        NSImage * image = [self thumbnailWithSize:0.0];
-//
-//        PDFPage *page = [[[PDFPage alloc] initWithImage:image] autorelease];
-//        PDFDocument *pdfDocument = [[[PDFDocument alloc] init] autorelease];
-//        [pdfDocument insertPage:page atIndex:0];
-//
-//        NSSavePanel *savePanel = [NSSavePanel savePanel];
-//        savePanel.allowedFileTypes = @[@"pdf"];
-//        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
-//            if (result) {
-//                if ([pdfDocument writeToURL:savePanel.URL]) {
-//                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
-//                                     inFileViewerRootedAtPath:@""];
-//                }
-//            }
-//        }];
+    @objc func menuItemClick_ExportPDF(_ sender: NSMenuItem) {
+        guard let image = self.thumbnailWithSize(0) else {
+            return
+        }
+
+        let document = CPDFDocument()
+        document?.km_insert(image: image, at: 0)
+        
+        NSPanel.savePanel_pdf_success(self.window!, document: document) { url in
+            NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
+        }
     }
      
-    func menuItemClick_ExportJPG(_ sender: NSMenuItem) {
-//        NSImage * image = [self thumbnailWithSize:0.0];
-//        NSData *data = image.TIFFRepresentation;
-//        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
-//        [imageRep setSize:image.size];
-//        NSData *imageData = [imageRep representationUsingType:NSJPEGFileType properties:@{}];
-//
-//        NSSavePanel *savePanel = [NSSavePanel savePanel];
-//        savePanel.allowedFileTypes = @[@"jpg"];
-//        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
-//            if (result) {
-//                if ([imageData writeToURL:savePanel.URL atomically:YES]) {
-//                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
-//                                     inFileViewerRootedAtPath:@""];
-//                }
-//            }
-//        }];
-    }
-    
-    func menuItemClick_Copy(_ sender: AnyObject?) {
-//        NSPasteboardItem *pasteboardItem = [[[NSPasteboardItem alloc] init] autorelease];
-//        NSImage * image = [self thumbnailWithSize:0.0];
-//        NSData *tiffData = [image TIFFRepresentation];
-//        if (tiffData) {
-//            [pasteboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
-//            if (pasteboardItem){
-//                NSPasteboard *pboard = [NSPasteboard generalPasteboard];
-//                [pboard clearContents];
-//
-//                [pboard writeObjects:[NSArray arrayWithObject:pasteboardItem]];
-//            }
-//        }
+    @objc func menuItemClick_ExportJPG(_ sender: NSMenuItem) {
+        guard let image = self.thumbnailWithSize(0) else {
+            return
+        }
+        
+        NSPanel.savePanel_data_success(self.window!, imageData: image.jpgData(), allowedTypes: ["jpg"]) { url in
+            NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
+        }
+    }
+    
+    @objc func menuItemClick_Copy(_ sender: AnyObject?) {
+        guard let image = self.thumbnailWithSize(0) else {
+            return
+        }
+        if let tiffData = image.tiffRepresentation {
+            let pasteboardItem = NSPasteboardItem()
+            pasteboardItem.setData(tiffData, forType: .tiff)
+            let pboard = NSPasteboard.general
+            pboard.clearContents()
+            pboard.writeObjects([pasteboardItem])
+        }
     }
 
-    func menuItemClick_ExportPNG(_ sender: NSMenuItem) {
-//        NSImage * image = [self thumbnailWithSize:0.0];
-//
-//        NSData *data = image.TIFFRepresentation;
-//        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:data];
-//        [imageRep setSize:image.size];
-//        NSData *imageData = [imageRep representationUsingType:NSPNGFileType properties:@{}];
-//
-//        NSSavePanel *savePanel = [NSSavePanel savePanel];
-//        savePanel.allowedFileTypes = @[@"png"];
-//        [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
-//            if (result) {
-//                if ([imageData writeToURL:savePanel.URL atomically:YES]) {
-//                    [[NSWorkspace sharedWorkspace] selectFile:savePanel.URL.path
-//                                     inFileViewerRootedAtPath:@""];
-//                }
-//            }
-//        }];
+    @objc func menuItemClick_ExportPNG(_ sender: NSMenuItem) {
+        guard let image = self.thumbnailWithSize(0) else {
+            return
+        }
+        
+        NSPanel.savePanel_data_success(self.window!, imageData: image.pngData(), allowedTypes: ["png"]) { url in
+            NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
+        }
     }
+    
 }
 
 // MARK: - Private Methods
@@ -495,14 +485,10 @@ extension KMSnapshotPDFView {
         self.autoFitPage = nil
         self.autoFitRect = .zero
         
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
-//                                                     name:NSViewFrameDidChangeNotification object:self];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
-//                                                     name:NSViewBoundsDidChangeNotification object:self];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedNotification:)
-//                                                     name:NSViewBoundsDidChangeNotification object:[[self scrollView] contentView]];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFContentViewFrameChangedDelayedNotification:)
-//                                                     name:SKPDFContentViewChangedNotification object:self];
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.frameDidChangeNotification, object: self)
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.boundsDidChangeNotification, object: self)
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePDFContentViewFrameChangedNotification), name: NSView.boundsDidChangeNotification, object: self.documentView()?.contentView)
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePDFContentViewFrameChangedDelayedNotification), name: NSNotification.Name(SKPDFContentViewChangedNotification), object: self)
 //        if ([PDFView instancesRespondToSelector:@selector(magnifyWithEvent:)] == NO || [PDFView instanceMethodForSelector:@selector(magnifyWithEvent:)] == [NSView instanceMethodForSelector:@selector(magnifyWithEvent:)])
 //            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewScaleChangedNotification:)
 //                                                         name:PDFViewScaleChangedNotification object:self];
@@ -580,10 +566,9 @@ extension KMSnapshotPDFView {
     
     private func _resetAutoFitRectIfNeeded() {
         if self.autoFits {
-            let clipView = self.enclosingScrollView?.contentView
+            let clipView = self.documentView().contentView
             self.autoFitPage = self.currentPage()
-//            autoFitRect = [self convertRect:[self convertRect:[clipView visibleRect] fromView:clipView] toPage:autoFitPage];
-            let rect = self.convert(clipView?.visibleRect ?? .zero, from: clipView)
+            let rect = self.convert(clipView.visibleRect, from: clipView)
             self.autoFitRect = self.convert(rect, to: self.autoFitPage)
         }
     }
@@ -598,3 +583,23 @@ extension KMSnapshotPDFView {
         }
     }
 }
+
+extension KMSnapshotPDFView: NSMenuItemValidation {
+    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
+        if (menuItem.action == #selector(doAutoFit)) {
+            menuItem.state = self.autoFits ? .on : .off
+            return true
+        } else if (menuItem.action == #selector(doActualSize)) {
+            menuItem.state = fabs(self.scaleFactor - 1.0) < 0.1 ? .on : .off
+            return true
+        }
+//        else if (menuItem.action == #selector(doPhysicalSize)) {
+//            [menuItem setState:([self autoScales] || fabs([self physicalScaleFactor] - 1.0 ) > 0.01) ? NSOffState : NSOnState];
+//            return true
+//        }
+//        } else if ([[SKSnapshotPDFView superclass] instancesRespondToSelector:_cmd]) {
+//            return [super validateMenuItem:menuItem];
+//        }
+        return true
+    }
+}

+ 135 - 180
PDF Office/PDF Master/Class/PDFTools/Snapshot/Window/KMSnapshotWindowController.swift

@@ -35,47 +35,9 @@ class KMSnapshotWindowController: NSWindowController {
     var thumbnail: NSImage?
     var windowImage: NSImage?
     
-    /*
-     extern NSString *SKSnapshotCurrentSetupKey;
-
-     @property (nonatomic, readonly) NSUInteger pageIndex;
-     @property (nonatomic, readonly) BOOL hasWindow;
-     @property (nonatomic, readonly) NSDictionary *pageAndWindow;
-     @property (nonatomic, readonly) NSDictionary *currentSetup;
-
-     @property (nonatomic, readonly) NSAttributedString *thumbnailAttachment, *thumbnail512Attachment, *thumbnail256Attachment, *thumbnail128Attachment, *thumbnail64Attachment, *thumbnail32Attachment;
-
-     - (void)setPdfDocument:(PDFDocument *)pdfDocument goToPageNumber:(NSInteger)pageNum rect:(NSRect)rect scaleFactor:(CGFloat)factor autoFits:(BOOL)autoFits;
-     - (void)setPdfDocument:(PDFDocument *)pdfDocument setup:(NSDictionary *)setup;
-
-     - (BOOL)isPageVisible:(PDFPage *)page;
-
-     - (void)redisplay;
-
-     - (NSImage *)thumbnailWithSize:(CGFloat)size;
-
-     - (NSAttributedString *)thumbnailAttachmentWithSize:(CGFloat)size;
-
-     - (void)miniaturize;
-     - (void)deminiaturize;
-
-     - (void)handleDocumentDidUnlockNotification:(NSNotification *)notification;
-     - (void)handlePDFViewFrameChangedNotification:(NSNotification *)notification;
-     - (void)handleViewChangedNotification:(NSNotification *)notification;
-     - (void)handleDidAddRemoveAnnotationNotification:(NSNotification *)notification;
-     - (void)handleDidMoveAnnotationNotification:(NSNotification *)notification;
-
-     - (void)setNeedsDisplayInRect:(NSRect)rect ofPage:(PDFPage *)page;
-     - (void)setNeedsDisplayForAnnotation:(PDFAnnotation *)annotation onPage:(PDFPage *)page;
-
-     @end
-
-     */
-    
     /*
      #define EM_DASH_CHARACTER (unichar)0x2014
      NSString *SKSnapshotCurrentSetupKey = @"currentSetup";
-
      static char SKSnaphotWindowDefaultsObservationContext;
      */
     
@@ -133,13 +95,6 @@ class KMSnapshotWindowController: NSWindowController {
          return [NSSet setWithObjects:PAGELABEL_KEY, HASWINDOW_KEY, nil];
      }
 
-     // these should never be reached, but just to be sure
-
-     - (void)windowDidDeminiaturize:(NSNotification *)notification {
-         [self updateWindowLevel];
-         [self setHasWindow:YES];
-     }
-
      - (NSString *)windowTitleForDocumentDisplayName:(NSString *)displayName {
          return [NSString stringWithFormat:@"%@ %C %@", displayName, EM_DASH_CHARACTER, [NSString stringWithFormat:NSLocalizedString(@"Page %@", @""), [self pageLabel]]];
      }
@@ -166,7 +121,6 @@ class KMSnapshotWindowController: NSWindowController {
      }
 */
 
-
     @objc func handlePageChangedNotification(_ notification: NSNotification?) {
 //         [self setPageLabel:[[pdfView currentPage] displayLabel]];
         let label = "\(self.pdfView.currentPage().pageIndex()+1)"
@@ -246,11 +200,10 @@ class KMSnapshotWindowController: NSWindowController {
          NSView *clipView = [[[pdfView documentView] enclosingScrollView] contentView];
          return [pdfView convertRect:[pdfView convertRect:[clipView bounds] fromView:clipView] toPage:[pdfView currentPage]];
      }
-
-     - (NSUInteger)pageIndex {
-         return [[pdfView currentPage] pageIndex];
-     }
 */
+    func pageIndex() -> UInt {
+        return self.pdfView.currentPage().pageIndex()
+    }
     
     func pageAndWindow() -> NSDictionary {
         return [SKSnapshotPageCellLabelKey : self.pageLabel, SKSnapshotPageCellHasWindowKey : NSNumber(booleanLiteral: self.hasWindow)]
@@ -270,83 +223,57 @@ class KMSnapshotWindowController: NSWindowController {
          BOOL autoFits = [pdfView autoFits];
          return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInteger:[self pageIndex]], PAGE_KEY, NSStringFromRect(rect), RECT_KEY, [NSNumber numberWithDouble:[pdfView scaleFactor]], SCALEFACTOR_KEY, [NSNumber numberWithBool:autoFits], AUTOFITS_KEY, [NSNumber numberWithBool:[[self window] isVisible]], HASWINDOW_KEY, NSStringFromRect([[self window] frame]), WINDOWFRAME_KEY, nil];
      }
+ */
+    
+    // MARK: - Actions
 
-     #pragma mark Actions
-
-     - (IBAction)doGoToNextPage:(id)sender {
-         [pdfView goToNextPage:sender];
-     }
-
-     - (IBAction)doGoToPreviousPage:(id)sender {
-         [pdfView goToPreviousPage:sender];
-     }
+    @IBAction func doGoToNextPage(_ sender: AnyObject?) {
+        self.pdfView.goToNextPage(sender)
+    }
 
-     - (IBAction)doGoToFirstPage:(id)sender {
-         [pdfView goToFirstPage:sender];
-     }
+    @IBAction func doGoToPreviousPage(_ sender: AnyObject?) {
+        self.pdfView.goToPreviousPage(sender)
+    }
 
-     - (IBAction)doGoToLastPage:(id)sender {
-         [pdfView goToLastPage:sender];
-     }
+    @IBAction func doGoToFirstPage(_ sender: AnyObject?) {
+        self.pdfView.goToFirstPage(sender)
+    }
 
-     - (IBAction)doGoBack:(id)sender {
-         [pdfView goBack:sender];
-     }
+    @IBAction func doGoToLastPage(_ sender: AnyObject?) {
+        self.pdfView.goToLastPage(sender)
+    }
 
-     - (IBAction)doGoForward:(id)sender {
-         [pdfView goForward:sender];
-     }
+    @IBAction func doGoBack(_ sender: AnyObject?) {
+        self.pdfView.km_goBack(sender)
+    }
 
-     - (IBAction)doZoomIn:(id)sender {
-         [pdfView zoomIn:sender];
-     }
+    @IBAction func doGoForward(_ sender: AnyObject?) {
+        self.pdfView.km_goForward(sender)
+    }
 
-     - (IBAction)doZoomOut:(id)sender {
-         [pdfView zoomOut:sender];
-     }
+    @IBAction func doZoomIn(_ sender: AnyObject?) {
+        self.pdfView.zoomIn(sender)
+    }
 
-     - (IBAction)doZoomToPhysicalSize:(id)sender {
-         [pdfView setPhysicalScaleFactor:1.0];
-     }
+    @IBAction func doZoomOut(_ sender: AnyObject?) {
+        self.pdfView.zoomOut(sender)
+    }
 
-     - (IBAction)doZoomToActualSize:(id)sender {
-         [pdfView setScaleFactor:1.0];
-     }
+//    @IBAction func doZoomToPhysicalSize(_ sender: AnyObject?) {
+//        self.pdfv
+//    }
+//    - (IBAction):(id)sender {
+//        [pdfView setPhysicalScaleFactor:1.0];
+//    }
 
-     - (IBAction)toggleAutoScale:(id)sender {
-         [pdfView setAutoFits:[pdfView autoFits] == NO];
-     }
+    @IBAction func doZoomToActualSize(_ sender: AnyObject?) {
+        self.pdfView.scaleFactor = 1.0
+    }
 
-     - (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
-         SEL action = [menuItem action];
-         if (action == @selector(doGoToNextPage:)) {
-             return [pdfView canGoToNextPage];
-         } else if (action == @selector(doGoToPreviousPage:)) {
-             return [pdfView canGoToPreviousPage];
-         } else if (action == @selector(doGoToFirstPage:)) {
-             return [pdfView canGoToFirstPage];
-         } else if (action == @selector(doGoToLastPage:)) {
-             return [pdfView canGoToLastPage];
-         } else if (action == @selector(doGoBack:)) {
-             return [pdfView canGoBack];
-         } else if (action == @selector(doGoForward:)) {
-             return [pdfView canGoForward];
-         } else if (action == @selector(doZoomIn:)) {
-             return [pdfView canZoomIn];
-         } else if (action == @selector(doZoomOut:)) {
-             return [pdfView canZoomOut];
-         } else if (action == @selector(doZoomToActualSize:)) {
-             return fabs([pdfView scaleFactor] - 1.0 ) > 0.01;
-         } else if (action == @selector(doZoomToPhysicalSize:)) {
-             return fabs([pdfView physicalScaleFactor] - 1.0 ) > 0.01;
-         } else if (action == @selector(toggleAutoScale:)) {
-             [menuItem setState:[pdfView autoFits] ? NSOnState : NSOffState];
-             return YES;
-         }
-         return YES;
-     }
+    @IBAction func toggleAutoScale(_ sender: AnyObject?) {
+        self.pdfView.autoFits = !self.pdfView.autoFits
+    }
 
- */
     // MARK: - Thumbnails
 
     func thumbnailWithSize(_ size: CGFloat) -> NSImage? {
@@ -404,49 +331,31 @@ class KMSnapshotWindowController: NSWindowController {
          
          return image
      }
-    /*
 
-     - (NSAttributedString *)thumbnailAttachmentWithSize:(CGFloat)size {
-         NSImage *image = [self thumbnailWithSize:size];
-         
-         NSFileWrapper *wrapper = [[NSFileWrapper alloc] initRegularFileWithContents:[image TIFFRepresentation]];
-         NSString *filename = [NSString stringWithFormat:@"snapshot_page_%lu.tiff",(unsigned long)( [self pageIndex] + 1)];
-         [wrapper setFilename:filename];
-         [wrapper setPreferredFilename:filename];
-
-         NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper:wrapper];
-         [wrapper release];
-         NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachment];
-         [attachment release];
-         
-         return attrString;
-     }
-
-     - (NSAttributedString *)thumbnailAttachment {
-         return [self thumbnailAttachmentWithSize:0.0];
-     }
-
-     - (NSAttributedString *)thumbnail512Attachment {
-         return [self thumbnailAttachmentWithSize:512.0];
-     }
-
-     - (NSAttributedString *)thumbnail256Attachment {
-         return [self thumbnailAttachmentWithSize:256.0];
-     }
-
-     - (NSAttributedString *)thumbnail128Attachment {
-         return [self thumbnailAttachmentWithSize:128.0];
-     }
-
-     - (NSAttributedString *)thumbnail64Attachment {
-         return [self thumbnailAttachmentWithSize:64.0];
-     }
-
-     - (NSAttributedString *)thumbnail32Attachment {
-         return [self thumbnailAttachmentWithSize:32.0];
-     }
-
- */
+    func thumbnailAttachment() -> NSAttributedString? {
+        return self._thumbnailAttachment(size: 0)
+    }
+    
+    func thumbnail512Attachment() -> NSAttributedString? {
+        return self._thumbnailAttachment(size: 512)
+    }
+    
+    func thumbnail256Attachment() -> NSAttributedString? {
+        return self._thumbnailAttachment(size: 256)
+    }
+    
+    func thumbnail128Attachment() -> NSAttributedString? {
+        return self._thumbnailAttachment(size: 128)
+    }
+    
+    func thumbnail64Attachment() -> NSAttributedString? {
+        return self._thumbnailAttachment(size: 64)
+    }
+    
+    func thumbnail32Attachment() -> NSAttributedString? {
+        return self._thumbnailAttachment(size: 32)
+    }
+    
     // MARK: - Miniaturize / Deminiaturize
 
     func miniaturizedRectForDockingRect(_ dockRect: NSRect) -> NSRect {
@@ -612,27 +521,19 @@ class KMSnapshotWindowController: NSWindowController {
 
         self.window?.makeFirstResponder(self.pdfView)
         self.handlePageChangedNotification(nil)
-//
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePageChangedNotification:)
-//                                                     name:PDFViewPageChangedNotification object:pdfView];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDocumentDidUnlockNotification:)
-//                                                     name:PDFDocumentDidUnlockNotification object:[pdfView document]];
-//
-//        NSView *clipView = [[[pdfView documentView] enclosingScrollView] contentView];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
-//                                                     name:NSViewFrameDidChangeNotification object:clipView];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePDFViewFrameChangedNotification:)
-//                                                     name:NSViewBoundsDidChangeNotification object:clipView];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleViewChangedNotification:)
-//                                                     name:SKSnapshotViewChangedNotification object:self];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDidAddRemoveAnnotationNotification:)
-//                                                     name:SKPDFViewDidAddAnnotationNotification object:nil];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDidAddRemoveAnnotationNotification:)
-//                                                     name:SKPDFViewDidRemoveAnnotationNotification object:nil];
-//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDidMoveAnnotationNotification:)
-//                                                     name:SKPDFViewDidMoveAnnotationNotification object:nil];
+
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.pdfView)
+        NotificationCenter.default.addObserver(self, selector: #selector(handleDocumentDidUnlockNotification), name: NSNotification.Name.CPDFDocumentDidUnlock, object: self.pdfView.document)
+
+        let clipView = self.pdfView.documentView().contentView
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.frameDidChangeNotification, object: clipView)
+        NotificationCenter.default.addObserver(self, selector: #selector(handlePDFViewFrameChangedNotification), name: NSView.boundsDidChangeNotification, object: clipView)
+        NotificationCenter.default.addObserver(self, selector: #selector(handleViewChangedNotification), name: NSNotification.Name(SKSnapshotViewChangedNotification), object: self)
+//        NotificationCenter.default.addObserver(self, selector: #selector(handleDidAddRemoveAnnotationNotification), name: SKPDFViewDidAddAnnotationNotification, object: nil)
+//        NotificationCenter.default.addObserver(self, selector: #selector(handleDidAddRemoveAnnotationNotification), name: SKPDFViewDidRemoveAnnotationNotification, object: nil)
+//        NotificationCenter.default.addObserver(self, selector: #selector(handleDidMoveAnnotationNotification), name: SKPDFViewDidMoveAnnotationNotification, object: nil)
         self.perform(#selector(notifiyDidFinishSetup), with: nil, afterDelay: SMALL_DELAY)
-//
+
         if self.hasWindow {
             self.showWindow(nil)
         }
@@ -685,9 +586,11 @@ class KMSnapshotWindowController: NSWindowController {
         
         self.pdfView.go(toPageIndex: pageNum, animated: false)
         
-        if (autoFits) {
-            self.pdfView.autoFits = autoFits
-        }
+//        if (autoFits) {
+//            self.pdfView.autoFits = autoFits
+//        }
+        self.pdfView.autoFits = true
+        self.pdfView.autoScales = true
         
         // Delayed to allow PDFView to finish its bookkeeping
         // fixes bug of apparently ignoring the point but getting the page right.
@@ -705,6 +608,20 @@ extension KMSnapshotWindowController {
         self.window?.level = onTop ? .floating : .normal
         self.window?.hidesOnDeactivate = onTop
     }
+    
+    private func _thumbnailAttachment(size: CGFloat) -> NSAttributedString? {
+        guard let imageData = self.thumbnailWithSize(size)?.tiffRepresentation else {
+            return nil
+        }
+        
+        let wrapper = FileWrapper(regularFileWithContents: imageData)
+        let filename = String(format: "snapshot_page_%lu.tiff", self.pageIndex() + 1)
+        wrapper.filename = filename
+        wrapper.preferredFilename = filename
+        let attachment = NSTextAttachment(fileWrapper: wrapper)
+            
+        return NSAttributedString(attachment: attachment)
+    }
 }
 
 extension KMSnapshotWindowController: NSWindowDelegate {
@@ -724,4 +641,42 @@ extension KMSnapshotWindowController: NSWindowDelegate {
         self.window?.orderOut(nil)
         self.hasWindow = false
     }
+    
+    func windowDidDeminiaturize(_ notification: Notification) {
+        self._updateWindowLevel()
+        self.hasWindow = true
+    }
+}
+
+extension KMSnapshotWindowController: NSMenuItemValidation {
+    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
+        let action = menuItem.action
+        if (action == #selector(doGoToNextPage)) {
+            return self.pdfView.canGoToNextPage()
+        } else if (action == #selector(doGoToPreviousPage)) {
+            return self.pdfView.canGoToPreviousPage()
+        } else if (action == #selector(doGoToFirstPage)) {
+            return self.pdfView.canGoToFirstPage()
+        } else if (action == #selector(doGoToLastPage)) {
+            return self.pdfView.canGoToLastPage()
+        } else if (action == #selector(doGoBack)) {
+            return self.pdfView.km_canGoBack()
+        } else if (action == #selector(doGoForward)) {
+            return self.pdfView.km_canGoForward()
+        } else if (action == #selector(doZoomIn)) {
+            return self.pdfView.canZoomIn
+        } else if (action == #selector(doZoomOut)) {
+            return self.pdfView.canZoomOut
+        } else if (action == #selector(doZoomToActualSize)) {
+            return abs(pdfView.scaleFactor - 1.0 ) > 0.01
+        }
+//        else if (action == #selector(doZoomToPhysicalSize)) {
+//            return fabs(pdfView.physicalScaleFactor - 1.0 ) > 0.01
+//        }
+        else if (action == #selector(toggleAutoScale)) {
+            menuItem.state = self.pdfView.autoFits ? .on : .off
+            return true
+        }
+        return true
+    }
 }

+ 13 - 1
PDF Office/PDF Master/Class/PDFWindowController/Side/LeftSide/KMSegmentedControl.swift

@@ -155,7 +155,8 @@ class KMSegmentedControl: NSControl {
         
         self._segments.removeAll()
         for i in 0 ..< self.segmentCount {
-            let button = NSButton()
+            let button = KMCoverButton()
+            button.wantsLayer = true
             button.bezelStyle = .regularSquare
             button.isBordered = false
             button.imageScaling = .scaleProportionallyDown
@@ -166,6 +167,17 @@ class KMSegmentedControl: NSControl {
             button.action = #selector(_buttonAction)
             self.contentView?.addSubview(button)
             self._segments.append(button)
+            
+            button.coverAction = { [unowned self] cbtn, action in
+                if self.selectedSegment == cbtn.tag {
+                    return
+                }
+                if action == .enter {
+                    cbtn.layer?.backgroundColor = NSColor(hex: "DFE1E5").cgColor
+                } else if action == .exit {
+                    cbtn.layer?.backgroundColor = .clear
+                }
+            }
         }
     }
     

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

@@ -2327,7 +2327,6 @@ import Cocoa
     
     func pdfListView(_ sender: CPDFListView!, showSnapshotAtPageNumber pageNum: Int, for rect: NSRect, scaleFactor: CGFloat, autoFits: Bool) {
         let swc = KMSnapshotWindowController(windowNibName: "SnapshotWindow")
-//        [swc setDelegate:self];
         swc.delegate = self
         swc.setPdfDocument(self.listView.document, goToPageNumber: pageNum, rect: rect, scaleFactor: scaleFactor, autoFits: autoFits)
 //        [swc setForceOnTop:[self interactionMode] != SKNormalMode];