KMMainViewController+Action.swift 197 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063
  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.searchResults = self.searchResults
  18. // self.leftSideViewController.searchViewController.reloadData()
  19. } else {
  20. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  21. var findArray : [[CPDFSelection]]
  22. if isCase {
  23. findArray = self.listView.document.findString(searchString) ?? []
  24. } else {
  25. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  26. }
  27. self.searchResults.removeAll()
  28. for selections in findArray {
  29. for selection in selections {
  30. let mode : KMSearchMode = KMSearchMode()
  31. mode.selection = selection
  32. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  33. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  34. self.searchResults.insert(mode, at: self.searchResults.count)
  35. }
  36. }
  37. // self.leftSideViewController.searchViewController.searchResults = self.searchResults
  38. // self.leftSideViewController.searchViewController.reloadData()
  39. self.leftSideViewController.searchResults = self.searchResults
  40. }
  41. if self.leftSideViewController.findPaneState == .singular {
  42. self.leftSideViewController.displayFindViewAnimating(true)
  43. } else {
  44. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  45. }
  46. }
  47. func removeSignatures(signatures:[CPDFSignature]) {
  48. for signature in signatures {
  49. self.listView.document.removeSignature(signature)
  50. }
  51. for i in 0..<self.listView.document.pageCount {
  52. let page : CPDFPage = self.listView.document.page(at: i)
  53. let annotations : [CPDFAnnotation] = page.annotations
  54. for j in 0..<annotations.count {
  55. let annotation = annotations[j]
  56. if annotation is CPDFSignatureWidgetAnnotation {
  57. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  58. }
  59. }
  60. }
  61. self.listView.setNeedsDisplayForVisiblePages()
  62. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  63. var mSignatures : [CPDFSignature] = []
  64. for sign in tSignatures {
  65. if sign.signers.count > 0 {
  66. mSignatures.append(sign)
  67. }
  68. }
  69. // self.leftSideViewController.signatureViewController.signatures = signatures
  70. // self.leftSideViewController.signatureViewController.reloadData()
  71. }
  72. //MARK: menu菜单
  73. func fontColorMenuItem()->NSMenuItem {
  74. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  75. return fontColorItem;
  76. }
  77. func fontSizeMenuItem()->NSMenuItem {
  78. let currentFontSize = self.listView.editingTextFontSize()
  79. let fontSizes = self.fontSizes()
  80. let submenu = NSMenu(title: "")
  81. for i in 0 ... fontSizes.count - 1 {
  82. let fontSize : String = fontSizes.object(at: i) as! String
  83. let item = NSMenuItem(title:fontSize as! String, action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  84. item.target = self
  85. item.tag = i
  86. submenu.addItem(item)
  87. if (Int(currentFontSize) == Int(fontSize)) {
  88. item.state = .on
  89. }
  90. }
  91. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  92. fontSizeItem.submenu = submenu
  93. return fontSizeItem;
  94. }
  95. func corpImageMenuItem()->NSMenuItem {
  96. var corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm Crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  97. return corpImageItem
  98. }
  99. func cancelCorpImageMenuItem()->NSMenuItem {
  100. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel Crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  101. return cancelCorpImageItem
  102. }
  103. func restoreCorpImageMenuItem()->NSMenuItem {
  104. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore Crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  105. return cancelCorpImageItem
  106. }
  107. func cutImageArea()->NSMenuItem {
  108. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  109. return deleteItem
  110. }
  111. func editAddBlanMenu(menu:NSMenu){
  112. menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  113. menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  114. }
  115. func addText() -> NSMenuItem {
  116. var addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  117. return addTextItem
  118. }
  119. func addImage() -> NSMenuItem {
  120. var addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  121. return addImageItem
  122. }
  123. func replaceImageArea()->NSMenuItem {
  124. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  125. return replaceItem
  126. }
  127. func exportImageArea()->NSMenuItem {
  128. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  129. return exportItem
  130. }
  131. func exportImageStampItem()->NSMenuItem {
  132. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  133. let menu = NSMenu()
  134. menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  135. menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  136. exportItem.submenu = menu
  137. return exportItem
  138. }
  139. func exportMenu() -> NSMenu {
  140. let menu = NSMenu()
  141. menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  142. menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  143. menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  144. return menu
  145. }
  146. func cropMenu() -> NSMenu {
  147. let menu = NSMenu()
  148. menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  149. menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  150. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  151. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  152. return menu
  153. }
  154. func zoomSelectionMenuItem() -> NSMenuItem {
  155. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  156. return item
  157. }
  158. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  159. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  160. return item
  161. }
  162. func enterAnnotationStype() -> NSMenuItem {
  163. let stypItem = NSMenuItem(title: NSLocalizedString("Annotation", comment: ""), action: nil, target: self)
  164. let stypeMenu = NSMenu()
  165. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  166. stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 0)
  167. stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 1)
  168. stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(addAnnotationForStyleMenu), target: self, tag: 2)
  169. stypeMenu.addItem(NSMenuItem.separator())
  170. }
  171. // stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  172. stypeMenu.addItem(withTitle: NSLocalizedString("Text Box", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  173. stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  174. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  175. stypeMenu.addItem(NSMenuItem.separator())
  176. stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  177. stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  178. stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  179. stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  180. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  181. if self.isReadMode {
  182. } else {
  183. stypeMenu.addItem(NSMenuItem.separator())
  184. stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  185. stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  186. stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  187. stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  188. }
  189. stypItem.submenu = stypeMenu
  190. if self.listView.annotationType == .ink {
  191. stypeMenu.item(at: 0)?.state = .on
  192. } else if self.listView.annotationType == .freeText {
  193. stypeMenu.item(at: 1)?.state = .on
  194. } else if self.listView.annotationType == .anchored {
  195. stypeMenu.item(at: 2)?.state = .on
  196. } else if self.listView.annotationType == .square {
  197. stypeMenu.item(at: 3)?.state = .on
  198. } else if self.listView.annotationType == .circle {
  199. stypeMenu.item(at: 4)?.state = .on
  200. } else if self.listView.annotationType == .arrow {
  201. stypeMenu.item(at: 5)?.state = .on
  202. } else if self.listView.annotationType == .line {
  203. stypeMenu.item(at: 6)?.state = .on
  204. } else if self.listView.annotationType == .link {
  205. stypeMenu.item(at: 7)?.state = .on
  206. } else if self.listView.annotationType == .stamp {
  207. stypeMenu.item(at: 8)?.state = .on
  208. } else if self.listView.annotationType == .signSignature {
  209. stypeMenu.item(at: 9)?.state = .on
  210. }
  211. return stypItem
  212. }
  213. func setAnnotationToolStype() -> NSMenuItem {
  214. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  215. let stypeMenu = NSMenu()
  216. stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 0)
  217. stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 1)
  218. stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 2)
  219. stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 3)
  220. // stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  221. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  222. stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 5)
  223. stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 6)
  224. stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 7)
  225. stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 8)
  226. stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 9)
  227. stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 10)
  228. stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 11)
  229. stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 12)
  230. stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 13)
  231. stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 14)
  232. stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode), target: self, tag: 15)
  233. stypItem.submenu = stypeMenu
  234. if self.toolbarController.toolbarType == .Annatiton {
  235. stypeMenu.item(at: 0)?.state = .on
  236. } else if self.toolbarController.toolbarType == .Move {
  237. stypeMenu.item(at: 1)?.state = .on
  238. } else if self.toolbarController.toolbarType == .Magnify {
  239. stypeMenu.item(at: 2)?.state = .on
  240. } else if self.toolbarController.toolbarType == .Select {
  241. stypeMenu.item(at: 3)?.state = .on
  242. } else if self.toolbarController.toolbarType == .SelectZoom {
  243. stypeMenu.item(at: 4)?.state = .on
  244. }
  245. return stypItem
  246. }
  247. func addReadModelStype() -> NSMenuItem {
  248. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  249. if self.isReadMode {
  250. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  251. }
  252. return stypItem
  253. }
  254. func addOutlineStype() -> NSMenuItem {
  255. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  256. return stypItem
  257. }
  258. func setTTSStype() -> NSMenuItem {
  259. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  260. return stypItem
  261. }
  262. func setShareStype() -> NSMenuItem {
  263. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: #selector(showShareAction), target: self)
  264. var string = ""
  265. if listView.activeAnnotation != nil {
  266. string = listView.activeAnnotation.contents
  267. }
  268. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  269. return stypItem
  270. }
  271. func setLookUpStype() -> NSMenuItem {
  272. let str = String(format: "Look Up %@", listView?.currentSelection?.string() ?? "")
  273. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(lookUpAction), target: self)
  274. return stypItem
  275. }
  276. func setSearchBaiduStype() -> NSMenuItem {
  277. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  278. return stypItem
  279. }
  280. func setCutStype() -> NSMenuItem {
  281. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  282. return stypItem
  283. }
  284. func setDeleteStype() -> NSMenuItem {
  285. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  286. return stypItem
  287. }
  288. func setColorsStype() -> NSMenuItem {
  289. let stypItem = NSMenuItem(title: NSLocalizedString("Colors...", comment: ""), action: #selector(ColorsItemAction), target: self)
  290. return stypItem
  291. }
  292. func setLinesStype() -> NSMenuItem {
  293. let stypItem = NSMenuItem(title: NSLocalizedString("Lines...", comment: ""), action: #selector(LinesItemAction), target: self)
  294. return stypItem
  295. }
  296. func setEditNoteStype() -> NSMenuItem {
  297. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  298. return stypItem
  299. }
  300. func setRotateStype() -> NSMenuItem {
  301. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  302. let stypeMenu = NSMenu()
  303. stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  304. stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  305. stypItem.submenu = stypeMenu
  306. if self.toolbarController.toolbarType == .Annatiton {
  307. stypeMenu.item(at: 0)?.state = .on
  308. } else if self.toolbarController.toolbarType == .Move {
  309. stypeMenu.item(at: 1)?.state = .on
  310. }
  311. return stypItem
  312. }
  313. func setNextPageStype() -> NSMenuItem {
  314. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  315. stypItem.isEnabled = false
  316. if listView.canGoToNextPage() {
  317. stypItem.isEnabled = true
  318. }
  319. return stypItem
  320. }
  321. func setPreviousPageStype() -> NSMenuItem {
  322. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  323. stypItem.isEnabled = false
  324. if listView.canGoToPreviousPage() {
  325. stypItem.isEnabled = true
  326. }
  327. return stypItem
  328. }
  329. func setTranslateStype() -> NSMenuItem {
  330. let str = String(format: "Translate %@", listView?.currentSelection?.string() ?? "")
  331. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(TranslateItemAction), target: self)
  332. return stypItem
  333. }
  334. func setAutoScrollStype() -> NSMenuItem {
  335. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  336. return stypItem
  337. }
  338. func setSnapshotStype() -> NSMenuItem {
  339. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  340. let stypeMenu = NSMenu()
  341. stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  342. stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  343. stypItem.submenu = stypeMenu
  344. // if self.toolbarController.toolbarType == .Annatiton {
  345. // stypeMenu.item(at: 0)?.state = .on
  346. // } else if self.toolbarController.toolbarType == .Move {
  347. // stypeMenu.item(at: 1)?.state = .on
  348. // }
  349. return stypItem
  350. }
  351. func setServicesStype() -> NSMenuItem {
  352. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  353. let stypeMenu = NSMenu()
  354. stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  355. stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  356. stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  357. stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  358. stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  359. stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  360. stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  361. stypItem.submenu = stypeMenu
  362. // if self.toolbarController.toolbarType == .Annatiton {
  363. // stypeMenu.item(at: 0)?.state = .on
  364. // } else if self.toolbarController.toolbarType == .Move {
  365. // stypeMenu.item(at: 1)?.state = .on
  366. // }
  367. return stypItem
  368. }
  369. func setCropStype() -> NSMenuItem {
  370. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  371. let stypeMenu = NSMenu()
  372. stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  373. stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  374. stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  375. stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  376. // if(NSIsEmptyRect(selectionRect)) {
  377. stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  378. stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  379. //
  380. // }
  381. stypItem.submenu = stypeMenu
  382. // if self.toolbarController.toolbarType == .Annatiton {
  383. // stypeMenu.item(at: 0)?.state = .on
  384. // } else if self.toolbarController.toolbarType == .Move {
  385. // stypeMenu.item(at: 1)?.state = .on
  386. // } else if self.toolbarController.toolbarType == .Magnify {
  387. // stypeMenu.item(at: 2)?.state = .on
  388. // } else if self.toolbarController.toolbarType == .Select {
  389. // stypeMenu.item(at: 3)?.state = .on
  390. // } else if self.toolbarController.toolbarType == .SelectZoom {
  391. // stypeMenu.item(at: 4)?.state = .on
  392. // }
  393. return stypItem
  394. }
  395. func addHighlightLinksStype() -> NSMenuItem {
  396. let highlightLink = KMPreferenceManager.shared.highlightLinks
  397. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  398. if highlightLink {
  399. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  400. }
  401. var highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  402. return highlightLinksItem
  403. }
  404. func addAnnotationForStyleMenu(menu:NSMenu) {
  405. if menu == nil {
  406. return
  407. }
  408. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  409. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  410. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  411. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  412. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  413. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  414. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  415. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  416. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  417. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  418. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  419. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  420. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  421. if listView.currentSelection.selectionType() != .image {
  422. menu.insertItem(height, at: menu.items.count)
  423. menu.insertItem(underline, at: menu.items.count)
  424. menu.insertItem(strickout, at: menu.items.count)
  425. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  426. }
  427. if self.isReadMode {
  428. } else {
  429. if listView.currentSelection.selectionType() != .image &&
  430. listView.currentSelection.selectionType() != .text {
  431. menu.insertItem(text, at: menu.items.count)
  432. menu.insertItem(note, at: menu.items.count)
  433. }
  434. }
  435. if self.isReadMode {
  436. } else {
  437. if listView.currentSelection.selectionType() != .image {
  438. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  439. menu.insertItem(rectangle, at: menu.items.count)
  440. menu.insertItem(oval, at: menu.items.count)
  441. }
  442. }
  443. if self.isReadMode {
  444. } else {
  445. if listView.currentSelection.selectionType() != .image &&
  446. listView.currentSelection.selectionType() != .text {
  447. menu.insertItem(line, at: menu.items.count)
  448. }
  449. }
  450. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  451. if self.isReadMode {
  452. } else {
  453. menu.insertItem(link, at: menu.items.count)
  454. }
  455. if self.isReadMode {
  456. } else {
  457. if listView.currentSelection.selectionType() != .image {
  458. menu.insertItem(outline, at: menu.items.count)
  459. }
  460. }
  461. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  462. if self.isReadMode {
  463. } else {
  464. if (listView.currentSelection.selectionType() != .image) {
  465. menu.insertItem(aiTranslation, at: menu.items.count)
  466. }
  467. }
  468. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  469. }
  470. func addBookmarkMenu() -> NSMenuItem {
  471. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  472. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  473. return bookMarkItem
  474. } else {
  475. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  476. return bookMarkItem
  477. }
  478. }
  479. func findStringMenu() -> NSMenuItem {
  480. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  481. menuItem.keyEquivalent = "f"
  482. return menuItem
  483. }
  484. func printingMenu() -> NSMenuItem {
  485. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  486. return menuItem
  487. }
  488. func fontSizes()->NSArray {
  489. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  490. }
  491. //MARK: menuItem Action
  492. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  493. let color = listView.editingSelectionFontColor()
  494. let panel = NSColorPanel.shared
  495. panel.setTarget(self)
  496. panel.setAction(#selector(fontColorChangeAction))
  497. panel.orderFront(nil)
  498. panel.showsAlpha = false
  499. panel.color = color ?? NSColor.black
  500. }
  501. @objc func fontColorChangeAction(sender: NSColorPanel) {
  502. self.listView.setEditingSelectionFontColor(sender.color)
  503. }
  504. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  505. let fontSize = self.fontSizes().object(at: sender.tag)
  506. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  507. }
  508. @objc func addImageText(sender: NSMenuItem) {
  509. let event = NSApp.currentEvent
  510. let clickLocation = event?.locationInWindow
  511. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  512. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  513. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  514. point = point2
  515. if sender.tag == 0 {
  516. KMPrint("添加文字")
  517. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  518. if !isSelect {
  519. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  520. }
  521. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  522. } else if sender.tag == 1 {
  523. KMPrint("添加图片")
  524. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  525. if !isSelect {
  526. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  527. }
  528. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  529. } else if sender.tag == 2 {
  530. KMPrint("粘贴")
  531. }
  532. }
  533. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  534. if self.rightSideViewController.eidtPDFImageProperty != nil {
  535. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  536. } else {
  537. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  538. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  539. }
  540. }
  541. }
  542. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  543. if self.rightSideViewController.eidtPDFImageProperty != nil {
  544. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  545. } else {
  546. self.listView.exitCrop(with: self.listView.selectImageAreas)
  547. self.listView.cropAreas = nil
  548. self.listView.isEditImage = false
  549. }
  550. }
  551. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  552. if self.rightSideViewController.eidtPDFImageProperty != nil {
  553. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  554. } else {
  555. self.listView.resetCrop(with: self.listView.selectImageAreas)
  556. }
  557. }
  558. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  559. if self.listView.selectImageAreas != nil {
  560. self.listView.isEditImage = true
  561. self.listView.enterCrop(with: self.listView.selectImageAreas)
  562. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  563. }
  564. }
  565. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  566. if self.listView.selectImageAreas == nil {
  567. return
  568. }
  569. let panel = NSOpenPanel()
  570. panel.allowsMultipleSelection = false
  571. panel.allowedFileTypes = ["png","jpg"]
  572. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  573. if response == .OK {
  574. let openPath = panel.url?.path
  575. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  576. if s {
  577. }
  578. }
  579. }
  580. }
  581. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  582. if self.listView.selectImageAreas == nil {
  583. return
  584. }
  585. let panel = NSSavePanel()
  586. // panel.nameFieldStringValue = "[新文件].png"
  587. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  588. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  589. // button.state = .on
  590. // panel.accessoryView = button
  591. panel.isExtensionHidden = true
  592. let response = panel.runModal()
  593. if response == .OK {
  594. let url = panel.url
  595. if FileManager.default.fileExists(atPath: url!.path) {
  596. try?FileManager.default.removeItem(atPath: url!.path)
  597. }
  598. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  599. if result {
  600. NSWorkspace.shared.activateFileViewerSelecting([url!])
  601. // if button.state == .on { /// 开启文档
  602. // NSWorkspace.shared.openFile(url!.path)
  603. // } else {
  604. //
  605. // }
  606. }
  607. }
  608. }
  609. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  610. }
  611. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  612. }
  613. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  614. }
  615. @objc func OpenItemAction(sender: NSMenuItem) {
  616. }
  617. @objc func takeSnapshot(sender: NSMenuItem) {
  618. }
  619. @objc func takeSnapshotSelectContent(sender: NSMenuItem) {
  620. }
  621. @objc func cropAllPageItem(sender: NSMenuItem) {
  622. }
  623. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  624. }
  625. @objc func autoCropAllItem(sender: NSMenuItem) {
  626. }
  627. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  628. }
  629. @objc func selectToolModel(sender: NSMenuItem) {
  630. }
  631. @objc func customCropModel(sender: NSMenuItem) {
  632. }
  633. @objc func rotateRightAction(sender: NSMenuItem) {
  634. }
  635. @objc func rotateLeftAction(sender: NSMenuItem) {
  636. }
  637. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  638. self.listView.toolMode = .noteToolMode
  639. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  640. var model : KMToolbarViewType = .None
  641. switch sender.tag {
  642. case 0:
  643. identifier = KMDocumentAnnotationToolbarItemIdentifier
  644. model = .Annatiton
  645. case 1:
  646. identifier = KMToolbarMoveToolModeItemIdentifier
  647. model = .Move
  648. case 2:
  649. identifier = KMToolbarMagnifyToolModeItemIdentifier
  650. model = .Magnify
  651. case 3:
  652. identifier = KMToolbarSelectToolModeItemIdentifier
  653. model = .Select
  654. case 4:
  655. identifier = KMToolbarZoomToSelectionItemIdentifier
  656. model = .SelectZoom
  657. default:
  658. break
  659. }
  660. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  661. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  662. }
  663. @objc func changeAnnotationMode(sender : NSMenuItem) {
  664. }
  665. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  666. var annotationType : CAnnotationType = .unkown
  667. switch sender.tag {
  668. case 0:
  669. annotationType = .highlight
  670. case 1:
  671. annotationType = .underline
  672. case 2:
  673. annotationType = .strikeOut
  674. case 3:
  675. annotationType = .freeText
  676. case 4:
  677. annotationType = .anchored
  678. case 5:
  679. annotationType = .square
  680. case 6:
  681. annotationType = .circle
  682. case 7:
  683. annotationType = .line
  684. case 8:
  685. annotationType = .link
  686. case 9:
  687. // var newOutline : CPDFOutline = CPDFOutline()
  688. // newOutline.label = "11111111"
  689. // let des = self.listView.currentDestination
  690. // if "\(des?.point.x ?? 0)" != "nan" {
  691. // newOutline.destination = self.listView.currentDestination
  692. // } else {
  693. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  694. // newOutline.destination = destination
  695. // }
  696. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  697. // let parent = current.parent ?? CPDFOutline()
  698. // let index = current.index + 1
  699. // parent.insertChild(newOutline, at: index)
  700. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  701. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  702. }
  703. // self.leftSideViewController.outlineViewController.addItemAction()
  704. return
  705. case 10:
  706. annotationType = .unkown
  707. default:
  708. break
  709. }
  710. if (annotationType != .link) {
  711. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  712. self.listView.currentSelection = nil;
  713. return
  714. }
  715. // link
  716. let selection = self.listView.currentSelection
  717. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  718. DispatchQueue.main.async {
  719. Task { @MainActor in
  720. #if VERSION_DMG
  721. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  722. return
  723. }
  724. #endif
  725. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  726. self.listView.currentSelection = nil;
  727. if (annotation != nil) {
  728. self.listView.updateActiveAnnotations([annotation!])
  729. }
  730. }
  731. }
  732. }
  733. @objc func aiTranslationAction(sender: NSMenuItem) {
  734. let content = self.listView.currentSelection.string() as? String ?? ""
  735. let origin = self.listView.currentSelection.bounds.origin
  736. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  737. self.aiTranslationWindow?.content = content
  738. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  739. self.aiTranslationWindow!.window?.center()
  740. }
  741. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  742. Task { @MainActor in
  743. #if VERSION_DMG
  744. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) {
  745. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  746. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  747. return
  748. }
  749. }
  750. #endif
  751. var point = mouseRightMenuEvent?.locationInWindow
  752. if (point == nil) {
  753. point = NSZeroPoint
  754. }
  755. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  756. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  757. let pagePoint = self.listView.convert(currentPoint, to: currentPage)
  758. var annotation: CPDFAnnotation?
  759. if self.isReadMode {
  760. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  761. self.listView.toolMode = .noteToolMode
  762. }
  763. switch sender.tag {
  764. case 0:
  765. self.listView.annotationType = CAnnotationType.ink
  766. case 1:
  767. // self.listView.annotationType = CAnnotationType.freeText
  768. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  769. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  770. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  771. if ((annotation) != nil) {
  772. self.listView.updateActiveAnnotations([annotation!])
  773. self.listView.edit(annotation)
  774. }
  775. case 2:
  776. // self.listView.annotationType = CAnnotationType.anchored
  777. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  778. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  779. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  780. self.listView.edit(annotation)
  781. case 3:
  782. // self.listView.annotationType = CAnnotationType.square
  783. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  784. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  785. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  786. case 4:
  787. // self.listView.annotationType = CAnnotationType.circle
  788. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  789. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  790. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  791. case 5:
  792. // self.listView.annotationType = CAnnotationType.arrow
  793. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  794. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  795. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  796. case 6:
  797. // self.listView.annotationType = CAnnotationType.line
  798. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  799. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  800. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  801. case 7:
  802. self.listView.annotationType = CAnnotationType.link
  803. self.openRightPane()
  804. case 8:
  805. self.listView.annotationType = CAnnotationType.stamp
  806. self.openRightPane()
  807. case 9:
  808. self.listView.annotationType = CAnnotationType.signSignature
  809. self.openRightPane()
  810. default:
  811. break
  812. }
  813. self.rightSideViewController.isHidden = true
  814. self.rightSideViewController.subViewType = .AnnotationProperts
  815. } else {
  816. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  817. if(self.toolbarController.toolbarType == .None) {
  818. self.toolbarController.toolbarType = .Annatiton
  819. }
  820. self.listView.toolMode = .noteToolMode
  821. }
  822. switch sender.tag {
  823. case 0:
  824. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  825. self.rightMouseEventing = true
  826. if(self.toolbarController.toolbarType == .None) {
  827. self.toolbarController.toolbarType = .Annatiton
  828. }
  829. self.listView.toolMode = .noteToolMode
  830. self.listView.annotationType = CAnnotationType.ink
  831. case 1:
  832. // self.listView.annotationType = CAnnotationType.freeText
  833. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  834. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  835. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  836. // self.view.window?.makeFirstResponder()
  837. if ((annotation) != nil) {
  838. // self.listView.updateActiveAnnotations([annotation!])
  839. self.listView.edit(annotation)
  840. }
  841. case 2:
  842. // self.listView.annotationType = CAnnotationType.anchored
  843. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  844. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  845. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  846. self.listView.edit(annotation)
  847. case 3:
  848. // self.listView.annotationType = CAnnotationType.square
  849. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  850. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  851. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  852. case 4:
  853. // self.listView.annotationType = CAnnotationType.circle
  854. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  855. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  856. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  857. case 5:
  858. // self.listView.annotationType = CAnnotationType.arrow
  859. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  860. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  861. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  862. case 6:
  863. // self.listView.annotationType = CAnnotationType.line
  864. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  865. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  866. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  867. case 7:
  868. self.listView.annotationType = CAnnotationType.link
  869. self.openRightPane()
  870. case 8:
  871. self.listView.annotationType = CAnnotationType.stamp
  872. self.openRightPane()
  873. case 9:
  874. self.listView.annotationType = CAnnotationType.signSignature
  875. self.openRightPane()
  876. default:
  877. break
  878. }
  879. // self.rightSideViewController.view.isHidden = false
  880. self.rightSideViewController.isHidden = false
  881. // self.openRightPane()
  882. self.rightSideViewController.subViewType = .AnnotationProperts
  883. }
  884. if (annotation != nil) {
  885. self.listView.updateIsRightActiveAnnotations([annotation!])
  886. }
  887. }
  888. }
  889. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  890. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  891. let index = self.listView.currentPageIndex
  892. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  893. self.listView.setNeedsDisplayForVisiblePages()
  894. } else {
  895. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  896. self.listView.setNeedsDisplayForVisiblePages()
  897. }
  898. if self.isReadMode {
  899. } else {
  900. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  901. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  902. }
  903. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  904. if bookMark != nil {
  905. let item = KMBookMarkItem()
  906. item.bookMark = bookMark!
  907. item.label = (bookMark?.label)!
  908. item.index = UInt(bookMark!.pageIndex)
  909. // self.leftSideViewController.bookViewController.reloadData()
  910. // self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  911. } else {
  912. // self.leftSideViewController.bookViewController.reloadData()
  913. }
  914. }
  915. }
  916. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  917. self.leftSideViewController.refreshMethodType(methodType: .Search)
  918. }
  919. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  920. let rect = listView.currentSelectionRect()
  921. let page = listView.currentPage()
  922. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  923. copyPage.setBounds(rect, for: .cropBox)
  924. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  925. // let pdfDocument : PDFDocument = PDFDocument()
  926. // let newpage : PDFPage = PDFPage(image: image)!
  927. // pdfDocument.insert(newpage, at: 0)
  928. // 执行右键操作后,需要取消框选区域
  929. if self.listView.toolMode == .selectToolMode {
  930. objc_sync_enter(self)
  931. self.listView.selectionRect = NSZeroRect
  932. self.listView.selectionPageIndex = UInt(NSNotFound)
  933. objc_sync_exit(self)
  934. }
  935. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  936. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  937. if (result == .cancel) {
  938. return
  939. }
  940. // 解除权限
  941. self?.isSaveKeyChain = false
  942. self?.listView.document.unlock(withPassword: password)
  943. // 隐藏提示
  944. self?.hiddenSecureLimitTip()
  945. // 去打印
  946. KMPrintWindowController.printImage(image: image)
  947. }
  948. return
  949. }
  950. KMPrintWindowController.printImage(image: image)
  951. }
  952. // MARK: Redact 【密文标记】
  953. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  954. self.listView.remove(self.listView.activeAnnotation)
  955. }
  956. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  957. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  958. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  959. self.view.window?.beginSheet(windowController.window!)
  960. self.currentWindowController = windowController
  961. windowController.itemClick = { [weak self] index, value in
  962. if (index == 1) { /// 取消
  963. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  964. self?.currentWindowController = nil
  965. return
  966. }
  967. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  968. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  969. annotaton.setBorderColor(windowController_redact.outsideColor)
  970. annotaton.setInteriorColor(windowController_redact.fillColor)
  971. if (windowController_redact.isOver) {
  972. annotaton.setFontColor(windowController_redact.fontColor)
  973. annotaton.setAlignment(windowController_redact.aligement)
  974. annotaton.setFont(windowController_redact.font)
  975. annotaton.setOverlayText(windowController_redact.overText)
  976. }
  977. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  978. self?.currentWindowController = nil
  979. }
  980. }
  981. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  982. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  983. return
  984. }
  985. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  986. let model = CPDFAnnotationModel(annotationType: .redact)
  987. model?.setColor(annotation.borderColor())
  988. model?.setInteriorColor(annotation.interiorColor())
  989. let overlayText: String = annotation.overlayText()
  990. if (overlayText.isEmpty) {
  991. model?.setIsOverlayText(false)
  992. } else {
  993. model?.setIsOverlayText(true)
  994. model?.setOverlayText(overlayText)
  995. model?.setFontColor(annotation.fontColor())
  996. model?.setAlignment(annotation.alignment())
  997. model?.setFontName(annotation.font().fontName)
  998. model?.setFontSize(annotation.font().pointSize)
  999. }
  1000. }
  1001. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1002. let anno = self.listView.activeAnnotation
  1003. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1004. return
  1005. }
  1006. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1007. windowController.pageCount = Int(self.listView.document.pageCount)
  1008. self.currentWindowController = windowController
  1009. self.view.window?.beginSheet(windowController.window!)
  1010. windowController.itemClick = { [weak self] index, value in
  1011. if (index == 1) {
  1012. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1013. self!.currentWindowController = nil
  1014. return
  1015. }
  1016. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1017. let pageType = windowController_mutilPageFlag.pageType
  1018. let pageString = windowController_mutilPageFlag.pageString
  1019. if (pageType == 4) { /// 自定义页面
  1020. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1021. if (array.count == 0) {
  1022. let alert = NSAlert()
  1023. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1024. alert.runModal()
  1025. return
  1026. }
  1027. }
  1028. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1029. self!.currentWindowController = nil
  1030. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  1031. if (indexs.count == 0) {
  1032. return
  1033. }
  1034. for i in indexs {
  1035. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1036. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1037. self?.listView.add(redactAnno, to: page)
  1038. }
  1039. }
  1040. }
  1041. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1042. self.exeRedactConfirm(.redactOne) {}
  1043. }
  1044. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1045. self.exeRedactConfirm(.eraserOne) {}
  1046. }
  1047. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1048. }
  1049. @objc func exportStampImage(sender:NSMenuItem) {
  1050. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1051. var image : NSImage = NSImage()
  1052. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1053. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1054. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1055. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1056. }
  1057. let data = image.tiffRepresentation
  1058. if sender.tag == 0 {
  1059. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1060. imageRep.size = image.size
  1061. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1062. let savePanel = NSSavePanel()
  1063. savePanel.allowedFileTypes = ["png"]
  1064. savePanel.beginSheetModal(for: self.view.window!) { response in
  1065. if (response != .OK) {
  1066. return
  1067. }
  1068. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1069. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1070. }
  1071. }
  1072. } else {
  1073. let pdfdocument = CPDFDocument()
  1074. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1075. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1076. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1077. let savePanel = NSSavePanel()
  1078. savePanel.allowedFileTypes = ["pdf"]
  1079. savePanel.beginSheetModal(for: self.view.window!) { response in
  1080. if (response != .OK) {
  1081. return
  1082. }
  1083. if pdfdocument!.write(to: savePanel.url!) {
  1084. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1085. }
  1086. }
  1087. }
  1088. }
  1089. }
  1090. }
  1091. @objc func exportCorpImage(sender:NSMenuItem) {
  1092. let rect = NSIntegralRect(listView.currentSelectionRect())
  1093. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1094. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1095. page.setBounds(rect, for: .cropBox)
  1096. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1097. let data = image.tiffRepresentation
  1098. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1099. imageRep.size = rect.size
  1100. let savePanel = NSSavePanel()
  1101. switch sender.tag {
  1102. case 0:
  1103. savePanel.allowedFileTypes = ["png"]
  1104. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1105. savePanel.beginSheetModal(for: self.view.window!) { response in
  1106. if (response != .OK) {
  1107. return
  1108. }
  1109. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1110. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1111. }
  1112. }
  1113. case 1:
  1114. savePanel.allowedFileTypes = ["jpg"]
  1115. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1116. savePanel.beginSheetModal(for: self.view.window!) { response in
  1117. if (response != .OK) {
  1118. return
  1119. }
  1120. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1121. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1122. }
  1123. }
  1124. case 2:
  1125. savePanel.allowedFileTypes = ["pdf"]
  1126. let pdfdocument = CPDFDocument()
  1127. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1128. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1129. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1130. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1131. savePanel.beginSheetModal(for: self.view.window!) { response in
  1132. if (response != .OK) {
  1133. return
  1134. }
  1135. if pdfdocument!.write(to: savePanel.url!) {
  1136. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1137. }
  1138. }
  1139. }
  1140. default:
  1141. break
  1142. }
  1143. // 执行右键操作后,需要取消框选区域
  1144. if self.listView.toolMode == .selectToolMode {
  1145. objc_sync_enter(self)
  1146. self.listView.selectionRect = NSZeroRect
  1147. self.listView.selectionPageIndex = UInt(NSNotFound)
  1148. objc_sync_exit(self)
  1149. }
  1150. }
  1151. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1152. let rect = listView.currentSelectionRect()
  1153. let page = listView.currentPage()
  1154. if NSIsEmptyRect(rect) == false && page != nil {
  1155. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1156. var bounds = listView.bounds
  1157. var scale = 1.0
  1158. if isLegacy {
  1159. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1160. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1161. }
  1162. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1163. scale = NSHeight(bounds) / NSHeight(rect)
  1164. } else {
  1165. scale = NSWidth(bounds) / NSWidth(rect)
  1166. }
  1167. listView.setScaleFactor(scale, animated: false)
  1168. let scrollView = listView.scroll()
  1169. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1170. if ((scrollView?.hasVerticalScroller) != nil) {
  1171. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1172. }
  1173. if ((scrollView?.hasHorizontalScroller) != nil) {
  1174. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1175. }
  1176. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1177. scale = NSHeight(bounds) / NSHeight(rect)
  1178. } else {
  1179. scale = NSWidth(bounds) / NSWidth(rect)
  1180. }
  1181. listView.setScaleFactor(scale, animated: false)
  1182. }
  1183. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1184. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1185. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1186. };
  1187. }
  1188. // 执行右键操作后,需要取消框选区域
  1189. if self.listView.toolMode == .selectToolMode {
  1190. objc_sync_enter(self)
  1191. self.listView.selectionRect = NSZeroRect
  1192. self.listView.selectionPageIndex = UInt(NSNotFound)
  1193. objc_sync_exit(self)
  1194. }
  1195. }
  1196. @IBAction func autoCropAll(sender:NSMenuItem) {
  1197. }
  1198. private func cropPagesToRects(rects:NSPointerArray) {
  1199. }
  1200. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1201. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1202. switch sender.tag {
  1203. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1204. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1205. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1206. var red: CGFloat = 0.0
  1207. var green: CGFloat = 0.0
  1208. var blue: CGFloat = 0.0
  1209. var alpha: CGFloat = 0.0
  1210. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1211. if sender.tag == CAnnotationType.highlight.rawValue {
  1212. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1213. } else if sender.tag == CAnnotationType.underline.rawValue {
  1214. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1215. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1216. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1217. }
  1218. case CAnnotationType.ink.rawValue:
  1219. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1220. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1221. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1222. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1223. var red: CGFloat = 0.0
  1224. var green: CGFloat = 0.0
  1225. var blue: CGFloat = 0.0
  1226. var alpha: CGFloat = 0.0
  1227. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1228. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1229. case CAnnotationType.freeText.rawValue:
  1230. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1231. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1232. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1233. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1234. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1235. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1236. var red: CGFloat = 0.0
  1237. var green: CGFloat = 0.0
  1238. var blue: CGFloat = 0.0
  1239. var alpha: CGFloat = 0.0
  1240. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1241. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1242. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1243. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1244. UserDefaults.standard.synchronize()
  1245. }
  1246. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1247. if (alignment == .left || alignment == .center || alignment == .right) {
  1248. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1249. UserDefaults.standard.synchronize()
  1250. }
  1251. case CAnnotationType.anchored.rawValue:
  1252. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1253. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1254. var red: CGFloat = 0.0
  1255. var green: CGFloat = 0.0
  1256. var blue: CGFloat = 0.0
  1257. var alpha: CGFloat = 0.0
  1258. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1259. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1260. case CAnnotationType.square.rawValue:
  1261. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1262. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1263. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1264. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1265. var red: CGFloat = 0.0
  1266. var green: CGFloat = 0.0
  1267. var blue: CGFloat = 0.0
  1268. var alpha: CGFloat = 0.0
  1269. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1270. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1271. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1272. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1273. case CAnnotationType.circle.rawValue:
  1274. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1275. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1276. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1277. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1278. var red: CGFloat = 0.0
  1279. var green: CGFloat = 0.0
  1280. var blue: CGFloat = 0.0
  1281. var alpha: CGFloat = 0.0
  1282. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1283. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1284. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1285. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1286. default:
  1287. break
  1288. }
  1289. }
  1290. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1291. self.showOrHideNotes()
  1292. }
  1293. //MARK: action
  1294. @objc func cropCurrentPage() {
  1295. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1296. var page: CPDFPage?
  1297. if ((self.listView.currentSelectionPage()) != nil) {
  1298. page = self.listView.currentSelectionPage()
  1299. } else {
  1300. page = self.listView.currentPage()
  1301. }
  1302. if (NSIsEmptyRect(rect)) {
  1303. rect = KMCropTools.getPageForegroundBox(page!)
  1304. }
  1305. let index: UInt = (page?.pageIndex())!
  1306. cropPage(at: index, in: rect)
  1307. // 执行右键操作后,需要取消框选区域
  1308. if self.listView.toolMode == .selectToolMode {
  1309. objc_sync_enter(self)
  1310. self.listView.selectionRect = NSZeroRect
  1311. self.listView.selectionPageIndex = UInt(NSNotFound)
  1312. objc_sync_exit(self)
  1313. }
  1314. }
  1315. func cropPage(at index: UInt, in rect: NSRect) {
  1316. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  1317. let undoManager = self.listView.undoManager
  1318. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  1319. let page = self.listView.document.page(at: index)
  1320. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  1321. page?.setBounds(newRect, for: .cropBox)
  1322. /// 刷新预览视图
  1323. self.listView.layoutDocumentView()
  1324. self.listView.displayBox = .cropBox
  1325. }
  1326. @objc private func cropAllPage() {
  1327. var size = NSZeroSize
  1328. for i in 0 ..< self.listView.document.pageCount {
  1329. let page = self.listView.document.page(at: i)
  1330. var rect = KMCropTools.getPageForegroundBox(page!)
  1331. size.width = fmax(size.width, NSWidth(rect))
  1332. size.height = fmax(size.height, NSHeight(rect))
  1333. }
  1334. var rectArray: Array<NSRect> = []
  1335. for i in 0 ..< self.listView.document.pageCount {
  1336. let page = self.listView.document.page(at: i)
  1337. var rect = KMCropTools.getPageForegroundBox(page!)
  1338. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1339. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1340. rect.origin.x = rect.maxX-size.width
  1341. }
  1342. rect.origin.y = rect.maxY-size.height
  1343. rect.size = size
  1344. if (NSWidth(rect) > NSWidth(bounds)) {
  1345. rect.size.width = NSWidth(bounds)
  1346. }
  1347. if (NSHeight(rect) > NSHeight(bounds)) {
  1348. rect.size.height = NSHeight(bounds)
  1349. }
  1350. if (NSMinX(rect) < NSMinX(bounds)) {
  1351. rect.origin.x = NSMinX(bounds)
  1352. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1353. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1354. }
  1355. if (NSMinY(rect) < NSMinY(bounds)) {
  1356. rect.origin.y = NSMinY(bounds)
  1357. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1358. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1359. }
  1360. rectArray.append(rect)
  1361. }
  1362. cropPages(to: rectArray)
  1363. }
  1364. func cropPages(to rects: Array<NSRect>) {
  1365. let currentPage = self.listView.currentPage()
  1366. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1367. var oldRectArray: Array<NSRect> = []
  1368. for i in 0 ..< self.listView.document.pageCount {
  1369. let page = self.listView.document.page(at: i)
  1370. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  1371. let oldRect = page?.bounds(for: .cropBox)
  1372. oldRectArray.append(oldRect!)
  1373. page?.setBounds(rect, for: .cropBox)
  1374. }
  1375. let undoManager = self.listView.undoManager
  1376. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1377. /// 刷新预览视图
  1378. self.listView.layoutDocumentView()
  1379. self.listView.displayBox = .cropBox
  1380. self.listView.go(to: currentPage)
  1381. self.listView.go(to: visibleRect, on: currentPage)
  1382. }
  1383. private func cropCustomArea() {
  1384. self.listView.toolMode = .selectToolMode
  1385. self.listView.autoScales = true
  1386. self.listView.autoScales = false
  1387. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1388. if (self.listView.displaysPageBreaks) {
  1389. pageHeight += 8
  1390. }
  1391. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1392. // if (scaleFactor < self.preView.scaleFactor) {
  1393. self.listView.scaleFactor = scaleFactor
  1394. // }
  1395. let tipView = KMCropTipView()
  1396. tipView.setString(string: "请框选裁剪区域")
  1397. tipView.frame = self.topTipBox.contentView!.frame
  1398. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1399. self.addTopTip(tipView)
  1400. tipView.enterAction = {
  1401. () in
  1402. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1403. if (NSIsEmptyRect(rect)) {
  1404. return
  1405. }
  1406. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1407. self.view.window?.beginSheet(window.window!)
  1408. self.cropSettingWindowController = window
  1409. window.itemClick = { [self]
  1410. (index: Int) in
  1411. if (index == 1) { /// 取消
  1412. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1413. self.cropSettingWindowController = nil
  1414. return
  1415. }
  1416. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1417. let pageCount: Int = Int(self.listView.document.pageCount)
  1418. var pages: Array<Int> = []
  1419. if (pageRangeType == 0) { /// 当前页面
  1420. pages.append(self.listView.currentPageIndex)
  1421. } else if (pageRangeType == 1) { /// 全部页面
  1422. for i in 0 ..< pageCount {
  1423. pages.append(i)
  1424. }
  1425. } else if (pageRangeType == 2) { /// 奇数页面
  1426. var string: String = ""
  1427. for i in 0 ..< pageCount {
  1428. if (i % 2 == 1) {
  1429. continue
  1430. }
  1431. pages.append(i)
  1432. }
  1433. } else if (pageRangeType == 3) { /// 偶数页面
  1434. var string: String = ""
  1435. for i in 0 ..< pageCount {
  1436. if (i % 2 == 0) {
  1437. continue
  1438. }
  1439. pages.append(i)
  1440. }
  1441. } else { /// 自定义
  1442. for i in self.cropSettingWindowController.pageRangePages {
  1443. pages.append(i)
  1444. }
  1445. }
  1446. if (pages.count < 0) {
  1447. let alert = NSAlert()
  1448. alert.messageText = "请选择页面"
  1449. alert.runModal()
  1450. return
  1451. }
  1452. var pageSize: NSSize = NSZeroSize
  1453. if (self.cropSettingWindowController.pageSize == "None") {
  1454. } else {
  1455. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1456. }
  1457. for i in pages {
  1458. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1459. var rect = NSIntegralRect(self.listView.selectionRect)
  1460. if (NSIsEmptyRect(rect)) {
  1461. rect = KMCropTools.getPageForegroundBox(page)
  1462. }
  1463. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1464. page.setBounds(newRect, for: .cropBox)
  1465. if (pageSize.width == 0 && pageSize.height == 0) {
  1466. } else {
  1467. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1468. let index: UInt = (page.pageIndex())
  1469. // let newPage: CPDFPage = nil
  1470. // self.listView.document.removePage(at: index)
  1471. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1472. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1473. let result = self.listView.document.insertPage(pageSize, at: index)
  1474. }
  1475. }
  1476. /// 保存到临时路径
  1477. let toPath: String = self.listView.document.documentURL.path
  1478. let documentPath = NSTemporaryDirectory()
  1479. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1480. if (FileManager.default.fileExists(atPath: tempPath)) {
  1481. try?FileManager.default.removeItem(atPath: tempPath)
  1482. }
  1483. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1484. if (result) {
  1485. if (FileManager.default.fileExists(atPath: toPath)) {
  1486. try?FileManager.default.removeItem(atPath: toPath)
  1487. }
  1488. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1489. } else {
  1490. try?FileManager.default.removeItem(atPath: tempPath)
  1491. }
  1492. DispatchQueue.main.async {
  1493. self.listView.toolMode = .textToolMode
  1494. /// 刷新预览视图
  1495. self.listView.layoutDocumentView()
  1496. self.listView.displayBox = .cropBox
  1497. }
  1498. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1499. self.cropSettingWindowController = nil
  1500. self.addTopTip(nil)
  1501. }
  1502. }
  1503. }
  1504. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1505. if (limit) {
  1506. var doucumentURL : URL = self.listView.document.documentURL
  1507. if doucumentURL != nil {
  1508. let docDir = NSTemporaryDirectory()
  1509. let documentName : String = doucumentURL.path.lastPathComponent
  1510. let path = docDir.stringByAppendingPathComponent(documentName)
  1511. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1512. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1513. let writeSuccess = data != nil
  1514. if writeSuccess == false {
  1515. __NSBeep()
  1516. return;
  1517. }
  1518. doucumentURL = URL(fileURLWithPath: path)
  1519. }
  1520. let array = [doucumentURL]
  1521. let picker = NSSharingServicePicker.init(items: array)
  1522. if sender.shareButton.window != nil {
  1523. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1524. } else {
  1525. 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)
  1526. }
  1527. return
  1528. }
  1529. var doucumentURL : URL = self.listView.document.documentURL
  1530. if doucumentURL != nil {
  1531. let docDir = NSTemporaryDirectory()
  1532. let documentName : String = doucumentURL.path.lastPathComponent
  1533. let path = docDir.stringByAppendingPathComponent(documentName)
  1534. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1535. if writeSuccess == false {
  1536. __NSBeep()
  1537. return;
  1538. }
  1539. doucumentURL = URL(fileURLWithPath: path)
  1540. }
  1541. let array = [doucumentURL]
  1542. let picker = NSSharingServicePicker.init(items: array)
  1543. if sender.shareButton.window != nil {
  1544. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1545. } else {
  1546. 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)
  1547. }
  1548. }
  1549. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1550. if (limit) {
  1551. let document = self.listView.document ?? CPDFDocument()
  1552. var path = document!.documentURL.path
  1553. if path != nil {
  1554. let docDir = NSTemporaryDirectory()
  1555. let documentName : String = path.lastPathComponent
  1556. path = docDir.stringByAppendingPathComponent(documentName)
  1557. }
  1558. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1559. var tfileName = path.deletingPathExtension.lastPathComponent
  1560. let tStdFileSuffix = "_flatten"
  1561. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1562. path = pathFolder + "/" + tfileName
  1563. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path))
  1564. let success = data != nil
  1565. if success {
  1566. let url = URL(fileURLWithPath: path)
  1567. let picker = NSSharingServicePicker.init(items: [url])
  1568. if sender.shareButton.window != nil {
  1569. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1570. } else {
  1571. 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)
  1572. }
  1573. }
  1574. return
  1575. }
  1576. let document = self.listView.document ?? CPDFDocument()
  1577. var path = document!.documentURL.path
  1578. if path != nil {
  1579. let docDir = NSTemporaryDirectory()
  1580. let documentName : String = path.lastPathComponent
  1581. path = docDir.stringByAppendingPathComponent(documentName)
  1582. }
  1583. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1584. var tfileName = path.deletingPathExtension.lastPathComponent
  1585. let tStdFileSuffix = "_flatten"
  1586. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1587. path = pathFolder + "/" + tfileName
  1588. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1589. if success {
  1590. let url = URL(fileURLWithPath: path)
  1591. let picker = NSSharingServicePicker.init(items: [url])
  1592. if sender.shareButton.window != nil {
  1593. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1594. } else {
  1595. 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)
  1596. }
  1597. }
  1598. }
  1599. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1600. if (limit) {
  1601. let document = self.listView.document ?? CPDFDocument()
  1602. var path = document!.documentURL.path
  1603. if path != nil {
  1604. let docDir = NSTemporaryDirectory()
  1605. let documentName : String = path.lastPathComponent
  1606. path = docDir.stringByAppendingPathComponent(documentName)
  1607. }
  1608. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1609. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1610. var writeSuccess = data != nil
  1611. if writeSuccess == false {
  1612. __NSBeep()
  1613. return;
  1614. }
  1615. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1616. for i in 0 ... newDocument.pageCount-1 {
  1617. let page = newDocument.page(at: i)
  1618. var annotations : [CPDFAnnotation] = []
  1619. for annotation in page!.annotations {
  1620. annotations.append(annotation)
  1621. }
  1622. for annotation in annotations {
  1623. annotation.page.removeAnnotation(annotation)
  1624. }
  1625. }
  1626. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1627. if writeSuccess {
  1628. let url = URL(fileURLWithPath: path)
  1629. let picker = NSSharingServicePicker.init(items: [url])
  1630. if sender.shareButton.window != nil {
  1631. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1632. } else {
  1633. 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)
  1634. }
  1635. }
  1636. return
  1637. }
  1638. let document = self.listView.document ?? CPDFDocument()
  1639. var path = document!.documentURL.path
  1640. if path != nil {
  1641. let docDir = NSTemporaryDirectory()
  1642. let documentName : String = path.lastPathComponent
  1643. path = docDir.stringByAppendingPathComponent(documentName)
  1644. }
  1645. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1646. if writeSuccess == false {
  1647. __NSBeep()
  1648. return;
  1649. }
  1650. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1651. for i in 0 ... newDocument.pageCount-1 {
  1652. let page = newDocument.page(at: i)
  1653. var annotations : [CPDFAnnotation] = []
  1654. for annotation in page!.annotations {
  1655. annotations.append(annotation)
  1656. }
  1657. for annotation in annotations {
  1658. annotation.page.removeAnnotation(annotation)
  1659. }
  1660. }
  1661. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1662. if writeSuccess {
  1663. let url = URL(fileURLWithPath: path)
  1664. let picker = NSSharingServicePicker.init(items: [url])
  1665. if sender.shareButton.window != nil {
  1666. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1667. } else {
  1668. 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)
  1669. }
  1670. }
  1671. }
  1672. // 开启/关闭左边栏
  1673. @objc func toggleLeftPane() -> Void {
  1674. // if lastLeftPanWidth >= functionWidth {
  1675. leftPanelOpen = true
  1676. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1677. // } else {
  1678. // leftPanelOpen = false
  1679. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1680. // }
  1681. }
  1682. // 开启左边栏
  1683. @objc func openLeftPane() -> Void {
  1684. leftPanelOpen = true
  1685. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1686. }
  1687. // 关闭左边栏
  1688. @objc func closeLeftPane() -> Void {
  1689. leftPanelOpen = false
  1690. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1691. }
  1692. // 开启/关闭右边栏
  1693. @objc func toggleRightPane() -> Void {
  1694. if lastRightPanWidth > 5 {
  1695. self.rightPanelIsOpen = false
  1696. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1697. } else {
  1698. self.rightPanelIsOpen = true
  1699. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1700. }
  1701. }
  1702. @objc func openRightPane() -> Void {
  1703. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1704. if self.rightPanelIsOpen {
  1705. return
  1706. }
  1707. self.rightPanelIsOpen = true
  1708. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1709. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1710. }
  1711. }
  1712. @objc func closeRightPane() -> Void {
  1713. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1714. self.rightPanelIsOpen = false
  1715. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1716. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1717. }
  1718. }
  1719. func rename(_ sender: NSNotification) -> Void {
  1720. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1721. return
  1722. }
  1723. let tabController = sender.object as? CTTabController
  1724. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1725. let outputSavePanel = NSSavePanel()
  1726. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1727. outputSavePanel.allowedFileTypes = ["pdf"]
  1728. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1729. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1730. let result = outputSavePanel.runModal()
  1731. if result == .OK {
  1732. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1733. let fileURL = pdfDocument?.documentURL
  1734. let fileManager = FileManager.default
  1735. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1736. var result = true
  1737. do {
  1738. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1739. } catch {
  1740. result = false
  1741. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1742. }
  1743. if (result) {
  1744. tabController?.title = outputSavePanel.url!.lastPathComponent
  1745. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1746. self.isSaveKeyChain = false
  1747. newPdfDocument.unlock(withPassword: self.document?.password)
  1748. if (newPdfDocument.pageCount > 0) {
  1749. self.setDocument = newPdfDocument
  1750. }
  1751. }
  1752. }
  1753. } else {
  1754. outputSavePanel.close()
  1755. }
  1756. }
  1757. }
  1758. func showInFinder(_ sender: Any) -> Void {
  1759. if sender is NSNotification {
  1760. let tabController = (sender as! NSNotification).object as? CTTabController
  1761. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1762. let file: URL = (self.myDocument?.fileURL)!
  1763. if FileManager.default.fileExists(atPath: file.path) {
  1764. NSWorkspace.shared.activateFileViewerSelecting([file])
  1765. }
  1766. }
  1767. } else {
  1768. let file: URL = (self.myDocument?.fileURL)!
  1769. if FileManager.default.fileExists(atPath: file.path) {
  1770. NSWorkspace.shared.activateFileViewerSelecting([file])
  1771. }
  1772. }
  1773. }
  1774. func showOrHideNotes() {
  1775. self.listView.hideNotes = !self.listView.hideNotes
  1776. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1777. //BOTA 注释列表显示隐藏
  1778. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1779. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1780. }
  1781. func closeTab(_ sender: NSNotification) -> Void {
  1782. let tabController = sender.object as? CTTabController
  1783. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1784. print("closeTab")
  1785. self.leftSideViewController.clearAnnotationFilterData()
  1786. self.leftSideViewController.clearNotification()
  1787. }
  1788. }
  1789. // MARK: -
  1790. // MARK: 显示窗口
  1791. internal func showCompressWindow(url: URL? = nil) {
  1792. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1793. KMPrint("压缩窗口已显示")
  1794. return
  1795. }
  1796. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  1797. self.view.window?.beginSheet(windowController.window!)
  1798. self.currentWindowController = windowController
  1799. if let _url = url {
  1800. windowController.documentURL = _url
  1801. windowController.oriDocumentUrl = self.listView.document.documentURL
  1802. } else {
  1803. windowController.documentURL = self.listView.document.documentURL
  1804. }
  1805. windowController.password = self.listView.document.password
  1806. windowController.itemClick = { [weak self] in
  1807. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1808. self?.currentWindowController = nil
  1809. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1810. }
  1811. windowController.batchAction = { [weak self] view, filePaths in
  1812. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1813. self?.currentWindowController = nil
  1814. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1815. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1816. batchWindowController.window?.makeKeyAndOrderFront("")
  1817. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path)
  1818. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1819. batchWindowController.window?.makeKeyAndOrderFront("")
  1820. }
  1821. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1822. if (result) {
  1823. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1824. self?.currentWindowController = nil
  1825. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1826. if (openDocument) {
  1827. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1828. } else {
  1829. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1830. }
  1831. } else {
  1832. let alert = NSAlert()
  1833. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1834. alert.runModal()
  1835. }
  1836. }
  1837. }
  1838. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1839. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1840. KMPrint("转档窗口已显示")
  1841. return
  1842. }
  1843. var convertT: KMConvertType = .Word
  1844. var windowController: KMConvertBaseWindowController?
  1845. if (type == .word) { /// Word
  1846. convertT = .Word
  1847. } else if (type == .excel) {
  1848. convertT = .Excel
  1849. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1850. if (type == .ppt) {
  1851. convertT = .PPT
  1852. } else if (type == .rtf) {
  1853. convertT = .RTF
  1854. } else if (type == .html) {
  1855. convertT = .HTML
  1856. } else if (type == .conversion_text) {
  1857. convertT = .Text
  1858. }
  1859. } else if (type == .csv) {
  1860. convertT = .CSV
  1861. } else if (type == .conversion_image) {
  1862. windowController = KMConvertImageWindowController()
  1863. }
  1864. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  1865. var url: URL?
  1866. if (documentUrl != nil) {
  1867. url = documentUrl
  1868. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1869. } else {
  1870. url = self.listView.document.documentURL
  1871. }
  1872. self.showAllConvertWindow(convertT: convertT)
  1873. // let model = KMDocumentModel(url: url!)
  1874. // if (self.listView.document.password != nil) {
  1875. // let _ = model.unlock(self.listView.document.password)
  1876. // }
  1877. // model.currentIndex = self.listView.currentPageIndex
  1878. // windowController?.documentModel = model
  1879. //
  1880. // windowController?.itemClick = { [weak self] index in
  1881. // if (identifier != nil) {
  1882. // self?.toolbarController.cancelSelected(identifier!)
  1883. // }
  1884. //
  1885. // if (self?.currentWindowController == nil) {
  1886. // return
  1887. // }
  1888. // self?.view.window?.endSheet(self!.currentWindowController.window!)
  1889. // self?.currentWindowController = nil
  1890. // }
  1891. //
  1892. // self.view.window?.beginSheet((windowController?.window)!)
  1893. // self.currentWindowController = windowController
  1894. }
  1895. //MARK: 转档 -
  1896. func showAllConvertWindow(convertT: KMConvertType) {
  1897. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1898. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1899. var type: KMConvertWithPDFType = .WordAdvance
  1900. switch convertT {
  1901. case .Word:
  1902. break
  1903. case .Excel:
  1904. type = .Excel
  1905. case .PPT:
  1906. type = .PowerPoint
  1907. case .RTF:
  1908. type = .RTF
  1909. case .CSV:
  1910. type = .CSV
  1911. case .HTML:
  1912. type = .HTML
  1913. case .Text:
  1914. type = .Text
  1915. case .JPEG:
  1916. type = .JPEG
  1917. case .PNG:
  1918. type = .PNG
  1919. case .GIF:
  1920. type = .GIF
  1921. case .JPG:
  1922. type = .JPG
  1923. case .TIFF:
  1924. type = .TIFF
  1925. case .TGA:
  1926. type = .TGA
  1927. case .BMP:
  1928. type = .BMP
  1929. case .JP2:
  1930. type = .JPEG2000
  1931. case .AdvancedWord:
  1932. break
  1933. default:
  1934. break
  1935. }
  1936. // let document = self.document
  1937. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1938. var needShowHint = false
  1939. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1940. needShowHint = true
  1941. } else {
  1942. var needContinue = false
  1943. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1944. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1945. let ss = self.document?.documentURL.path
  1946. if arr.contains(ss!) {
  1947. needContinue = false
  1948. }else {
  1949. needContinue = true
  1950. }
  1951. }else {
  1952. needContinue = true
  1953. }
  1954. if needContinue {
  1955. let ss = self.document?.documentURL.path
  1956. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1957. file.password = document?.password ?? ""
  1958. KMBatchOperateManager.defaultManager.files?.append(file)
  1959. }
  1960. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1961. batchWindowController.switchToConvertType(convertType: type)
  1962. }
  1963. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1964. if needShowHint {
  1965. batchWindowController.showIsConvertingHint()
  1966. } else {
  1967. }
  1968. }
  1969. }
  1970. self.km_beginSheet(windowC: convertWC)
  1971. }
  1972. //MARK: 转档 - OCR
  1973. func showOCRWindow() {
  1974. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  1975. self.km_beginSheet(windowC: com)
  1976. }
  1977. //MARK: 导出图片
  1978. func extractImageAction(num: Int) {
  1979. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  1980. let alert = NSAlert()
  1981. alert.alertStyle = .critical
  1982. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1983. alert.runModal()
  1984. return
  1985. }
  1986. // if sender is KMToolbarItem {
  1987. // (sender as! KMToolbarItem).isSelected = false
  1988. // }
  1989. // if !IAPProductsManager.defaultManager.isAvailableAllFunction {
  1990. // KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1991. // return
  1992. // }
  1993. let document = self.listView.document
  1994. var fileURL = document?.documentURL
  1995. if num == 1 {
  1996. let pageCount = self.document?.pageCount ?? 0
  1997. var indeSet = NSMutableIndexSet()
  1998. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  1999. if indeSet.count == 0 {
  2000. return
  2001. }
  2002. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2003. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2004. let outputSavePanel = NSSavePanel()
  2005. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2006. outputSavePanel.allowsOtherFileTypes = true
  2007. outputSavePanel.isExtensionHidden = true
  2008. outputSavePanel.canCreateDirectories = true
  2009. outputSavePanel.nameFieldStringValue = tFileName
  2010. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2011. if result == NSApplication.ModalResponse.OK {
  2012. DispatchQueue.main.async {
  2013. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2014. let tDestFile = outputSavePanel.url!.path
  2015. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2016. let pdfconverter = PDFConvertObject()
  2017. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2018. self.dismissProgressSheet()
  2019. let fileManager = FileManager.default
  2020. if fileManager.fileExists(atPath: tDestFile) {
  2021. let workspace = NSWorkspace.shared
  2022. let url = URL(fileURLWithPath: tDestFile)
  2023. workspace.activateFileViewerSelecting([url])
  2024. }
  2025. }
  2026. }
  2027. })
  2028. return
  2029. }
  2030. if fileURL != nil {
  2031. self.myDocument?.save(nil)
  2032. } else {
  2033. let myDocument = self.myDocument
  2034. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2035. let writeSuccess = self.document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2036. if writeSuccess {
  2037. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2038. fileURL = self.document?.documentURL
  2039. } else {
  2040. NSSound.beep()
  2041. return
  2042. }
  2043. }
  2044. let extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2045. extract.docPath = fileURL?.path ?? ""
  2046. extract.password = document?.password ?? ""
  2047. extract.currentPage = self.listView.currentPageIndex - 1
  2048. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2049. // self.km_beginSheet(windowC: extract)
  2050. // extract.selectCurrentPageBtn()
  2051. self.showCreateStamp()
  2052. // self.showAddSignature()
  2053. }
  2054. //MARK: 创建文字图章示例实际上不会在这里使用
  2055. func showCreateStamp() {
  2056. let stampCreaterWindowController = KMStampCreaterWindowController()
  2057. stampCreaterWindowController.window?.backgroundColor = .clear
  2058. self.km_beginSheet(windowC: stampCreaterWindowController)
  2059. stampCreaterWindowController.closeCallBack = { result in
  2060. if result == 1 {
  2061. }
  2062. }
  2063. }
  2064. //MARK: 添加签名示例实际上不会在这里使用
  2065. func showAddSignature() {
  2066. var signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")//[[KMSignatureWindowController alloc] initWithWindowNibName:@"KMSignatureWindowController"];
  2067. // signatureWindowController.window?.backgroundColor = .clear
  2068. signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2069. }
  2070. }
  2071. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2072. // if progressController == nil {
  2073. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2074. // }
  2075. let progress = SKProgressController()
  2076. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2077. progress.window?.contentView?.wantsLayer = true
  2078. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2079. progress.progressField.textColor = NSColor.white
  2080. progress.message = NSLocalizedString("Converting...", comment: "")
  2081. progressController = progress
  2082. progressController?.message = message
  2083. if maxValue > 0 {
  2084. progressController?.indeterminate = false
  2085. progressController?.maxValue = Double(maxValue)
  2086. } else {
  2087. progressController?.indeterminate = true
  2088. }
  2089. self.km_beginSheet(windowC: progressController!)
  2090. }
  2091. func dismissProgressSheet() {
  2092. progressController?.stopAnimation()
  2093. self.km_endSheet()
  2094. progressController = nil
  2095. }
  2096. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2097. let newArr = NSMutableArray()
  2098. for item in files {
  2099. newArr.add(item.filePath)
  2100. }
  2101. return newArr as! [String]
  2102. }
  2103. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2104. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2105. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2106. if (result == .cancel) {
  2107. return
  2108. }
  2109. // 解除权限
  2110. self?.listView.document.unlock(withPassword: password)
  2111. // 隐藏提示
  2112. self?.hiddenSecureLimitTip()
  2113. // 去打印
  2114. if let data = self?.saveWatermarkFlag, !data {
  2115. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  2116. return
  2117. }
  2118. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  2119. _ = CPDFDocument(url: _url)
  2120. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  2121. } else {
  2122. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2123. }
  2124. }
  2125. return
  2126. }
  2127. if (!self.saveWatermarkFlag) {
  2128. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2129. return
  2130. }
  2131. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  2132. let _document = CPDFDocument(url: _url)
  2133. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  2134. } else {
  2135. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2136. }
  2137. }
  2138. // MARK: - Split View
  2139. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2140. }
  2141. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2142. if !isSinglePage && isHorizontal {
  2143. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2144. }
  2145. if (!isSinglePage && !isHorizontal) {
  2146. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2147. }
  2148. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2149. }
  2150. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2151. if isSinglePage {
  2152. pdfSplitView.dividerStyle = .thin
  2153. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  2154. } else {
  2155. pdfSplitView.dividerStyle = .paneSplitter
  2156. pdfSplitView.isVertical = !isHorizontal
  2157. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  2158. if secondaryPdfView.document != nil {
  2159. // secondaryPdfView.frame = pdfSplitSecondView.frame
  2160. // pdfSplitSecondView.contentView = secondaryPdfView
  2161. } else {
  2162. openSecondaryPdfView = KMSecondaryViewController.init()
  2163. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  2164. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  2165. openSecondaryPdfView?.delegate = self
  2166. }
  2167. }
  2168. }
  2169. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  2170. if (pdfSplitView.isVertical) {
  2171. return Float(NSWidth(rect))
  2172. } else {
  2173. return Float(NSHeight(rect))
  2174. }
  2175. }
  2176. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  2177. let document = CPDFDocument.init(url: url)
  2178. if document != nil {
  2179. secondaryPdfView.frame = pdfSplitSecondView.frame
  2180. pdfSplitSecondView.contentView = secondaryPdfView
  2181. secondaryPdfView.document = nil
  2182. secondaryPdfView.document = document
  2183. return true
  2184. } else {
  2185. return false
  2186. }
  2187. }
  2188. func updateNextAndPreViousButtonState() {
  2189. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2190. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2191. if self.listView.canGoToNextPage() {
  2192. item?.unEnabled = false
  2193. } else {
  2194. item?.unEnabled = true
  2195. }
  2196. if self.listView.canGoToPreviousPage() {
  2197. toItem?.unEnabled = false
  2198. } else {
  2199. toItem?.unEnabled = true
  2200. }
  2201. }
  2202. func updateBackAndForwardButtonState() {
  2203. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2204. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2205. if self.listView.km_canGoBack() {
  2206. item?.unEnabled = false
  2207. } else {
  2208. item?.unEnabled = true
  2209. }
  2210. if self.listView.km_canGoForward() {
  2211. toItem?.unEnabled = false
  2212. } else {
  2213. toItem?.unEnabled = true
  2214. }
  2215. }
  2216. func updateZoomInOutButtonState() {
  2217. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  2218. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  2219. if self.listView.canZoomIn {
  2220. item.unEnabled = false
  2221. } else {
  2222. item.unEnabled = true
  2223. }
  2224. if self.listView.canZoomOut {
  2225. toItem.unEnabled = false
  2226. } else {
  2227. toItem.unEnabled = true
  2228. }
  2229. }
  2230. }
  2231. // MARK: -
  2232. // MARK: - KMSecondaryViewControllerDelegate
  2233. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  2234. func receivedFileUrl(_ url: URL!) {
  2235. let state = self.displaySecondaryPDFView(withUrl: url)
  2236. if !state {
  2237. let alert = NSAlert()
  2238. alert.alertStyle = .critical
  2239. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  2240. alert.runModal()
  2241. return
  2242. }
  2243. }
  2244. }
  2245. // MARK: -
  2246. // MARK: - KMMainToolbarControllerDelegate
  2247. extension KMMainViewController : KMMainToolbarControllerDelegate {
  2248. func changeModelAction(mode: CToolMode) {
  2249. self.listView.toolMode = mode
  2250. if mode == .editPDFToolMode {
  2251. self.childToolbarController.updateType(newType: .editPDF)
  2252. }
  2253. }
  2254. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2255. switch selectedTag {
  2256. case 2:
  2257. if self.listView.scaleFactor != 1.0 {
  2258. self.listView.scaleFactor = 1.0
  2259. self.listView.autoScales = false
  2260. }
  2261. break
  2262. case 1:
  2263. let pageHeight = self.listView.currentPage()!.size.height
  2264. let pdfviewHeight = self.listView.bounds.size.height
  2265. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2266. self.listView.autoScales = false
  2267. break
  2268. case 0:
  2269. // self.listView.autoScales = !self.listView.autoScales
  2270. self.listView.autoScales = true
  2271. break
  2272. case 3:
  2273. self.listView.scaleFactor = 0.1
  2274. break
  2275. case 4:
  2276. self.listView.scaleFactor = 0.25
  2277. break
  2278. case 5:
  2279. self.listView.scaleFactor = 0.5
  2280. break
  2281. case 6:
  2282. self.listView.scaleFactor = 0.75
  2283. break
  2284. case 7:
  2285. self.listView.scaleFactor = 1.0
  2286. break
  2287. case 8:
  2288. self.listView.scaleFactor = 1.5
  2289. break
  2290. case 9:
  2291. self.listView.scaleFactor = 2.0
  2292. break
  2293. case 10:
  2294. self.listView.scaleFactor = 4.0
  2295. break
  2296. case 11:
  2297. self.listView.scaleFactor = 8.0
  2298. break
  2299. case 12:
  2300. self.listView.scaleFactor = 10.0
  2301. break
  2302. default:
  2303. break
  2304. }
  2305. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2306. }
  2307. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2308. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2309. if scale > 100 {
  2310. scale = 100
  2311. }
  2312. if (scale <= 0.101) {
  2313. self.listView.scaleFactor = self.listView.minScaleFactor()
  2314. } else {
  2315. self.listView.scaleFactor = scale
  2316. }
  2317. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2318. DispatchQueue.main.async {
  2319. self.updateZoomInOutButtonState()
  2320. }
  2321. }
  2322. func changePDFViewZoomInAction() {
  2323. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2324. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2325. switch scale {
  2326. case 0...0.25:
  2327. scale += 0.25
  2328. case 0.25...3:
  2329. scale += 0.25
  2330. case 3.1...10:
  2331. scale += 0.4
  2332. case 10.1...100:
  2333. scale += 1
  2334. default:
  2335. scale += 1
  2336. }
  2337. self.listView.scaleFactor = scale
  2338. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2339. // self.listView.zoomIn(nil)
  2340. }
  2341. func changePDFViewZoomOutAction() {
  2342. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2343. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2344. switch scale {
  2345. case 0...0.25:
  2346. scale = 0
  2347. case 0.25...3:
  2348. scale -= 0.25
  2349. case 3.1...10:
  2350. scale -= 0.4
  2351. case 10.1...100:
  2352. scale -= 1
  2353. default:
  2354. scale -= 1
  2355. }
  2356. self.listView.scaleFactor = scale
  2357. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2358. // self.listView.zoomOut(nil)
  2359. // self.updateZoomInOutButtonState()
  2360. }
  2361. func changePDFViewGotoNextPageAction() {
  2362. self.listView.km_goBack(nil)
  2363. if (self.listView.canGoToNextPage()) {
  2364. self.listView.goToNextPage(nil)
  2365. }
  2366. self.updateNextAndPreViousButtonState()
  2367. }
  2368. func changePDFViewGoToPreviousPageAction() {
  2369. if (self.listView.canGoToPreviousPage()) {
  2370. self.listView.goToPreviousPage(nil)
  2371. }
  2372. self.updateNextAndPreViousButtonState()
  2373. }
  2374. func changePDFViewGotoBackAction() {
  2375. self.listView.km_goBack(nil)
  2376. self.updateBackAndForwardButtonState()
  2377. }
  2378. func changePDFViewGoToForwardAction() {
  2379. self.listView.km_goForward(nil)
  2380. self.updateBackAndForwardButtonState()
  2381. }
  2382. func aiTranslationPDFFileAction() {
  2383. #if VERSION_DMG
  2384. #else
  2385. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  2386. KMLoginWindowController.show(window: NSApp.mainWindow!)
  2387. return
  2388. }
  2389. #endif
  2390. self.trackEvent_aiTranslate()
  2391. self._aiTranslationPDFFileAction()
  2392. // Task { @MainActor in
  2393. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2394. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  2395. // if (isClose) {
  2396. // return
  2397. // }
  2398. // if (isSub) {
  2399. // self._aiTranslationPDFFileAction()
  2400. // return
  2401. // }
  2402. // }
  2403. // return
  2404. // }
  2405. //
  2406. // self._aiTranslationPDFFileAction()
  2407. // }
  2408. }
  2409. private func _aiTranslationPDFFileAction() {
  2410. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2411. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2412. let alert = NSAlert()
  2413. alert.alertStyle = .critical
  2414. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2415. alert.runModal()
  2416. return
  2417. } else if isExceedsLimit {
  2418. let alert = NSAlert()
  2419. alert.alertStyle = .critical
  2420. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2421. alert.runModal()
  2422. return
  2423. }
  2424. let alert = NSAlert()
  2425. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2426. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2427. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2428. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2429. if (result == .alertFirstButtonReturn) {
  2430. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  2431. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  2432. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  2433. } else if result == .alertSecondButtonReturn {
  2434. return
  2435. }
  2436. }
  2437. }
  2438. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2439. self.trackEvent_share()
  2440. }
  2441. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2442. if (!self.saveWatermarkFlag) {
  2443. self.shareDocument(sender: viewController)
  2444. return
  2445. }
  2446. Task { @MainActor in
  2447. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2448. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2449. if (isClose) {
  2450. return
  2451. }
  2452. if (isSubscribeSuccess) {
  2453. self.shareDocument(sender: viewController)
  2454. return
  2455. }
  2456. if (isWaterMarkExport) {
  2457. self.shareDocument(sender: viewController, limit: true)
  2458. return
  2459. }
  2460. }
  2461. return
  2462. }
  2463. self.shareDocument(sender: viewController)
  2464. }
  2465. }
  2466. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2467. // if (!self.saveWatermarkFlag) {
  2468. // self.shareFlatten(sender: viewController)
  2469. // return
  2470. // }
  2471. Task { @MainActor in
  2472. #if VERSION_DMG
  2473. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2474. let _ = KMComparativeTableViewController.show(window: self.view.window!, .shareFlatten)
  2475. return
  2476. }
  2477. #endif
  2478. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2479. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2480. if (isClose) {
  2481. return
  2482. }
  2483. if (isSubscribeSuccess) {
  2484. self.shareFlatten(sender: viewController)
  2485. return
  2486. }
  2487. if (isWaterMarkExport) {
  2488. self.shareFlatten(sender: viewController, limit: true)
  2489. return
  2490. }
  2491. }
  2492. return
  2493. }
  2494. self.shareFlatten(sender: viewController)
  2495. }
  2496. }
  2497. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2498. if (!self.saveWatermarkFlag) {
  2499. self.shareOriginalPDF(sender: viewController)
  2500. return
  2501. }
  2502. Task { @MainActor in
  2503. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2504. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2505. if (isClose) {
  2506. return
  2507. }
  2508. if (isSubscribeSuccess) {
  2509. self.shareOriginalPDF(sender: viewController)
  2510. return
  2511. }
  2512. if (isWaterMarkExport) {
  2513. self.shareOriginalPDF(sender: viewController, limit: true)
  2514. return
  2515. }
  2516. }
  2517. return
  2518. }
  2519. self.shareOriginalPDF(sender: viewController)
  2520. }
  2521. }
  2522. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2523. if(0 == selectedTag) {
  2524. // self.documentAIViewController?.enteredIncreaseAllPage()
  2525. // self.documentAIViewController?.updateToolState(false)
  2526. } else {
  2527. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  2528. // self.documentAIViewController?.recognitionPartModel(with: .english)
  2529. // self.documentAIViewController?.updateToolState(true)
  2530. }
  2531. // 0 : Scan 1:OCR Text
  2532. }
  2533. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2534. if beforeType == .editPDF {
  2535. // self.asyncSaveDocument { params in
  2536. //
  2537. // }
  2538. }
  2539. // 埋点
  2540. self.trackEvent(toolType: type)
  2541. if(type != .Page) {
  2542. if (hasEnterPageEdit()) {
  2543. self.exitPageEdit()
  2544. }
  2545. }
  2546. if(type != .ScanOCR) {
  2547. // if ((self.documentAIViewController?.view.superview) != nil) {
  2548. // self.listView.isHidden = false
  2549. // self.documentAIViewController?.creatRecognitionDocument()
  2550. // self.documentAIViewController?.view .removeFromSuperview()
  2551. // self.documentAIViewController = nil;
  2552. // self.listView.layoutDocumentView()
  2553. // }
  2554. }
  2555. if (type == .Page) {
  2556. if (hasEnterPageEdit()) {
  2557. self.exitPageEdit()
  2558. } else {
  2559. self.enterPageEdit(pages)
  2560. }
  2561. } else if(type == .ScanOCR) {
  2562. // if((self.documentAIViewController?.view.superview) != nil) {
  2563. // let alert = NSAlert()
  2564. // alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  2565. // alert.addButton(withTitle: "YES")
  2566. // alert.addButton(withTitle: "NO")
  2567. // let result = alert.runModal()
  2568. // if (result == .alertFirstButtonReturn) { /// 取消
  2569. // self.listView.isHidden = false
  2570. // self.documentAIViewController?.creatRecognitionDocument()
  2571. // self.documentAIViewController?.view .removeFromSuperview()
  2572. // self.documentAIViewController = nil;
  2573. // self.listView.layoutDocumentView()
  2574. // } else {
  2575. // self.toolbarController.toolbarType = .ScanOCR
  2576. // }
  2577. // } else {
  2578. // self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  2579. // self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  2580. // self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  2581. // self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  2582. // self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  2583. // }
  2584. } else if type == .editPDF {
  2585. self.listView.annotationType = .editTextImage
  2586. } else if type == .Annatiton {
  2587. self.rightSideViewController.subViewType = .AnnotationProperts
  2588. }
  2589. }
  2590. func clickChildTool(type: KMToolbarType, index: Int) {
  2591. if (type == .secure) {
  2592. if (index == 1) {
  2593. self.trackEvent_setPassword()
  2594. } else if (index == 2) {
  2595. self.trackEvent_removePassword()
  2596. }
  2597. } else {
  2598. self.trackEvent(toolBarType: type)
  2599. }
  2600. Task { @MainActor in
  2601. if (type == .compress) { /// 压缩
  2602. // #if VERSION_DMG
  2603. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2604. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  2605. // self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2606. // return
  2607. // }
  2608. // #endif
  2609. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2610. // self.view.window?.contentView?.superview?.beginLoading()
  2611. let document = self.listView.document
  2612. let secureOptions = self.secureOptions
  2613. let removeSecureFlag = self.removeSecureFlag
  2614. // DispatchQueue.global().async { [unowned self] in
  2615. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  2616. // DispatchQueue.main.async {
  2617. // self.view.window?.contentView?.superview?.endLoading()
  2618. // }
  2619. return
  2620. }
  2621. // DispatchQueue.main.async {
  2622. // self.view.window?.contentView?.superview?.endLoading()
  2623. self.showCompressWindow(url: _url)
  2624. // }
  2625. // }
  2626. return
  2627. }
  2628. if (self.needSaveDocument()) {
  2629. self.saveDocumentWithProgressAlert { [unowned self] params in
  2630. self.showCompressWindow()
  2631. }
  2632. return
  2633. }
  2634. self.showCompressWindow()
  2635. return
  2636. }
  2637. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  2638. var identifier: String?
  2639. if (type == .word) { /// Word
  2640. identifier = KMToolbarConversionWordItemIdentifier
  2641. } else if (type == .excel) {
  2642. identifier = KMToolbarConversionExcelItemIdentifier
  2643. } else if (type == .ppt) {
  2644. identifier = KMToolbarConversionPPTItemIdentifier
  2645. } else if (type == .rtf) {
  2646. identifier = KMToolbarConversionRTFItemIdentifier
  2647. } else if (type == .html) {
  2648. identifier = KMToolbarConversionHTMLItemIdentifier
  2649. } else if (type == .conversion_text) {
  2650. identifier = KMToolbarConversionTextItemIdentifier
  2651. } else if (type == .csv) {
  2652. identifier = KMToolbarConversionCSVItemIdentifier
  2653. } else if (type == .conversion_image) {
  2654. identifier = KMToolbarConversionImageItemIdentifier
  2655. }
  2656. #if VERSION_DMG
  2657. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2658. // if (identifier != nil) {
  2659. // self.toolbarController.cancelSelected(identifier!)
  2660. // }
  2661. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .convert)
  2662. // return
  2663. // }
  2664. #endif
  2665. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2666. // guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2667. // return
  2668. // }
  2669. // self.showConvertWindow(type: type, documentUrl: _url, identifier: identifier)
  2670. // return
  2671. // }
  2672. if (self.needSaveDocument()) {
  2673. self.saveDocumentWithProgressAlert { [unowned self] params in
  2674. self.showConvertWindow(type: type, identifier: identifier)
  2675. }
  2676. return
  2677. }
  2678. self.showConvertWindow(type: type, identifier: identifier)
  2679. return
  2680. }
  2681. if (type == .merge) { /// 合并
  2682. // #if VERSION_DMG
  2683. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2684. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  2685. //
  2686. // self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  2687. // return
  2688. // }
  2689. // #endif
  2690. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2691. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2692. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2693. if (result == .cancel) {
  2694. return
  2695. }
  2696. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2697. return
  2698. }
  2699. self.showMergeWindow(url: _url, password)
  2700. }
  2701. return
  2702. }
  2703. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2704. if (result == .cancel) {
  2705. return
  2706. }
  2707. if (self.needSaveDocument()) {
  2708. self.saveDocumentWithProgressAlert { [unowned self] params in
  2709. self.showMergeWindow(password)
  2710. }
  2711. return
  2712. }
  2713. self.showMergeWindow(password)
  2714. }
  2715. return
  2716. }
  2717. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2718. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2719. return
  2720. }
  2721. self.showMergeWindow(url: _url, password)
  2722. return
  2723. }
  2724. if (self.needSaveDocument()) {
  2725. self.saveDocumentWithProgressAlert { [unowned self] params in
  2726. self.showMergeWindow(self.listView.document.password)
  2727. }
  2728. return
  2729. }
  2730. self.showMergeWindow(self.listView.document.password)
  2731. return
  2732. }
  2733. if (type == .crop) {
  2734. #if VERSION_DMG
  2735. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2736. let _ = KMComparativeTableViewController.show(window: self.view.window!, .crop)
  2737. return
  2738. }
  2739. #endif
  2740. self.recordSaveWatermarkFlag(type: .crop)
  2741. if (index == 1) {
  2742. self.cropCurrentPage()
  2743. return
  2744. }
  2745. if (index == 2) {
  2746. self.cropAllPage()
  2747. return
  2748. }
  2749. //// 自定义裁剪区域
  2750. // self.cropCustomArea()
  2751. } else if (type == .bates || type == .headerAndFooter) {
  2752. if (index == 1) {
  2753. var windowController: KMBaseWindowController = KMBaseWindowController()
  2754. if (type == .bates) {
  2755. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2756. windowController.isBates = true
  2757. } else if (type == .headerAndFooter) {
  2758. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2759. } else if (type == .background) {
  2760. // controller = KMBackgroundController()
  2761. } else if (type == .watermark) {
  2762. // controller = KMWatermarkViewController()
  2763. }
  2764. windowController.pdfDocument = self.listView.document
  2765. windowController.cancelAction = { [unowned self] controller in
  2766. self.view.window?.endSheet((self.currentWindowController.window)!)
  2767. self.currentWindowController = nil
  2768. }
  2769. self.currentWindowController = windowController
  2770. await self.view.window?.beginSheet(windowController.window!)
  2771. return
  2772. }
  2773. if (index == 1) { /// 取消
  2774. self.toolbarController.exitWatermarkAdjective()
  2775. // self.rightSideViewController.view.isHidden = true
  2776. self.rightSideViewController.isHidden = true
  2777. self.rightSideViewController.subViewType = .None
  2778. self.closeRightPane()
  2779. return
  2780. } else if index == 3 {
  2781. if type == .bates {
  2782. self.showBatchWindow(type: .AddBates, files: [])
  2783. } else {
  2784. self.showBatchWindow(type: .AddHeaderFooter, files: [])
  2785. }
  2786. } else if index == 4 {
  2787. if type == .bates {
  2788. self.showBatchWindow(type: .RemoveBates, files: [])
  2789. } else {
  2790. self.showBatchWindow(type: .RemoveHeaderFooter, files: [])
  2791. }
  2792. } else if (index == 2) { //// 移除
  2793. if (type == .watermark) {
  2794. let watermarks = self.listView.document.watermarks()
  2795. if (watermarks == nil || watermarks!.count <= 0) {
  2796. let alert = NSAlert()
  2797. alert.alertStyle = .warning
  2798. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  2799. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  2800. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2801. alert.runModal()
  2802. return
  2803. }
  2804. let alert = NSAlert()
  2805. alert.alertStyle = .warning
  2806. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  2807. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  2808. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2809. let result = alert.runModal()
  2810. if (result != .alertFirstButtonReturn) {
  2811. return
  2812. }
  2813. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  2814. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  2815. result in
  2816. DispatchQueue.main.async {
  2817. self.listView.layoutDocumentView()
  2818. self.listView.setNeedsDisplayForVisiblePages()
  2819. }
  2820. if (result) {
  2821. let alert = NSAlert()
  2822. alert.alertStyle = .warning
  2823. alert.messageText = "成功"
  2824. alert.runModal()
  2825. } else {
  2826. let alert = NSAlert()
  2827. alert.alertStyle = .critical
  2828. alert.messageText = "失败"
  2829. alert.runModal()
  2830. }
  2831. }
  2832. } else if type == .headerAndFooter {
  2833. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2834. let savePanel = NSSavePanel()
  2835. savePanel.nameFieldStringValue = (document?.documentURL.lastPathComponent.deletingPathExtension)!
  2836. savePanel.allowedFileTypes = ["pdf"]
  2837. savePanel.accessoryView = savePanelAccessoryViewController.view
  2838. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2839. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2840. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2841. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2842. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2843. }
  2844. } else {
  2845. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2846. }
  2847. }
  2848. }
  2849. }
  2850. } else if type == .bates {
  2851. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2852. let savePanel = NSSavePanel()
  2853. savePanel.nameFieldStringValue = (document?.documentURL.lastPathComponent.deletingPathExtension)!
  2854. savePanel.allowedFileTypes = ["pdf"]
  2855. savePanel.accessoryView = savePanelAccessoryViewController.view
  2856. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2857. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2858. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2859. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2860. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2861. }
  2862. } else {
  2863. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2864. }
  2865. }
  2866. }
  2867. }
  2868. }
  2869. return
  2870. } else if (index == 2) { /// 应用
  2871. let model = self.rightSideViewController.model
  2872. if (type == .bates || type == .headerAndFooter) {
  2873. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2874. let alert = NSAlert()
  2875. alert.alertStyle = .critical
  2876. alert.messageText = "没有找到模型"
  2877. alert.runModal()
  2878. return
  2879. }
  2880. if ((model as! KMBatesModel).hasVaild == false) {
  2881. let alert = NSAlert()
  2882. alert.alertStyle = .critical
  2883. alert.messageText = "没有找到内容"
  2884. alert.runModal()
  2885. return
  2886. }
  2887. }
  2888. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2889. result in
  2890. DispatchQueue.main.async {
  2891. self.listView.layoutDocumentView()
  2892. self.listView.setNeedsDisplayForVisiblePages()
  2893. }
  2894. if (result) {
  2895. let alert = NSAlert()
  2896. alert.alertStyle = .warning
  2897. alert.messageText = "成功"
  2898. alert.runModal()
  2899. } else {
  2900. let alert = NSAlert()
  2901. alert.alertStyle = .critical
  2902. alert.messageText = "失败"
  2903. alert.runModal()
  2904. }
  2905. }
  2906. return
  2907. } else if index == 5 {
  2908. self.rightSideViewController.isHidden = false
  2909. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2910. self.openRightPane()
  2911. }
  2912. } else if (type == .redact) { /// 标记密文
  2913. if (index == 1) { /// 取消
  2914. if (self.hasAddRedact) {
  2915. let alert = NSAlert()
  2916. 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: "")
  2917. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2918. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2919. let result = alert.runModal()
  2920. if (result == .alertFirstButtonReturn) {
  2921. self.listView.toolMode = .moveToolMode
  2922. self.toolbarController.exitRedact()
  2923. }
  2924. return
  2925. }
  2926. self.listView.toolMode = .moveToolMode
  2927. self.toolbarController.exitRedact()
  2928. return
  2929. }
  2930. if (index == 2) { /// 擦除
  2931. self.exeRedactConfirm(.eraserAll) {}
  2932. return
  2933. }
  2934. if (index == 3) { /// 应用
  2935. self.exeRedactConfirm(.redactAll) {}
  2936. return
  2937. }
  2938. if (index == 4) { /// 文本&图像
  2939. self.listView.toolMode = .redactToolMode
  2940. return
  2941. }
  2942. if (index == 5) { /// 页面
  2943. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2944. await self.view.window?.beginSheet(windowController.window!)
  2945. self.currentWindowController = windowController
  2946. windowController.itemClick = { [weak self] index, value in
  2947. if (index == 1) {
  2948. let topBarView = self?.toolbarController.fetchTopBarView()
  2949. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  2950. return
  2951. }
  2952. (topBarView as! KMRedactTopToolBar).selectItem(0)
  2953. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2954. self?.currentWindowController = nil
  2955. return
  2956. }
  2957. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2958. let pageType = windowController_pageRange.pageType
  2959. let pageString = windowController_pageRange.pageString
  2960. if (pageType == 5) { /// 自定义页面
  2961. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  2962. if (array.count == 0) {
  2963. let alert = NSAlert()
  2964. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2965. alert.runModal()
  2966. return
  2967. }
  2968. }
  2969. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2970. self!.currentWindowController = nil
  2971. var indexs: IndexSet = []
  2972. if (pageType == 1) { /// 当前页面
  2973. indexs.insert((self?.listView.currentPageIndex)!)
  2974. } else {
  2975. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  2976. }
  2977. if (indexs.count == 0) {
  2978. return
  2979. }
  2980. for i in indexs {
  2981. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2982. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2983. redactAnno.bounds = page.bounds
  2984. self?.listView.add(redactAnno, to: page)
  2985. }
  2986. }
  2987. return
  2988. }
  2989. } else if (type == .secure) { /// 安全
  2990. #if VERSION_DMG
  2991. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2992. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  2993. return
  2994. }
  2995. #endif
  2996. if (index == 1) { /// 设置密码
  2997. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2998. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2999. if (result == .cancel) {
  3000. return
  3001. }
  3002. self?.isSaveKeyChain = false
  3003. self?.listView.document.unlock(withPassword: password)
  3004. self?.hiddenSecureLimitTip()
  3005. self?.showSecureWindow((self?.listView.document.documentURL)!)
  3006. }
  3007. return
  3008. }
  3009. self.showSecureWindow(self.listView.document.documentURL)
  3010. return
  3011. } else if index == 2 {
  3012. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3013. self.currentWindowController = controller
  3014. controller.batchAction = { [unowned self] controller, files in
  3015. self.view.window?.endSheet((self.currentWindowController.window)!)
  3016. self.currentWindowController = nil
  3017. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3018. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3019. batchWindowController.window?.makeKeyAndOrderFront("")
  3020. let batchOperateFile = KMBatchOperateFile(filePath: files.first?.filePath ?? "")
  3021. batchWindowController.switchToOperateType(.RemovePassword, files: [batchOperateFile])
  3022. batchWindowController.window?.makeKeyAndOrderFront("")
  3023. }
  3024. controller.cancelAction = { [unowned self] controller in
  3025. self.view.window?.endSheet((self.currentWindowController.window)!)
  3026. self.currentWindowController = nil
  3027. }
  3028. controller.doneAction = { [unowned self] controller in
  3029. self.view.window?.endSheet((self.currentWindowController.window)!)
  3030. self.currentWindowController = nil
  3031. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  3032. if success {
  3033. /// 删除安全性设置
  3034. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3035. self.isSaveKeyChain = false
  3036. self.listView.document.unlock(withPassword: password)
  3037. self.hiddenSecureLimitTip()
  3038. self.recordRemoveSecureFlag()
  3039. self.recordSaveWatermarkFlag(type: .removePassword)
  3040. let tip = KMRemovePasswordResultTipView()
  3041. tip.result = .success
  3042. tip.showInView(superView: (self.listView.superview)!)
  3043. } else {
  3044. self.recordRemoveSecureFlag()
  3045. self.recordSaveWatermarkFlag(type: .removePassword)
  3046. let tip = KMRemovePasswordResultTipView()
  3047. tip.result = .success
  3048. self.hiddenSecureLimitTip()
  3049. tip.showInView(superView: self.listView.superview!)
  3050. }
  3051. }
  3052. }
  3053. }
  3054. await NSWindow.currentWindow().beginSheet(controller.window!)
  3055. return
  3056. }
  3057. } else if type == .comparison {
  3058. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3059. self.currentWindowController = controller
  3060. controller.filePath = (self.document?.documentURL.path)!
  3061. controller.cancelAction = { [unowned self] controller in
  3062. self.view.window?.endSheet((self.currentWindowController.window)!)
  3063. self.currentWindowController = nil
  3064. }
  3065. controller.contentComplete = { [unowned self] controller, result, oldDocument, document in
  3066. self.openContentCompareVC(with: controller.pdfCompareContent!, results: result, oldDocument: oldDocument, document: document)
  3067. }
  3068. controller.coveringComplete = { [unowned self] controller, document in
  3069. self.openCoveringCompareVC(with: document)
  3070. }
  3071. if index == 1 {
  3072. controller.fileType = .content
  3073. } else {
  3074. controller.fileType = .coverting
  3075. }
  3076. await NSWindow.currentWindow().beginSheet(controller.window!)
  3077. } else if type == .watermark {
  3078. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  3079. self.currentWindowController = controller
  3080. controller.pdfDocument = self.document
  3081. controller.cancelAction = { [unowned self] controller in
  3082. self.view.window?.endSheet((self.currentWindowController.window)!)
  3083. self.currentWindowController = nil
  3084. }
  3085. if index == 1 {
  3086. } else if index == 3 {
  3087. self.showBatchWindow(type: .AddWatermark, files: [])
  3088. } else if index == 4 {
  3089. self.showBatchWindow(type: .RemoveWatermark, files: [])
  3090. } else if index == 5 {
  3091. self.rightSideViewController.isHidden = false
  3092. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3093. self.openRightPane()
  3094. return
  3095. }
  3096. await NSWindow.currentWindow().beginSheet(controller.window!)
  3097. } else if type == .background {
  3098. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  3099. self.currentWindowController = controller
  3100. controller.pdfDocument = self.document
  3101. controller.cancelAction = { [unowned self] controller in
  3102. self.view.window?.endSheet((self.currentWindowController.window)!)
  3103. self.currentWindowController = nil
  3104. }
  3105. if index == 1 {
  3106. } else if index == 3 {
  3107. self.showBatchWindow(type: .AddBackground, files: [])
  3108. } else if index == 4 {
  3109. self.showBatchWindow(type: .RemoveBackground, files: [])
  3110. } else if index == 5 {
  3111. self.rightSideViewController.isHidden = false
  3112. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3113. self.openRightPane()
  3114. return
  3115. }
  3116. await NSWindow.currentWindow().beginSheet(controller.window!)
  3117. }
  3118. }
  3119. }
  3120. func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  3121. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3122. batchWindowController.window?.makeKeyAndOrderFront("")
  3123. let batchOperateFile = KMBatchOperateFile(filePath: "")
  3124. batchWindowController.switchToOperateType(type, files: [batchOperateFile])
  3125. batchWindowController.window?.makeKeyAndOrderFront("")
  3126. }
  3127. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3128. if let itemID = toolbarItem.itemIdentifier {
  3129. if isMainToolItem(itemID) {
  3130. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3131. Swift.debugPrint("KMDocumentHomeToolbarItemIdentifier ...")
  3132. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3133. self.changePDFViewGoToPreviousPageAction()
  3134. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  3135. self.changePDFViewGotoNextPageAction()
  3136. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3137. Swift.debugPrint("KMDocumentViewDisplayToolbarItemIdentifier ...")
  3138. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  3139. toolbarItem.isSelected = !toolbarItem.isSelected
  3140. self.toggleLeftPane()
  3141. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  3142. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3143. toolbarItem.isSelected = !toolbarItem.isSelected
  3144. self.toggleRightPane()
  3145. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  3146. Swift.debugPrint("KMDocumentRedactToolbarItemIdentifier ...")
  3147. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  3148. Swift.debugPrint("KMDocumentScanOCRToolbarItemIdentifier ...")
  3149. showOCRWindow()
  3150. }
  3151. } else {
  3152. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  3153. let windowC = KMToolbarCustomWindowController()
  3154. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  3155. self.km_beginSheet(windowC: windowC)
  3156. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  3157. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  3158. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  3159. self.trackEvent_print()
  3160. self.showPrintWindow()
  3161. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  3162. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  3163. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  3164. windowC.callBack = { [weak self] string in
  3165. // if (string.length > 0) {
  3166. // [blockSelf.pdfView addTextFieldWithSubType:KMSelfSignAnnotationFreeTextSubType_Profile string:string];
  3167. // }
  3168. self?.km_endSheet()
  3169. }
  3170. self.km_beginSheet(windowC: windowC)
  3171. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  3172. Swift.debugPrint("KMToolbarViewSettingIdentifier ...")
  3173. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  3174. Swift.debugPrint("KMToolbarSnapshotIdentifier ...")
  3175. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  3176. Swift.debugPrint("KMToolbarTTSIdentifier ...")
  3177. }
  3178. }
  3179. }
  3180. }
  3181. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3182. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3183. KMPrint("KMToolbarToolWatermarkItemIdentifier \(index)")
  3184. self.clickChildTool(type: .watermark, index: index)
  3185. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3186. KMPrint("KMToolbarToolBackgroundItemIdentifier \(index)")
  3187. self.clickChildTool(type: .background, index: index)
  3188. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3189. KMPrint("KMToolbarToolHeaderFooterItemIdentifier \(index)")
  3190. self.clickChildTool(type: .headerAndFooter, index: index)
  3191. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3192. KMPrint("KMToolbarToolBatesItemIdentifier \(index)")
  3193. self.clickChildTool(type: .bates, index: index)
  3194. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3195. KMPrint("KMToolbarComparisonItemIdentifier \(index)")
  3196. self.clickChildTool(type: .comparison, index: index)
  3197. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3198. KMPrint("KMToolbarToolFormAlignIdentifier \(index)")
  3199. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3200. KMPrint("KMToolbarConversionImageItemIdentifier \(index)")
  3201. convertToImg(index: index)
  3202. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3203. KMPrint("KMToolbarConversionExportImageItemIdentifier \(index)")
  3204. extractImageAction(num: index)
  3205. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3206. KMPrint("KMToolbarConversionCreatePDFItemIdentifier \(index)")
  3207. self.createPdf(index: index)
  3208. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3209. KMPrint("KMToolbarCropIdentifier \(index)")
  3210. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3211. KMPrint("KMToolbarToolSecureItemIdentifier \(index)")
  3212. self.clickChildTool(type: .secure, index: index)
  3213. }
  3214. }
  3215. func convertToImg(index: Int) {
  3216. var convertT: KMConvertType = .JPEG
  3217. switch index {
  3218. case 7:
  3219. convertT = .JPEG
  3220. case 8:
  3221. convertT = .JPG
  3222. case 9:
  3223. convertT = .PNG
  3224. case 10:
  3225. convertT = .GIF
  3226. case 11:
  3227. convertT = .TIFF
  3228. case 12:
  3229. convertT = .TGA
  3230. case 13:
  3231. convertT = .BMP
  3232. default:
  3233. convertT = .JPEG
  3234. }
  3235. showAllConvertWindow(convertT: convertT)
  3236. }
  3237. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String) {
  3238. Swift.debugPrint("Search Result " + searchString)
  3239. }
  3240. }
  3241. // MARK: -
  3242. // MARK: - Mouse
  3243. extension KMMainViewController {
  3244. override func mouseDown(with event: NSEvent) {
  3245. super.mouseDown(with: event)
  3246. KMPrint("KMMainViewController mouseDown")
  3247. self.leftSideViewCancelSelect()
  3248. self.pageNumberDisplayView.isEdit = false
  3249. }
  3250. }
  3251. //MARK: LeftSideViewController
  3252. extension KMMainViewController {
  3253. func leftSideViewCancelSelect() {
  3254. // switch self.leftSideViewController.type.methodType {
  3255. // case .Thumbnail:
  3256. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  3257. // break
  3258. // case .Outline:
  3259. //// self.leftSideViewController.outlineViewController.cancelSelect()
  3260. // break
  3261. // case .BookMark:
  3262. //// self.leftSideViewController.bookViewController.cancelSelect()
  3263. // break
  3264. // case .Search:
  3265. //// self.leftSideViewController.searchViewController.cancelSelect()
  3266. // break
  3267. // case .Annotation:
  3268. //// self.leftSideViewController.annotationViewController.cancelSelect()
  3269. // break
  3270. // default:
  3271. if self.listView.isEditing() {
  3272. if self.listView.editingAreas() != nil &&
  3273. self.listView.editingAreas().count != 0 {
  3274. let areas = self.listView.editingAreas().first
  3275. if areas is CPDFEditTextArea {
  3276. self.listView.clearEditingSelectCharItem()
  3277. self.listView.updateEditing([])
  3278. KMPrint("取消选中")
  3279. }
  3280. }
  3281. }
  3282. KMPrint("其他")
  3283. // }
  3284. }
  3285. }
  3286. extension KMMainViewController: KMReadModelViewDelegate {
  3287. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3288. self.listView.goToFirstPage(nil)
  3289. }
  3290. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  3291. self.listView.goToPreviousPage(nil)
  3292. }
  3293. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3294. self.listView.goToNextPage(nil)
  3295. }
  3296. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3297. self.listView.goToLastPage(nil)
  3298. }
  3299. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  3300. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  3301. }
  3302. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  3303. var scale: Double = 1.0
  3304. switch type {
  3305. case .fitWidth:
  3306. self.listView.autoScales = !self.listView.autoScales
  3307. scale = self.listView.scaleFactor
  3308. break
  3309. case .actualSize:
  3310. if self.listView.scaleFactor != 1.0 {
  3311. self.listView.scaleFactor = 1.0
  3312. self.listView.autoScales = false
  3313. }
  3314. scale = self.listView.scaleFactor
  3315. break
  3316. case .autoSize:
  3317. self.listView.autoScales = true
  3318. self.listView.autoScales = false
  3319. scale = self.listView.scaleFactor
  3320. break
  3321. case ._10:
  3322. scale = 0.1
  3323. break
  3324. case ._25:
  3325. scale = 0.25
  3326. break
  3327. case ._50:
  3328. scale = 0.5
  3329. break
  3330. case ._100:
  3331. scale = 1.0
  3332. break
  3333. case ._150:
  3334. scale = 1.5
  3335. break
  3336. case ._200:
  3337. scale = 2.0
  3338. break
  3339. case ._400:
  3340. scale = 4.0
  3341. break
  3342. case ._800:
  3343. scale = 8.0
  3344. break
  3345. default:
  3346. break
  3347. }
  3348. self.listView.scaleFactor = scale
  3349. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3350. }
  3351. func cancelReadModel(view: KMReadModelView, sender: Any) {
  3352. if self.isReadMode {
  3353. self.closeReadModel()
  3354. }
  3355. }
  3356. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  3357. // if self.readModelViewWidthConstraint.constant != width {
  3358. self.readModelViewWidthConstraint.constant = width
  3359. // }
  3360. }
  3361. }
  3362. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  3363. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  3364. self.listView.go(toPageIndex: pageIndex, animated: true)
  3365. }
  3366. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  3367. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  3368. self.tipCurrentPageBoxWidthConstraint.constant = width
  3369. }
  3370. }
  3371. func commitEditingIfNeed() {
  3372. let isEdited = self.listView?.isEdited() ?? false
  3373. if isEdited || self.isPDFTextImageEdited {
  3374. self.listView.commitEditing()
  3375. }
  3376. }
  3377. }
  3378. // MARK: - Analytics (埋点)
  3379. extension KMMainViewController {
  3380. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  3381. if (type == .Annatiton) {
  3382. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Annotation", parameters: [
  3383. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3384. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3385. } else if (type == .editPDF) {
  3386. KMAnalytics.trackEvent(eventName: "Btn_Tbr_EditPDF", parameters: [
  3387. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3388. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3389. } else if (type == .Page) {
  3390. KMAnalytics.trackEvent(eventName: "Btn_Tbr_PageEdit", parameters: [
  3391. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3392. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3393. } else if (type == .Conversion) {
  3394. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Converter", parameters: [
  3395. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3396. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3397. } else if (type == .Tool) {
  3398. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Tools", parameters: [
  3399. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3400. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3401. }
  3402. }
  3403. func trackEvent_aiTranslate() -> Void {
  3404. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  3405. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3406. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3407. }
  3408. func trackEvent_print() -> Void {
  3409. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  3410. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3411. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3412. }
  3413. func trackEvent_share() -> Void {
  3414. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  3415. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3416. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3417. }
  3418. func trackEvent_upgrade() -> Void {
  3419. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  3420. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3421. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3422. }
  3423. func trackEvent(annotationType type: CAnnotationType) -> Void {
  3424. if (type == .highlight) {
  3425. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  3426. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3427. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3428. } else if (type == .underline) {
  3429. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  3430. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3431. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3432. } else if (type == .strikeOut) {
  3433. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  3434. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3435. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3436. } else if (type == .ink) {
  3437. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  3438. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3439. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3440. } else if (type == .freeText) {
  3441. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  3442. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3443. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3444. } else if (type == .anchored) {
  3445. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  3446. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3447. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3448. } else if (type == .square) {
  3449. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  3450. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3451. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3452. } else if (type == .link) {
  3453. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  3454. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3455. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3456. } else if (type == .stamp) {
  3457. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  3458. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3459. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3460. } else if (type == .signSignature) {
  3461. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  3462. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3463. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3464. } else if (type == .addText) {
  3465. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  3466. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3467. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3468. } else if (type == .addImage) {
  3469. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  3470. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3471. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3472. } else {
  3473. }
  3474. }
  3475. func trackEvent(toolMode mode: CToolMode) -> Void {
  3476. if (mode == .selectToolMode) {
  3477. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3478. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3479. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3480. } else if (mode == .moveToolMode) {
  3481. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3482. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3483. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3484. }
  3485. }
  3486. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3487. if (type == .word) {
  3488. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toWord", parameters: [
  3489. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3490. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3491. } else if (type == .excel) {
  3492. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toExcel", parameters: [
  3493. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3494. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3495. } else if (type == .ppt) {
  3496. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toPPT", parameters: [
  3497. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3498. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3499. } else if (type == .rtf) {
  3500. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toRTF", parameters: [
  3501. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3502. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3503. } else if (type == .csv) {
  3504. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toCSV", parameters: [
  3505. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3506. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3507. } else if (type == .html) {
  3508. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toHTML", parameters: [
  3509. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3510. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3511. } else if (type == .conversion_text) {
  3512. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toText", parameters: [
  3513. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3514. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3515. } else if (type == .conversion_image) {
  3516. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toImage", parameters: [
  3517. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3518. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3519. } else if (type == .compress) {
  3520. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Compress", parameters: [
  3521. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3522. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3523. } else if (type == .merge) {
  3524. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Merge", parameters: [
  3525. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3526. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3527. } else if (type == .secure) {
  3528. } else if (type == .crop) {
  3529. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Crop", parameters: [
  3530. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3531. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3532. }
  3533. }
  3534. func trackEvent_setPassword() -> Void {
  3535. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3536. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3537. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3538. }
  3539. func trackEvent_removePassword() -> Void {
  3540. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3541. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3542. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3543. }
  3544. }
  3545. extension KMMainViewController {
  3546. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3547. let contentController: KMCompareContentWindowController = KMCompareContentWindowController.init(document: document, oldDocument: oldDocument, results: results)
  3548. contentController.hideCloseInfo = true
  3549. contentController.saveHandle = { [unowned self] controller in
  3550. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3551. saveController.cancelHandle = { [unowned self] controller in
  3552. NSWindow.currentWindow().endSheet(controller.window!)
  3553. }
  3554. saveController.saveHandle = { [unowned self] controller, saveType in
  3555. let folderPath = controller.fileSaveFolderPath
  3556. //#if VERSION_DMG
  3557. //
  3558. //#else
  3559. // if let url = URL(string: folderPath) {
  3560. // AppSandboxFileAccess.fileAccess().persistPermissionURL(url)
  3561. // if let bookmarkData = try? url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) {
  3562. // AppSandboxFileAccess.fileAccess().bookmarkPersistanceDelegate?.setBookmarkData(bookmarkData, forURL: url)
  3563. // AppSandboxFileAccess.fileAccess().bookmarkPersistanceDelegate?.setBookmarkData(bookmarkData, forURL: URL(fileURLWithPath: url.path))
  3564. // }
  3565. // }
  3566. //#endif
  3567. if folderPath != nil {
  3568. if !FileManager.default.fileExists(atPath: folderPath) {
  3569. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3570. }
  3571. var savePath: String
  3572. switch saveType {
  3573. case 0:
  3574. savePath = "\(folderPath)/\(oldDocument.documentURL.path.lastPathComponent.deletingPathExtension)_compare.\(oldDocument.documentURL.path.extension)"
  3575. savePath = self.getValidFilePath(savePath)
  3576. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3577. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3578. case 1:
  3579. savePath = "\(folderPath)/\(document.documentURL.path.lastPathComponent.deletingPathExtension)_compare.\(document.documentURL.path.extension)"
  3580. savePath = self.getValidFilePath(savePath)
  3581. document.write(to: URL(fileURLWithPath: savePath))
  3582. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3583. case 2:
  3584. savePath = "\(folderPath)/MergedCompareFile.\(oldDocument.documentURL.path.extension)"
  3585. savePath = self.getValidFilePath(savePath)
  3586. pdfCompareContent.saveAsComparisonDocument(withFilePath: savePath)
  3587. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3588. default:
  3589. break
  3590. }
  3591. }
  3592. NSWindow.currentWindow().endSheet(controller.window!)
  3593. }
  3594. }
  3595. contentController.closeHandle = { [unowned self] controller in
  3596. contentController.close()
  3597. }
  3598. NSWindow.currentWindow().km_beginSheet(windowC: contentController)
  3599. }
  3600. func getValidFilePath(_ oldPath: String) -> String {
  3601. let fileManager = FileManager.default
  3602. do {
  3603. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3604. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3605. return oldPath
  3606. }
  3607. var i = 1
  3608. var newPath = oldPath
  3609. while fileManager.fileExists(atPath: newPath) {
  3610. if fileType == FileAttributeType.typeDirectory.rawValue {
  3611. newPath = oldPath + "(\(i))"
  3612. } else {
  3613. let fileExtension = (oldPath as NSString).pathExtension
  3614. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3615. }
  3616. i += 1
  3617. }
  3618. return newPath
  3619. } catch {
  3620. print("Error getting file attributes: \(error)")
  3621. return oldPath
  3622. }
  3623. }
  3624. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3625. var coveringController: KMCompareCoveringWindowController = KMCompareCoveringWindowController.init(document: pdfDocument)
  3626. coveringController.hideCloseInfo = true
  3627. coveringController.saveHandle = { [unowned self] controller in
  3628. let savePanel = NSSavePanel()
  3629. savePanel.nameFieldStringValue = "untitled"
  3630. savePanel.allowedFileTypes = ["pdf"]
  3631. savePanel.beginSheetModal(for: controller.window!) { result in
  3632. if result == .OK {
  3633. pdfDocument.write(to: savePanel.url!)
  3634. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3635. }
  3636. }
  3637. }
  3638. coveringController.closeHandle = { [unowned self] controller in
  3639. NSWindow.currentWindow().endSheet(controller.window!)
  3640. }
  3641. NSWindow.currentWindow().km_beginSheet(windowC: coveringController)
  3642. }
  3643. }