KMPDFEditViewController.swift 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  1. //
  2. // KMPDFEditViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/1/6.
  6. //
  7. typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set<IndexPath>) -> ()
  8. typealias KMIndexChooseBlock = (_ index: Int) -> Void
  9. class KMPDFEditViewController: KMPDFThumbViewBaseController {
  10. static let kNoPagesSelectedTipMessage = "No pages selected. Please select one or more pages first to organize."
  11. @IBOutlet weak var topBarBox: NSBox!
  12. @IBOutlet weak var contentBox: NSBox!
  13. @IBOutlet weak var thumbnailSizeView: NSView!
  14. @IBOutlet weak var zoomInButton: NSButton!
  15. @IBOutlet weak var zoomOutButton: NSButton!
  16. @IBOutlet weak var lineBoxView: NSView!
  17. var toolBar = KMPDFEditToolbar(frame: NSZeroRect)
  18. override var thumbnailView: KMPDFThumbnailView {
  19. get {
  20. if (super.thumbnailView is KMPageEditThumbnailView) {
  21. return super.thumbnailView
  22. }
  23. super.thumbnailView = KMPageEditThumbnailView()
  24. return super.thumbnailView
  25. }
  26. set {
  27. super.thumbnailView = newValue
  28. }
  29. }
  30. var pageEditThumbnailView: KMPageEditThumbnailView {
  31. get {
  32. return self.thumbnailView as! KMPageEditThumbnailView
  33. }
  34. }
  35. override var menuItems: [[KMPDFThumbViewMenu.Item]] {
  36. get {
  37. return [[.insert ,.extract], [.leftRotate, .rightRotate, .copy, .paste, .reverse],
  38. [.delete], [.share]]
  39. }
  40. }
  41. private var pdfDocument: CPDFDocument?
  42. var listView: CPDFView?
  43. var pageIsUpdate: Bool = true
  44. var selectedPages: [Int] = []
  45. private let defaultItemSize = NSMakeSize(215, 250)
  46. var itemSize: NSSize = NSMakeSize(215, 250)
  47. // index=1 双击退出;index=2 打印
  48. var itemClick: KMCommonClickBlock?
  49. private var _isEdited = false
  50. var isEdited: Bool {
  51. return self._isEdited
  52. }
  53. var documentEditedCallback: KMCommonBlock?
  54. var selectionDidChange: KMPDFEditViewControllerSelectionDidChange?
  55. internal var viewFirstAppear = true
  56. private var _listViewCurrentIndex: Int = 0
  57. var listViewCurrentIndex: Int {
  58. get {
  59. return self._listViewCurrentIndex
  60. }
  61. }
  62. private var fileAttri_: KMFileAttribute?
  63. private var popOver_: NSPopover?
  64. deinit {
  65. }
  66. required init?(coder: NSCoder) {
  67. super.init(coder: coder)
  68. }
  69. init(_ document: CPDFDocument) {
  70. super.init(nibName: "KMPDFEditViewController", bundle: nil)
  71. self.pdfDocument = document
  72. self.kmUndoManager = UndoManager()
  73. self.fileAttri_ = KMFileAttribute()
  74. self.fileAttri_?.password = document.password ?? ""
  75. self.fileAttri_?.filePath = document.documentURL.path
  76. }
  77. override func viewDidAppear() {
  78. super.viewDidAppear()
  79. let isLocked = self.pdfDocument?.isLocked ?? false
  80. let first = self.viewFirstAppear
  81. if (isLocked == false && self.viewFirstAppear) {
  82. self.viewFirstAppear = false
  83. if let doc = self.pdfDocument {
  84. self.thumbnailView.document = doc
  85. }
  86. self.thumbnailView.reloadData()
  87. }
  88. if let view = self.listView { // 存储阅读视图的当前页面索引
  89. self._listViewCurrentIndex = view.currentPageIndex
  90. }
  91. var item: Int = 0
  92. if (self.selectedPages.isEmpty) {
  93. let index = self.listView?.currentPageIndex ?? 0
  94. self.selectPages(indexs: IndexSet(integer: index))
  95. self.toolBar.setPageRangeString("\(index+1)")
  96. item = index
  97. } else {
  98. var indexs: IndexSet = []
  99. for pageIndex in self.selectedPages {
  100. let pageCnt = self.listView?.document?.pageCount ?? 0
  101. if (pageIndex < 0 || pageIndex >= pageCnt) {
  102. continue
  103. }
  104. indexs.insert(pageIndex)
  105. }
  106. self.selectPages(indexs: indexs)
  107. self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  108. item = indexs.sorted().last ?? 0
  109. }
  110. if first {
  111. let cnt = self.thumbnailView.document?.pageCount ?? 0
  112. if cnt > 0 {
  113. var ips = Set<IndexPath>()
  114. ips.insert(IndexPath(item: item, section: 0))
  115. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .bottom)
  116. }
  117. }
  118. self.view.window?.makeFirstResponder(self)
  119. self._showPDFEditDetails()
  120. }
  121. override func viewDidLoad() {
  122. super.viewDidLoad()
  123. self._isEdited = false
  124. // 显示拖放移动动效
  125. // self.thumbnailView.dragMoveEffectAnimated = true
  126. // self.thumbnailView.collectionView.backgroundColor(NSColor.km_init(hex: "#CED0D4"))
  127. self.thumbnailView.collectionView.wantsLayer = true
  128. // self.thumbnailView.collectionView.layer?.backgroundColor = KMAppearance.PDFViewBackgroundColor().cgColor
  129. if KMAppearance.isDarkMode() {
  130. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor
  131. } else {
  132. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor
  133. }
  134. self.thumbnailSizeView.wantsLayer = true
  135. self.thumbnailSizeView.layer?.backgroundColor = KMAppearance.Layout.b80Color().cgColor
  136. self.lineBoxView.wantsLayer = true
  137. self.lineBoxView.layer?.backgroundColor = KMAppearance.Layout.h2Color().cgColor
  138. var allowedFileTypes: [String] = []
  139. // if let _types = KMConvertPDFManager.supportFileType() {
  140. allowedFileTypes = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType()
  141. // } else {
  142. // allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
  143. // }
  144. self.thumbnailView.kmAllowedFileTypes = allowedFileTypes
  145. let toolBar = self.toolBar
  146. self.topBarBox.contentView = toolBar
  147. self.topBarBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  148. toolBar.itemClick = { [unowned self] item, index in
  149. guard let type = KMPageEditType(rawValue: index) else {
  150. if (index == KMPageEditType.insert_files) {
  151. self.insertFileAction()
  152. self.trackEvent(type: .insert, index: index)
  153. } else if (index == KMPageEditType.insert_blank_page) {
  154. self.insertBlankPageAction()
  155. self.trackEvent(type: .insert, index: index)
  156. } else if (index == KMPageEditType.insert_custom_page) {
  157. self.item_insertCustomPage(sender: nil)
  158. self.trackEvent(type: .insert, index: index)
  159. } else if (index == KMPageEditType.insert_fromImage) {
  160. self.item_insertFromImage(sender: nil)
  161. self.trackEvent(type: .insert, index: index)
  162. } else if (index == KMPageEditType.insert_fromClipboard) {
  163. self.item_insertFromClipboard(sender: nil)
  164. self.trackEvent(type: .insert, index: index)
  165. } else if (index == KMPageEditType.insert_fromScanner) {
  166. self.item_insertFromScanner(sender: nil)
  167. self.trackEvent(type: .insert, index: index)
  168. } else if (index == KMPageEditType.extract_selected_pages) {
  169. self.extractSelectPageItemAction()
  170. } else if (index == KMPageEditType.split_selected_pages) {
  171. self.splitMenuAction()
  172. }
  173. return
  174. }
  175. if (type == .leftRotate) {
  176. self.leftRotateAction()
  177. } else if (type == .rightRotate) {
  178. self.rightRotateAction()
  179. } else if (type == .zoomOut) {
  180. self.zoomOutButtonAction(sender: item?.zoomOutButton)
  181. } else if (type == .zoomIn) {
  182. self.zoomInButtonAction(sender: item?.zoomInButton)
  183. } else if (type == .extract) {
  184. self.extractAction()
  185. } else if (type == .replace) {
  186. self.replaceAction()
  187. } else if (type == .split) {
  188. self.splitAction()
  189. } else if (type == .reverse) {
  190. self.reverseAction()
  191. } else if (type == .delete) {
  192. self.deleteAction()
  193. } else if (type == .pageRange) {
  194. } else if (type == .insert) {
  195. self.trackEvent(type: .insert)
  196. } else if (type == .copy) {
  197. self.copyAction()
  198. } else if (type == .paste) {
  199. self.pasteAction()
  200. }
  201. }
  202. toolBar.pageRangeitemClick = { [weak self] type in
  203. self?.km_comboBoxSelectionDidChange(type)
  204. }
  205. toolBar.pageRangeValueDidChange = { [weak self] value, _ in
  206. if let data = self?.toolBar.pageRangeView {
  207. self?.km_controlTextDidEndEditing(data)
  208. }
  209. }
  210. let view = self.thumbnailView
  211. self.contentBox.contentView?.addSubview(view)
  212. view.frame = self.contentBox.contentView?.bounds ?? .zero
  213. view.autoresizingMask = [.width, .height]
  214. self.pageEditThumbnailView.delegate = self
  215. self.pageEditThumbnailView.selectionDidChange = { [weak self] selectedIndexs in
  216. guard let self = self else {
  217. return
  218. }
  219. self.selectionDidChange?(selectedIndexs)
  220. self.view.window?.makeFirstResponder(self)
  221. let enabled = (selectedIndexs.count > 0)
  222. for i in 0 ..< self.toolBar.toolBar.items.count {
  223. let item = self.toolBar.toolBar.items[i]
  224. if item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier
  225. || item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier {
  226. item.unEnabled = !enabled
  227. }
  228. }
  229. if (self.pageIsUpdate == false) {
  230. self.pageIsUpdate = true
  231. return
  232. }
  233. var indexs: Array<Int> = []
  234. for indexPath in selectedIndexs {
  235. indexs.append(indexPath.item)
  236. }
  237. indexs.sort(){$0 < $1}
  238. self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs))
  239. if self.listView != nil { // 存储阅读视图的当前页面索引
  240. if indexs.count != 0 {
  241. self._listViewCurrentIndex = indexs.last!
  242. }
  243. }
  244. }
  245. }
  246. override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
  247. super.interfaceThemeDidChanged(appearance)
  248. self.thumbnailView.collectionView.wantsLayer = true
  249. if KMAppearance.isDarkMode() {
  250. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor
  251. } else {
  252. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor
  253. }
  254. Task { @MainActor in
  255. let ips = self.thumbnailView.selectionIndexPaths
  256. self.thumbnailView.collectionView.reloadData()
  257. self.thumbnailView.selectionIndexPaths = ips
  258. }
  259. }
  260. override func keyDown(with event: NSEvent) {
  261. // super.keyDown(with: event)
  262. let cmd = event.modifierFlags.contains(.command)
  263. let shift = event.modifierFlags.contains(.shift)
  264. let code = event.keyCode
  265. let isLeft = code == 123
  266. let isUp = code == 126
  267. let isRight = code == 124
  268. let isDown = code == 125
  269. if cmd {
  270. if code == 0 { // cmd + a
  271. self.km_comboBoxSelectionDidChange(.all)
  272. return
  273. }
  274. // let ips = self.thumbnailView.selectionIndexPaths
  275. // let indexs = self.indexpathsToIndexs(indexpaths: ips)
  276. //// let idx = indexs.last ?? 0
  277. // var selectedIndexs = indexs
  278. // let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0)
  279. // let firstIdx = 0
  280. // let lastIdx = max(numberItems-1, 0)
  281. // if isLeft { // +
  282. // if self.isEmptySelection() {
  283. // selectedIndexs.insert(lastIdx)
  284. // } else {
  285. // if let idx = selectedIndexs.first, idx > 0 {
  286. // selectedIndexs.insert(idx-1)
  287. // }
  288. // }
  289. // } else if isRight { // -
  290. // if self.isEmptySelection() {
  291. // selectedIndexs.insert(firstIdx)
  292. // } else {
  293. // if let idx = selectedIndexs.last, idx < lastIdx {
  294. // selectedIndexs.insert(idx+1)
  295. // }
  296. // }
  297. // } else {
  298. // var numberPerLine = 0
  299. // let itemW = self.thumbnailView.itemSize.width
  300. // if itemW > 0 {
  301. // numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW)
  302. // }
  303. // if isUp {
  304. // if self.isEmptySelection() {
  305. // selectedIndexs.insert(lastIdx)
  306. // } else {
  307. // if let idx = selectedIndexs.first, idx > 0 {
  308. // selectedIndexs.insert(max(idx-numberPerLine, 0))
  309. // }
  310. // }
  311. // } else if isDown {
  312. // if self.isEmptySelection() {
  313. // selectedIndexs.insert(firstIdx)
  314. // } else {
  315. // if let idx = selectedIndexs.last, idx < lastIdx {
  316. // selectedIndexs.insert(min(idx+numberPerLine, lastIdx))
  317. // }
  318. // }
  319. // }
  320. // }
  321. //
  322. // if selectedIndexs.isEmpty == false {
  323. // let ips = self.indexsToIndexpaths(indexs: selectedIndexs)
  324. // self.thumbnailView.selectionIndexPaths = ips
  325. // self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  326. // }
  327. } else if shift {
  328. } else {
  329. let ips = self.thumbnailView.selectionIndexPaths
  330. let indexs = self.indexpathsToIndexs(indexpaths: ips)
  331. let idx = indexs.last ?? 0
  332. var selectedIndexs = IndexSet()
  333. let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0)
  334. let firstIdx = 0
  335. let lastIdx = max(numberItems-1, 0)
  336. if isLeft {
  337. if self.isEmptySelection() {
  338. selectedIndexs.insert(lastIdx)
  339. } else {
  340. if idx > 0 {
  341. selectedIndexs.insert(idx-1)
  342. }
  343. }
  344. } else if isRight {
  345. if self.isEmptySelection() {
  346. selectedIndexs.insert(firstIdx)
  347. } else {
  348. if idx < lastIdx {
  349. selectedIndexs.insert(idx+1)
  350. }
  351. }
  352. } else {
  353. var numberPerLine = 0
  354. let itemW = self.thumbnailView.itemSize.width
  355. if itemW > 0 {
  356. numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW)
  357. }
  358. if isUp {
  359. if self.isEmptySelection() {
  360. selectedIndexs.insert(lastIdx)
  361. } else {
  362. selectedIndexs.insert(max(idx-numberPerLine, 0))
  363. }
  364. } else if isDown {
  365. if self.isEmptySelection() {
  366. selectedIndexs.insert(firstIdx)
  367. } else {
  368. selectedIndexs.insert(min(idx+numberPerLine, lastIdx))
  369. }
  370. }
  371. }
  372. if selectedIndexs.isEmpty == false {
  373. let ips = self.indexsToIndexpaths(indexs: selectedIndexs)
  374. self.thumbnailView.selectionIndexPaths = ips
  375. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  376. }
  377. }
  378. }
  379. // MARK: Private Methods
  380. private func getSelecteIndex() -> Int {
  381. let index = self.getPasteIndex()
  382. if (index != NSNotFound) {
  383. return index
  384. }
  385. return 0
  386. }
  387. private func getSelectedPage() -> CPDFPage? {
  388. return self.pdfDocument?.page(at: UInt(getSelecteIndex()))
  389. }
  390. private func selectPages(indexs: IndexSet) {
  391. var indexpaths: Set<IndexPath> = []
  392. for index in indexs {
  393. indexpaths.insert(IndexPath(item: index, section: 0))
  394. }
  395. self.selectPages(indexpaths: indexpaths)
  396. }
  397. private func km_becomeFirstResponder() {
  398. DispatchQueue.main.async {
  399. self.view.window?.makeFirstResponder(self)
  400. }
  401. }
  402. fileprivate func dealPdfDocumentDidEditCallback(type: KMPageEditType = .none) {
  403. self._isEdited = true
  404. // 提醒外面文档已编辑
  405. guard let callback = self.documentEditedCallback else {
  406. return
  407. }
  408. callback(type)
  409. }
  410. private func _progressHUD(message: String, style: KMCustomAlertStyle = .blue) {
  411. _ = CustomAlertView.alertView(message: message, fromView: self.thumbnailView, withStyle: style)
  412. }
  413. private func _showPDFEditDetails() {
  414. var insertItem: KMToolbarItemView?
  415. for item in self.toolBar.toolBar.items {
  416. if item.itemIdentifier == KMToolbarPageEditInsetItemIdentifier {
  417. insertItem = item
  418. break
  419. }
  420. }
  421. if insertItem?.window == nil {
  422. return
  423. }
  424. let showConvertDetails = KMPageEditPopViewController.showPageEditDetails()
  425. if (showConvertDetails) {
  426. let item = insertItem
  427. let popViewController = KMPageEditPopViewController()
  428. self.popOver_ = NSPopover()
  429. self.popOver_?.contentViewController = popViewController
  430. self.popOver_?.animates = false
  431. self.popOver_?.setBackgroundColor(KMAppearance.Interactive.a0Color())
  432. self.popOver_?.behavior = .transient
  433. // self.popOver.appearance = NSPopoverAppearanceMinimal;
  434. // self.popOver_?.appearance = .minimal
  435. self.popOver_?.contentSize = popViewController.view.frame.size
  436. self.popOver_?.show(relativeTo: item?.bounds ?? .zero, of: item!, preferredEdge: .maxY)
  437. }
  438. }
  439. // MARK: - 清空选择
  440. private func clearSelectPages() {
  441. self.selectPages(indexs: IndexSet())
  442. }
  443. override func refreshUI(indexpaths: Set<IndexPath> = [], keepSelected: Bool = false) {
  444. super.refreshUI(indexpaths: indexpaths, keepSelected: keepSelected)
  445. self.listView?.layoutDocumentView()
  446. }
  447. override func cutAction() {
  448. if IAPProductsManager.default().isAvailableAllFunction() == false {
  449. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  450. return
  451. }
  452. let pageCnt = self.pdfDocument?.pageCount ?? 0
  453. if (self.thumbnailView.selectionIndexPaths.count == pageCnt) {
  454. self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: ""))
  455. return
  456. }
  457. super.cutAction()
  458. }
  459. override func copyAction() {
  460. self.trackEvent_copy()
  461. super.copyAction()
  462. }
  463. override func deleteAction() {
  464. if IAPProductsManager.default().isAvailableAllFunction() == false {
  465. let winC = KMPurchaseCompareWindowController.sharedInstance()
  466. if self.kEventTag == 1 {
  467. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  468. } else {
  469. winC?.kEventName = "Reading_Delete_BuyNow"
  470. }
  471. winC?.showWindow(nil)
  472. return
  473. }
  474. if self.isEmptySelection() {
  475. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  476. return
  477. }
  478. let msg = String(format: NSLocalizedString("Are you sure to delete page %@ ?", comment: ""), KMTools.parseIndexSet(indexSet: self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths)))
  479. Task {
  480. let res = await KMAlertTool.runModel(message: msg, buttons: [NSLocalizedString("Delete", comment: ""), NSLocalizedString("Cancel", comment: "")])
  481. if res != .alertFirstButtonReturn {
  482. return
  483. }
  484. self.trackEvent(type: .delete)
  485. super.deleteAction()
  486. self.toolBar.unSelectItem(for: KMToolbarPageEditDeleteItemIdentifier)
  487. }
  488. }
  489. override func deleteIndexPaths(indexpaths: Set<IndexPath>) {
  490. guard let pageCount = self.thumbnailView.document?.pageCount else {
  491. KMPrint("pageCount invalid.")
  492. return
  493. }
  494. if (indexpaths.count == pageCount) {
  495. self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: ""))
  496. return
  497. }
  498. self.dealPdfDocumentDidEditCallback(type: .delete)
  499. super.deleteIndexPaths(indexpaths: indexpaths)
  500. }
  501. override func leftRotateAction() {
  502. if IAPProductsManager.default().isAvailableAllFunction() == false {
  503. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  504. return
  505. }
  506. self.trackEvent(type: .leftRotate)
  507. super.leftRotateAction()
  508. // self.toolBar.unSelectItem(for: KMToolbarPageEditLeftRotateItemIdentifier)
  509. }
  510. override func leftRotateIndexpaths(indexpaths: Set<IndexPath>) {
  511. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  512. return
  513. }
  514. super.leftRotateIndexpaths(indexpaths: indexpaths)
  515. self.dealPdfDocumentDidEditCallback(type: .leftRotate)
  516. }
  517. override func rightRotateAction() {
  518. if IAPProductsManager.default().isAvailableAllFunction() == false {
  519. let winC = KMPurchaseCompareWindowController.sharedInstance()
  520. if self.kEventTag == 1 {
  521. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  522. } else {
  523. winC?.kEventName = "Reading_Rotate_BuyNow"
  524. }
  525. winC?.showWindow(nil)
  526. return
  527. }
  528. if self.isEmptySelection() {
  529. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  530. return
  531. }
  532. self.trackEvent(type: .rightRotate)
  533. super.rightRotateAction()
  534. // self.toolBar.unSelectItem(for: KMToolbarPageEditRightRotateItemIdentifier)
  535. }
  536. override func rightRotateIndexpaths(indexpaths: Set<IndexPath>) {
  537. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  538. return
  539. }
  540. super.rightRotateIndexpaths(indexpaths: indexpaths)
  541. self.dealPdfDocumentDidEditCallback(type: .rightRotate)
  542. }
  543. override func insertPages(pages: Array<CPDFPage>, at indexs: IndexSet) {
  544. super.insertPages(pages: pages, at: indexs)
  545. if (!indexs.isEmpty) {
  546. self.selectPages(indexs: indexs)
  547. self.dealPdfDocumentDidEditCallback(type: .insert)
  548. }
  549. }
  550. override func pasteAction() {
  551. if IAPProductsManager.default().isAvailableAllFunction() == false {
  552. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  553. return
  554. }
  555. if (self.canPaste()) {
  556. super.pasteAction()
  557. self.dealPdfDocumentDidEditCallback(type: .paste)
  558. } else {
  559. if KMThumbnailManager.manager.copyPages.count <= 0 {
  560. self._progressHUD(message: KMLocalizedString("No copied page selected. Please select and copy a page first."))
  561. }
  562. }
  563. }
  564. @objc func pasteActonForEmpty(_ sender: NSMenuItem) {
  565. guard let indexpaths = sender.representedObject as? IndexPath else {
  566. NSSound.beep()
  567. return
  568. }
  569. let idx = max(0, indexpaths.item-1)
  570. // self.pastePage(at: indexpaths.item)
  571. self.pastePage(at: idx)
  572. dealPdfDocumentDidEditCallback(type: .copy)
  573. }
  574. override func pastePage(at index: Int) {
  575. if IAPProductsManager.default().isAvailableAllFunction() == false {
  576. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  577. return
  578. }
  579. super.pastePage(at: index)
  580. }
  581. override func extractAction() {
  582. if IAPProductsManager.default().isAvailableAllFunction() == false {
  583. let winC = KMPurchaseCompareWindowController.sharedInstance()
  584. if self.kEventTag == 1 {
  585. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  586. } else {
  587. winC?.kEventName = "Reading_Extract_BuyNow"
  588. }
  589. winC?.showWindow(nil)
  590. return
  591. }
  592. if self.isEmptySelection() {
  593. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  594. return
  595. }
  596. self.trackEvent(type: .extract)
  597. super.extractAction()
  598. DispatchQueue.main.async {
  599. self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier)
  600. }
  601. }
  602. override func replaceAction() {
  603. if IAPProductsManager.default().isAvailableAllFunction() == false {
  604. let winC = KMPurchaseCompareWindowController.sharedInstance()
  605. if self.kEventTag == 1 {
  606. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  607. } else {
  608. winC?.kEventName = "Reading_Replace_BuyNow"
  609. }
  610. winC?.showWindow(nil)
  611. return
  612. }
  613. if self.isEmptySelection() {
  614. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  615. return
  616. }
  617. self.trackEvent(type: .replace)
  618. super.replaceAction()
  619. DispatchQueue.main.async {
  620. self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier)
  621. }
  622. }
  623. override func replacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument]) {
  624. self.model.insertedDocumentSet.formUnion(documents)
  625. super.replacePages(of: targetIndexpaths, with: documents)
  626. }
  627. // 插入规则:选中后面插入[多选插入第后个后面];没有选中,插入阅读页当前页;
  628. override func getInsertIndex() -> Int {
  629. let ips = self.thumbnailView.selectionIndexPaths.sorted()
  630. if ips.isEmpty {
  631. return self.listView?.currentPageIndex ?? 0
  632. }
  633. return ips.last?.item ?? 0
  634. }
  635. override func splitAction() {
  636. if IAPProductsManager.default().isAvailableAllFunction() == false {
  637. let winC = KMPurchaseCompareWindowController.sharedInstance()
  638. if self.kEventTag == 1 {
  639. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  640. } else {
  641. winC?.kEventName = "Reading_Split_BuyNow"
  642. }
  643. winC?.showWindow(nil)
  644. return
  645. }
  646. if self.isEmptySelection() {
  647. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  648. return
  649. }
  650. guard let doc = self.pdfDocument else {
  651. NSSound.beep()
  652. return
  653. }
  654. let windowC = SplitWindowController(document: doc)
  655. windowC.fileAttribute?.pagesType = .custom
  656. let ips = self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths).sorted()
  657. let string = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: ips)
  658. windowC.fileAttribute?.pagesString = string
  659. self.km_beginSheet(windowC: windowC)
  660. }
  661. func splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
  662. if IAPProductsManager.default().isAvailableAllFunction() == false {
  663. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  664. return
  665. }
  666. if self.isEmptySelection() {
  667. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  668. return
  669. }
  670. self._splitMethod(windowC: windowC, model: model, limit: limit)
  671. }
  672. func splitMenuAction() {
  673. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  674. // #if VERSION_DMG
  675. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  676. // #else
  677. // KMToolCompareWindowController * vc = [KMToolCompareWindowController toolCompareWithType:KMCompareWithToolType_PageEdit setSelectIndex:1];
  678. // [vc startModal:nil];
  679. // #endif
  680. // return;
  681. // }
  682. if IAPProductsManager.default().isAvailableAllFunction() == false {
  683. let winC = KMPurchaseCompareWindowController.sharedInstance()
  684. if self.kEventTag == 1 {
  685. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  686. } else {
  687. winC?.kEventName = "Reading_Split_BuyNow"
  688. }
  689. winC?.showWindow(nil)
  690. return
  691. }
  692. let pdf = self.thumbnailView.document
  693. let pages = self.thumbnailView.selectionIndexPaths
  694. if (pages.isEmpty == false) {
  695. if self.fileAttri_ == nil {
  696. self.fileAttri_ = KMFileAttribute()
  697. self.fileAttri_?.password = self.thumbnailView.document?.password ?? ""
  698. self.fileAttri_?.filePath = self.thumbnailView.document?.documentURL.path ?? ""
  699. }
  700. let fileAttribute = self.fileAttri_
  701. fileAttribute?.bAllPage = false
  702. fileAttribute?.pagesType = .custom
  703. fileAttribute?.pdfDocument = pdf
  704. fileAttribute?.pagesString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: self.indexpathsToIndexs(indexpaths: pages).sorted())
  705. fileAttribute?.pageCnt = Int(self.thumbnailView.document?.pageCount ?? 0)
  706. let pages = fileAttribute?.fetchSelectPages() ?? []
  707. if pages.isEmpty {
  708. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  709. } else {
  710. let panel = NSOpenPanel()
  711. panel.canChooseFiles = false
  712. panel.canChooseDirectories = true
  713. panel.canCreateDirectories = true
  714. panel.beginSheetModal(for: self.view.window!) { result in
  715. if (result == .OK) {
  716. let outputURL = panel.urls.first!
  717. var tFolderPath = outputURL.path
  718. var index = 0
  719. var folderName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent
  720. if folderName == nil {
  721. folderName = KMLocalizedString("Untitled", nil)
  722. }
  723. var folderPath = "\(tFolderPath)/\(folderName ?? "")"
  724. //创建目录
  725. while (FileManager.default.fileExists(atPath: folderPath)) {
  726. index += 1
  727. folderPath = "\(tFolderPath)/\(folderName ?? "")_\(index)"
  728. // folderPath = [tFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld",folderName,index]];
  729. }
  730. tFolderPath = folderPath
  731. let result = try?FileManager.default.createDirectory(atPath: tFolderPath, withIntermediateDirectories: true)
  732. if (result == nil) {
  733. // if (![[NSFileManager defaultManager] createDirectoryAtPath:tFolderPath withIntermediateDirectories:YES attributes:nil error:nil]) {
  734. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
  735. return
  736. }
  737. let vc = KMProgressWindowController()
  738. NSApp.beginSheet(vc.window!, modalFor: self.view.window!, modalDelegate: nil, didEnd: nil, contextInfo: nil)
  739. DispatchQueue.global().async {
  740. // NSArray * successArray = [self.pdfDocument splitByFileWithPages:fileAttribute folerPath:tFolderPath fileName:folderName];
  741. let successArray = self.pdfDocument?.splitByFileWithPages(fileAttribute!, folerPath: tFolderPath, fileName: folderName ?? "") ?? []
  742. DispatchQueue.main.async {
  743. if successArray.count > 0 {
  744. let filePath = successArray.first ?? ""
  745. let workSpace = NSWorkspace.shared
  746. workSpace.activateFileViewerSelecting([URL(fileURLWithPath: filePath)])
  747. } else {
  748. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
  749. }
  750. NSApp.endSheet(vc.window!)
  751. vc.close()
  752. }
  753. }
  754. }
  755. }
  756. }
  757. } else{
  758. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  759. }
  760. }
  761. override func reverseAction() {
  762. if IAPProductsManager.default().isAvailableAllFunction() == false {
  763. let winC = KMPurchaseCompareWindowController.sharedInstance()
  764. winC?.kEventName = "Reading_Reverse_BuyNow"
  765. winC?.showWindow(nil)
  766. return
  767. }
  768. let cnt = self.thumbnailView.selectionIndexPaths.count
  769. if cnt < 2 {
  770. self._progressHUD(message: KMLocalizedString("No page selected. Please select at least two pages to organize."))
  771. return
  772. }
  773. self.trackEvent(type: .reverse)
  774. self.toolBar.unSelectItem(for: KMToolbarPageEditReverseItemIdentifier)
  775. self.reverseMenuAction(sender: nil)
  776. }
  777. func showSplitWindow(callback: @escaping (KMPageEditSplitWindowController, KMPageEditSplitSettingModel)->Void) {
  778. let model = KMPageEditSplitSettingModel()
  779. model.documentURL = self.listView?.document.documentURL
  780. if let pagecnt = self.thumbnailView.document?.pageCount {
  781. model.pageCount = Int(pagecnt)
  782. }
  783. model.fileName = model.documentURL?.lastPathComponent ?? ""
  784. model.pathExtension = model.fileName?.components(separatedBy: ".").last
  785. if (self.isEmptySelection() == false) {
  786. model.type = 2
  787. model.pageRangeType = 2
  788. var selectedIndexs: Array<Int> = []
  789. for indexpath in self.thumbnailView.selectionIndexPaths {
  790. selectedIndexs.append(indexpath.item)
  791. }
  792. model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs)
  793. } else {
  794. model.type = 0
  795. }
  796. let windowController = KMPageEditSplitWindowController(model)
  797. self.km_beginSheet(windowC: windowController)
  798. windowController.itemClick = { [weak self] index, value in
  799. if (index == 1) { /// 取消
  800. self?.km_endSheet()
  801. return
  802. }
  803. guard let _windowC = self?.kmCurrentWindowC as? KMPageEditSplitWindowController else {
  804. self?.km_endSheet()
  805. return
  806. }
  807. callback(_windowC, model)
  808. }
  809. }
  810. private func _splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
  811. let outputModel = windowC.model as! KMPageEditSplitSettingModel
  812. DispatchQueue.main.async {
  813. let panel = NSOpenPanel()
  814. panel.canChooseFiles = false
  815. panel.canChooseDirectories = true
  816. panel.canCreateDirectories = true
  817. panel.beginSheetModal(for: NSWindow.currentWindow()) { response in
  818. if (response == .cancel) {
  819. return
  820. }
  821. let file_indexs = outputModel.getSplitIndexSets ?? []
  822. if (file_indexs.count <= 0) {
  823. return
  824. }
  825. DispatchQueue.main.async {
  826. self.showProgressWindow(message: NSLocalizedString("Spliting...", comment: ""))
  827. self.progressC?.maxValue = Double(file_indexs.count)
  828. let _document = self.listView?.document
  829. let filePath = "\(panel.url!.path)/\(_document?.documentURL.deletingPathExtension().lastPathComponent ?? "")"
  830. let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath)
  831. // Swift.debugPrint(uniqueFilePath)
  832. if (!FileManager.default.fileExists(atPath: uniqueFilePath)) {
  833. try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true)
  834. }
  835. var filepaths: [String] = []
  836. for i in 0 ..< file_indexs.count {
  837. let indexs = file_indexs[i]
  838. if (indexs.isEmpty) {
  839. continue
  840. }
  841. let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1))
  842. filepaths.append(filepath)
  843. let newDocument = CPDFDocument()
  844. newDocument?.importPages(indexs, from: _document, at: 0)
  845. self.progressC?.increment(by: 1.0)
  846. newDocument?.write(to: URL(fileURLWithPath: filepath))
  847. }
  848. self.hiddenProgressWindow()
  849. self.km_endSheet()
  850. if let _urlString = filepaths.first?.deletingLastPathComponent {
  851. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
  852. }
  853. }
  854. }
  855. }
  856. }
  857. // MARK: Undo / Redo
  858. @objc private func reversePages(indexs: IndexSet) {
  859. if let doc = self.thumbnailView.document {
  860. KMThumbnailCache.shared.clearCache()
  861. // KMPageEditTools.reverse(doc, indexs
  862. // ) { result, error in
  863. // if (result) {
  864. // self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  865. //
  866. // self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  867. // }
  868. // }
  869. var theIdxs = indexs
  870. var res = false
  871. for i in 0 ..< indexs.count {
  872. guard let first = theIdxs.first else {
  873. break
  874. }
  875. guard let last = theIdxs.last else {
  876. break
  877. }
  878. if first == last {
  879. break
  880. }
  881. res = self.pdfDocument?.exchangePage(at: UInt(first), withPageAt: UInt(last)) ?? false
  882. if res {
  883. theIdxs.remove(first)
  884. theIdxs.remove(last)
  885. }
  886. }
  887. if res {
  888. self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  889. self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  890. }
  891. }
  892. }
  893. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  894. if (indexs.count <= 0) {
  895. return
  896. }
  897. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  898. // 插入位置偏移量
  899. var toIndexOffset: Int = 0
  900. // 需要移动的页面index数组
  901. var newPages: [CPDFPage] = []
  902. var currentPage: CPDFPage?
  903. var originalIndex = self.listViewCurrentIndex
  904. // 从后面往前删除
  905. for index in indexs.reversed() {
  906. let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
  907. if (newPage == nil) {
  908. continue
  909. }
  910. newPages.insert(newPage!, at: 0)
  911. self.pdfDocument?.removePage(at: UInt(index))
  912. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  913. toIndexOffset += 1
  914. }
  915. if (currentPage == nil) && (originalIndex == index) {
  916. currentPage = newPage
  917. }
  918. }
  919. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  920. toIndexOffset -= 1
  921. }
  922. let insertIndex = max(0, toIndex-toIndexOffset)
  923. var selectIndexs: IndexSet = []
  924. for (index, page) in newPages.enumerated() {
  925. self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
  926. selectIndexs.insert(insertIndex+index)
  927. if (currentPage?.pageIndex() == page.pageIndex()) {
  928. // self._listViewCurrentIndex = insertIndex+index
  929. }
  930. }
  931. // 新增 undo
  932. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  933. target.clearSelectPages()
  934. target.dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  935. }
  936. KMThumbnailCache.shared.clearCache()
  937. // 刷新UI
  938. self.refreshUI()
  939. if (reversed == false) {
  940. self.selectPages(indexs: selectIndexs)
  941. }
  942. }
  943. @objc private func new_dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  944. if (indexs.count <= 0) {
  945. return
  946. }
  947. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  948. // 插入位置偏移量
  949. var toIndexOffset: Int = 0
  950. // 需要移动的页面index数组
  951. var newPages: [CPDFPage] = []
  952. var currentPage: CPDFPage?
  953. var originalIndex = self.listViewCurrentIndex
  954. // 从后面往前删除
  955. for index in indexs.reversed() {
  956. let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
  957. if (newPage == nil) {
  958. continue
  959. }
  960. newPages.insert(newPage!, at: 0)
  961. // self.pdfDocument?.removePage(at: UInt(index))
  962. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  963. toIndexOffset += 1
  964. }
  965. if (currentPage == nil) && (originalIndex == index) {
  966. currentPage = newPage
  967. }
  968. }
  969. var after = false
  970. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  971. toIndexOffset -= 1
  972. after = true
  973. }
  974. let insertIndex = max(0, toIndex-toIndexOffset)
  975. var selectIndexs: IndexSet = []
  976. for (index, page) in newPages.enumerated() {
  977. // self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
  978. selectIndexs.insert(insertIndex+index)
  979. if (currentPage?.pageIndex() == page.pageIndex()) {
  980. // self._listViewCurrentIndex = insertIndex+index
  981. }
  982. // self.pdfDocument?.movePage(at: UInt(index), withPageAt: UInt(insertIndex+index))
  983. }
  984. var theToIndex = toIndex
  985. if indexs.count == 1 {
  986. theToIndex = insertIndex
  987. }
  988. if after {
  989. var offset = 0
  990. for index in indexs {
  991. self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(theToIndex))
  992. offset += 1
  993. }
  994. } else {
  995. var offset = 0
  996. for index in indexs.reversed() {
  997. self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(theToIndex))
  998. offset += 1
  999. }
  1000. }
  1001. // 新增 undo
  1002. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1003. target.clearSelectPages()
  1004. target.new_dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  1005. }
  1006. KMThumbnailCache.shared.clearCache()
  1007. // 刷新UI
  1008. self.refreshUI()
  1009. if (reversed == false) {
  1010. self.selectPages(indexs: selectIndexs)
  1011. }
  1012. }
  1013. @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  1014. if (indexs.count <= 0) {
  1015. return
  1016. }
  1017. // 插入位置偏移量
  1018. var toIndexOffset: Int = 0
  1019. for index in indexs {
  1020. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1021. toIndexOffset += 1
  1022. }
  1023. }
  1024. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  1025. toIndexOffset -= 1
  1026. }
  1027. let insertIndex = max(0, toIndex-toIndexOffset)
  1028. // 需要移动的页面index数组
  1029. var datas: [Int] = []
  1030. for index in insertIndex ..< (insertIndex + indexs.count) {
  1031. datas.append(index)
  1032. }
  1033. // 从后面开始删除
  1034. for index in datas.reversed() {
  1035. self.pdfDocument?.removePage(at: UInt(index))
  1036. }
  1037. // 再插入到对应的位置
  1038. for (index,value) in indexs.enumerated() {
  1039. var page: CPDFPage?
  1040. if (index < pages.count) {
  1041. page = pages[index]
  1042. }
  1043. if (page != nil) {
  1044. self.pdfDocument?.insertPageObject(page!, at: UInt(value))
  1045. }
  1046. }
  1047. // 新增 undo
  1048. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1049. target.dragPages(indexs, toIndex, dp: dp, reversed: true)
  1050. }
  1051. // 刷新UI
  1052. self.refreshUI()
  1053. }
  1054. @objc private func new_dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  1055. if (indexs.count <= 0) {
  1056. return
  1057. }
  1058. // 插入位置偏移量
  1059. var toIndexOffset: Int = 0
  1060. for index in indexs {
  1061. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1062. toIndexOffset += 1
  1063. }
  1064. }
  1065. var after = false
  1066. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  1067. toIndexOffset -= 1
  1068. after = true
  1069. }
  1070. let insertIndex = max(0, toIndex-toIndexOffset)
  1071. // 需要移动的页面index数组
  1072. var datas: [Int] = []
  1073. for index in insertIndex ..< (insertIndex + indexs.count) {
  1074. datas.append(index)
  1075. }
  1076. // 从后面开始删除
  1077. for index in datas.reversed() {
  1078. // self.pdfDocument?.removePage(at: UInt(index))
  1079. }
  1080. // 再插入到对应的位置
  1081. for (index,value) in indexs.enumerated() {
  1082. var page: CPDFPage?
  1083. if (index < pages.count) {
  1084. page = pages[index]
  1085. }
  1086. if (page != nil) {
  1087. // self.pdfDocument?.insertPageObject(page!, at: UInt(value))
  1088. }
  1089. }
  1090. if after {
  1091. // var offset = 0
  1092. for (index,value) in indexs.enumerated() {
  1093. let idx = datas[index]
  1094. self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
  1095. // offset += 1
  1096. }
  1097. // for index in datas.reversed() {
  1098. // self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(toIndex))
  1099. // offset += 1
  1100. // }
  1101. } else {
  1102. // var offset = 0
  1103. for (index,value) in indexs.reversed().enumerated() {
  1104. let idx = datas.reversed()[index]
  1105. self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
  1106. }
  1107. // for index in indexs {
  1108. // self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(toIndex))
  1109. // offset += 1
  1110. // }
  1111. }
  1112. // 新增 undo
  1113. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1114. target.new_dragPages(indexs, toIndex, dp: dp, reversed: true)
  1115. }
  1116. KMThumbnailCache.shared.clearCache()
  1117. // 刷新UI
  1118. self.refreshUI()
  1119. }
  1120. // MARK: topBar 事件
  1121. @objc func zoomOutButtonAction(sender: NSButton?) {
  1122. if (self.itemSize.width > self.defaultItemSize.width) {
  1123. return
  1124. }
  1125. if (self.itemSize.width < self.defaultItemSize.width) {
  1126. self.itemSize = self.defaultItemSize
  1127. } else if (self.itemSize.width == self.defaultItemSize.width) {
  1128. self.itemSize = NSSize(width: self.defaultItemSize.width*2, height: self.defaultItemSize.height*2)
  1129. }
  1130. // self.toolBar.zoomInButton?.isEnabled = true
  1131. // if (self.itemSize.width > self.defaultItemSize.width) {
  1132. // sender?.isEnabled = false
  1133. // }
  1134. KMThumbnailCache.shared.clearCache()
  1135. self.pageEditThumbnailView.zoomOut()
  1136. if pageEditThumbnailView.canZoomIn() {
  1137. zoomOutButton.isEnabled = true
  1138. } else {
  1139. zoomOutButton.isEnabled = false
  1140. }
  1141. if pageEditThumbnailView.canZoomOut() {
  1142. zoomInButton.isEnabled = true
  1143. } else {
  1144. zoomInButton.isEnabled = false
  1145. }
  1146. }
  1147. @objc func zoomInButtonAction(sender: NSButton?) {
  1148. if (self.itemSize.width < self.defaultItemSize.width) {
  1149. return
  1150. }
  1151. if (self.itemSize.width > self.defaultItemSize.width) {
  1152. self.itemSize = self.defaultItemSize
  1153. } else if (self.itemSize.width == self.defaultItemSize.width) {
  1154. self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
  1155. }
  1156. // self.toolBar.zoomOutButton?.isEnabled = true
  1157. // if (self.itemSize.width < self.defaultItemSize.width) {
  1158. // sender?.isEnabled = false
  1159. // }
  1160. KMThumbnailCache.shared.clearCache()
  1161. self.pageEditThumbnailView.zoomIn()
  1162. if pageEditThumbnailView.canZoomIn() {
  1163. zoomOutButton.isEnabled = true
  1164. } else {
  1165. zoomOutButton.isEnabled = false
  1166. }
  1167. if pageEditThumbnailView.canZoomOut() {
  1168. zoomInButton.isEnabled = true
  1169. } else {
  1170. zoomInButton.isEnabled = false
  1171. }
  1172. }
  1173. // MARK: menu 菜单事件
  1174. override func menuNeedsUpdate(_ menu: NSMenu) {
  1175. // let row = self.thumbnailView.collectionView.selectionIndexes
  1176. // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil)
  1177. let point = self.view.window?.currentEvent?.locationInView(self.thumbnailView.collectionView) ?? .zero
  1178. let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point)
  1179. menu.removeAllItems()
  1180. if indexpaths == nil || indexpaths!.isEmpty { // 空白处点击
  1181. if KMThumbnailManager.manager.copyPages.isEmpty { // 不能粘贴
  1182. // if self.canPaste() {
  1183. return
  1184. }
  1185. let item_ = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pasteActonForEmpty), target: self)
  1186. // item_?.keyEquivalent = KMKeyEquivalent.paste
  1187. let repObj = self.thumbnailView.collectionView.km_indexPathForItem(at: point, nearest: true)
  1188. item_?.representedObject = repObj
  1189. return
  1190. }
  1191. super.menuNeedsUpdate(menu)
  1192. }
  1193. @objc func item_insertCustomPage(sender: NSMenuItem?) {
  1194. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1195. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1196. if self.kEventTag == 1 {
  1197. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1198. } else {
  1199. winC?.kEventName = "Reading_InsertBlankPage_BuyNow"
  1200. }
  1201. winC?.showWindow(nil)
  1202. return
  1203. }
  1204. guard let doc = self.pdfDocument else {
  1205. NSSound.beep()
  1206. return
  1207. }
  1208. let windowC = KMPDFEditInsertBlankPageWindow(document: doc)
  1209. windowC.currentPage = self.getSelecteIndex() + 1
  1210. windowC.insertLocation = 3
  1211. windowC.callback = { [weak self] pdfDoc, _, pages, insertI in
  1212. if pages != nil {
  1213. // mm 单位的大小
  1214. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  1215. self?.km_endSheet()
  1216. return
  1217. }
  1218. var pageSize = _winC.pageSize
  1219. let direction = windowC.pageRotation == 0 ? 0 : 1
  1220. if (direction == 0) { // 纵向
  1221. if (pageSize.width > pageSize.height) { // 需要交换
  1222. let tmp = pageSize.width
  1223. pageSize.width = pageSize.height
  1224. pageSize.height = tmp
  1225. } else {
  1226. // no things.
  1227. }
  1228. } else { // 横向
  1229. if (pageSize.width > pageSize.height) {
  1230. // no things.
  1231. } else { // 需要交换
  1232. let tmp = pageSize.width
  1233. pageSize.width = pageSize.height
  1234. pageSize.height = tmp
  1235. }
  1236. }
  1237. /// 插入位置
  1238. let document = CPDFDocument()
  1239. document?.insertPage(pageSize, at: 0)
  1240. if let page: CPDFPage = (document?.page(at: 0)) {
  1241. self?.insertPages(pages: [page], at: IndexSet(integer: insertI))
  1242. }
  1243. let ips: Set<IndexPath> = [IndexPath(item: insertI, section: 0)]
  1244. self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1245. }
  1246. self?.km_endSheet()
  1247. }
  1248. self.km_beginSheet(windowC: windowC)
  1249. }
  1250. @objc func item_insertFromImage(sender: NSMenuItem?) {
  1251. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1252. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1253. if self.kEventTag == 1 {
  1254. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1255. } else {
  1256. winC?.kEventName = "Reading_InsertImage_BuyNow"
  1257. }
  1258. winC?.showWindow(nil)
  1259. return
  1260. }
  1261. let openPanel = NSOpenPanel()
  1262. openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  1263. openPanel.allowsMultipleSelection = true
  1264. openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
  1265. openPanel.canChooseDirectories = false
  1266. openPanel.allowsMultipleSelection = false
  1267. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1268. if result == NSApplication.ModalResponse.OK {
  1269. if let fileURL = openPanel.urls.first {
  1270. // self.choosePositionWindow {[weak self] index in
  1271. // /// 插入位置
  1272. if NSDocument.isDamage(url: fileURL, needAlertIfDamage: true) { // 损坏图片
  1273. return
  1274. }
  1275. if let imag = NSImage(contentsOfFile: fileURL.path ) {
  1276. let index = self.getInsertIndex() + 1
  1277. let document = CPDFDocument()
  1278. _ = document?.km_insertPage(imag.size, withImage: fileURL.path , at: 0)
  1279. if let page: CPDFPage = (document?.page(at: 0)) {
  1280. self.insertPages(pages: [page], at: IndexSet(integer: index))
  1281. }
  1282. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1283. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1284. }
  1285. // }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. func choosePositionWindow(completion: @escaping KMIndexChooseBlock) -> Void {
  1291. // guard let doc = self.pdfDocument else {
  1292. // NSSound.beep()
  1293. // return
  1294. // }
  1295. // let windowC = KMFileInsertPositionWindowController(document: doc)
  1296. // windowC.currentPage = self.getSelecteIndex() + 1
  1297. // windowC.insertLocation = 3
  1298. // windowC.callback = { [weak self] pdfDoc, _, insertI in
  1299. // if insertI >= 0 {
  1300. // if (completion != nil) {
  1301. // completion(insertI);
  1302. // }
  1303. // }
  1304. // self?.km_endSheet()
  1305. // }
  1306. // self.km_beginSheet(windowC: windowC)
  1307. }
  1308. @objc func item_insertFromClipboard(sender: NSMenuItem?) {
  1309. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1310. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1311. if self.kEventTag == 1 {
  1312. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1313. } else {
  1314. winC?.kEventName = "Reading_InsertClipboard_BuyNow"
  1315. }
  1316. winC?.showWindow(nil)
  1317. return
  1318. }
  1319. // self.choosePositionWindow {[weak self] index in
  1320. /// 插入位置
  1321. var error: NSError?
  1322. guard let document: CPDFDocument = self.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
  1323. return
  1324. }
  1325. let index = self.getInsertIndex() + 1
  1326. if let page: CPDFPage = (document.page(at: 0)) {
  1327. self.insertPages(pages: [page], at: IndexSet(integer: index))
  1328. }
  1329. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1330. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1331. // }
  1332. }
  1333. @objc func item_insertFromScanner(sender: NSMenuItem?) {
  1334. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1335. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1336. if self.kEventTag == 1 {
  1337. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1338. } else {
  1339. winC?.kEventName = "Reading_InsertSacnner_BuyNow"
  1340. }
  1341. winC?.showWindow(nil)
  1342. return
  1343. }
  1344. let vc = KMDeviceBrowserWindowController.shared
  1345. vc.type = .scanner
  1346. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1347. // self?.choosePositionWindow {[weak self] index in
  1348. /// 插入位置
  1349. if let imag = NSImage(contentsOfFile: url.path! ) {
  1350. let index = (self?.getInsertIndex())! + 1
  1351. let document = CPDFDocument()
  1352. _ = document?.km_insertPage(imag.size, withImage: url.path! , at: 0)
  1353. if let page: CPDFPage = (document?.page(at: 0)) {
  1354. self?.insertPages(pages: [page], at: IndexSet(integer: index))
  1355. }
  1356. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1357. self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1358. }
  1359. // }
  1360. vc.close()
  1361. }
  1362. vc.showWindow(NSApp.mainWindow)
  1363. }
  1364. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
  1365. var document: CPDFDocument? = nil
  1366. var data: Data? = nil
  1367. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  1368. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  1369. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  1370. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  1371. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  1372. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  1373. } else {
  1374. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  1375. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  1376. if images?.count ?? 0 > 0 {
  1377. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  1378. } else if strings?.count ?? 0 > 0 {
  1379. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  1380. }
  1381. }
  1382. if let data = data {
  1383. document = CPDFDocument(data: data)
  1384. } else if let outError = outError {
  1385. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  1386. }
  1387. return document
  1388. }
  1389. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  1390. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  1391. let pdfData = NSMutableData(capacity: tiffData.count)
  1392. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  1393. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  1394. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  1395. ctxt!.beginPDFPage(nil)
  1396. ctxt!.draw(cgImage, in: rect)
  1397. ctxt!.endPDFPage()
  1398. ctxt!.closePDF()
  1399. return pdfData as? Data
  1400. }
  1401. func extractSelectPageItemAction() {
  1402. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1403. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1404. if self.kEventTag == 1 {
  1405. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1406. } else {
  1407. winC?.kEventName = "Reading_Extract_BuyNow"
  1408. }
  1409. winC?.showWindow(nil)
  1410. return
  1411. }
  1412. let indexs = self.thumbnailView.selectionIndexPaths
  1413. if indexs.isEmpty {
  1414. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  1415. return
  1416. }
  1417. self.extractPages(indexpaths: indexs, oneDocumentPerPage: false) { result, params in }
  1418. }
  1419. // MARK: toolBar 菜单事件
  1420. @objc func reverseMenuAction(sender: AnyObject?) {
  1421. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  1422. if (selectedIndexs.count < 2 ) {
  1423. let alertView = CustomAlertView.alertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), fromView: self.thumbnailView, withStyle: .blue)
  1424. alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1425. alertView?.layer?.cornerRadius = 4
  1426. return
  1427. }
  1428. self.reversePages(indexs: self.indexpathsToIndexs(indexpaths: selectedIndexs))
  1429. self.dealPdfDocumentDidEditCallback(type: .reverse)
  1430. }
  1431. override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? {
  1432. var item_: NSMenuItem?
  1433. if (item.sel == KMPDFThumbViewMenu.insertSelector) {
  1434. item_ = menu.addItem(withTitle: NSLocalizedString("Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self)
  1435. } else if (item.sel == KMPDFThumbViewMenu.splitSelector) {
  1436. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  1437. item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self)
  1438. }
  1439. } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) {
  1440. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  1441. item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self)
  1442. }
  1443. } else {
  1444. return super.addMenuItem(menu: menu, item: item)
  1445. }
  1446. return item_
  1447. }
  1448. // MARK: - Zoom Methods
  1449. @IBAction func buttonClicked_Bigger(_ sender: AnyObject?) {
  1450. // if (self.thumbnailView.thumbnailSize.width == 100.) {
  1451. // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
  1452. // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
  1453. // self.thumbnailView.thumbnailSize = CGSizeMake(400, 400);
  1454. // }
  1455. self.zoomOutButtonAction(sender: sender as? NSButton)
  1456. }
  1457. @IBAction func buttonClicked_Smaller(_ sender: AnyObject?) {
  1458. // if (self.thumbnailView.thumbnailSize.width == 400.) {
  1459. // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
  1460. // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
  1461. // self.thumbnailView.thumbnailSize = CGSizeMake(100, 100);
  1462. // }
  1463. self.zoomInButtonAction(sender: sender as? NSButton)
  1464. }
  1465. override func mouseMoved(with event: NSEvent) {
  1466. super.mouseMoved(with: event)
  1467. self.view.window?.mouseMoved(with: event)
  1468. }
  1469. }
  1470. extension KMPDFEditViewController {
  1471. //MARK: menu Action
  1472. @objc func insertPageItemAction(menu:NSMenuItem) {
  1473. if (menu.tag == 0) {
  1474. self.insertBlankPageAction()
  1475. } else if (menu.tag == 1) {
  1476. self.item_insertCustomPage(sender: nil)
  1477. } else if (menu.tag == 2) {
  1478. self.insertFileAction()
  1479. }
  1480. }
  1481. @objc func sharePageItemAction(menu:NSMenuItem) {
  1482. guard let item = menu.parent else {
  1483. NSSound.beep()
  1484. return
  1485. }
  1486. let index = (item.representedObject as? IndexSet)?.first ?? -1
  1487. if Int(index) >= 0 {
  1488. let doucument = self.pdfDocument
  1489. // let page = doucument.page(at: UInt(index))
  1490. let filename : String = doucument?.documentURL.lastPathComponent ?? ""
  1491. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename)) ?? ""
  1492. try? FileManager.default.removeItem(atPath: folderPath)
  1493. let pdfdocument = CPDFDocument()
  1494. let ret = pdfdocument?.importPages((item.representedObject as? IndexSet) ?? [], from: self.thumbnailView.document, at: 0) ?? false
  1495. let url = URL(fileURLWithPath: folderPath)
  1496. if ret {
  1497. let success = pdfdocument?.write(to:url) ?? false
  1498. // if success {
  1499. // let workspace = NSWorkspace.shared
  1500. // workspace.activateFileViewerSelecting([url])
  1501. // }
  1502. }
  1503. let represent = menu.representedObject as? NSSharingService
  1504. represent?.perform(withItems: [url])
  1505. }
  1506. }
  1507. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  1508. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  1509. self.refreshUIForKeepSelecteds()
  1510. }
  1511. @objc func printItemAction(menu:NSMenuItem) {
  1512. var datas: [Int] = []
  1513. for indexpath in self.thumbnailView.selectionIndexPaths {
  1514. datas.append(indexpath.item)
  1515. }
  1516. guard let callback = self.itemClick else {
  1517. return
  1518. }
  1519. callback(2, datas.sorted())
  1520. }
  1521. override func menuItemAction_extract(_ sender: Any?) {
  1522. self.extractSelectPageItemAction()
  1523. }
  1524. }
  1525. extension KMPDFEditViewController {
  1526. override func menuItemAction_print(_ sender: Any?) {
  1527. if let item = sender as? NSMenuItem {
  1528. self.printItemAction(menu: item)
  1529. }
  1530. }
  1531. override func menuItemAction_showPageSize(_ sender: Any?) {
  1532. if let item = sender as? NSMenuItem {
  1533. self.showPageSizeItemAction(menu: item)
  1534. }
  1535. }
  1536. override func menuItemAction_share(_ sender: Any?) {
  1537. if let item = sender as? NSMenuItem {
  1538. self.sharePageItemAction(menu: item)
  1539. }
  1540. }
  1541. }
  1542. // MARK: - KMSelectPopButtonDelegate
  1543. extension KMPDFEditViewController {
  1544. func km_comboBoxSelectionDidChange(_ obj: KMPageRange) {
  1545. self.pageIsUpdate = false
  1546. var indexpaths: Set<IndexPath> = []
  1547. let type: KMPageRange? = obj
  1548. let pageCnt = self.pdfDocument?.pageCount ?? 0
  1549. for i in 0 ..< pageCnt {
  1550. if (type == .all) {
  1551. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1552. } else if (type == .odd) {
  1553. if (i % 2 == 1) {
  1554. continue
  1555. }
  1556. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1557. } else if (type == .even) {
  1558. if (i % 2 == 0) {
  1559. continue
  1560. }
  1561. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1562. } else if (type == .horizontal) {
  1563. let page = self.pdfDocument?.page(at: i)
  1564. guard let isVertical = page?.isVertical(), !isVertical else {
  1565. continue
  1566. }
  1567. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1568. } else if (type == .vertical) {
  1569. let page = self.pdfDocument?.page(at: i)
  1570. guard let isHorizontal = page?.isHorizontal(), !isHorizontal else {
  1571. continue
  1572. }
  1573. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1574. }
  1575. }
  1576. if (type == .custom) {
  1577. let windowC = KMPDFEditPageRangeWindowController()
  1578. windowC.pdfDocument = self.pdfDocument
  1579. windowC.pageSelectCallBack = { [weak self] pagesArray in
  1580. var indexpaths = Set<IndexPath>()
  1581. for page in pagesArray {
  1582. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1583. }
  1584. self?.km_endSheet()
  1585. self?.selectPages(indexpaths: indexpaths)
  1586. self?.thumbnailView.collectionView.scrollToItems(at: indexpaths, scrollPosition: .bottom)
  1587. }
  1588. self.km_beginSheet(windowC: windowC)
  1589. } else {
  1590. self.pageEditThumbnailView.selectPages(at: indexpaths)
  1591. }
  1592. }
  1593. func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
  1594. self.view.window?.makeFirstResponder(self)
  1595. for index in 0 ..< obj.numberOfItems {
  1596. if (obj.items[index] == obj.stringValue) {
  1597. return
  1598. }
  1599. }
  1600. let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView?.stringValue ?? "", pageCount: Int((self.listView?.document.pageCount) ?? 0))
  1601. if (pages.isEmpty) {
  1602. let alert = NSAlert()
  1603. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1604. alert.runModal()
  1605. self.toolBar.setPageRangeString("")
  1606. DispatchQueue.main.async {
  1607. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  1608. }
  1609. return
  1610. }
  1611. var indexpaths: Set<IndexPath> = []
  1612. for page in pages {
  1613. if (page >= 1) {
  1614. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1615. }
  1616. }
  1617. self.pageIsUpdate = false
  1618. self.pageEditThumbnailView.selectPages(at: indexpaths)
  1619. }
  1620. }
  1621. // MARK: -
  1622. // MARK: KMThumbnailViewDelegate
  1623. extension KMPDFEditViewController: KMThumbnailViewDelegate {
  1624. func thumbnailView(thumbanView: KMThumbnailView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
  1625. return IAPProductsManager.default().isAvailableAllFunction()
  1626. }
  1627. func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  1628. return true
  1629. }
  1630. func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  1631. self.km_add_file_multi(fileUrls: files) { index, params in
  1632. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  1633. return
  1634. }
  1635. let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  1636. if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
  1637. if (_fileUrl!.path.isPDFValid() == false) {
  1638. let alert = NSAlert()
  1639. alert.alertStyle = .critical
  1640. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1641. alert.runModal()
  1642. }
  1643. }
  1644. } completionBlock: { [weak self] documents in
  1645. var insertIndex: Int = indexpath.item
  1646. var pages: Array<CPDFPage> = []
  1647. var indexs = IndexSet()
  1648. self?.model.insertedDocumentSet.formUnion(documents)
  1649. for document in documents {
  1650. for i in 0 ..< document.pageCount {
  1651. if let page = document.page(at: i) {
  1652. pages.append(page)
  1653. indexs.insert(insertIndex)
  1654. insertIndex += 1
  1655. }
  1656. }
  1657. }
  1658. self?.insertPages(pages: pages, at: indexs)
  1659. }
  1660. }
  1661. func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
  1662. let toIndex = max(0, indexpath.item)
  1663. var indexs = IndexSet()
  1664. for indexpath in dragedIndexPaths {
  1665. indexs.insert(indexpath.item)
  1666. }
  1667. var dp = NSCollectionView.DropOperation.on
  1668. if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation {
  1669. dp = _dp
  1670. }
  1671. self.new_dragPages(indexs, toIndex, dp: dp)
  1672. if (dragedIndexPaths.count > 0) {
  1673. self.dealPdfDocumentDidEditCallback()
  1674. }
  1675. }
  1676. func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
  1677. // if (!self.canPayFunction) {
  1678. // return false
  1679. // }
  1680. return true
  1681. }
  1682. func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  1683. return NSEdgeInsets(top: 6, left: 40, bottom: 0, right: 40)
  1684. }
  1685. func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  1686. self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
  1687. if (!self.thumbnailView.isShowPageSize) {
  1688. return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
  1689. }
  1690. return self.itemSize
  1691. }
  1692. func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int {
  1693. if let count = self.pdfDocument?.pageCount {
  1694. return Int(count)
  1695. }
  1696. return 0
  1697. }
  1698. func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
  1699. let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.km.dequeueReusableCell(for: indexpath)
  1700. cellView.isShowPageSize = self.thumbnailView.isShowPageSize
  1701. if let data = self.pdfDocument?.page(at: UInt(indexpath.item)) {
  1702. cellView.setPage(page: data)
  1703. }
  1704. let bks = self.listView?.document.bookmarks()
  1705. var hasBookmark = false
  1706. for bk in bks ?? [] {
  1707. if indexpath.item == bk.pageIndex {
  1708. hasBookmark = true
  1709. break
  1710. }
  1711. }
  1712. cellView.bkIcon.isHidden = !hasBookmark
  1713. cellView.doubleClickAction = { [weak self] _ in
  1714. guard let callback = self?.itemClick else {
  1715. return
  1716. }
  1717. callback(1, indexpath.item)
  1718. }
  1719. cellView.mouseDownAction = { [unowned self] _ in
  1720. let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
  1721. if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
  1722. return
  1723. }
  1724. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1725. }
  1726. cellView.rightMouseDownAction = { [weak self] _ in
  1727. self?.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1728. }
  1729. return cellView
  1730. }
  1731. }
  1732. // MARK: - 系统菜单栏
  1733. extension KMPDFEditViewController {
  1734. override func undo(_ sender: Any?) {
  1735. super.undo(sender)
  1736. self.km_becomeFirstResponder()
  1737. }
  1738. override func redo(_ sender: Any?) {
  1739. super.redo(sender)
  1740. self.km_becomeFirstResponder()
  1741. }
  1742. }
  1743. // MARK: - KMExtensions
  1744. extension KMPDFEditViewController {
  1745. override func deleteAfter(indexpaths: Set<IndexPath>) {
  1746. self.clearSelectPages()
  1747. self.km_becomeFirstResponder()
  1748. }
  1749. override func copyAfter(indexpaths: Set<IndexPath>) {
  1750. self.km_becomeFirstResponder()
  1751. }
  1752. override func pasteAfter(at index: Int) {
  1753. self.km_becomeFirstResponder()
  1754. }
  1755. override func cutAfter(indexpaths: Set<IndexPath>) {
  1756. self.clearSelectPages()
  1757. self.km_becomeFirstResponder()
  1758. }
  1759. override func leftRotateAfter(indexpaths: Set<IndexPath>) {
  1760. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1761. self.km_becomeFirstResponder()
  1762. }
  1763. override func rightRotateAfter(indexpaths: Set<IndexPath>) {
  1764. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1765. self.km_becomeFirstResponder()
  1766. }
  1767. override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) {
  1768. var indexpaths = Set<IndexPath>()
  1769. var insertIndex = index
  1770. for _ in pages {
  1771. indexpaths.insert(IndexPath(item: insertIndex, section: 0))
  1772. insertIndex += 1
  1773. }
  1774. self.thumbnailView.selectionIndexPaths = indexpaths
  1775. self.dealPdfDocumentDidEditCallback(type: .replace)
  1776. }
  1777. override func insertBlankPageAfter(size: NSSize, at index: Int) {
  1778. self.selectPages(indexs: IndexSet(integer: index))
  1779. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1780. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1781. self.dealPdfDocumentDidEditCallback(type: .insert)
  1782. }
  1783. func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) {
  1784. if (indexs.isEmpty) {
  1785. return
  1786. }
  1787. // listView 当前页面 被拖拽
  1788. if (indexs.contains(self._listViewCurrentIndex)) {
  1789. // let idx = indexs.firstIndex(of: self._listViewCurrentIndex)
  1790. var idx: Int = 0
  1791. for index in indexs {
  1792. if (index == self._listViewCurrentIndex) {
  1793. break
  1794. }
  1795. idx += 1
  1796. }
  1797. // 插入位置偏移量
  1798. var toIndexOffset: Int = 0
  1799. // 从后面往前删除
  1800. for index in indexs.reversed() {
  1801. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  1802. if (newPage == nil) {
  1803. continue
  1804. }
  1805. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1806. toIndexOffset += 1
  1807. }
  1808. }
  1809. if (indexs.last! < toIndex) { // 往后拖拽
  1810. toIndexOffset -= 1
  1811. }
  1812. let insertIndex = max(0, toIndex-toIndexOffset)
  1813. self._listViewCurrentIndex = insertIndex+idx
  1814. } else {
  1815. var forwardCnt = 0
  1816. var nextCnt = 0
  1817. for index in indexs {
  1818. if (index > self._listViewCurrentIndex) {
  1819. nextCnt += 1
  1820. } else {
  1821. forwardCnt += 1
  1822. }
  1823. }
  1824. if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式
  1825. self._listViewCurrentIndex += nextCnt
  1826. } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式
  1827. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1828. } else { // 插入到目标位置 [跟插入到目标后面一样]
  1829. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1830. }
  1831. }
  1832. }
  1833. }
  1834. // MARK: - Analytics (埋点)
  1835. extension KMPDFEditViewController {
  1836. func trackEvent(type: KMPageEditType, index: Int = 0) -> Void {
  1837. if (type == .insert) {
  1838. if index == 0 {
  1839. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [
  1840. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1841. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1842. } else if index == KMPageEditType.insert_blank_page || index == KMPageEditType.insert_custom_page {
  1843. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertBlankPage"], platform: .AppCenter)
  1844. } else if index == KMPageEditType.insert_files {
  1845. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertPDF"], platform: .AppCenter)
  1846. } else if index == KMPageEditType.insert_fromImage {
  1847. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertImage"], platform: .AppCenter)
  1848. } else if index == KMPageEditType.insert_fromClipboard {
  1849. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertClipboard"], platform: .AppCenter)
  1850. } else if index == KMPageEditType.insert_fromScanner {
  1851. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertScanner"], platform: .AppCenter)
  1852. }
  1853. } else if (type == .extract) {
  1854. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [
  1855. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1856. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1857. } else if (type == .leftRotate || type == .rightRotate) {
  1858. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [
  1859. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1860. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1861. } else if (type == .replace) {
  1862. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [
  1863. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1864. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1865. } else if (type == .split) {
  1866. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [
  1867. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1868. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1869. } else if (type == .reverse) {
  1870. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [
  1871. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1872. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1873. } else if (type == .delete) {
  1874. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [
  1875. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1876. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1877. }
  1878. }
  1879. func trackEvent_copy() -> Void {
  1880. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [
  1881. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1882. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1883. }
  1884. }