KMMainViewController+Action.swift 205 KB

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