KMMainViewController+Action.swift 210 KB

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