KMPDFEditViewController.swift 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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 KMMemberInfo.shared.isMemberAllFunction == false {
  449. KMMemberInfo.shared.advancedFunctionUsage()
  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 KMMemberInfo.shared.isMemberAllFunction == false {
  465. let winC = KMProductCompareWC.shared
  466. if self.kEventTag == 1 {
  467. winC.kEventName = "Onbrd_EditPage_BuyNow"
  468. } else {
  469. winC.kEventName = "Reading_Delete_BuyNow"
  470. }
  471. KMMemberInfo.shared.advancedFunctionUsage()
  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 KMMemberInfo.shared.isMemberAllFunction == false {
  503. KMMemberInfo.shared.advancedFunctionUsage()
  504. return
  505. }
  506. self.trackEvent(type: .leftRotate)
  507. super.leftRotateAction()
  508. }
  509. override func leftRotateIndexpaths(indexpaths: Set<IndexPath>) {
  510. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  511. return
  512. }
  513. super.leftRotateIndexpaths(indexpaths: indexpaths)
  514. self.dealPdfDocumentDidEditCallback(type: .leftRotate)
  515. }
  516. override func rightRotateAction() {
  517. if KMMemberInfo.shared.isMemberAllFunction == false {
  518. let winC = KMProductCompareWC.shared
  519. if self.kEventTag == 1 {
  520. winC.kEventName = "Onbrd_EditPage_BuyNow"
  521. } else {
  522. winC.kEventName = "Reading_Rotate_BuyNow"
  523. }
  524. KMMemberInfo.shared.advancedFunctionUsage()
  525. return
  526. }
  527. if self.isEmptySelection() {
  528. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  529. return
  530. }
  531. self.trackEvent(type: .rightRotate)
  532. super.rightRotateAction()
  533. }
  534. override func rightRotateIndexpaths(indexpaths: Set<IndexPath>) {
  535. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  536. return
  537. }
  538. super.rightRotateIndexpaths(indexpaths: indexpaths)
  539. self.dealPdfDocumentDidEditCallback(type: .rightRotate)
  540. }
  541. override func insertPages(pages: Array<CPDFPage>, at indexs: IndexSet) {
  542. super.insertPages(pages: pages, at: indexs)
  543. if (!indexs.isEmpty) {
  544. self.selectPages(indexs: indexs)
  545. self.dealPdfDocumentDidEditCallback(type: .insert)
  546. }
  547. }
  548. override func pasteAction() {
  549. if KMMemberInfo.shared.isMemberAllFunction == false {
  550. KMMemberInfo.shared.advancedFunctionUsage()
  551. return
  552. }
  553. if (self.canPaste()) {
  554. super.pasteAction()
  555. self.dealPdfDocumentDidEditCallback(type: .paste)
  556. } else {
  557. if KMThumbnailManager.manager.copyPages.count <= 0 {
  558. self._progressHUD(message: KMLocalizedString("No copied page selected. Please select and copy a page first."))
  559. }
  560. }
  561. }
  562. @objc func pasteActonForEmpty(_ sender: NSMenuItem) {
  563. guard let indexpaths = sender.representedObject as? IndexPath else {
  564. NSSound.beep()
  565. return
  566. }
  567. let idx = max(0, indexpaths.item-1)
  568. // self.pastePage(at: indexpaths.item)
  569. self.pastePage(at: idx)
  570. dealPdfDocumentDidEditCallback(type: .copy)
  571. }
  572. override func pastePage(at index: Int) {
  573. if KMMemberInfo.shared.isMemberAllFunction == false {
  574. KMMemberInfo.shared.advancedFunctionUsage()
  575. return
  576. }
  577. super.pastePage(at: index)
  578. }
  579. override func extractAction() {
  580. if KMMemberInfo.shared.isMemberAllFunction == false {
  581. let winC = KMProductCompareWC.shared
  582. if self.kEventTag == 1 {
  583. winC.kEventName = "Onbrd_EditPage_BuyNow"
  584. } else {
  585. winC.kEventName = "Reading_Extract_BuyNow"
  586. }
  587. KMMemberInfo.shared.advancedFunctionUsage()
  588. return
  589. }
  590. if self.isEmptySelection() {
  591. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  592. return
  593. }
  594. self.trackEvent(type: .extract)
  595. super.extractAction()
  596. DispatchQueue.main.async {
  597. self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier)
  598. }
  599. }
  600. override func replaceAction() {
  601. if KMMemberInfo.shared.isMemberAllFunction == false {
  602. let winC = KMProductCompareWC.shared
  603. if self.kEventTag == 1 {
  604. winC.kEventName = "Onbrd_EditPage_BuyNow"
  605. } else {
  606. winC.kEventName = "Reading_Replace_BuyNow"
  607. }
  608. KMMemberInfo.shared.advancedFunctionUsage()
  609. return
  610. }
  611. if self.isEmptySelection() {
  612. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  613. return
  614. }
  615. self.trackEvent(type: .replace)
  616. super.replaceAction()
  617. DispatchQueue.main.async {
  618. self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier)
  619. }
  620. }
  621. override func replacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument]) {
  622. self.model.insertedDocumentSet.formUnion(documents)
  623. super.replacePages(of: targetIndexpaths, with: documents)
  624. }
  625. // 插入规则:选中后面插入[多选插入第后个后面];没有选中,插入阅读页当前页;
  626. override func getInsertIndex() -> Int {
  627. let ips = self.thumbnailView.selectionIndexPaths.sorted()
  628. if ips.isEmpty {
  629. return self.listView?.currentPageIndex ?? 0
  630. }
  631. return ips.last?.item ?? 0
  632. }
  633. override func splitAction() {
  634. if KMMemberInfo.shared.isMemberAllFunction == false {
  635. let winC = KMProductCompareWC.shared
  636. if self.kEventTag == 1 {
  637. winC.kEventName = "Onbrd_EditPage_BuyNow"
  638. } else {
  639. winC.kEventName = "Reading_Split_BuyNow"
  640. }
  641. KMMemberInfo.shared.advancedFunctionUsage()
  642. return
  643. }
  644. if self.isEmptySelection() {
  645. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  646. return
  647. }
  648. guard let doc = self.pdfDocument else {
  649. NSSound.beep()
  650. return
  651. }
  652. let windowC = SplitWindowController(document: doc)
  653. windowC.fileAttribute?.pagesType = .custom
  654. let ips = self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths).sorted()
  655. let string = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: ips)
  656. windowC.fileAttribute?.pagesString = string
  657. self.km_beginSheet(windowC: windowC)
  658. }
  659. func splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
  660. if KMMemberInfo.shared.isMemberAllFunction == false {
  661. KMMemberInfo.shared.advancedFunctionUsage()
  662. return
  663. }
  664. if self.isEmptySelection() {
  665. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  666. return
  667. }
  668. self._splitMethod(windowC: windowC, model: model, limit: limit)
  669. }
  670. func splitMenuAction() {
  671. if KMMemberInfo.shared.isMemberAllFunction == false {
  672. let winC = KMProductCompareWC.shared
  673. if self.kEventTag == 1 {
  674. winC.kEventName = "Onbrd_EditPage_BuyNow"
  675. } else {
  676. winC.kEventName = "Reading_Split_BuyNow"
  677. }
  678. KMMemberInfo.shared.advancedFunctionUsage()
  679. return
  680. }
  681. let pdf = self.thumbnailView.document
  682. let pages = self.thumbnailView.selectionIndexPaths
  683. if (pages.isEmpty == false) {
  684. if self.fileAttri_ == nil {
  685. self.fileAttri_ = KMFileAttribute()
  686. self.fileAttri_?.password = self.thumbnailView.document?.password ?? ""
  687. self.fileAttri_?.filePath = self.thumbnailView.document?.documentURL.path ?? ""
  688. }
  689. let fileAttribute = self.fileAttri_
  690. fileAttribute?.bAllPage = false
  691. fileAttribute?.pagesType = .custom
  692. fileAttribute?.pdfDocument = pdf
  693. fileAttribute?.pagesString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: self.indexpathsToIndexs(indexpaths: pages).sorted())
  694. fileAttribute?.pageCnt = Int(self.thumbnailView.document?.pageCount ?? 0)
  695. let pages = fileAttribute?.fetchSelectPages() ?? []
  696. if pages.isEmpty {
  697. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  698. } else {
  699. let panel = NSOpenPanel()
  700. panel.canChooseFiles = false
  701. panel.canChooseDirectories = true
  702. panel.canCreateDirectories = true
  703. panel.beginSheetModal(for: self.view.window!) { result in
  704. if (result == .OK) {
  705. let outputURL = panel.urls.first!
  706. var tFolderPath = outputURL.path
  707. var index = 0
  708. var folderName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent
  709. if folderName == nil {
  710. folderName = KMLocalizedString("Untitled", nil)
  711. }
  712. var folderPath = "\(tFolderPath)/\(folderName ?? "")"
  713. //创建目录
  714. while (FileManager.default.fileExists(atPath: folderPath)) {
  715. index += 1
  716. folderPath = "\(tFolderPath)/\(folderName ?? "")_\(index)"
  717. // folderPath = [tFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld",folderName,index]];
  718. }
  719. tFolderPath = folderPath
  720. let result = try?FileManager.default.createDirectory(atPath: tFolderPath, withIntermediateDirectories: true)
  721. if (result == nil) {
  722. // if (![[NSFileManager defaultManager] createDirectoryAtPath:tFolderPath withIntermediateDirectories:YES attributes:nil error:nil]) {
  723. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
  724. return
  725. }
  726. let vc = KMProgressWindowController()
  727. NSApp.beginSheet(vc.window!, modalFor: self.view.window!, modalDelegate: nil, didEnd: nil, contextInfo: nil)
  728. DispatchQueue.global().async {
  729. // NSArray * successArray = [self.pdfDocument splitByFileWithPages:fileAttribute folerPath:tFolderPath fileName:folderName];
  730. let successArray = self.pdfDocument?.splitByFileWithPages(fileAttribute!, folerPath: tFolderPath, fileName: folderName ?? "") ?? []
  731. DispatchQueue.main.async {
  732. if successArray.count > 0 {
  733. let filePath = successArray.first ?? ""
  734. let workSpace = NSWorkspace.shared
  735. workSpace.activateFileViewerSelecting([URL(fileURLWithPath: filePath)])
  736. } else {
  737. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
  738. }
  739. NSApp.endSheet(vc.window!)
  740. vc.close()
  741. }
  742. }
  743. }
  744. }
  745. }
  746. } else{
  747. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  748. }
  749. }
  750. override func reverseAction() {
  751. if KMMemberInfo.shared.isMemberAllFunction == false {
  752. let winC = KMProductCompareWC.shared
  753. winC.kEventName = "Reading_Reverse_BuyNow"
  754. KMMemberInfo.shared.advancedFunctionUsage()
  755. return
  756. }
  757. let cnt = self.thumbnailView.selectionIndexPaths.count
  758. if cnt < 2 {
  759. self._progressHUD(message: KMLocalizedString("No page selected. Please select at least two pages to organize."))
  760. return
  761. }
  762. self.trackEvent(type: .reverse)
  763. self.toolBar.unSelectItem(for: KMToolbarPageEditReverseItemIdentifier)
  764. self.reverseMenuAction(sender: nil)
  765. }
  766. func showSplitWindow(callback: @escaping (KMPageEditSplitWindowController, KMPageEditSplitSettingModel)->Void) {
  767. let model = KMPageEditSplitSettingModel()
  768. model.documentURL = self.listView?.document.documentURL
  769. if let pagecnt = self.thumbnailView.document?.pageCount {
  770. model.pageCount = Int(pagecnt)
  771. }
  772. model.fileName = model.documentURL?.lastPathComponent ?? ""
  773. model.pathExtension = model.fileName?.components(separatedBy: ".").last
  774. if (self.isEmptySelection() == false) {
  775. model.type = 2
  776. model.pageRangeType = 2
  777. var selectedIndexs: Array<Int> = []
  778. for indexpath in self.thumbnailView.selectionIndexPaths {
  779. selectedIndexs.append(indexpath.item)
  780. }
  781. model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs)
  782. } else {
  783. model.type = 0
  784. }
  785. let windowController = KMPageEditSplitWindowController(model)
  786. self.km_beginSheet(windowC: windowController)
  787. windowController.itemClick = { [weak self] index, value in
  788. if (index == 1) { /// 取消
  789. self?.km_endSheet()
  790. return
  791. }
  792. guard let _windowC = self?.kmCurrentWindowC as? KMPageEditSplitWindowController else {
  793. self?.km_endSheet()
  794. return
  795. }
  796. callback(_windowC, model)
  797. }
  798. }
  799. private func _splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
  800. let outputModel = windowC.model as! KMPageEditSplitSettingModel
  801. DispatchQueue.main.async {
  802. let panel = NSOpenPanel()
  803. panel.canChooseFiles = false
  804. panel.canChooseDirectories = true
  805. panel.canCreateDirectories = true
  806. panel.beginSheetModal(for: NSWindow.currentWindow()) { response in
  807. if (response == .cancel) {
  808. return
  809. }
  810. let file_indexs = outputModel.getSplitIndexSets ?? []
  811. if (file_indexs.count <= 0) {
  812. return
  813. }
  814. DispatchQueue.main.async {
  815. self.showProgressWindow(message: NSLocalizedString("Spliting...", comment: ""))
  816. self.progressC?.maxValue = Double(file_indexs.count)
  817. let _document = self.listView?.document
  818. let filePath = "\(panel.url!.path)/\(_document?.documentURL.deletingPathExtension().lastPathComponent ?? "")"
  819. let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath)
  820. // Swift.debugPrint(uniqueFilePath)
  821. if (!FileManager.default.fileExists(atPath: uniqueFilePath)) {
  822. try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true)
  823. }
  824. var filepaths: [String] = []
  825. for i in 0 ..< file_indexs.count {
  826. let indexs = file_indexs[i]
  827. if (indexs.isEmpty) {
  828. continue
  829. }
  830. let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1))
  831. filepaths.append(filepath)
  832. let newDocument = CPDFDocument()
  833. newDocument?.importPages(indexs, from: _document, at: 0)
  834. self.progressC?.increment(by: 1.0)
  835. newDocument?.write(to: URL(fileURLWithPath: filepath))
  836. }
  837. self.hiddenProgressWindow()
  838. self.km_endSheet()
  839. if let _urlString = filepaths.first?.deletingLastPathComponent {
  840. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
  841. }
  842. }
  843. }
  844. }
  845. }
  846. // MARK: Undo / Redo
  847. @objc private func reversePages(indexs: IndexSet) {
  848. if let doc = self.thumbnailView.document {
  849. KMThumbnailCache.shared.clearCache()
  850. // KMPageEditTools.reverse(doc, indexs
  851. // ) { result, error in
  852. // if (result) {
  853. // self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  854. //
  855. // self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  856. // }
  857. // }
  858. var theIdxs = indexs
  859. var res = false
  860. for i in 0 ..< indexs.count {
  861. guard let first = theIdxs.first else {
  862. break
  863. }
  864. guard let last = theIdxs.last else {
  865. break
  866. }
  867. if first == last {
  868. break
  869. }
  870. res = self.pdfDocument?.exchangePage(at: UInt(first), withPageAt: UInt(last)) ?? false
  871. if res {
  872. theIdxs.remove(first)
  873. theIdxs.remove(last)
  874. }
  875. }
  876. if res {
  877. self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  878. self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  879. }
  880. }
  881. }
  882. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  883. if (indexs.count <= 0) {
  884. return
  885. }
  886. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  887. // 插入位置偏移量
  888. var toIndexOffset: Int = 0
  889. // 需要移动的页面index数组
  890. var newPages: [CPDFPage] = []
  891. var currentPage: CPDFPage?
  892. var originalIndex = self.listViewCurrentIndex
  893. // 从后面往前删除
  894. for index in indexs.reversed() {
  895. let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
  896. if (newPage == nil) {
  897. continue
  898. }
  899. newPages.insert(newPage!, at: 0)
  900. self.pdfDocument?.removePage(at: UInt(index))
  901. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  902. toIndexOffset += 1
  903. }
  904. if (currentPage == nil) && (originalIndex == index) {
  905. currentPage = newPage
  906. }
  907. }
  908. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  909. toIndexOffset -= 1
  910. }
  911. let insertIndex = max(0, toIndex-toIndexOffset)
  912. var selectIndexs: IndexSet = []
  913. for (index, page) in newPages.enumerated() {
  914. self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
  915. selectIndexs.insert(insertIndex+index)
  916. if (currentPage?.pageIndex() == page.pageIndex()) {
  917. // self._listViewCurrentIndex = insertIndex+index
  918. }
  919. }
  920. // 新增 undo
  921. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  922. target.clearSelectPages()
  923. target.dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  924. }
  925. KMThumbnailCache.shared.clearCache()
  926. // 刷新UI
  927. self.refreshUI()
  928. if (reversed == false) {
  929. self.selectPages(indexs: selectIndexs)
  930. }
  931. }
  932. @objc private func new_dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  933. if (indexs.count <= 0) {
  934. return
  935. }
  936. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  937. // 插入位置偏移量
  938. var toIndexOffset: Int = 0
  939. // 需要移动的页面index数组
  940. var newPages: [CPDFPage] = []
  941. var currentPage: CPDFPage?
  942. var originalIndex = self.listViewCurrentIndex
  943. // 从后面往前删除
  944. for index in indexs.reversed() {
  945. let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
  946. if (newPage == nil) {
  947. continue
  948. }
  949. newPages.insert(newPage!, at: 0)
  950. // self.pdfDocument?.removePage(at: UInt(index))
  951. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  952. toIndexOffset += 1
  953. }
  954. if (currentPage == nil) && (originalIndex == index) {
  955. currentPage = newPage
  956. }
  957. }
  958. var after = false
  959. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  960. toIndexOffset -= 1
  961. after = true
  962. }
  963. let insertIndex = max(0, toIndex-toIndexOffset)
  964. var selectIndexs: IndexSet = []
  965. for (index, page) in newPages.enumerated() {
  966. // self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
  967. selectIndexs.insert(insertIndex+index)
  968. if (currentPage?.pageIndex() == page.pageIndex()) {
  969. // self._listViewCurrentIndex = insertIndex+index
  970. }
  971. // self.pdfDocument?.movePage(at: UInt(index), withPageAt: UInt(insertIndex+index))
  972. }
  973. var theToIndex = toIndex
  974. if indexs.count == 1 {
  975. theToIndex = insertIndex
  976. }
  977. if after {
  978. var offset = 0
  979. for index in indexs {
  980. self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(theToIndex))
  981. offset += 1
  982. }
  983. } else {
  984. var offset = 0
  985. for index in indexs.reversed() {
  986. self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(theToIndex))
  987. offset += 1
  988. }
  989. }
  990. // 新增 undo
  991. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  992. target.clearSelectPages()
  993. target.new_dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  994. }
  995. KMThumbnailCache.shared.clearCache()
  996. // 刷新UI
  997. self.refreshUI()
  998. if (reversed == false) {
  999. self.selectPages(indexs: selectIndexs)
  1000. }
  1001. }
  1002. @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  1003. if (indexs.count <= 0) {
  1004. return
  1005. }
  1006. // 插入位置偏移量
  1007. var toIndexOffset: Int = 0
  1008. for index in indexs {
  1009. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1010. toIndexOffset += 1
  1011. }
  1012. }
  1013. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  1014. toIndexOffset -= 1
  1015. }
  1016. let insertIndex = max(0, toIndex-toIndexOffset)
  1017. // 需要移动的页面index数组
  1018. var datas: [Int] = []
  1019. for index in insertIndex ..< (insertIndex + indexs.count) {
  1020. datas.append(index)
  1021. }
  1022. // 从后面开始删除
  1023. for index in datas.reversed() {
  1024. self.pdfDocument?.removePage(at: UInt(index))
  1025. }
  1026. // 再插入到对应的位置
  1027. for (index,value) in indexs.enumerated() {
  1028. var page: CPDFPage?
  1029. if (index < pages.count) {
  1030. page = pages[index]
  1031. }
  1032. if (page != nil) {
  1033. self.pdfDocument?.insertPageObject(page!, at: UInt(value))
  1034. }
  1035. }
  1036. // 新增 undo
  1037. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1038. target.dragPages(indexs, toIndex, dp: dp, reversed: true)
  1039. }
  1040. // 刷新UI
  1041. self.refreshUI()
  1042. }
  1043. @objc private func new_dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  1044. if (indexs.count <= 0) {
  1045. return
  1046. }
  1047. // 插入位置偏移量
  1048. var toIndexOffset: Int = 0
  1049. for index in indexs {
  1050. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1051. toIndexOffset += 1
  1052. }
  1053. }
  1054. var after = false
  1055. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  1056. toIndexOffset -= 1
  1057. after = true
  1058. }
  1059. let insertIndex = max(0, toIndex-toIndexOffset)
  1060. // 需要移动的页面index数组
  1061. var datas: [Int] = []
  1062. for index in insertIndex ..< (insertIndex + indexs.count) {
  1063. datas.append(index)
  1064. }
  1065. // 从后面开始删除
  1066. for index in datas.reversed() {
  1067. // self.pdfDocument?.removePage(at: UInt(index))
  1068. }
  1069. // 再插入到对应的位置
  1070. for (index,value) in indexs.enumerated() {
  1071. var page: CPDFPage?
  1072. if (index < pages.count) {
  1073. page = pages[index]
  1074. }
  1075. if (page != nil) {
  1076. // self.pdfDocument?.insertPageObject(page!, at: UInt(value))
  1077. }
  1078. }
  1079. if after {
  1080. // var offset = 0
  1081. for (index,value) in indexs.enumerated() {
  1082. let idx = datas[index]
  1083. self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
  1084. // offset += 1
  1085. }
  1086. // for index in datas.reversed() {
  1087. // self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(toIndex))
  1088. // offset += 1
  1089. // }
  1090. } else {
  1091. // var offset = 0
  1092. for (index,value) in indexs.reversed().enumerated() {
  1093. let idx = datas.reversed()[index]
  1094. self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
  1095. }
  1096. // for index in indexs {
  1097. // self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(toIndex))
  1098. // offset += 1
  1099. // }
  1100. }
  1101. // 新增 undo
  1102. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1103. target.new_dragPages(indexs, toIndex, dp: dp, reversed: true)
  1104. }
  1105. KMThumbnailCache.shared.clearCache()
  1106. // 刷新UI
  1107. self.refreshUI()
  1108. }
  1109. // MARK: topBar 事件
  1110. @objc func zoomOutButtonAction(sender: NSButton?) {
  1111. if (self.itemSize.width > self.defaultItemSize.width) {
  1112. return
  1113. }
  1114. if (self.itemSize.width < self.defaultItemSize.width) {
  1115. self.itemSize = self.defaultItemSize
  1116. } else if (self.itemSize.width == self.defaultItemSize.width) {
  1117. self.itemSize = NSSize(width: self.defaultItemSize.width*2, height: self.defaultItemSize.height*2)
  1118. }
  1119. // self.toolBar.zoomInButton?.isEnabled = true
  1120. // if (self.itemSize.width > self.defaultItemSize.width) {
  1121. // sender?.isEnabled = false
  1122. // }
  1123. KMThumbnailCache.shared.clearCache()
  1124. self.pageEditThumbnailView.zoomOut()
  1125. if pageEditThumbnailView.canZoomIn() {
  1126. zoomOutButton.isEnabled = true
  1127. } else {
  1128. zoomOutButton.isEnabled = false
  1129. }
  1130. if pageEditThumbnailView.canZoomOut() {
  1131. zoomInButton.isEnabled = true
  1132. } else {
  1133. zoomInButton.isEnabled = false
  1134. }
  1135. }
  1136. @objc func zoomInButtonAction(sender: NSButton?) {
  1137. if (self.itemSize.width < self.defaultItemSize.width) {
  1138. return
  1139. }
  1140. if (self.itemSize.width > self.defaultItemSize.width) {
  1141. self.itemSize = self.defaultItemSize
  1142. } else if (self.itemSize.width == self.defaultItemSize.width) {
  1143. self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
  1144. }
  1145. // self.toolBar.zoomOutButton?.isEnabled = true
  1146. // if (self.itemSize.width < self.defaultItemSize.width) {
  1147. // sender?.isEnabled = false
  1148. // }
  1149. KMThumbnailCache.shared.clearCache()
  1150. self.pageEditThumbnailView.zoomIn()
  1151. if pageEditThumbnailView.canZoomIn() {
  1152. zoomOutButton.isEnabled = true
  1153. } else {
  1154. zoomOutButton.isEnabled = false
  1155. }
  1156. if pageEditThumbnailView.canZoomOut() {
  1157. zoomInButton.isEnabled = true
  1158. } else {
  1159. zoomInButton.isEnabled = false
  1160. }
  1161. }
  1162. // MARK: menu 菜单事件
  1163. override func menuNeedsUpdate(_ menu: NSMenu) {
  1164. // let row = self.thumbnailView.collectionView.selectionIndexes
  1165. // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil)
  1166. let point = self.view.window?.currentEvent?.locationInView(self.thumbnailView.collectionView) ?? .zero
  1167. let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point)
  1168. menu.removeAllItems()
  1169. if indexpaths == nil || indexpaths!.isEmpty { // 空白处点击
  1170. if KMThumbnailManager.manager.copyPages.isEmpty { // 不能粘贴
  1171. // if self.canPaste() {
  1172. return
  1173. }
  1174. let item_ = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pasteActonForEmpty), target: self)
  1175. // item_?.keyEquivalent = KMKeyEquivalent.paste
  1176. let repObj = self.thumbnailView.collectionView.km_indexPathForItem(at: point, nearest: true)
  1177. item_?.representedObject = repObj
  1178. return
  1179. }
  1180. super.menuNeedsUpdate(menu)
  1181. }
  1182. @objc func item_insertCustomPage(sender: NSMenuItem?) {
  1183. if KMMemberInfo.shared.isMemberAllFunction == false {
  1184. let winC = KMProductCompareWC.shared
  1185. if self.kEventTag == 1 {
  1186. winC.kEventName = "Onbrd_EditPage_BuyNow"
  1187. } else {
  1188. winC.kEventName = "Reading_InsertBlankPage_BuyNow"
  1189. }
  1190. KMMemberInfo.shared.advancedFunctionUsage()
  1191. return
  1192. }
  1193. guard let doc = self.pdfDocument else {
  1194. NSSound.beep()
  1195. return
  1196. }
  1197. let windowC = KMPDFEditInsertBlankPageWindow(document: doc)
  1198. windowC.currentPage = self.getSelecteIndex() + 1
  1199. windowC.insertLocation = 3
  1200. windowC.callback = { [weak self] pdfDoc, _, pages, insertI in
  1201. if pages != nil {
  1202. // mm 单位的大小
  1203. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  1204. self?.km_endSheet()
  1205. return
  1206. }
  1207. var pageSize = _winC.pageSize
  1208. let direction = windowC.pageRotation == 0 ? 0 : 1
  1209. if (direction == 0) { // 纵向
  1210. if (pageSize.width > pageSize.height) { // 需要交换
  1211. let tmp = pageSize.width
  1212. pageSize.width = pageSize.height
  1213. pageSize.height = tmp
  1214. } else {
  1215. // no things.
  1216. }
  1217. } else { // 横向
  1218. if (pageSize.width > pageSize.height) {
  1219. // no things.
  1220. } else { // 需要交换
  1221. let tmp = pageSize.width
  1222. pageSize.width = pageSize.height
  1223. pageSize.height = tmp
  1224. }
  1225. }
  1226. /// 插入位置
  1227. let document = CPDFDocument()
  1228. document?.insertPage(pageSize, at: 0)
  1229. if let page: CPDFPage = (document?.page(at: 0)) {
  1230. self?.insertPages(pages: [page], at: IndexSet(integer: insertI))
  1231. }
  1232. let ips: Set<IndexPath> = [IndexPath(item: insertI, section: 0)]
  1233. self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1234. }
  1235. self?.km_endSheet()
  1236. }
  1237. self.km_beginSheet(windowC: windowC)
  1238. }
  1239. @objc func item_insertFromImage(sender: NSMenuItem?) {
  1240. if KMMemberInfo.shared.isMemberAllFunction == false {
  1241. let winC = KMProductCompareWC.shared
  1242. if self.kEventTag == 1 {
  1243. winC.kEventName = "Onbrd_EditPage_BuyNow"
  1244. } else {
  1245. winC.kEventName = "Reading_InsertImage_BuyNow"
  1246. }
  1247. KMMemberInfo.shared.advancedFunctionUsage()
  1248. return
  1249. }
  1250. let openPanel = NSOpenPanel()
  1251. openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  1252. openPanel.allowsMultipleSelection = true
  1253. 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)
  1254. openPanel.canChooseDirectories = false
  1255. openPanel.allowsMultipleSelection = false
  1256. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1257. if result == NSApplication.ModalResponse.OK {
  1258. if let fileURL = openPanel.urls.first {
  1259. // self.choosePositionWindow {[weak self] index in
  1260. // /// 插入位置
  1261. if NSDocument.isDamage(url: fileURL, needAlertIfDamage: true) { // 损坏图片
  1262. return
  1263. }
  1264. if let imag = NSImage(contentsOfFile: fileURL.path ) {
  1265. let index = self.getInsertIndex() + 1
  1266. let document = CPDFDocument()
  1267. _ = document?.km_insertPage(imag.size, withImage: fileURL.path , at: 0)
  1268. if let page: CPDFPage = (document?.page(at: 0)) {
  1269. self.insertPages(pages: [page], at: IndexSet(integer: index))
  1270. }
  1271. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1272. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1273. }
  1274. // }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. func choosePositionWindow(completion: @escaping KMIndexChooseBlock) -> Void {
  1280. // guard let doc = self.pdfDocument else {
  1281. // NSSound.beep()
  1282. // return
  1283. // }
  1284. // let windowC = KMFileInsertPositionWindowController(document: doc)
  1285. // windowC.currentPage = self.getSelecteIndex() + 1
  1286. // windowC.insertLocation = 3
  1287. // windowC.callback = { [weak self] pdfDoc, _, insertI in
  1288. // if insertI >= 0 {
  1289. // if (completion != nil) {
  1290. // completion(insertI);
  1291. // }
  1292. // }
  1293. // self?.km_endSheet()
  1294. // }
  1295. // self.km_beginSheet(windowC: windowC)
  1296. }
  1297. @objc func item_insertFromClipboard(sender: NSMenuItem?) {
  1298. if KMMemberInfo.shared.isMemberAllFunction == false {
  1299. let winC = KMProductCompareWC.shared
  1300. if self.kEventTag == 1 {
  1301. winC.kEventName = "Onbrd_EditPage_BuyNow"
  1302. } else {
  1303. winC.kEventName = "Reading_InsertClipboard_BuyNow"
  1304. }
  1305. KMMemberInfo.shared.advancedFunctionUsage()
  1306. return
  1307. }
  1308. /// 插入位置
  1309. var error: NSError?
  1310. guard let document: CPDFDocument = self.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
  1311. return
  1312. }
  1313. let index = self.getInsertIndex() + 1
  1314. if let page: CPDFPage = (document.page(at: 0)) {
  1315. self.insertPages(pages: [page], at: IndexSet(integer: index))
  1316. }
  1317. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1318. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1319. }
  1320. @objc func item_insertFromScanner(sender: NSMenuItem?) {
  1321. if KMMemberInfo.shared.isMemberAllFunction == false {
  1322. let winC = KMProductCompareWC.shared
  1323. if self.kEventTag == 1 {
  1324. winC.kEventName = "Onbrd_EditPage_BuyNow"
  1325. } else {
  1326. winC.kEventName = "Reading_InsertSacnner_BuyNow"
  1327. }
  1328. KMMemberInfo.shared.advancedFunctionUsage()
  1329. return
  1330. }
  1331. let vc = KMDeviceBrowserWindowController.shared
  1332. vc.type = .scanner
  1333. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1334. /// 插入位置
  1335. if let imag = NSImage(contentsOfFile: url.path! ) {
  1336. let index = (self?.getInsertIndex())! + 1
  1337. let document = CPDFDocument()
  1338. _ = document?.km_insertPage(imag.size, withImage: url.path! , at: 0)
  1339. if let page: CPDFPage = (document?.page(at: 0)) {
  1340. self?.insertPages(pages: [page], at: IndexSet(integer: index))
  1341. }
  1342. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1343. self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1344. }
  1345. vc.close()
  1346. }
  1347. vc.showWindow(NSApp.mainWindow)
  1348. }
  1349. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
  1350. var document: CPDFDocument? = nil
  1351. var data: Data? = nil
  1352. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  1353. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  1354. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  1355. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  1356. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  1357. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  1358. } else {
  1359. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  1360. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  1361. if images?.count ?? 0 > 0 {
  1362. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  1363. } else if strings?.count ?? 0 > 0 {
  1364. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  1365. }
  1366. }
  1367. if let data = data {
  1368. document = CPDFDocument(data: data)
  1369. } else if let outError = outError {
  1370. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  1371. }
  1372. return document
  1373. }
  1374. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  1375. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  1376. let pdfData = NSMutableData(capacity: tiffData.count)
  1377. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  1378. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  1379. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  1380. ctxt!.beginPDFPage(nil)
  1381. ctxt!.draw(cgImage, in: rect)
  1382. ctxt!.endPDFPage()
  1383. ctxt!.closePDF()
  1384. return pdfData as? Data
  1385. }
  1386. func extractSelectPageItemAction() {
  1387. if KMMemberInfo.shared.isMemberAllFunction == false {
  1388. let winC = KMProductCompareWC.shared
  1389. if self.kEventTag == 1 {
  1390. winC.kEventName = "Onbrd_EditPage_BuyNow"
  1391. } else {
  1392. winC.kEventName = "Reading_Extract_BuyNow"
  1393. }
  1394. KMMemberInfo.shared.advancedFunctionUsage()
  1395. return
  1396. }
  1397. let indexs = self.thumbnailView.selectionIndexPaths
  1398. if indexs.isEmpty {
  1399. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  1400. return
  1401. }
  1402. self.extractPages(indexpaths: indexs, oneDocumentPerPage: false) { result, params in }
  1403. }
  1404. // MARK: toolBar 菜单事件
  1405. @objc func reverseMenuAction(sender: AnyObject?) {
  1406. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  1407. if (selectedIndexs.count < 2 ) {
  1408. let alertView = CustomAlertView.alertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), fromView: self.thumbnailView, withStyle: .blue)
  1409. alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1410. alertView?.layer?.cornerRadius = 4
  1411. return
  1412. }
  1413. self.reversePages(indexs: self.indexpathsToIndexs(indexpaths: selectedIndexs))
  1414. self.dealPdfDocumentDidEditCallback(type: .reverse)
  1415. }
  1416. override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? {
  1417. var item_: NSMenuItem?
  1418. if (item.sel == KMPDFThumbViewMenu.insertSelector) {
  1419. item_ = menu.addItem(withTitle: NSLocalizedString("Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self)
  1420. } else if (item.sel == KMPDFThumbViewMenu.splitSelector) {
  1421. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  1422. item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self)
  1423. }
  1424. } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) {
  1425. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  1426. item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self)
  1427. }
  1428. } else {
  1429. return super.addMenuItem(menu: menu, item: item)
  1430. }
  1431. return item_
  1432. }
  1433. // MARK: - Zoom Methods
  1434. @IBAction func buttonClicked_Bigger(_ sender: AnyObject?) {
  1435. // if (self.thumbnailView.thumbnailSize.width == 100.) {
  1436. // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
  1437. // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
  1438. // self.thumbnailView.thumbnailSize = CGSizeMake(400, 400);
  1439. // }
  1440. self.zoomOutButtonAction(sender: sender as? NSButton)
  1441. }
  1442. @IBAction func buttonClicked_Smaller(_ sender: AnyObject?) {
  1443. // if (self.thumbnailView.thumbnailSize.width == 400.) {
  1444. // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
  1445. // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
  1446. // self.thumbnailView.thumbnailSize = CGSizeMake(100, 100);
  1447. // }
  1448. self.zoomInButtonAction(sender: sender as? NSButton)
  1449. }
  1450. override func mouseMoved(with event: NSEvent) {
  1451. super.mouseMoved(with: event)
  1452. self.view.window?.mouseMoved(with: event)
  1453. }
  1454. }
  1455. extension KMPDFEditViewController {
  1456. //MARK: menu Action
  1457. @objc func insertPageItemAction(menu:NSMenuItem) {
  1458. if (menu.tag == 0) {
  1459. self.insertBlankPageAction()
  1460. } else if (menu.tag == 1) {
  1461. self.item_insertCustomPage(sender: nil)
  1462. } else if (menu.tag == 2) {
  1463. self.insertFileAction()
  1464. }
  1465. }
  1466. @objc func sharePageItemAction(menu:NSMenuItem) {
  1467. guard let item = menu.parent else {
  1468. NSSound.beep()
  1469. return
  1470. }
  1471. let index = (item.representedObject as? IndexSet)?.first ?? -1
  1472. if Int(index) >= 0 {
  1473. let doucument = self.pdfDocument
  1474. // let page = doucument.page(at: UInt(index))
  1475. let filename : String = doucument?.documentURL.lastPathComponent ?? ""
  1476. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename)) ?? ""
  1477. try? FileManager.default.removeItem(atPath: folderPath)
  1478. let pdfdocument = CPDFDocument()
  1479. let ret = pdfdocument?.importPages((item.representedObject as? IndexSet) ?? [], from: self.thumbnailView.document, at: 0) ?? false
  1480. let url = URL(fileURLWithPath: folderPath)
  1481. if ret {
  1482. let success = pdfdocument?.write(to:url) ?? false
  1483. // if success {
  1484. // let workspace = NSWorkspace.shared
  1485. // workspace.activateFileViewerSelecting([url])
  1486. // }
  1487. }
  1488. let represent = menu.representedObject as? NSSharingService
  1489. represent?.perform(withItems: [url])
  1490. }
  1491. }
  1492. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  1493. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  1494. self.refreshUIForKeepSelecteds()
  1495. }
  1496. @objc func printItemAction(menu:NSMenuItem) {
  1497. var datas: [Int] = []
  1498. for indexpath in self.thumbnailView.selectionIndexPaths {
  1499. datas.append(indexpath.item)
  1500. }
  1501. guard let callback = self.itemClick else {
  1502. return
  1503. }
  1504. callback(2, datas.sorted())
  1505. }
  1506. override func menuItemAction_extract(_ sender: Any?) {
  1507. self.extractSelectPageItemAction()
  1508. }
  1509. }
  1510. extension KMPDFEditViewController {
  1511. override func menuItemAction_print(_ sender: Any?) {
  1512. if let item = sender as? NSMenuItem {
  1513. self.printItemAction(menu: item)
  1514. }
  1515. }
  1516. override func menuItemAction_showPageSize(_ sender: Any?) {
  1517. if let item = sender as? NSMenuItem {
  1518. self.showPageSizeItemAction(menu: item)
  1519. }
  1520. }
  1521. override func menuItemAction_share(_ sender: Any?) {
  1522. if let item = sender as? NSMenuItem {
  1523. self.sharePageItemAction(menu: item)
  1524. }
  1525. }
  1526. }
  1527. // MARK: - KMSelectPopButtonDelegate
  1528. extension KMPDFEditViewController {
  1529. func km_comboBoxSelectionDidChange(_ obj: KMPageRange) {
  1530. self.pageIsUpdate = false
  1531. var indexpaths: Set<IndexPath> = []
  1532. let type: KMPageRange? = obj
  1533. let pageCnt = self.pdfDocument?.pageCount ?? 0
  1534. for i in 0 ..< pageCnt {
  1535. if (type == .all) {
  1536. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1537. } else if (type == .odd) {
  1538. if (i % 2 == 1) {
  1539. continue
  1540. }
  1541. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1542. } else if (type == .even) {
  1543. if (i % 2 == 0) {
  1544. continue
  1545. }
  1546. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1547. } else if (type == .horizontal) {
  1548. let page = self.pdfDocument?.page(at: i)
  1549. guard let isVertical = page?.isVertical(), !isVertical else {
  1550. continue
  1551. }
  1552. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1553. } else if (type == .vertical) {
  1554. let page = self.pdfDocument?.page(at: i)
  1555. guard let isHorizontal = page?.isHorizontal(), !isHorizontal else {
  1556. continue
  1557. }
  1558. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1559. }
  1560. }
  1561. if (type == .custom) {
  1562. let windowC = KMPDFEditPageRangeWindowController()
  1563. windowC.pdfDocument = self.pdfDocument
  1564. windowC.pageSelectCallBack = { [weak self] pagesArray in
  1565. var indexpaths = Set<IndexPath>()
  1566. for page in pagesArray {
  1567. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1568. }
  1569. self?.km_endSheet()
  1570. self?.selectPages(indexpaths: indexpaths)
  1571. self?.thumbnailView.collectionView.scrollToItems(at: indexpaths, scrollPosition: .bottom)
  1572. }
  1573. self.km_beginSheet(windowC: windowC)
  1574. } else {
  1575. self.pageEditThumbnailView.selectPages(at: indexpaths)
  1576. }
  1577. }
  1578. func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
  1579. self.view.window?.makeFirstResponder(self)
  1580. for index in 0 ..< obj.numberOfItems {
  1581. if (obj.items[index] == obj.stringValue) {
  1582. return
  1583. }
  1584. }
  1585. let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView?.stringValue ?? "", pageCount: Int((self.listView?.document.pageCount) ?? 0))
  1586. if (pages.isEmpty) {
  1587. let alert = NSAlert()
  1588. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1589. alert.runModal()
  1590. self.toolBar.setPageRangeString("")
  1591. DispatchQueue.main.async {
  1592. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  1593. }
  1594. return
  1595. }
  1596. var indexpaths: Set<IndexPath> = []
  1597. for page in pages {
  1598. if (page >= 1) {
  1599. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1600. }
  1601. }
  1602. self.pageIsUpdate = false
  1603. self.pageEditThumbnailView.selectPages(at: indexpaths)
  1604. }
  1605. }
  1606. // MARK: -
  1607. // MARK: KMThumbnailViewDelegate
  1608. extension KMPDFEditViewController: KMThumbnailViewDelegate {
  1609. func thumbnailView(thumbanView: KMThumbnailView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
  1610. return KMMemberInfo.shared.isMemberAllFunction
  1611. }
  1612. func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  1613. return true
  1614. }
  1615. func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  1616. self.km_add_file_multi(fileUrls: files) { index, params in
  1617. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  1618. return
  1619. }
  1620. let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  1621. if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
  1622. if (_fileUrl!.path.isPDFValid() == false) {
  1623. let alert = NSAlert()
  1624. alert.alertStyle = .critical
  1625. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1626. alert.runModal()
  1627. }
  1628. }
  1629. } completionBlock: { [weak self] documents in
  1630. var insertIndex: Int = indexpath.item
  1631. var pages: Array<CPDFPage> = []
  1632. var indexs = IndexSet()
  1633. self?.model.insertedDocumentSet.formUnion(documents)
  1634. for document in documents {
  1635. for i in 0 ..< document.pageCount {
  1636. if let page = document.page(at: i) {
  1637. pages.append(page)
  1638. indexs.insert(insertIndex)
  1639. insertIndex += 1
  1640. }
  1641. }
  1642. }
  1643. self?.insertPages(pages: pages, at: indexs)
  1644. }
  1645. }
  1646. func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
  1647. let toIndex = max(0, indexpath.item)
  1648. var indexs = IndexSet()
  1649. for indexpath in dragedIndexPaths {
  1650. indexs.insert(indexpath.item)
  1651. }
  1652. var dp = NSCollectionView.DropOperation.on
  1653. if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation {
  1654. dp = _dp
  1655. }
  1656. self.new_dragPages(indexs, toIndex, dp: dp)
  1657. if (dragedIndexPaths.count > 0) {
  1658. self.dealPdfDocumentDidEditCallback()
  1659. }
  1660. }
  1661. func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
  1662. // if (!self.canPayFunction) {
  1663. // return false
  1664. // }
  1665. return true
  1666. }
  1667. func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  1668. return NSEdgeInsets(top: 6, left: 40, bottom: 0, right: 40)
  1669. }
  1670. func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  1671. self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
  1672. if (!self.thumbnailView.isShowPageSize) {
  1673. return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
  1674. }
  1675. return self.itemSize
  1676. }
  1677. func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int {
  1678. if let count = self.pdfDocument?.pageCount {
  1679. return Int(count)
  1680. }
  1681. return 0
  1682. }
  1683. func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
  1684. let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.km.dequeueReusableCell(for: indexpath)
  1685. cellView.isShowPageSize = self.thumbnailView.isShowPageSize
  1686. if let data = self.pdfDocument?.page(at: UInt(indexpath.item)) {
  1687. cellView.setPage(page: data)
  1688. }
  1689. let bks = self.listView?.document.bookmarks()
  1690. var hasBookmark = false
  1691. for bk in bks ?? [] {
  1692. if indexpath.item == bk.pageIndex {
  1693. hasBookmark = true
  1694. break
  1695. }
  1696. }
  1697. cellView.bkIcon.isHidden = !hasBookmark
  1698. cellView.doubleClickAction = { [weak self] _ in
  1699. guard let callback = self?.itemClick else {
  1700. return
  1701. }
  1702. callback(1, indexpath.item)
  1703. }
  1704. cellView.mouseDownAction = { [unowned self] _ in
  1705. let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
  1706. if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
  1707. return
  1708. }
  1709. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1710. }
  1711. cellView.rightMouseDownAction = { [weak self] _ in
  1712. self?.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1713. }
  1714. return cellView
  1715. }
  1716. }
  1717. // MARK: - 系统菜单栏
  1718. extension KMPDFEditViewController {
  1719. override func undo(_ sender: Any?) {
  1720. super.undo(sender)
  1721. self.km_becomeFirstResponder()
  1722. }
  1723. override func redo(_ sender: Any?) {
  1724. super.redo(sender)
  1725. self.km_becomeFirstResponder()
  1726. }
  1727. }
  1728. // MARK: - KMExtensions
  1729. extension KMPDFEditViewController {
  1730. override func deleteAfter(indexpaths: Set<IndexPath>) {
  1731. self.clearSelectPages()
  1732. self.km_becomeFirstResponder()
  1733. }
  1734. override func copyAfter(indexpaths: Set<IndexPath>) {
  1735. self.km_becomeFirstResponder()
  1736. }
  1737. override func pasteAfter(at index: Int) {
  1738. self.km_becomeFirstResponder()
  1739. }
  1740. override func cutAfter(indexpaths: Set<IndexPath>) {
  1741. self.clearSelectPages()
  1742. self.km_becomeFirstResponder()
  1743. }
  1744. override func leftRotateAfter(indexpaths: Set<IndexPath>) {
  1745. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1746. self.km_becomeFirstResponder()
  1747. }
  1748. override func rightRotateAfter(indexpaths: Set<IndexPath>) {
  1749. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1750. self.km_becomeFirstResponder()
  1751. }
  1752. override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) {
  1753. var indexpaths = Set<IndexPath>()
  1754. var insertIndex = index
  1755. for _ in pages {
  1756. indexpaths.insert(IndexPath(item: insertIndex, section: 0))
  1757. insertIndex += 1
  1758. }
  1759. self.thumbnailView.selectionIndexPaths = indexpaths
  1760. self.dealPdfDocumentDidEditCallback(type: .replace)
  1761. }
  1762. override func insertBlankPageAfter(size: NSSize, at index: Int) {
  1763. self.selectPages(indexs: IndexSet(integer: index))
  1764. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1765. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1766. self.dealPdfDocumentDidEditCallback(type: .insert)
  1767. }
  1768. func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) {
  1769. if (indexs.isEmpty) {
  1770. return
  1771. }
  1772. // listView 当前页面 被拖拽
  1773. if (indexs.contains(self._listViewCurrentIndex)) {
  1774. // let idx = indexs.firstIndex(of: self._listViewCurrentIndex)
  1775. var idx: Int = 0
  1776. for index in indexs {
  1777. if (index == self._listViewCurrentIndex) {
  1778. break
  1779. }
  1780. idx += 1
  1781. }
  1782. // 插入位置偏移量
  1783. var toIndexOffset: Int = 0
  1784. // 从后面往前删除
  1785. for index in indexs.reversed() {
  1786. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  1787. if (newPage == nil) {
  1788. continue
  1789. }
  1790. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1791. toIndexOffset += 1
  1792. }
  1793. }
  1794. if (indexs.last! < toIndex) { // 往后拖拽
  1795. toIndexOffset -= 1
  1796. }
  1797. let insertIndex = max(0, toIndex-toIndexOffset)
  1798. self._listViewCurrentIndex = insertIndex+idx
  1799. } else {
  1800. var forwardCnt = 0
  1801. var nextCnt = 0
  1802. for index in indexs {
  1803. if (index > self._listViewCurrentIndex) {
  1804. nextCnt += 1
  1805. } else {
  1806. forwardCnt += 1
  1807. }
  1808. }
  1809. if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式
  1810. self._listViewCurrentIndex += nextCnt
  1811. } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式
  1812. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1813. } else { // 插入到目标位置 [跟插入到目标后面一样]
  1814. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1815. }
  1816. }
  1817. }
  1818. }
  1819. // MARK: - Analytics (埋点)
  1820. extension KMPDFEditViewController {
  1821. func trackEvent(type: KMPageEditType, index: Int = 0) -> Void {
  1822. if (type == .insert) {
  1823. if index == 0 {
  1824. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [
  1825. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1826. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1827. } else if index == KMPageEditType.insert_blank_page || index == KMPageEditType.insert_custom_page {
  1828. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertBlankPage"], platform: .AppCenter)
  1829. } else if index == KMPageEditType.insert_files {
  1830. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertPDF"], platform: .AppCenter)
  1831. } else if index == KMPageEditType.insert_fromImage {
  1832. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertImage"], platform: .AppCenter)
  1833. } else if index == KMPageEditType.insert_fromClipboard {
  1834. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertClipboard"], platform: .AppCenter)
  1835. } else if index == KMPageEditType.insert_fromScanner {
  1836. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertScanner"], platform: .AppCenter)
  1837. }
  1838. } else if (type == .extract) {
  1839. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [
  1840. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1841. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1842. } else if (type == .leftRotate || type == .rightRotate) {
  1843. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [
  1844. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1845. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1846. } else if (type == .replace) {
  1847. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [
  1848. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1849. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1850. } else if (type == .split) {
  1851. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [
  1852. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1853. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1854. } else if (type == .reverse) {
  1855. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [
  1856. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1857. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1858. } else if (type == .delete) {
  1859. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [
  1860. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1861. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1862. }
  1863. }
  1864. func trackEvent_copy() -> Void {
  1865. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [
  1866. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1867. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1868. }
  1869. }