KMMainViewController+Action.swift 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool) {
  10. let document = self.listView.document
  11. if ((document?.isFinding) != nil) {
  12. document?.cancelFindString()
  13. }
  14. if searchString == "" {
  15. self.searchResults = []
  16. self.leftSideViewController.searchViewController.searchResults = self.searchResults
  17. self.leftSideViewController.searchViewController.reloadData()
  18. } else {
  19. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  20. var findArray : [[CPDFSelection]]
  21. if isCase {
  22. findArray = self.listView.document.findString(searchString) ?? []
  23. } else {
  24. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  25. }
  26. self.searchResults.removeAll()
  27. for selections in findArray {
  28. for selection in selections {
  29. let mode : KMSearchMode = KMSearchMode()
  30. mode.selection = selection
  31. mode.attributedString = KMOCToolClass.getAttributedString(with: selection, keyword: searchString)
  32. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  33. self.searchResults.insert(mode, at: self.searchResults.count)
  34. }
  35. }
  36. self.leftSideViewController.searchViewController.searchResults = self.searchResults
  37. self.leftSideViewController.searchViewController.reloadData()
  38. }
  39. }
  40. func removeSignatures(signatures:[CPDFSignature]) {
  41. for signature in signatures {
  42. self.listView.document.removeSignature(signature)
  43. }
  44. for i in 0..<self.listView.document.pageCount {
  45. let page : CPDFPage = self.listView.document.page(at: i)
  46. let annotations : [CPDFAnnotation] = page.annotations
  47. for j in 0..<annotations.count {
  48. let annotation = annotations[j]
  49. if annotation is CPDFSignatureWidgetAnnotation {
  50. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  51. }
  52. }
  53. }
  54. self.listView.setNeedsDisplayForVisiblePages()
  55. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  56. var mSignatures : [CPDFSignature] = []
  57. for sign in tSignatures {
  58. if sign.signers.count > 0 {
  59. mSignatures.append(sign)
  60. }
  61. }
  62. self.leftSideViewController.signatureViewController.signatures = signatures
  63. self.leftSideViewController.signatureViewController.reloadData()
  64. }
  65. //MARK: menu菜单
  66. func fontColorMenuItem()->NSMenuItem {
  67. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  68. return fontColorItem;
  69. }
  70. func fontSizeMenuItem()->NSMenuItem {
  71. let currentFontSize = self.listView.editingTextFontSize()
  72. let fontSizes = self.fontSizes()
  73. let submenu = NSMenu(title: "")
  74. for i in 0 ... fontSizes.count - 1 {
  75. let fontSize : String = fontSizes.object(at: i) as! String
  76. let item = NSMenuItem(title:fontSize as! String, action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  77. item.target = self
  78. item.tag = i
  79. submenu.addItem(item)
  80. if (Int(currentFontSize) == Int(fontSize)) {
  81. item.state = .on
  82. }
  83. }
  84. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  85. fontSizeItem.submenu = submenu
  86. return fontSizeItem;
  87. }
  88. func corpImageMenuItem()->NSMenuItem {
  89. var corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm Crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)!
  90. return corpImageItem
  91. }
  92. func cancelCorpImageMenuItem()->NSMenuItem {
  93. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel Crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)!
  94. return cancelCorpImageItem
  95. }
  96. func restoreCorpImageMenuItem()->NSMenuItem {
  97. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString(" Restore Crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)!
  98. return cancelCorpImageItem
  99. }
  100. func cutImageArea()->NSMenuItem {
  101. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)!
  102. return deleteItem
  103. }
  104. func editAddBlanMenu(menu:NSMenu){
  105. menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  106. menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  107. }
  108. func addText() -> NSMenuItem {
  109. var addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)!
  110. return addTextItem
  111. }
  112. func addImage() -> NSMenuItem {
  113. var addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)!
  114. return addImageItem
  115. }
  116. func replaceImageArea()->NSMenuItem {
  117. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)!
  118. return replaceItem
  119. }
  120. func exportImageArea()->NSMenuItem {
  121. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)!
  122. return exportItem
  123. }
  124. func exportImageStampItem()->NSMenuItem {
  125. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)!
  126. let menu = NSMenu()
  127. menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  128. menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  129. exportItem.submenu = menu
  130. return exportItem
  131. }
  132. func exportMenu() -> NSMenu {
  133. let menu = NSMenu()
  134. menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  135. menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  136. menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  137. return menu
  138. }
  139. func cropMenu() -> NSMenu {
  140. let menu = NSMenu()
  141. menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  142. menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  143. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  144. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  145. return menu
  146. }
  147. func zoomSelectionMenuItem() -> NSMenuItem {
  148. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)!
  149. return item
  150. }
  151. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  152. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)!
  153. return item
  154. }
  155. func enterAnnotationStype() -> NSMenuItem {
  156. let stypItem = NSMenuItem(title: NSLocalizedString("Add Annotation", comment: ""), action: nil, target: self)!
  157. let stypeMenu = NSMenu()
  158. stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  159. stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  160. stypeMenu.addItem(withTitle: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  161. stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  162. stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  163. stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  164. stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  165. if self.isReadMode {
  166. } else {
  167. stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  168. stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  169. stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  170. }
  171. stypItem.submenu = stypeMenu
  172. if self.listView.annotationType == .ink {
  173. stypeMenu.item(at: 0)?.state = .on
  174. } else if self.listView.annotationType == .freeText {
  175. stypeMenu.item(at: 1)?.state = .on
  176. } else if self.listView.annotationType == .anchored {
  177. stypeMenu.item(at: 2)?.state = .on
  178. } else if self.listView.annotationType == .square {
  179. stypeMenu.item(at: 3)?.state = .on
  180. } else if self.listView.annotationType == .circle {
  181. stypeMenu.item(at: 4)?.state = .on
  182. } else if self.listView.annotationType == .arrow {
  183. stypeMenu.item(at: 5)?.state = .on
  184. } else if self.listView.annotationType == .line {
  185. stypeMenu.item(at: 6)?.state = .on
  186. } else if self.listView.annotationType == .link {
  187. stypeMenu.item(at: 7)?.state = .on
  188. } else if self.listView.annotationType == .stamp {
  189. stypeMenu.item(at: 8)?.state = .on
  190. } else if self.listView.annotationType == .signSignature {
  191. stypeMenu.item(at: 9)?.state = .on
  192. }
  193. return stypItem
  194. }
  195. func setAnnotationToolStype() -> NSMenuItem {
  196. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)!
  197. let stypeMenu = NSMenu()
  198. stypeMenu.addItem(withTitle: NSLocalizedString("Default Tool", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 0)
  199. stypeMenu.addItem(withTitle: NSLocalizedString("Scroll Tool", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 1)
  200. stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 2)
  201. stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 3)
  202. stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  203. stypItem.submenu = stypeMenu
  204. if self.toolbarController.toolbarType == .Annatiton {
  205. stypeMenu.item(at: 0)?.state = .on
  206. } else if self.toolbarController.toolbarType == .Move {
  207. stypeMenu.item(at: 1)?.state = .on
  208. } else if self.toolbarController.toolbarType == .Magnify {
  209. stypeMenu.item(at: 2)?.state = .on
  210. } else if self.toolbarController.toolbarType == .Select {
  211. stypeMenu.item(at: 3)?.state = .on
  212. } else if self.toolbarController.toolbarType == .SelectZoom {
  213. stypeMenu.item(at: 4)?.state = .on
  214. }
  215. return stypItem
  216. }
  217. func addReadModelStype() -> NSMenuItem {
  218. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)!
  219. if self.isReadMode {
  220. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)!
  221. }
  222. return stypItem
  223. }
  224. func addHighlightLinksStype() -> NSMenuItem {
  225. let highlightLink = KMPreferenceManager.shared.highlightLinks
  226. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  227. if highlightLink {
  228. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  229. }
  230. var highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)!
  231. return highlightLinksItem
  232. }
  233. func addAnnotationForStyleMenu(menu:NSMenu) {
  234. if menu == nil {
  235. return
  236. }
  237. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)!
  238. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)!
  239. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)!
  240. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)!
  241. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)!
  242. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)!
  243. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)!
  244. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)!
  245. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)!
  246. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)!
  247. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)!
  248. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  249. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  250. if listView.currentSelection.selectionType() != .image {
  251. menu.insertItem(height, at: menu.items.count)
  252. menu.insertItem(underline, at: menu.items.count)
  253. menu.insertItem(strickout, at: menu.items.count)
  254. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  255. }
  256. if self.isReadMode {
  257. } else {
  258. if listView.currentSelection.selectionType() != .image &&
  259. listView.currentSelection.selectionType() != .text {
  260. menu.insertItem(text, at: menu.items.count)
  261. menu.insertItem(note, at: menu.items.count)
  262. }
  263. }
  264. if self.isReadMode {
  265. } else {
  266. if listView.currentSelection.selectionType() != .image {
  267. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  268. menu.insertItem(rectangle, at: menu.items.count)
  269. menu.insertItem(oval, at: menu.items.count)
  270. }
  271. }
  272. if self.isReadMode {
  273. } else {
  274. if listView.currentSelection.selectionType() != .image &&
  275. listView.currentSelection.selectionType() != .text {
  276. menu.insertItem(line, at: menu.items.count)
  277. }
  278. }
  279. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  280. if self.isReadMode {
  281. } else {
  282. menu.insertItem(link, at: menu.items.count)
  283. }
  284. if self.isReadMode {
  285. } else {
  286. if listView.currentSelection.selectionType() != .image {
  287. menu.insertItem(outline, at: menu.items.count)
  288. }
  289. }
  290. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  291. if self.isReadMode {
  292. } else {
  293. menu.insertItem(aiTranslation, at: menu.items.count)
  294. }
  295. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  296. }
  297. func addBookmarkMenu() -> NSMenuItem {
  298. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  299. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add BookMark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)!
  300. return bookMarkItem
  301. } else {
  302. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove BookMark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)!
  303. return bookMarkItem
  304. }
  305. }
  306. func findStringMenu() -> NSMenuItem {
  307. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)!
  308. menuItem.keyEquivalent = "f"
  309. return menuItem
  310. }
  311. func printingMenu() -> NSMenuItem {
  312. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  313. return menuItem
  314. }
  315. func fontSizes()->NSArray {
  316. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  317. }
  318. //MARK: menuItem Action
  319. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  320. let color = listView.editingSelectionFontColor()
  321. let panel = NSColorPanel.shared
  322. panel.setTarget(self)
  323. panel.setAction(#selector(fontColorChangeAction))
  324. panel.orderFront(nil)
  325. panel.showsAlpha = false
  326. panel.color = color ?? NSColor.black
  327. }
  328. @objc func fontColorChangeAction(sender: NSColorPanel) {
  329. self.listView.setEditingSelectionFontColor(sender.color)
  330. }
  331. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  332. let fontSize = self.fontSizes().object(at: sender.tag)
  333. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  334. }
  335. @objc func addImageText(sender: NSMenuItem) {
  336. let event = NSApp.currentEvent
  337. let clickLocation = event?.locationInWindow
  338. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  339. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  340. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  341. point = point2
  342. if sender.tag == 0 {
  343. print("添加文字")
  344. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  345. if !isSelect {
  346. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  347. }
  348. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  349. } else if sender.tag == 1 {
  350. print("添加图片")
  351. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  352. if !isSelect {
  353. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  354. }
  355. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  356. } else if sender.tag == 2 {
  357. print("粘贴")
  358. }
  359. }
  360. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  361. if self.rightSideViewController.eidtPDFImageProperty != nil {
  362. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  363. } else {
  364. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  365. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  366. }
  367. }
  368. }
  369. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  370. if self.rightSideViewController.eidtPDFImageProperty != nil {
  371. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  372. } else {
  373. self.listView.exitCrop(with: self.listView.selectImageAreas)
  374. self.listView.cropAreas = nil
  375. self.listView.isEditImage = false
  376. }
  377. }
  378. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  379. if self.rightSideViewController.eidtPDFImageProperty != nil {
  380. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  381. } else {
  382. self.listView.resetCrop(with: self.listView.selectImageAreas)
  383. }
  384. }
  385. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  386. if self.listView.selectImageAreas != nil {
  387. self.listView.isEditImage = true
  388. self.listView.enterCrop(with: self.listView.selectImageAreas)
  389. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  390. }
  391. }
  392. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  393. if self.listView.selectImageAreas == nil {
  394. return
  395. }
  396. let panel = NSOpenPanel()
  397. panel.allowsMultipleSelection = false
  398. panel.allowedFileTypes = ["png","jpg"]
  399. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  400. if response == .OK {
  401. let openPath = panel.url?.path
  402. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  403. if s {
  404. }
  405. }
  406. }
  407. }
  408. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  409. if self.listView.selectImageAreas == nil {
  410. return
  411. }
  412. let panel = NSSavePanel()
  413. // panel.nameFieldStringValue = "[新文件].png"
  414. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  415. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  416. // button.state = .on
  417. // panel.accessoryView = button
  418. panel.isExtensionHidden = true
  419. let response = panel.runModal()
  420. if response == .OK {
  421. let url = panel.url
  422. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  423. if result {
  424. NSWorkspace.shared.activateFileViewerSelecting([url!])
  425. // if button.state == .on { /// 开启文档
  426. // NSWorkspace.shared.openFile(url!.path)
  427. // } else {
  428. //
  429. // }
  430. }
  431. }
  432. }
  433. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  434. self.listView.toolMode = .noteToolMode
  435. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  436. var model : KMToolbarViewType = .None
  437. switch sender.tag {
  438. case 0:
  439. identifier = KMDocumentAnnotationToolbarItemIdentifier
  440. model = .Annatiton
  441. case 1:
  442. identifier = KMToolbarMoveToolModeItemIdentifier
  443. model = .Move
  444. case 2:
  445. identifier = KMToolbarMagnifyToolModeItemIdentifier
  446. model = .Magnify
  447. case 3:
  448. identifier = KMToolbarSelectToolModeItemIdentifier
  449. model = .Select
  450. case 4:
  451. identifier = KMToolbarZoomToSelectionItemIdentifier
  452. model = .SelectZoom
  453. default:
  454. break
  455. }
  456. let item : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  457. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  458. }
  459. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  460. var annotationType : CAnnotationType = .unkown
  461. switch sender.tag {
  462. case 0:
  463. annotationType = .highlight
  464. case 1:
  465. annotationType = .underline
  466. case 2:
  467. annotationType = .strikeOut
  468. case 3:
  469. annotationType = .freeText
  470. case 4:
  471. annotationType = .anchored
  472. case 5:
  473. annotationType = .square
  474. case 6:
  475. annotationType = .circle
  476. case 7:
  477. annotationType = .line
  478. case 8:
  479. annotationType = .link
  480. case 9:
  481. // var newOutline : CPDFOutline = CPDFOutline()
  482. // newOutline.label = "11111111"
  483. // let des = self.listView.currentDestination
  484. // if "\(des?.point.x ?? 0)" != "nan" {
  485. // newOutline.destination = self.listView.currentDestination
  486. // } else {
  487. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  488. // newOutline.destination = destination
  489. // }
  490. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  491. // let parent = current.parent ?? CPDFOutline()
  492. // let index = current.index + 1
  493. // parent.insertChild(newOutline, at: index)
  494. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  495. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  496. }
  497. self.leftSideViewController.outlineViewController.addItemAction()
  498. return
  499. case 10:
  500. annotationType = .unkown
  501. default:
  502. break
  503. }
  504. if (annotationType != .link) {
  505. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  506. self.listView.currentSelection = nil;
  507. return
  508. }
  509. // link
  510. let selection = self.listView.currentSelection
  511. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  512. DispatchQueue.main.async {
  513. Task { @MainActor in
  514. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  515. return
  516. }
  517. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  518. self.listView.currentSelection = nil;
  519. if (annotation != nil) {
  520. self.listView.updateActiveAnnotations([annotation!])
  521. }
  522. }
  523. }
  524. }
  525. @objc func aiTranslationAction(sender: NSMenuItem) {
  526. let content = self.listView.currentSelection.string() as? String ?? ""
  527. let origin = self.listView.currentSelection.bounds.origin
  528. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  529. self.aiTranslationWindow?.content = content
  530. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  531. self.aiTranslationWindow!.window?.center()
  532. }
  533. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  534. Task { @MainActor in
  535. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) {
  536. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  537. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  538. return
  539. }
  540. }
  541. var point = mouseRightMenuEvent?.locationInWindow
  542. if (point == nil) {
  543. point = NSZeroPoint
  544. }
  545. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  546. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  547. let pagePoint = self.listView.convert(currentPoint, to: currentPage)
  548. var annotation: CPDFAnnotation?
  549. if self.isReadMode {
  550. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  551. self.listView.toolMode = .noteToolMode
  552. }
  553. switch sender.tag {
  554. case 0:
  555. self.listView.annotationType = CAnnotationType.ink
  556. case 1:
  557. // self.listView.annotationType = CAnnotationType.freeText
  558. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  559. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  560. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  561. if ((annotation) != nil) {
  562. self.listView.updateActiveAnnotations([annotation!])
  563. self.listView.edit(annotation)
  564. }
  565. case 2:
  566. // self.listView.annotationType = CAnnotationType.anchored
  567. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  568. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  569. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  570. self.listView.edit(annotation)
  571. case 3:
  572. // self.listView.annotationType = CAnnotationType.square
  573. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  574. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  575. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  576. case 4:
  577. // self.listView.annotationType = CAnnotationType.circle
  578. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  579. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  580. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  581. case 5:
  582. // self.listView.annotationType = CAnnotationType.arrow
  583. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  584. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  585. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  586. case 6:
  587. // self.listView.annotationType = CAnnotationType.line
  588. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  589. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  590. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  591. case 7:
  592. self.listView.annotationType = CAnnotationType.link
  593. self.openRightPane()
  594. case 8:
  595. self.listView.annotationType = CAnnotationType.stamp
  596. self.openRightPane()
  597. case 9:
  598. self.listView.annotationType = CAnnotationType.signSignature
  599. self.openRightPane()
  600. default:
  601. break
  602. }
  603. self.rightSideViewController.isHidden = true
  604. self.rightSideViewController.subViewType = .AnnotationProperts
  605. } else {
  606. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  607. if(self.toolbarController.toolbarType == .None) {
  608. self.toolbarController.toolbarType = .Annatiton
  609. }
  610. self.listView.toolMode = .noteToolMode
  611. }
  612. switch sender.tag {
  613. case 0:
  614. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  615. self.rightMouseEventing = true
  616. if(self.toolbarController.toolbarType == .None) {
  617. self.toolbarController.toolbarType = .Annatiton
  618. }
  619. self.listView.toolMode = .noteToolMode
  620. self.listView.annotationType = CAnnotationType.ink
  621. case 1:
  622. // self.listView.annotationType = CAnnotationType.freeText
  623. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  624. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  625. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  626. // self.view.window?.makeFirstResponder()
  627. if ((annotation) != nil) {
  628. // self.listView.updateActiveAnnotations([annotation!])
  629. self.listView.edit(annotation)
  630. }
  631. case 2:
  632. // self.listView.annotationType = CAnnotationType.anchored
  633. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  634. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  635. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  636. self.listView.edit(annotation)
  637. case 3:
  638. // self.listView.annotationType = CAnnotationType.square
  639. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  640. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  641. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  642. case 4:
  643. // self.listView.annotationType = CAnnotationType.circle
  644. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  645. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  646. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  647. case 5:
  648. // self.listView.annotationType = CAnnotationType.arrow
  649. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  650. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  651. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  652. case 6:
  653. // self.listView.annotationType = CAnnotationType.line
  654. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  655. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  656. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  657. case 7:
  658. self.listView.annotationType = CAnnotationType.link
  659. self.openRightPane()
  660. case 8:
  661. self.listView.annotationType = CAnnotationType.stamp
  662. self.openRightPane()
  663. case 9:
  664. self.listView.annotationType = CAnnotationType.signSignature
  665. self.openRightPane()
  666. default:
  667. break
  668. }
  669. // self.rightSideViewController.view.isHidden = false
  670. self.rightSideViewController.isHidden = false
  671. // self.openRightPane()
  672. self.rightSideViewController.subViewType = .AnnotationProperts
  673. }
  674. if (annotation != nil) {
  675. self.listView.updateIsRightActiveAnnotations([annotation!])
  676. }
  677. }
  678. }
  679. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  680. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  681. let index = self.listView.currentPageIndex
  682. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  683. self.listView.setNeedsDisplayForVisiblePages()
  684. } else {
  685. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  686. self.listView.setNeedsDisplayForVisiblePages()
  687. }
  688. if self.isReadMode {
  689. } else {
  690. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  691. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  692. }
  693. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  694. if bookMark != nil {
  695. let item = KMBookMarkItem()
  696. item.bookMark = bookMark!
  697. item.label = (bookMark?.label)!
  698. item.index = UInt(bookMark!.pageIndex)
  699. self.leftSideViewController.bookViewController.reloadData()
  700. self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  701. } else {
  702. self.leftSideViewController.bookViewController.reloadData()
  703. }
  704. }
  705. }
  706. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  707. self.leftSideViewController.refreshMethodType(methodType: .Search)
  708. }
  709. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  710. let rect = listView.currentSelectionRect()
  711. let page = listView.currentPage()
  712. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  713. copyPage.setBounds(rect, for: .cropBox)
  714. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  715. // let pdfDocument : PDFDocument = PDFDocument()
  716. // let newpage : PDFPage = PDFPage(image: image)!
  717. // pdfDocument.insert(newpage, at: 0)
  718. // 执行右键操作后,需要取消框选区域
  719. if self.listView.toolMode == .selectToolMode {
  720. objc_sync_enter(self)
  721. self.listView.selectionRect = NSZeroRect
  722. self.listView.selectionPageIndex = UInt(NSNotFound)
  723. objc_sync_exit(self)
  724. }
  725. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  726. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  727. if (result == .cancel) {
  728. return
  729. }
  730. // 解除权限
  731. self?.isSaveKeyChain = false
  732. self?.listView.document.unlock(withPassword: password)
  733. // 隐藏提示
  734. self?.hiddenSecureLimitTip()
  735. // 去打印
  736. KMPrintWindowController.printImage(image: image)
  737. }
  738. return
  739. }
  740. KMPrintWindowController.printImage(image: image)
  741. }
  742. // MARK: Redact 【密文标记】
  743. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  744. self.listView.remove(self.listView.activeAnnotation)
  745. }
  746. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  747. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  748. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  749. self.view.window?.beginSheet(windowController.window!)
  750. self.currentWindowController = windowController
  751. windowController.itemClick = { [weak self] index, value in
  752. if (index == 1) { /// 取消
  753. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  754. self?.currentWindowController = nil
  755. return
  756. }
  757. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  758. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  759. annotaton.setBorderColor(windowController_redact.outsideColor)
  760. annotaton.setInteriorColor(windowController_redact.fillColor)
  761. if (windowController_redact.isOver) {
  762. annotaton.setFontColor(windowController_redact.fontColor)
  763. annotaton.setAlignment(windowController_redact.aligement)
  764. annotaton.setFont(windowController_redact.font)
  765. annotaton.setOverlayText(windowController_redact.overText)
  766. }
  767. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  768. self?.currentWindowController = nil
  769. }
  770. }
  771. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  772. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  773. return
  774. }
  775. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  776. let model = CPDFAnnotationModel(annotationType: .redact)
  777. model?.setColor(annotation.borderColor())
  778. model?.setInteriorColor(annotation.interiorColor())
  779. let overlayText: String = annotation.overlayText()
  780. if (overlayText.isEmpty) {
  781. model?.setIsOverlayText(false)
  782. } else {
  783. model?.setIsOverlayText(true)
  784. model?.setOverlayText(overlayText)
  785. model?.setFontColor(annotation.fontColor())
  786. model?.setAlignment(annotation.alignment())
  787. model?.setFontName(annotation.font().fontName)
  788. model?.setFontSize(annotation.font().pointSize)
  789. }
  790. }
  791. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  792. let anno = self.listView.activeAnnotation
  793. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  794. return
  795. }
  796. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  797. windowController.pageCount = Int(self.listView.document.pageCount)
  798. self.currentWindowController = windowController
  799. self.view.window?.beginSheet(windowController.window!)
  800. windowController.itemClick = { [weak self] index, value in
  801. if (index == 1) {
  802. self!.view.window?.endSheet(self!.currentWindowController.window!)
  803. self!.currentWindowController = nil
  804. return
  805. }
  806. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  807. let pageType = windowController_mutilPageFlag.pageType
  808. let pageString = windowController_mutilPageFlag.pageString
  809. if (pageType == 4) { /// 自定义页面
  810. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  811. if (array.count == 0) {
  812. let alert = NSAlert()
  813. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  814. alert.runModal()
  815. return
  816. }
  817. }
  818. self!.view.window?.endSheet(self!.currentWindowController.window!)
  819. self!.currentWindowController = nil
  820. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  821. if (indexs.count == 0) {
  822. return
  823. }
  824. for i in indexs {
  825. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  826. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  827. self?.listView.add(redactAnno, to: page)
  828. }
  829. }
  830. }
  831. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  832. self.exeRedactConfirm(.redactOne) {}
  833. }
  834. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  835. self.exeRedactConfirm(.eraserOne) {}
  836. }
  837. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  838. }
  839. @objc func exportStampImage(sender:NSMenuItem) {
  840. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  841. var image : NSImage = NSImage()
  842. if (listView.activeAnnotation is CPDFStampAnnotation) {
  843. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  844. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  845. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  846. }
  847. let data = image.tiffRepresentation
  848. if sender.tag == 0 {
  849. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  850. imageRep.size = image.size
  851. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  852. let savePanel = NSSavePanel()
  853. savePanel.allowedFileTypes = ["png"]
  854. savePanel.beginSheetModal(for: self.view.window!) { response in
  855. if (response != .OK) {
  856. return
  857. }
  858. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  859. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  860. }
  861. }
  862. } else {
  863. let pdfdocument = CPDFDocument()
  864. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  865. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  866. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  867. let savePanel = NSSavePanel()
  868. savePanel.allowedFileTypes = ["pdf"]
  869. savePanel.beginSheetModal(for: self.view.window!) { response in
  870. if (response != .OK) {
  871. return
  872. }
  873. if pdfdocument!.write(to: savePanel.url!) {
  874. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  875. }
  876. }
  877. }
  878. }
  879. }
  880. }
  881. @objc func exportCorpImage(sender:NSMenuItem) {
  882. let rect = NSIntegralRect(listView.currentSelectionRect())
  883. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  884. let page : CPDFPage = orgPage.copy() as! CPDFPage
  885. page.setBounds(rect, for: .cropBox)
  886. let image = page.thumbnail(of: rect.size) ?? NSImage()
  887. let data = image.tiffRepresentation
  888. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  889. imageRep.size = rect.size
  890. let savePanel = NSSavePanel()
  891. switch sender.tag {
  892. case 0:
  893. savePanel.allowedFileTypes = ["png"]
  894. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  895. savePanel.beginSheetModal(for: self.view.window!) { response in
  896. if (response != .OK) {
  897. return
  898. }
  899. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  900. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  901. }
  902. }
  903. case 1:
  904. savePanel.allowedFileTypes = ["jpg"]
  905. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  906. savePanel.beginSheetModal(for: self.view.window!) { response in
  907. if (response != .OK) {
  908. return
  909. }
  910. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  911. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  912. }
  913. }
  914. case 2:
  915. savePanel.allowedFileTypes = ["pdf"]
  916. let pdfdocument = CPDFDocument()
  917. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  918. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  919. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  920. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  921. savePanel.beginSheetModal(for: self.view.window!) { response in
  922. if (response != .OK) {
  923. return
  924. }
  925. if pdfdocument!.write(to: savePanel.url!) {
  926. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  927. }
  928. }
  929. }
  930. default:
  931. break
  932. }
  933. // 执行右键操作后,需要取消框选区域
  934. if self.listView.toolMode == .selectToolMode {
  935. objc_sync_enter(self)
  936. self.listView.selectionRect = NSZeroRect
  937. self.listView.selectionPageIndex = UInt(NSNotFound)
  938. objc_sync_exit(self)
  939. }
  940. }
  941. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  942. let rect = listView.currentSelectionRect()
  943. let page = listView.currentPage()
  944. if NSIsEmptyRect(rect) == false && page != nil {
  945. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  946. var bounds = listView.bounds
  947. var scale = 1.0
  948. if isLegacy {
  949. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  950. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  951. }
  952. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  953. scale = NSHeight(bounds) / NSHeight(rect)
  954. } else {
  955. scale = NSWidth(bounds) / NSWidth(rect)
  956. }
  957. listView.setScaleFactor(scale, animated: false)
  958. let scrollView = listView.scroll()
  959. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  960. if ((scrollView?.hasVerticalScroller) != nil) {
  961. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  962. }
  963. if ((scrollView?.hasHorizontalScroller) != nil) {
  964. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  965. }
  966. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  967. scale = NSHeight(bounds) / NSHeight(rect)
  968. } else {
  969. scale = NSWidth(bounds) / NSWidth(rect)
  970. }
  971. listView.setScaleFactor(scale, animated: false)
  972. }
  973. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  974. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  975. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  976. };
  977. }
  978. // 执行右键操作后,需要取消框选区域
  979. if self.listView.toolMode == .selectToolMode {
  980. objc_sync_enter(self)
  981. self.listView.selectionRect = NSZeroRect
  982. self.listView.selectionPageIndex = UInt(NSNotFound)
  983. objc_sync_exit(self)
  984. }
  985. }
  986. @IBAction func autoCropAll(sender:NSMenuItem) {
  987. }
  988. private func cropPagesToRects(rects:NSPointerArray) {
  989. }
  990. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  991. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  992. switch sender.tag {
  993. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  994. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  995. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  996. var red: CGFloat = 0.0
  997. var green: CGFloat = 0.0
  998. var blue: CGFloat = 0.0
  999. var alpha: CGFloat = 0.0
  1000. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1001. if sender.tag == CAnnotationType.highlight.rawValue {
  1002. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1003. } else if sender.tag == CAnnotationType.underline.rawValue {
  1004. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1005. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1006. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1007. }
  1008. case CAnnotationType.ink.rawValue:
  1009. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1010. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1011. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1012. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1013. var red: CGFloat = 0.0
  1014. var green: CGFloat = 0.0
  1015. var blue: CGFloat = 0.0
  1016. var alpha: CGFloat = 0.0
  1017. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1018. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1019. case CAnnotationType.freeText.rawValue:
  1020. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1021. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1022. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1023. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1024. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1025. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1026. var red: CGFloat = 0.0
  1027. var green: CGFloat = 0.0
  1028. var blue: CGFloat = 0.0
  1029. var alpha: CGFloat = 0.0
  1030. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1031. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1032. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1033. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1034. UserDefaults.standard.synchronize()
  1035. }
  1036. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1037. if (alignment == .left || alignment == .center || alignment == .right) {
  1038. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1039. UserDefaults.standard.synchronize()
  1040. }
  1041. case CAnnotationType.anchored.rawValue:
  1042. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1043. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1044. var red: CGFloat = 0.0
  1045. var green: CGFloat = 0.0
  1046. var blue: CGFloat = 0.0
  1047. var alpha: CGFloat = 0.0
  1048. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1049. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1050. case CAnnotationType.square.rawValue:
  1051. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1052. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1053. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1054. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1055. var red: CGFloat = 0.0
  1056. var green: CGFloat = 0.0
  1057. var blue: CGFloat = 0.0
  1058. var alpha: CGFloat = 0.0
  1059. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1060. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1061. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1062. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1063. case CAnnotationType.circle.rawValue:
  1064. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1065. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1066. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1067. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1068. var red: CGFloat = 0.0
  1069. var green: CGFloat = 0.0
  1070. var blue: CGFloat = 0.0
  1071. var alpha: CGFloat = 0.0
  1072. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1073. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1074. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1075. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1076. default:
  1077. break
  1078. }
  1079. }
  1080. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1081. self.showOrHideNotes()
  1082. }
  1083. //MARK: action
  1084. @objc func cropCurrentPage() {
  1085. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1086. var page: CPDFPage?
  1087. if ((self.listView.currentSelectionPage()) != nil) {
  1088. page = self.listView.currentSelectionPage()
  1089. } else {
  1090. page = self.listView.currentPage()
  1091. }
  1092. if (NSIsEmptyRect(rect)) {
  1093. rect = KMCropTools.getPageForegroundBox(page!)
  1094. }
  1095. let index: UInt = (page?.pageIndex())!
  1096. cropPage(at: index, in: rect)
  1097. // 执行右键操作后,需要取消框选区域
  1098. if self.listView.toolMode == .selectToolMode {
  1099. objc_sync_enter(self)
  1100. self.listView.selectionRect = NSZeroRect
  1101. self.listView.selectionPageIndex = UInt(NSNotFound)
  1102. objc_sync_exit(self)
  1103. }
  1104. }
  1105. func cropPage(at index: UInt, in rect: NSRect) {
  1106. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  1107. let undoManager = self.listView.undoManager
  1108. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  1109. let page = self.listView.document.page(at: index)
  1110. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  1111. page?.setBounds(newRect, for: .cropBox)
  1112. /// 刷新预览视图
  1113. self.listView.layoutDocumentView()
  1114. self.listView.displayBox = .cropBox
  1115. }
  1116. @objc private func cropAllPage() {
  1117. var size = NSZeroSize
  1118. for i in 0 ..< self.listView.document.pageCount {
  1119. let page = self.listView.document.page(at: i)
  1120. var rect = KMCropTools.getPageForegroundBox(page!)
  1121. size.width = fmax(size.width, NSWidth(rect))
  1122. size.height = fmax(size.height, NSHeight(rect))
  1123. }
  1124. var rectArray: Array<NSRect> = []
  1125. for i in 0 ..< self.listView.document.pageCount {
  1126. let page = self.listView.document.page(at: i)
  1127. var rect = KMCropTools.getPageForegroundBox(page!)
  1128. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1129. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1130. rect.origin.x = rect.maxX-size.width
  1131. }
  1132. rect.origin.y = rect.maxY-size.height
  1133. rect.size = size
  1134. if (NSWidth(rect) > NSWidth(bounds)) {
  1135. rect.size.width = NSWidth(bounds)
  1136. }
  1137. if (NSHeight(rect) > NSHeight(bounds)) {
  1138. rect.size.height = NSHeight(bounds)
  1139. }
  1140. if (NSMinX(rect) < NSMinX(bounds)) {
  1141. rect.origin.x = NSMinX(bounds)
  1142. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1143. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1144. }
  1145. if (NSMinY(rect) < NSMinY(bounds)) {
  1146. rect.origin.y = NSMinY(bounds)
  1147. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1148. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1149. }
  1150. rectArray.append(rect)
  1151. }
  1152. cropPages(to: rectArray)
  1153. }
  1154. func cropPages(to rects: Array<NSRect>) {
  1155. let currentPage = self.listView.currentPage()
  1156. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1157. var oldRectArray: Array<NSRect> = []
  1158. for i in 0 ..< self.listView.document.pageCount {
  1159. let page = self.listView.document.page(at: i)
  1160. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  1161. let oldRect = page?.bounds(for: .cropBox)
  1162. oldRectArray.append(oldRect!)
  1163. page?.setBounds(rect, for: .cropBox)
  1164. }
  1165. let undoManager = self.listView.undoManager
  1166. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1167. /// 刷新预览视图
  1168. self.listView.layoutDocumentView()
  1169. self.listView.displayBox = .cropBox
  1170. self.listView.go(to: currentPage)
  1171. self.listView.go(to: visibleRect, on: currentPage)
  1172. }
  1173. private func cropCustomArea() {
  1174. self.listView.toolMode = .selectToolMode
  1175. self.listView.autoScales = true
  1176. self.listView.autoScales = false
  1177. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1178. if (self.listView.displaysPageBreaks) {
  1179. pageHeight += 8
  1180. }
  1181. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1182. // if (scaleFactor < self.preView.scaleFactor) {
  1183. self.listView.scaleFactor = scaleFactor
  1184. // }
  1185. let tipView = KMCropTipView()
  1186. tipView.setString(string: "请框选裁剪区域")
  1187. tipView.frame = self.topTipBox.contentView!.frame
  1188. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1189. self.addTopTip(tipView)
  1190. tipView.enterAction = {
  1191. () in
  1192. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1193. if (NSIsEmptyRect(rect)) {
  1194. return
  1195. }
  1196. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1197. self.view.window?.beginSheet(window.window!)
  1198. self.cropSettingWindowController = window
  1199. window.itemClick = { [self]
  1200. (index: Int) in
  1201. if (index == 1) { /// 取消
  1202. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1203. self.cropSettingWindowController = nil
  1204. return
  1205. }
  1206. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1207. let pageCount: Int = Int(self.listView.document.pageCount)
  1208. var pages: Array<Int> = []
  1209. if (pageRangeType == 0) { /// 当前页面
  1210. pages.append(self.listView.currentPageIndex)
  1211. } else if (pageRangeType == 1) { /// 全部页面
  1212. for i in 0 ..< pageCount {
  1213. pages.append(i)
  1214. }
  1215. } else if (pageRangeType == 2) { /// 奇数页面
  1216. var string: String = ""
  1217. for i in 0 ..< pageCount {
  1218. if (i % 2 == 1) {
  1219. continue
  1220. }
  1221. pages.append(i)
  1222. }
  1223. } else if (pageRangeType == 3) { /// 偶数页面
  1224. var string: String = ""
  1225. for i in 0 ..< pageCount {
  1226. if (i % 2 == 0) {
  1227. continue
  1228. }
  1229. pages.append(i)
  1230. }
  1231. } else { /// 自定义
  1232. for i in self.cropSettingWindowController.pageRangePages {
  1233. pages.append(i)
  1234. }
  1235. }
  1236. if (pages.count < 0) {
  1237. let alert = NSAlert()
  1238. alert.messageText = "请选择页面"
  1239. alert.runModal()
  1240. return
  1241. }
  1242. var pageSize: NSSize = NSZeroSize
  1243. if (self.cropSettingWindowController.pageSize == "None") {
  1244. } else {
  1245. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1246. }
  1247. for i in pages {
  1248. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1249. var rect = NSIntegralRect(self.listView.selectionRect)
  1250. if (NSIsEmptyRect(rect)) {
  1251. rect = KMCropTools.getPageForegroundBox(page)
  1252. }
  1253. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1254. page.setBounds(newRect, for: .cropBox)
  1255. if (pageSize.width == 0 && pageSize.height == 0) {
  1256. } else {
  1257. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1258. let index: UInt = (page.pageIndex())
  1259. // let newPage: CPDFPage = nil
  1260. // self.listView.document.removePage(at: index)
  1261. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1262. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1263. let result = self.listView.document.insertPage(pageSize, at: index)
  1264. }
  1265. }
  1266. /// 保存到临时路径
  1267. let toPath: String = self.listView.document.documentURL.path
  1268. let documentPath = NSTemporaryDirectory()
  1269. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1270. if (FileManager.default.fileExists(atPath: tempPath)) {
  1271. try?FileManager.default.removeItem(atPath: tempPath)
  1272. }
  1273. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1274. if (result) {
  1275. if (FileManager.default.fileExists(atPath: toPath)) {
  1276. try?FileManager.default.removeItem(atPath: toPath)
  1277. }
  1278. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1279. } else {
  1280. try?FileManager.default.removeItem(atPath: tempPath)
  1281. }
  1282. DispatchQueue.main.async {
  1283. self.listView.toolMode = .textToolMode
  1284. /// 刷新预览视图
  1285. self.listView.layoutDocumentView()
  1286. self.listView.displayBox = .cropBox
  1287. }
  1288. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1289. self.cropSettingWindowController = nil
  1290. self.addTopTip(nil)
  1291. }
  1292. }
  1293. }
  1294. @objc private func shareDocument(sender:KMToolbarViewController) {
  1295. var doucumentURL : URL = self.listView.document.documentURL
  1296. if doucumentURL != nil {
  1297. let docDir = NSTemporaryDirectory()
  1298. let documentName : String = doucumentURL.path.lastPathComponent
  1299. let path = docDir.stringByAppendingPathComponent(documentName)
  1300. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1301. if writeSuccess == false {
  1302. __NSBeep()
  1303. return;
  1304. }
  1305. doucumentURL = URL(fileURLWithPath: path)
  1306. }
  1307. let array = [doucumentURL]
  1308. let picker = NSSharingServicePicker.init(items: array)
  1309. if sender.shareButton.window != nil {
  1310. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1311. } else {
  1312. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1313. }
  1314. }
  1315. @objc private func shareFlatten(sender:KMToolbarViewController) {
  1316. let document = self.listView.document ?? CPDFDocument()
  1317. var path = document!.documentURL.path
  1318. if path != nil {
  1319. let docDir = NSTemporaryDirectory()
  1320. let documentName : String = path.lastPathComponent
  1321. path = docDir.stringByAppendingPathComponent(documentName)
  1322. }
  1323. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1324. var tfileName = path.deletingPathExtension.lastPathComponent
  1325. let tStdFileSuffix = "_flatten"
  1326. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1327. path = pathFolder + "/" + tfileName
  1328. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1329. if success {
  1330. let url = URL(fileURLWithPath: path)
  1331. let picker = NSSharingServicePicker.init(items: [url])
  1332. if sender.shareButton.window != nil {
  1333. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1334. } else {
  1335. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1336. }
  1337. }
  1338. }
  1339. @objc private func shareOriginalPDF(sender:KMToolbarViewController) {
  1340. let document = self.listView.document ?? CPDFDocument()
  1341. var path = document!.documentURL.path
  1342. if path != nil {
  1343. let docDir = NSTemporaryDirectory()
  1344. let documentName : String = path.lastPathComponent
  1345. path = docDir.stringByAppendingPathComponent(documentName)
  1346. }
  1347. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1348. if writeSuccess == false {
  1349. __NSBeep()
  1350. return;
  1351. }
  1352. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1353. for i in 0 ... newDocument.pageCount-1 {
  1354. let page = newDocument.page(at: i)
  1355. var annotations : [CPDFAnnotation] = []
  1356. for annotation in page!.annotations {
  1357. annotations.append(annotation)
  1358. }
  1359. for annotation in annotations {
  1360. annotation.page.removeAnnotation(annotation)
  1361. }
  1362. }
  1363. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1364. if writeSuccess {
  1365. let url = URL(fileURLWithPath: path)
  1366. let picker = NSSharingServicePicker.init(items: [url])
  1367. if sender.shareButton.window != nil {
  1368. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1369. } else {
  1370. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1371. }
  1372. }
  1373. }
  1374. // 开启/关闭左边栏
  1375. @objc func toggleLeftPane() -> Void {
  1376. // if lastLeftPanWidth >= functionWidth {
  1377. leftPanelOpen = true
  1378. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1379. // } else {
  1380. // leftPanelOpen = false
  1381. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1382. // }
  1383. }
  1384. // 开启左边栏
  1385. @objc func openLeftPane() -> Void {
  1386. leftPanelOpen = true
  1387. applyLeftSideWidth(panelWidth+functionWidth,rightSideWidth: lastRightPanWidth)
  1388. }
  1389. // 关闭左边栏
  1390. @objc func closeLeftPane() -> Void {
  1391. leftPanelOpen = false
  1392. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1393. }
  1394. // 开启/关闭右边栏
  1395. @objc func toggleRightPane() -> Void {
  1396. if lastRightPanWidth > 5 {
  1397. self.rightPanelIsOpen = false
  1398. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1399. } else {
  1400. self.rightPanelIsOpen = true
  1401. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1402. }
  1403. }
  1404. @objc func openRightPane() -> Void {
  1405. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1406. if self.rightPanelIsOpen {
  1407. return
  1408. }
  1409. self.rightPanelIsOpen = true
  1410. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1411. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1412. }
  1413. }
  1414. @objc func closeRightPane() -> Void {
  1415. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1416. self.rightPanelIsOpen = false
  1417. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1418. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1419. }
  1420. }
  1421. func rename(_ sender: NSNotification) -> Void {
  1422. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1423. return
  1424. }
  1425. let tabController = sender.object as? CTTabController
  1426. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1427. let outputSavePanel = NSSavePanel()
  1428. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1429. outputSavePanel.allowedFileTypes = ["pdf"]
  1430. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1431. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1432. let result = outputSavePanel.runModal()
  1433. if result == .OK {
  1434. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1435. let fileURL = pdfDocument?.documentURL
  1436. let fileManager = FileManager.default
  1437. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1438. var result = true
  1439. do {
  1440. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1441. } catch {
  1442. result = false
  1443. print("Error renaming file! Threw: \(error.localizedDescription)")
  1444. }
  1445. if (result) {
  1446. tabController?.title = outputSavePanel.url!.lastPathComponent
  1447. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1448. self.isSaveKeyChain = false
  1449. newPdfDocument.unlock(withPassword: self.document?.password)
  1450. if (newPdfDocument.pageCount > 0) {
  1451. self.setDocument = newPdfDocument
  1452. }
  1453. }
  1454. }
  1455. } else {
  1456. outputSavePanel.close()
  1457. }
  1458. }
  1459. }
  1460. func showInFinder(_ sender: Any) -> Void {
  1461. if sender is NSNotification {
  1462. let tabController = (sender as! NSNotification).object as? CTTabController
  1463. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1464. let file: URL = (self.myDocument?.fileURL)!
  1465. if FileManager.default.fileExists(atPath: file.path) {
  1466. NSWorkspace.shared.activateFileViewerSelecting([file])
  1467. }
  1468. }
  1469. } else {
  1470. let file: URL = (self.myDocument?.fileURL)!
  1471. if FileManager.default.fileExists(atPath: file.path) {
  1472. NSWorkspace.shared.activateFileViewerSelecting([file])
  1473. }
  1474. }
  1475. }
  1476. func showOrHideNotes() {
  1477. self.listView.hideNotes = !self.listView.hideNotes
  1478. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1479. //BOTA 注释列表显示隐藏
  1480. self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1481. self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1482. }
  1483. func closeTab(_ sender: NSNotification) -> Void {
  1484. let tabController = sender.object as? CTTabController
  1485. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1486. print("closeTab")
  1487. self.leftSideViewController.clearAnnotationFilterData()
  1488. self.leftSideViewController.clearNotification()
  1489. }
  1490. }
  1491. // MARK: -
  1492. // MARK: 显示窗口
  1493. internal func showCompressWindow() {
  1494. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1495. KMPrint("压缩窗口已显示")
  1496. return
  1497. }
  1498. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1499. self.view.window?.beginSheet(windowController.window!)
  1500. self.currentWindowController = windowController
  1501. windowController.documentURL = self.listView.document.documentURL
  1502. windowController.password = self.listView.document.password
  1503. windowController.itemClick = { [weak self] _ in
  1504. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1505. self?.currentWindowController = nil
  1506. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1507. }
  1508. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1509. if (result) {
  1510. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1511. self?.currentWindowController = nil
  1512. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1513. if (openDocument) {
  1514. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1515. } else {
  1516. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1517. }
  1518. } else {
  1519. let alert = NSAlert()
  1520. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1521. alert.runModal()
  1522. }
  1523. }
  1524. }
  1525. internal func showConvertWindow(type: KMToolbarType, identifier: String?) {
  1526. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1527. KMPrint("转档窗口已显示")
  1528. return
  1529. }
  1530. var windowController: KMConvertBaseWindowController?
  1531. if (type == .word) { /// Word
  1532. windowController = KMConvertWordWindowController()
  1533. } else if (type == .excel) {
  1534. windowController = KMConvertExcelWindowController()
  1535. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1536. windowController = KMConvertPPTsWindowController()
  1537. if (type == .ppt) {
  1538. windowController?.subType = 1
  1539. } else if (type == .rtf) {
  1540. windowController?.subType = 2
  1541. } else if (type == .html) {
  1542. windowController?.subType = 3
  1543. } else if (type == .conversion_text) {
  1544. windowController?.subType = 4
  1545. }
  1546. } else if (type == .csv) {
  1547. windowController = KMConvertCSVWindowController()
  1548. } else if (type == .conversion_image) {
  1549. windowController = KMConvertImageWindowController()
  1550. }
  1551. let model = KMDocumentModel(url: self.listView.document.documentURL)
  1552. if (self.listView.document.password != nil) {
  1553. let _ = model.unlock(self.listView.document.password)
  1554. }
  1555. model.currentIndex = self.listView.currentPageIndex
  1556. windowController?.documentModel = model
  1557. windowController?.itemClick = { [weak self] index in
  1558. if (identifier != nil) {
  1559. self?.toolbarController.cancelSelected(identifier!)
  1560. }
  1561. if (self?.currentWindowController == nil) {
  1562. return
  1563. }
  1564. self?.view.window?.endSheet(self!.currentWindowController.window!)
  1565. self?.currentWindowController = nil
  1566. }
  1567. self.view.window?.beginSheet((windowController?.window)!)
  1568. self.currentWindowController = windowController
  1569. }
  1570. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1571. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1572. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1573. if (result == .cancel) {
  1574. return
  1575. }
  1576. // 解除权限
  1577. self?.listView.document.unlock(withPassword: password)
  1578. // 隐藏提示
  1579. self?.hiddenSecureLimitTip()
  1580. // 去打印
  1581. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  1582. }
  1583. return
  1584. }
  1585. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  1586. }
  1587. // MARK: - Split View
  1588. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  1589. }
  1590. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  1591. if !isSinglePage && isHorizontal {
  1592. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  1593. }
  1594. if (!isSinglePage && !isHorizontal) {
  1595. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  1596. }
  1597. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  1598. }
  1599. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  1600. if isSinglePage {
  1601. pdfSplitView.dividerStyle = .thin
  1602. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  1603. } else {
  1604. pdfSplitView.dividerStyle = .paneSplitter
  1605. pdfSplitView.isVertical = !isHorizontal
  1606. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  1607. if secondaryPdfView.document != nil {
  1608. // secondaryPdfView.frame = pdfSplitSecondView.frame
  1609. // pdfSplitSecondView.contentView = secondaryPdfView
  1610. } else {
  1611. openSecondaryPdfView = KMSecondaryViewController.init()
  1612. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  1613. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  1614. openSecondaryPdfView?.delegate = self
  1615. }
  1616. }
  1617. }
  1618. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  1619. if (pdfSplitView.isVertical) {
  1620. return Float(NSWidth(rect))
  1621. } else {
  1622. return Float(NSHeight(rect))
  1623. }
  1624. }
  1625. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  1626. let document = CPDFDocument.init(url: url)
  1627. if document != nil {
  1628. secondaryPdfView.frame = pdfSplitSecondView.frame
  1629. pdfSplitSecondView.contentView = secondaryPdfView
  1630. secondaryPdfView.document = nil
  1631. secondaryPdfView.document = document
  1632. return true
  1633. } else {
  1634. return false
  1635. }
  1636. }
  1637. func updateNextAndPreViousButtonState() {
  1638. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  1639. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  1640. if self.listView.canGoToNextPage() {
  1641. item?.unEnabled = false
  1642. } else {
  1643. item?.unEnabled = true
  1644. }
  1645. if self.listView.canGoToPreviousPage() {
  1646. toItem?.unEnabled = false
  1647. } else {
  1648. toItem?.unEnabled = true
  1649. }
  1650. }
  1651. func updateZoomInOutButtonState() {
  1652. let item : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier))!
  1653. let toItem : KMToolBoxItem = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier))!
  1654. if self.listView.canZoomIn {
  1655. item.unEnabled = false
  1656. } else {
  1657. item.unEnabled = true
  1658. }
  1659. if self.listView.canZoomOut {
  1660. toItem.unEnabled = false
  1661. } else {
  1662. toItem.unEnabled = true
  1663. }
  1664. }
  1665. }
  1666. // MARK: -
  1667. // MARK: - KMSecondaryViewControllerDelegate
  1668. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  1669. func receivedFileUrl(_ url: URL!) {
  1670. let state = self.displaySecondaryPDFView(withUrl: url)
  1671. if !state {
  1672. let alert = NSAlert()
  1673. alert.alertStyle = .critical
  1674. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1675. alert.runModal()
  1676. return
  1677. }
  1678. }
  1679. }
  1680. // MARK: -
  1681. // MARK: - KMMainToolbarControllerDelegate
  1682. extension KMMainViewController : KMMainToolbarControllerDelegate {
  1683. func changeModelAction(mode: CToolMode) {
  1684. self.listView.toolMode = mode
  1685. if mode == .editPDFToolMode {
  1686. self.childToolbarController.updateType(newType: .editPDF)
  1687. }
  1688. }
  1689. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  1690. switch selectedTag {
  1691. case 2:
  1692. if self.listView.scaleFactor != 1.0 {
  1693. self.listView.scaleFactor = 1.0
  1694. self.listView.autoScales = false
  1695. }
  1696. break
  1697. case 1:
  1698. let pageHeight = self.listView.currentPage()!.size.height
  1699. let pdfviewHeight = self.listView.bounds.size.height
  1700. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1701. self.listView.autoScales = false
  1702. break
  1703. case 0:
  1704. // self.listView.autoScales = !self.listView.autoScales
  1705. self.listView.autoScales = true
  1706. break
  1707. case 3:
  1708. self.listView.scaleFactor = 0.1
  1709. break
  1710. case 4:
  1711. self.listView.scaleFactor = 0.25
  1712. break
  1713. case 5:
  1714. self.listView.scaleFactor = 0.5
  1715. break
  1716. case 6:
  1717. self.listView.scaleFactor = 0.75
  1718. break
  1719. case 7:
  1720. self.listView.scaleFactor = 1.0
  1721. break
  1722. case 8:
  1723. self.listView.scaleFactor = 1.5
  1724. break
  1725. case 9:
  1726. self.listView.scaleFactor = 2.0
  1727. break
  1728. case 10:
  1729. self.listView.scaleFactor = 4.0
  1730. break
  1731. case 11:
  1732. self.listView.scaleFactor = 8.0
  1733. break
  1734. case 12:
  1735. self.listView.scaleFactor = 10.0
  1736. break
  1737. default:
  1738. break
  1739. }
  1740. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1741. self.updateZoomInOutButtonState()
  1742. }
  1743. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  1744. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1745. if scale > 100 {
  1746. scale = 100
  1747. }
  1748. if (scale <= 0.101) {
  1749. self.listView.scaleFactor = self.listView.minScaleFactor()
  1750. } else {
  1751. self.listView.scaleFactor = scale
  1752. }
  1753. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  1754. DispatchQueue.main.async {
  1755. self.updateZoomInOutButtonState()
  1756. }
  1757. }
  1758. func changePDFViewZoomInAction() {
  1759. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  1760. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1761. switch scale {
  1762. case 0...0.25:
  1763. scale += 0.25
  1764. case 0.25...3:
  1765. scale += 0.25
  1766. case 3.1...10:
  1767. scale += 0.4
  1768. case 10.1...100:
  1769. scale += 1
  1770. default:
  1771. scale += 1
  1772. }
  1773. self.listView.scaleFactor = scale
  1774. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  1775. self.updateZoomInOutButtonState()
  1776. // self.listView.zoomIn(nil)
  1777. }
  1778. func changePDFViewZoomOutAction() {
  1779. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  1780. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  1781. switch scale {
  1782. case 0...0.25:
  1783. scale = 0
  1784. case 0.25...3:
  1785. scale -= 0.25
  1786. case 3.1...10:
  1787. scale -= 0.4
  1788. case 10.1...100:
  1789. scale -= 1
  1790. default:
  1791. scale -= 1
  1792. }
  1793. self.listView.scaleFactor = scale
  1794. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  1795. self.updateZoomInOutButtonState()
  1796. // self.listView.zoomOut(nil)
  1797. // self.updateZoomInOutButtonState()
  1798. }
  1799. func changePDFViewGotoNextPageAction() {
  1800. self.listView.goToNextPage(nil)
  1801. self.updateNextAndPreViousButtonState()
  1802. }
  1803. func changePDFViewGoToPreviousPageAction() {
  1804. self.listView.goToPreviousPage(nil)
  1805. self.updateNextAndPreViousButtonState()
  1806. }
  1807. func showPDFViewPrintViewController() {
  1808. // self.menuItemAnnotationClick_Print(sender: NSMenuItem())
  1809. self.showPrintWindow()
  1810. }
  1811. func aiTranslationPDFFileAction() {
  1812. if !KMLightMemberManager.manager.isLogin() {
  1813. KMLoginWindowController.show(window: NSApp.mainWindow!)
  1814. return
  1815. }
  1816. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  1817. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  1818. let alert = NSAlert()
  1819. alert.alertStyle = .critical
  1820. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  1821. alert.runModal()
  1822. return
  1823. } else if isExceedsLimit {
  1824. let alert = NSAlert()
  1825. alert.alertStyle = .critical
  1826. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  1827. alert.runModal()
  1828. return
  1829. }
  1830. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  1831. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  1832. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  1833. }
  1834. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  1835. self.shareDocument(sender: viewController)
  1836. }
  1837. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  1838. self.shareFlatten(sender: viewController)
  1839. }
  1840. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  1841. self.shareOriginalPDF(sender: viewController)
  1842. }
  1843. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  1844. if(0 == selectedTag) {
  1845. self.documentAIViewController?.enteredIncreaseAllPage()
  1846. self.documentAIViewController?.updateToolState(false)
  1847. } else {
  1848. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  1849. // self.documentAIViewController?.recognitionPartModel(with: .english)
  1850. // self.documentAIViewController?.updateToolState(true)
  1851. }
  1852. // 0 : Scan 1:OCR Text
  1853. }
  1854. func mainToolDidClicked(_ toolController: KMToolbarController, _ type: KMToolbarViewType, _ item: KMToolBoxItem , _ pages: [Int]) {
  1855. print("mainToolDidClicked")
  1856. if(type != .Page) {
  1857. if (hasEnterPageEdit()) {
  1858. self.exitPageEdit()
  1859. }
  1860. }
  1861. if(type != .ScanOCR) {
  1862. if ((self.documentAIViewController?.view.superview) != nil) {
  1863. self.listView.isHidden = false
  1864. self.documentAIViewController?.creatRecognitionDocument()
  1865. self.documentAIViewController?.view .removeFromSuperview()
  1866. self.documentAIViewController = nil;
  1867. self.listView.layoutDocumentView()
  1868. }
  1869. }
  1870. if (type == .Page) {
  1871. if (hasEnterPageEdit()) {
  1872. self.exitPageEdit()
  1873. } else {
  1874. self.enterPageEdit(pages)
  1875. }
  1876. } else if(type == .ScanOCR) {
  1877. if((self.documentAIViewController?.view.superview) != nil) {
  1878. let alert = NSAlert()
  1879. alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  1880. alert.addButton(withTitle: "YES")
  1881. alert.addButton(withTitle: "NO")
  1882. let result = alert.runModal()
  1883. if (result == .alertFirstButtonReturn) { /// 取消
  1884. self.listView.isHidden = false
  1885. self.documentAIViewController?.creatRecognitionDocument()
  1886. self.documentAIViewController?.view .removeFromSuperview()
  1887. self.documentAIViewController = nil;
  1888. self.listView.layoutDocumentView()
  1889. } else {
  1890. self.toolbarController.toolbarType = .ScanOCR
  1891. }
  1892. } else {
  1893. self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  1894. self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  1895. self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  1896. self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  1897. self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  1898. }
  1899. } else if type == .editPDF {
  1900. self.listView.annotationType = .editTextImage
  1901. }
  1902. }
  1903. func clickChildTool(type: KMToolbarType, index: Int) {
  1904. print("clickChildTool")
  1905. Task { @MainActor in
  1906. if (type == .compress) { /// 压缩
  1907. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1908. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1909. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1910. return
  1911. }
  1912. if (self.needSaveDocument()) {
  1913. self.saveDocumentWithProgressAlert { [unowned self] params in
  1914. self.showCompressWindow()
  1915. }
  1916. return
  1917. }
  1918. self.showCompressWindow()
  1919. return
  1920. }
  1921. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  1922. var identifier: String?
  1923. if (type == .word) { /// Word
  1924. identifier = KMToolbarConversionWordItemIdentifier
  1925. } else if (type == .excel) {
  1926. identifier = KMToolbarConversionExcelItemIdentifier
  1927. } else if (type == .ppt) {
  1928. identifier = KMToolbarConversionPPTItemIdentifier
  1929. } else if (type == .rtf) {
  1930. identifier = KMToolbarConversionRTFItemIdentifier
  1931. } else if (type == .html) {
  1932. identifier = KMToolbarConversionHTMLItemIdentifier
  1933. } else if (type == .conversion_text) {
  1934. identifier = KMToolbarConversionTextItemIdentifier
  1935. } else if (type == .csv) {
  1936. identifier = KMToolbarConversionCSVItemIdentifier
  1937. } else if (type == .conversion_image) {
  1938. identifier = KMToolbarConversionImageItemIdentifier
  1939. }
  1940. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1941. if (identifier != nil) {
  1942. self.toolbarController.cancelSelected(identifier!)
  1943. }
  1944. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1945. return
  1946. }
  1947. if (self.needSaveDocument()) {
  1948. self.saveDocumentWithProgressAlert { [unowned self] params in
  1949. self.showConvertWindow(type: type, identifier: identifier)
  1950. }
  1951. return
  1952. }
  1953. self.showConvertWindow(type: type, identifier: identifier)
  1954. return
  1955. }
  1956. if (type == .merge) { /// 合并
  1957. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1958. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1959. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  1960. return
  1961. }
  1962. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  1963. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  1964. if (result == .cancel) {
  1965. return
  1966. }
  1967. if (self.needSaveDocument()) {
  1968. self.saveDocumentWithProgressAlert { [unowned self] params in
  1969. self.showMergeWindow(password)
  1970. }
  1971. return
  1972. }
  1973. self.showMergeWindow(password)
  1974. }
  1975. return
  1976. }
  1977. if (self.needSaveDocument()) {
  1978. self.saveDocumentWithProgressAlert { [unowned self] params in
  1979. self.showMergeWindow(self.listView.document.password)
  1980. }
  1981. return
  1982. }
  1983. self.showMergeWindow(self.listView.document.password)
  1984. return
  1985. }
  1986. if (type == .crop) {
  1987. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1988. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1989. return
  1990. }
  1991. if (index == 1) {
  1992. self.cropCurrentPage()
  1993. return
  1994. }
  1995. if (index == 2) {
  1996. self.cropAllPage()
  1997. return
  1998. }
  1999. //// 自定义裁剪区域
  2000. // self.cropCustomArea()
  2001. } else if (type == .bates || type == .headerAndFooter || type == .background || type == .watermark) {
  2002. if (index == 0) {
  2003. var controller: KMWatermarkAdjectivePreViewBaseController!
  2004. if (type == .bates) {
  2005. controller = KMBatesPreviewController()
  2006. } else if (type == .headerAndFooter) {
  2007. controller = KMHeaderFooterPreviewController()
  2008. } else if (type == .background) {
  2009. controller = KMBackgroundController()
  2010. } else if (type == .watermark) {
  2011. controller = KMWatermarkViewController()
  2012. }
  2013. controller.applyDocument = self.listView.document
  2014. controller.view.frame = self.view.bounds
  2015. controller.view.autoresizingMask = [.width, .height]
  2016. controller.documentURL = self.listView.document.documentURL
  2017. self.view.addSubview(controller.view)
  2018. self.addChild(controller)
  2019. controller.itemClick = { [weak self] index, param in
  2020. if (index == 0 || index == 1) { /// 取消 和 应用
  2021. var controller_watermarkAdjective_preView: KMWatermarkAdjectivePreViewBaseController?
  2022. for i in 0 ..< self!.children.count {
  2023. let vc: NSViewController = self!.children[self!.children.count-1-i]
  2024. if (vc.isKind(of: KMWatermarkAdjectivePreViewBaseController.self) == true) {
  2025. controller_watermarkAdjective_preView = vc as! KMWatermarkAdjectivePreViewBaseController
  2026. break
  2027. }
  2028. }
  2029. if (controller_watermarkAdjective_preView == nil) {
  2030. return
  2031. }
  2032. controller_watermarkAdjective_preView!.view.removeFromSuperview()
  2033. controller_watermarkAdjective_preView?.removeFromParent()
  2034. // if (index == 1) {
  2035. self?.listView.document = CPDFDocument(url: self?.listView.document.documentURL)
  2036. self?.listView.layoutDocumentView()
  2037. self?.listView.setNeedsDisplayForVisiblePages()
  2038. // }
  2039. return
  2040. }
  2041. }
  2042. return
  2043. }
  2044. if (index == 1) { /// 取消
  2045. self.toolbarController.exitWatermarkAdjective()
  2046. // self.rightSideViewController.view.isHidden = true
  2047. self.rightSideViewController.isHidden = true
  2048. self.rightSideViewController.subViewType = .None
  2049. self.closeRightPane()
  2050. return
  2051. }
  2052. if (index == 5) { /// 批量
  2053. return
  2054. }
  2055. if (index == 4) { //// 移除
  2056. if (type == .watermark) {
  2057. let watermarks = self.listView.document.watermarks()
  2058. if (watermarks == nil || watermarks!.count <= 0) {
  2059. let alert = NSAlert()
  2060. alert.alertStyle = .warning
  2061. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  2062. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  2063. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2064. alert.runModal()
  2065. return
  2066. }
  2067. let alert = NSAlert()
  2068. alert.alertStyle = .warning
  2069. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  2070. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  2071. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2072. let result = alert.runModal()
  2073. if (result != .alertFirstButtonReturn) {
  2074. return
  2075. }
  2076. }
  2077. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  2078. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  2079. result in
  2080. DispatchQueue.main.async {
  2081. self.listView.layoutDocumentView()
  2082. self.listView.setNeedsDisplayForVisiblePages()
  2083. }
  2084. if (result) {
  2085. let alert = NSAlert()
  2086. alert.alertStyle = .warning
  2087. alert.messageText = "成功"
  2088. alert.runModal()
  2089. } else {
  2090. let alert = NSAlert()
  2091. alert.alertStyle = .critical
  2092. alert.messageText = "失败"
  2093. alert.runModal()
  2094. }
  2095. }
  2096. return
  2097. }
  2098. if (index == 2) { /// 应用
  2099. let model = self.rightSideViewController.model
  2100. if (type == .bates || type == .headerAndFooter) {
  2101. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2102. let alert = NSAlert()
  2103. alert.alertStyle = .critical
  2104. alert.messageText = "没有找到模型"
  2105. alert.runModal()
  2106. return
  2107. }
  2108. if ((model as! KMBatesModel).hasVaild == false) {
  2109. let alert = NSAlert()
  2110. alert.alertStyle = .critical
  2111. alert.messageText = "没有找到内容"
  2112. alert.runModal()
  2113. return
  2114. }
  2115. }
  2116. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2117. result in
  2118. DispatchQueue.main.async {
  2119. self.listView.layoutDocumentView()
  2120. self.listView.setNeedsDisplayForVisiblePages()
  2121. }
  2122. if (result) {
  2123. let alert = NSAlert()
  2124. alert.alertStyle = .warning
  2125. alert.messageText = "成功"
  2126. alert.runModal()
  2127. } else {
  2128. let alert = NSAlert()
  2129. alert.alertStyle = .critical
  2130. alert.messageText = "失败"
  2131. alert.runModal()
  2132. }
  2133. }
  2134. return
  2135. }
  2136. /// 新增
  2137. // self.rightSideViewController.view.isHidden = false
  2138. self.rightSideViewController.isHidden = false
  2139. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2140. self.openRightPane()
  2141. } else if (type == .redact) { /// 标记密文
  2142. if (index == 1) { /// 取消
  2143. if (self.hasAddRedact) {
  2144. let alert = NSAlert()
  2145. alert.messageText = NSLocalizedString("You can save a document with unapplied cipher text and edit it again. If you do not save, all changes will be lost.", comment: "")
  2146. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2147. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2148. let result = alert.runModal()
  2149. if (result == .alertFirstButtonReturn) {
  2150. self.listView.toolMode = .moveToolMode
  2151. self.toolbarController.exitRedact()
  2152. }
  2153. return
  2154. }
  2155. self.listView.toolMode = .moveToolMode
  2156. self.toolbarController.exitRedact()
  2157. return
  2158. }
  2159. if (index == 2) { /// 擦除
  2160. self.exeRedactConfirm(.eraserAll) {}
  2161. return
  2162. }
  2163. if (index == 3) { /// 应用
  2164. self.exeRedactConfirm(.redactAll) {}
  2165. return
  2166. }
  2167. if (index == 4) { /// 文本&图像
  2168. self.listView.toolMode = .redactToolMode
  2169. return
  2170. }
  2171. if (index == 5) { /// 页面
  2172. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2173. await self.view.window?.beginSheet(windowController.window!)
  2174. self.currentWindowController = windowController
  2175. windowController.itemClick = { [weak self] index, value in
  2176. if (index == 1) {
  2177. let topBarView = self?.toolbarController.fetchTopBarView()
  2178. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  2179. return
  2180. }
  2181. (topBarView as! KMRedactTopToolBar).selectItem(0)
  2182. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2183. self?.currentWindowController = nil
  2184. return
  2185. }
  2186. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2187. let pageType = windowController_pageRange.pageType
  2188. let pageString = windowController_pageRange.pageString
  2189. if (pageType == 5) { /// 自定义页面
  2190. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  2191. if (array.count == 0) {
  2192. let alert = NSAlert()
  2193. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2194. alert.runModal()
  2195. return
  2196. }
  2197. }
  2198. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2199. self!.currentWindowController = nil
  2200. var indexs: IndexSet = []
  2201. if (pageType == 1) { /// 当前页面
  2202. indexs.insert((self?.listView.currentPageIndex)!)
  2203. } else {
  2204. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  2205. }
  2206. if (indexs.count == 0) {
  2207. return
  2208. }
  2209. for i in indexs {
  2210. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2211. let redactAnno = CPDFRedactAnnotation(pdfListViewNoteWith: self?.listView.document)
  2212. redactAnno?.bounds = page.bounds
  2213. self?.listView.add(redactAnno, to: page)
  2214. }
  2215. }
  2216. return
  2217. }
  2218. } else if (type == .secure) { /// 安全
  2219. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2220. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  2221. return
  2222. }
  2223. if (index == 1) { /// 设置密码
  2224. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2225. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2226. if (result == .cancel) {
  2227. return
  2228. }
  2229. self?.isSaveKeyChain = false
  2230. self?.listView.document.unlock(withPassword: password)
  2231. self?.hiddenSecureLimitTip()
  2232. self?.showSecureWindow((self?.listView.document.documentURL)!)
  2233. }
  2234. return
  2235. }
  2236. self.showSecureWindow(self.listView.document.documentURL)
  2237. return
  2238. }
  2239. /// 删除安全性设置
  2240. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2241. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2242. if (result == .cancel) {
  2243. return
  2244. }
  2245. self?.isSaveKeyChain = false
  2246. self?.listView.document.unlock(withPassword: password)
  2247. self?.hiddenSecureLimitTip()
  2248. self?.recordRemoveSecureFlag()
  2249. let tip = KMRemovePasswordResultTipView()
  2250. tip.result = .success
  2251. tip.showInView(superView: (self?.listView.superview)!)
  2252. }
  2253. return
  2254. }
  2255. let alert = NSAlert()
  2256. alert.messageText = NSLocalizedString("Are you sure you want to remove the security settings for the file?", comment: "")
  2257. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2258. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2259. let response = alert.runModal()
  2260. if (response != .alertFirstButtonReturn) {
  2261. return
  2262. }
  2263. self.recordRemoveSecureFlag()
  2264. let tip = KMRemovePasswordResultTipView()
  2265. tip.result = .success
  2266. self.hiddenSecureLimitTip()
  2267. tip.showInView(superView: self.listView.superview!)
  2268. }
  2269. }
  2270. }
  2271. }
  2272. // MARK: -
  2273. // MARK: - Mouse
  2274. extension KMMainViewController {
  2275. override func mouseDown(with event: NSEvent) {
  2276. super.mouseDown(with: event)
  2277. print("KMMainViewController mouseDown")
  2278. self.leftSideViewCancelSelect()
  2279. self.pageNumberDisplayView.isEdit = false
  2280. }
  2281. }
  2282. //MARK: LeftSideViewController
  2283. extension KMMainViewController {
  2284. func leftSideViewCancelSelect() {
  2285. switch self.leftSideViewController.type.methodType {
  2286. // case .Thumbnail:
  2287. // self.leftSideViewController.thumbnailViewController.cancelSelect()
  2288. case .Outline:
  2289. self.leftSideViewController.outlineViewController.cancelSelect()
  2290. case .BookMark:
  2291. self.leftSideViewController.bookViewController.cancelSelect()
  2292. case .Search:
  2293. self.leftSideViewController.searchViewController.cancelSelect()
  2294. case .Annotation:
  2295. self.leftSideViewController.annotationViewController.cancelSelect()
  2296. default:
  2297. print("其他")
  2298. }
  2299. }
  2300. }
  2301. extension KMMainViewController: KMReadModelViewDelegate {
  2302. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2303. self.listView.goToFirstPage(nil)
  2304. }
  2305. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  2306. self.listView.goToPreviousPage(nil)
  2307. }
  2308. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2309. self.listView.goToNextPage(nil)
  2310. }
  2311. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  2312. self.listView.goToLastPage(nil)
  2313. }
  2314. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  2315. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  2316. }
  2317. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  2318. var scale: Double = 1.0
  2319. switch type {
  2320. case .fitWidth:
  2321. self.listView.autoScales = !self.listView.autoScales
  2322. scale = self.listView.scaleFactor
  2323. break
  2324. case .actualSize:
  2325. if self.listView.scaleFactor != 1.0 {
  2326. self.listView.scaleFactor = 1.0
  2327. self.listView.autoScales = false
  2328. }
  2329. scale = self.listView.scaleFactor
  2330. break
  2331. case .autoSize:
  2332. self.listView.autoScales = true
  2333. self.listView.autoScales = false
  2334. scale = self.listView.scaleFactor
  2335. break
  2336. case ._10:
  2337. scale = 0.1
  2338. break
  2339. case ._25:
  2340. scale = 0.25
  2341. break
  2342. case ._50:
  2343. scale = 0.5
  2344. break
  2345. case ._100:
  2346. scale = 1.0
  2347. break
  2348. case ._150:
  2349. scale = 1.5
  2350. break
  2351. case ._200:
  2352. scale = 2.0
  2353. break
  2354. case ._400:
  2355. scale = 4.0
  2356. break
  2357. case ._800:
  2358. scale = 8.0
  2359. break
  2360. default:
  2361. break
  2362. }
  2363. self.listView.scaleFactor = scale
  2364. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2365. }
  2366. func cancelReadModel(view: KMReadModelView, sender: Any) {
  2367. if self.isReadMode {
  2368. self.closeReadModel()
  2369. }
  2370. }
  2371. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  2372. // if self.readModelViewWidthConstraint.constant != width {
  2373. self.readModelViewWidthConstraint.constant = width
  2374. // }
  2375. }
  2376. }
  2377. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  2378. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  2379. self.listView.go(toPageIndex: pageIndex, animated: true)
  2380. }
  2381. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  2382. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  2383. self.tipCurrentPageBoxWidthConstraint.constant = width
  2384. }
  2385. }
  2386. func commitEditingIfNeed() {
  2387. let isEdited = self.listView?.isEdited() ?? false
  2388. if isEdited || self.isPDFTextImageEdited {
  2389. self.listView.commitEditing()
  2390. }
  2391. }
  2392. }