KMMainViewController+Action.swift 239 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let isEditing = self.listView.isEditing() ?? false
  11. if isEditing {
  12. if searchString.isEmpty {
  13. self.listView.setHighlightedSelection(nil, animated: false)
  14. self.leftSideViewController.searchResults = []
  15. if display {
  16. if self.leftSideViewController.findPaneState == .singular {
  17. self.leftSideViewController.displayFindViewAnimating(true)
  18. } else {
  19. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  20. }
  21. }
  22. return
  23. }
  24. let isWholeWord = self.leftSideViewController.mwcFlags.wholeWordSearch == 1
  25. var opt = CPDFSearchOptions()
  26. if isCase == false {
  27. opt.insert(.caseSensitive)
  28. }
  29. if isWholeWord {
  30. opt.insert(.matchWholeWord)
  31. }
  32. let datas = self.srHanddler.pdfView?.document.findEditAllPageString(searchString, with: opt) ?? []
  33. if let sel = datas.first?.first {
  34. self.srHanddler.showSelection(sel)
  35. }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in datas {
  39. for selection in selections {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = selection
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  43. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  44. self.searchResults.insert(mode, at: self.searchResults.count)
  45. _selections.append(selection)
  46. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  47. }
  48. }
  49. if needShowAll {
  50. self.listView.setHighlightedSelections(_selections)
  51. }
  52. if _selections.isEmpty {
  53. self.listView.setHighlightedSelection(nil, animated: false)
  54. }
  55. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  56. self.leftSideViewController.searchResults = self.searchResults
  57. if display {
  58. if self.leftSideViewController.findPaneState == .singular {
  59. self.leftSideViewController.displayFindViewAnimating(true)
  60. } else {
  61. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  62. }
  63. }
  64. return
  65. }
  66. let document = self.listView.document
  67. if let data = document?.isFinding, data {
  68. document?.cancelFindString()
  69. }
  70. if searchString == "" {
  71. self.searchResults = []
  72. self.leftSideViewController.searchResults = self.searchResults
  73. self.listView.setHighlightedSelections([])
  74. self.listView.setHighlightedSelection(nil, animated: false)
  75. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  76. } else {
  77. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  78. var findArray : [[CPDFSelection]]
  79. if isCase {
  80. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  81. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  82. } else {
  83. findArray = self.listView.document.findString(searchString) ?? []
  84. }
  85. } else {
  86. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  87. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  88. } else {
  89. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  90. }
  91. }
  92. self.searchResults.removeAll()
  93. var _selections: [CPDFSelection] = []
  94. for selections in findArray {
  95. for selection in selections {
  96. let mode : KMSearchMode = KMSearchMode()
  97. mode.selection = selection
  98. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  99. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  100. self.searchResults.insert(mode, at: self.searchResults.count)
  101. _selections.append(selection)
  102. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  103. }
  104. }
  105. if needShowAll {
  106. self.listView.setHighlightedSelections(_selections)
  107. }
  108. if _selections.isEmpty {
  109. self.listView.setHighlightedSelection(nil, animated: false)
  110. }
  111. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  112. self.leftSideViewController.searchResults = self.searchResults
  113. }
  114. if display {
  115. if self.leftSideViewController.findPaneState == .singular {
  116. self.leftSideViewController.displayFindViewAnimating(true)
  117. } else {
  118. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  119. }
  120. }
  121. }
  122. func removeSignatures(signatures:[CPDFSignature]) {
  123. for signature in signatures {
  124. self.listView.document.removeSignature(signature)
  125. }
  126. for i in 0..<self.listView.document.pageCount {
  127. let page : CPDFPage = self.listView.document.page(at: i)
  128. let annotations : [CPDFAnnotation] = page.annotations
  129. for j in 0..<annotations.count {
  130. let annotation = annotations[j]
  131. if annotation is CPDFSignatureWidgetAnnotation {
  132. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  133. }
  134. }
  135. }
  136. self.listView.setNeedsDisplayForVisiblePages()
  137. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  138. var mSignatures : [CPDFSignature] = []
  139. for sign in tSignatures {
  140. if sign.signers.count > 0 {
  141. mSignatures.append(sign)
  142. }
  143. }
  144. }
  145. //MARK: menu菜单
  146. func fontColorMenuItem()->NSMenuItem {
  147. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  148. return fontColorItem;
  149. }
  150. func fontSizeMenuItem()->NSMenuItem {
  151. let currentFontSize = self.listView.editingTextFontSize()
  152. let fontSizes = self.fontSizes()
  153. let submenu = NSMenu(title: "")
  154. for i in 0 ... fontSizes.count - 1 {
  155. let fontSize : String = fontSizes.object(at: i) as! String
  156. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  157. item.target = self
  158. item.tag = i
  159. submenu.addItem(item)
  160. if (Int(currentFontSize) == Int(fontSize)) {
  161. item.state = .on
  162. }
  163. }
  164. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  165. fontSizeItem.submenu = submenu
  166. return fontSizeItem;
  167. }
  168. func corpImageMenuItem()->NSMenuItem {
  169. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  170. return corpImageItem
  171. }
  172. func cancelCorpImageMenuItem()->NSMenuItem {
  173. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  174. return cancelCorpImageItem
  175. }
  176. func restoreCorpImageMenuItem()->NSMenuItem {
  177. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  178. return cancelCorpImageItem
  179. }
  180. func cutImageArea()->NSMenuItem {
  181. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  182. return deleteItem
  183. }
  184. func editAddBlanMenu(menu:NSMenu){
  185. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  186. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  187. }
  188. func addText() -> NSMenuItem {
  189. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  190. return addTextItem
  191. }
  192. func addImage() -> NSMenuItem {
  193. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  194. return addImageItem
  195. }
  196. func replaceImageArea()->NSMenuItem {
  197. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  198. return replaceItem
  199. }
  200. func exportImageArea()->NSMenuItem {
  201. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  202. let menu = NSMenu()
  203. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  204. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(menuItemEditingClick_ExportImage), target: self, tag:1, at: 1)
  205. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 2)
  206. exportItem.submenu = menu
  207. return exportItem
  208. }
  209. func exportImageStampItem()->NSMenuItem {
  210. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  211. let menu = NSMenu()
  212. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  213. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  214. exportItem.submenu = menu
  215. return exportItem
  216. }
  217. func exportMenu() -> NSMenu {
  218. let menu = NSMenu()
  219. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  220. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  221. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  222. return menu
  223. }
  224. func cropMenu() -> NSMenu {
  225. let menu = NSMenu()
  226. _ = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  227. _ = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  228. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  229. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(smartAutoCropAll), target: self, at: 2)
  230. return menu
  231. }
  232. func zoomSelectionMenuItem() -> NSMenuItem {
  233. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  234. return item
  235. }
  236. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  237. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  238. return item
  239. }
  240. func enterAnnotationStype() -> NSMenuItem {
  241. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  242. let stypeMenu = NSMenu()
  243. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  244. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  245. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  246. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  247. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  248. stypeMenu.addItem(NSMenuItem.separator())
  249. }
  250. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  251. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  252. stypeMenu.addItem(NSMenuItem.separator())
  253. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  254. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  255. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  256. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  257. if viewManager.isPDFReadMode {
  258. } else {
  259. stypeMenu.addItem(NSMenuItem.separator())
  260. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  261. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  262. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  263. }
  264. stypItem.submenu = stypeMenu
  265. if self.listView.annotationType == .ink {
  266. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  267. } else if self.listView.annotationType == .freeText {
  268. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  269. } else if self.listView.annotationType == .anchored {
  270. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  271. } else if self.listView.annotationType == .square {
  272. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  273. } else if self.listView.annotationType == .circle {
  274. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  275. } else if self.listView.annotationType == .arrow {
  276. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  277. } else if self.listView.annotationType == .line {
  278. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  279. } else if self.listView.annotationType == .link {
  280. stypeMenu.item(at: 7)?.state = .on
  281. } else if self.listView.annotationType == .stamp {
  282. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  283. } else if self.listView.annotationType == .signSignature {
  284. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  285. }
  286. return stypItem
  287. }
  288. func setAnnotationToolStype() -> NSMenuItem {
  289. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  290. let stypeMenu = NSMenu()
  291. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.textToolMode.rawValue)
  292. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  293. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  294. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  295. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  296. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  297. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  298. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  299. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.squiggly.rawValue)
  300. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  301. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  302. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  303. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  304. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  305. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  306. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  307. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  308. stypItem.submenu = stypeMenu
  309. return stypItem
  310. }
  311. func addReadModelStype() -> NSMenuItem {
  312. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openPDFReadMode), target: self)
  313. if viewManager.isPDFReadMode {
  314. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(exitPDFReadMode), target: self)
  315. }
  316. return stypItem
  317. }
  318. func addOutlineStype() -> NSMenuItem {
  319. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  320. return stypItem
  321. }
  322. func setTTSStype() -> NSMenuItem {
  323. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  324. return stypItem
  325. }
  326. func setShareStype() -> NSMenuItem {
  327. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  328. var string = ""
  329. if listView.activeAnnotation != nil {
  330. string = self.listView.activeAnnotation?.contents ?? ""
  331. }
  332. if string.count < 1{
  333. string = self.listView.currentSelection?.string() ?? ""
  334. }
  335. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  336. return stypItem
  337. }
  338. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  339. var number = 0
  340. var indexN = 0
  341. guard str.count > 0 else {return (0, 0)}
  342. for i in 0...str.count - 1 {
  343. let c: unichar = (str as NSString).character(at: i)
  344. if (c >= 0x4E00) {
  345. number += 2
  346. }else {
  347. number += 1
  348. }
  349. if number > 56{
  350. indexN = i
  351. number = 100
  352. break
  353. }
  354. }
  355. return (number, indexN)
  356. }
  357. func setLookUpStype() -> NSMenuItem {
  358. guard let str = listView.currentSelection?.string() else {
  359. return NSMenuItem.separator()
  360. }//String(format: "Look Up %@", listView.currentSelection?.string() ?? "")
  361. let dic = numberOfChars(str)
  362. var newStr = str
  363. if dic.num == 100{
  364. newStr = str.prefix(dic.indexN) + "..."
  365. }
  366. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  367. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  368. return stypItem
  369. }
  370. func setSearchBaiduStype() -> NSMenuItem {
  371. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  372. return stypItem
  373. }
  374. func setCutStype() -> NSMenuItem {
  375. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  376. return stypItem
  377. }
  378. func setDeleteStype() -> NSMenuItem {
  379. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  380. return stypItem
  381. }
  382. func setColorsStype() -> NSMenuItem {
  383. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  384. return stypItem
  385. }
  386. func setLinesStype() -> NSMenuItem {
  387. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  388. return stypItem
  389. }
  390. func setEditNoteStype() -> NSMenuItem {
  391. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  392. return stypItem
  393. }
  394. func setRotateStype() -> NSMenuItem {
  395. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  396. let stypeMenu = NSMenu()
  397. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  398. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  399. stypItem.submenu = stypeMenu
  400. return stypItem
  401. }
  402. func setNextPageStype() -> NSMenuItem {
  403. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  404. stypItem.isEnabled = false
  405. if listView.canGoToNextPage() {
  406. stypItem.isEnabled = true
  407. }
  408. return stypItem
  409. }
  410. func setPreviousPageStype() -> NSMenuItem {
  411. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  412. stypItem.isEnabled = false
  413. if listView.canGoToPreviousPage() {
  414. stypItem.isEnabled = true
  415. }
  416. return stypItem
  417. }
  418. func setTranslateStype() -> NSMenuItem {
  419. let str = listView.currentSelection?.string() ?? ""//String(format: "Translate %@", listView.currentSelection?.string() ?? "")
  420. let dic = numberOfChars(str)
  421. var newStr = str
  422. if dic.num == 100{
  423. newStr = str.prefix(dic.indexN) + "..."
  424. }
  425. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  426. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  427. return stypItem
  428. }
  429. func setAutoScrollStype() -> NSMenuItem {
  430. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  431. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  432. return stypItem
  433. }
  434. func setSnapshotStype() -> NSMenuItem {
  435. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  436. let stypeMenu = NSMenu()
  437. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  438. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  439. stypItem.submenu = stypeMenu
  440. return stypItem
  441. }
  442. func setServicesStype() -> NSMenuItem {
  443. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  444. let stypeMenu = NSMenu()
  445. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  446. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  447. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  448. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  449. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  450. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  451. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  452. stypItem.submenu = stypeMenu
  453. return stypItem
  454. }
  455. func setCropStype() -> NSMenuItem {
  456. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  457. let stypeMenu = NSMenu()
  458. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  459. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  460. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  461. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  462. if NSIsEmptyRect(listView.selectionRect){
  463. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  464. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  465. }
  466. stypItem.submenu = stypeMenu
  467. return stypItem
  468. }
  469. func setAITranslateStype() -> NSMenuItem {
  470. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  471. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  472. return stypItem
  473. }
  474. func setAIProofreadStype() -> NSMenuItem {
  475. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  476. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  477. return stypItem
  478. }
  479. func setAIRewriteStype() -> NSMenuItem {
  480. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  481. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  482. return stypItem
  483. }
  484. func addHighlightLinksStype() -> NSMenuItem {
  485. let highlightLink = KMPreferenceManager.shared.highlightLinks
  486. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  487. if highlightLink {
  488. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  489. }
  490. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  491. return highlightLinksItem
  492. }
  493. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  494. if item == nil {
  495. return
  496. }
  497. let menu = NSMenu()
  498. item?.submenu = menu
  499. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  500. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  501. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  502. let wavyLine = NSMenuItem(title: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  503. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  504. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  505. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  506. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  507. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  508. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  509. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  510. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  511. if listView.currentSelection.selectionType() != .image {
  512. menu.insertItem(height, at: menu.items.count)
  513. menu.insertItem(underline, at: menu.items.count)
  514. menu.insertItem(strickout, at: menu.items.count)
  515. menu.insertItem(wavyLine, at: menu.items.count)
  516. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  517. }
  518. if viewManager.isPDFReadMode {
  519. } else {
  520. if listView.currentSelection.selectionType() != .image &&
  521. listView.currentSelection.selectionType() != .text {
  522. menu.insertItem(text, at: menu.items.count)
  523. menu.insertItem(note, at: menu.items.count)
  524. }
  525. }
  526. if viewManager.isPDFReadMode {
  527. } else {
  528. if listView.currentSelection.selectionType() != .image {
  529. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  530. menu.insertItem(rectangle, at: menu.items.count)
  531. menu.insertItem(oval, at: menu.items.count)
  532. }
  533. }
  534. if viewManager.isPDFReadMode {
  535. } else {
  536. if listView.currentSelection.selectionType() != .image &&
  537. listView.currentSelection.selectionType() != .text {
  538. menu.insertItem(line, at: menu.items.count)
  539. }
  540. }
  541. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  542. if viewManager.isPDFReadMode {
  543. } else {
  544. menu.insertItem(link, at: menu.items.count)
  545. }
  546. if viewManager.isPDFReadMode {
  547. } else {
  548. if listView.currentSelection.selectionType() != .image {
  549. menu.insertItem(outline, at: menu.items.count)
  550. }
  551. }
  552. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  553. if viewManager.isPDFReadMode {
  554. } else {
  555. if (listView.currentSelection.selectionType() != .image) {
  556. }
  557. }
  558. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  559. }
  560. func addBookmarkMenu() -> NSMenuItem {
  561. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  562. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  563. return bookMarkItem
  564. } else {
  565. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  566. return bookMarkItem
  567. }
  568. }
  569. func findStringMenu() -> NSMenuItem {
  570. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  571. menuItem.keyEquivalent = "f"
  572. return menuItem
  573. }
  574. func printingMenu() -> NSMenuItem {
  575. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  576. return menuItem
  577. }
  578. func fontSizes()->NSArray {
  579. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  580. }
  581. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  582. if interactionMode == .presentation {
  583. listView.goToPreviousPage(nil)
  584. return true
  585. }
  586. return false
  587. }
  588. func useNativeFullScreen() -> Bool {
  589. var isFull = false
  590. let sel = NSSelectorFromString("toggleFullscreen:")
  591. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  592. isFull = true
  593. }
  594. return isFull
  595. }
  596. func forceSubwindowsOnTop(_ flag: Bool) {
  597. }
  598. //MARK: menuItem Action
  599. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  600. let color = listView.editingSelectionFontColor()
  601. let panel = NSColorPanel.shared
  602. panel.setTarget(self)
  603. panel.setAction(#selector(fontColorChangeAction))
  604. panel.orderFront(nil)
  605. panel.showsAlpha = false
  606. panel.color = color ?? NSColor.black
  607. }
  608. @objc func fontColorChangeAction(sender: NSColorPanel) {
  609. self.listView.setEditingSelectionFontColor(sender.color)
  610. }
  611. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  612. let fontSize = self.fontSizes().object(at: sender.tag)
  613. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  614. }
  615. @objc func addImageText(sender: NSMenuItem) {
  616. let event = NSApp.currentEvent
  617. let clickLocation = event?.locationInWindow
  618. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  619. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  620. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  621. point = point2
  622. if sender.tag == 0 {
  623. KMPrint("添加文字")
  624. } else if sender.tag == 1 {
  625. } else if sender.tag == 2 {
  626. KMPrint("粘贴")
  627. }
  628. }
  629. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  630. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  631. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  632. }
  633. }
  634. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  635. self.listView.exitCrop(with: self.listView.selectImageAreas)
  636. self.listView.cropAreas = nil
  637. self.listView.isEditImage = false
  638. }
  639. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  640. self.listView.resetCrop(with: self.listView.selectImageAreas)
  641. }
  642. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  643. self.editPDFHanddler?.cropAction()
  644. }
  645. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  646. if self.listView.selectImageAreas == nil {
  647. return
  648. }
  649. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  650. let panel = NSOpenPanel()
  651. panel.allowsMultipleSelection = false
  652. panel.allowedFileTypes = ["png","jpg"]
  653. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  654. if response == .OK {
  655. let openPath = panel.url?.path
  656. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  657. if s {
  658. }
  659. }
  660. }
  661. }
  662. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  663. if self.listView.selectImageAreas == nil {
  664. return
  665. }
  666. let panel = NSSavePanel()
  667. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  668. panel.isExtensionHidden = true
  669. let response = panel.runModal()
  670. if response == .OK {
  671. let url = panel.url
  672. if FileManager.default.fileExists(atPath: url!.path) {
  673. try?FileManager.default.removeItem(atPath: url!.path)
  674. }
  675. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  676. if result {
  677. NSWorkspace.shared.activateFileViewerSelecting([url!])
  678. }
  679. }
  680. }
  681. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  682. }
  683. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  684. }
  685. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  686. }
  687. @objc func OpenItemAction(sender: NSMenuItem) {
  688. }
  689. @objc func cropAllPageItem(sender: NSMenuItem) {
  690. self.cropAll(nil)
  691. }
  692. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  693. self.crop(nil)
  694. }
  695. @objc func autoCropAllItem(sender: NSMenuItem) {
  696. self.autoCropAll(nil)
  697. }
  698. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  699. self.smartAutoCropAll(nil)
  700. }
  701. @objc func customCropModel(sender: NSMenuItem) {
  702. let pdfDoc: CPDFDocument = self.listView.document
  703. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  704. let alert = NSAlert()
  705. alert.alertStyle = .critical
  706. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  707. alert.runModal()
  708. return
  709. }
  710. let window = NSWindow.currentWindow()
  711. let currentPage = pdfDoc.index(for: self.listView.currentPage())
  712. let cropVC = KMPDFCropWindowController(document: pdfDoc, pwd: "", currentPage: Int(currentPage), cropSize: NSMakeRect(100, 100, 50, 80), selectPageString: "\(currentPage)")
  713. window.km_beginSheet(windowC: cropVC)
  714. cropVC.cropWindowCloseBlock = { [weak self] doc in
  715. window.km_quick_endSheet()
  716. let isSuccessful = doc.write(to: self?.listView.document?.documentURL)
  717. if isSuccessful {
  718. if let documen = CPDFDocument(url: self?.document?.documentURL) {
  719. if documen.isLocked {
  720. documen.unlock(withPassword: pdfDoc.password)
  721. }
  722. self?.setDocument = documen
  723. }
  724. }
  725. }
  726. }
  727. @objc func rotateRightAction(sender: NSMenuItem) {
  728. }
  729. @objc func rotateLeftAction(sender: NSMenuItem) {
  730. }
  731. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  732. self.listView.toolMode = .noteToolMode
  733. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  734. var model : KMToolbarViewType = .None
  735. switch sender.tag {
  736. case 0:
  737. identifier = KMDocumentAnnotationToolbarItemIdentifier
  738. model = .Annatiton
  739. case 1:
  740. identifier = KMToolbarMoveToolModeItemIdentifier
  741. model = .Move
  742. case 2:
  743. identifier = KMToolbarMagnifyToolModeItemIdentifier
  744. model = .Magnify
  745. case 3:
  746. identifier = KMToolbarSelectToolModeItemIdentifier
  747. model = .Select
  748. case 4:
  749. identifier = KMToolbarZoomToSelectionItemIdentifier
  750. model = .SelectZoom
  751. default:
  752. break
  753. }
  754. }
  755. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  756. var itemId: String?
  757. if sender.tag == CAnnotationType.highlight.rawValue {
  758. itemId = KMToolbarHighlightAnnotationItemIdentifier
  759. } else if sender.tag == CAnnotationType.underline.rawValue {
  760. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  761. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  762. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  763. } else if sender.tag == CAnnotationType.squiggly.rawValue {
  764. itemId = KMToolbarSquigglyAnnotationItemIdentifier
  765. } else if sender.tag == CAnnotationType.ink.rawValue {
  766. itemId = KMToolbarInkAnnotationItemIdentifier
  767. } else if sender.tag == CAnnotationType.freeText.rawValue {
  768. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  769. } else if sender.tag == CAnnotationType.anchored.rawValue {
  770. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  771. } else if sender.tag == CAnnotationType.square.rawValue {
  772. itemId = KMToolbarSquareAnnotationItemIdentifier
  773. } else if sender.tag == CAnnotationType.circle.rawValue {
  774. itemId = KMToolbarCircleAnnotationItemIdentifier
  775. } else if sender.tag == CAnnotationType.arrow.rawValue {
  776. itemId = KMToolbarArrowAnnotationItemIdentifier
  777. } else if sender.tag == CAnnotationType.line.rawValue {
  778. itemId = KMToolbarLineAnnotationItemIdentifier
  779. } else if sender.tag == CAnnotationType.link.rawValue {
  780. itemId = KMToolbarLinkAnnotationItemIdentifier
  781. }
  782. }
  783. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  784. var annotationType : CAnnotationType = .unkown
  785. switch sender.tag {
  786. case 0:
  787. annotationType = .highlight
  788. case 1:
  789. annotationType = .underline
  790. case 2:
  791. if sender.title == NSLocalizedString("Squiggly", comment: "") {
  792. annotationType = .squiggly
  793. } else {
  794. annotationType = .strikeOut
  795. }
  796. case 3:
  797. annotationType = .freeText
  798. case 4:
  799. annotationType = .anchored
  800. case 5:
  801. annotationType = .square
  802. case 6:
  803. annotationType = .circle
  804. case 7:
  805. annotationType = .line
  806. case 8:
  807. annotationType = .link
  808. case 9:
  809. if self.model.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  810. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  811. }
  812. return
  813. case 10:
  814. annotationType = .unkown
  815. default:
  816. break
  817. }
  818. if (annotationType != .link) {
  819. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  820. self.listView.currentSelection = nil;
  821. return
  822. }
  823. // link
  824. let selection = self.listView.currentSelection
  825. DispatchQueue.main.async {
  826. Task { @MainActor in
  827. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  828. self.listView.currentSelection = nil;
  829. if (annotation != nil) {
  830. self.listView.updateActiveAnnotations([annotation!])
  831. }
  832. }
  833. }
  834. }
  835. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  836. Task { @MainActor in
  837. let idx = sender.tag
  838. if idx == 10 {
  839. if IAPProductsManager.default().isAvailableAllFunction() == false {
  840. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  841. return
  842. }
  843. }
  844. var point = mouseRightMenuEvent?.locationInWindow
  845. if (point == nil) {
  846. point = NSZeroPoint
  847. }
  848. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  849. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  850. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  851. var annotation: CPDFAnnotation?
  852. if viewManager.isPDFReadMode {
  853. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  854. self.listView.toolMode = .noteToolMode
  855. }
  856. switch sender.tag {
  857. case 0:
  858. self.listView.annotationType = CAnnotationType.ink
  859. case 1:
  860. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  861. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  862. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  863. if ((annotation) != nil) {
  864. self.listView.updateActiveAnnotations([annotation!])
  865. self.listView.edit(annotation)
  866. }
  867. case 2:
  868. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  869. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  870. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  871. self.listView.edit(annotation)
  872. case 3:
  873. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  874. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  875. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  876. case 4:
  877. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  878. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  879. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  880. case 5:
  881. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  882. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  883. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  884. case 6:
  885. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  886. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  887. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  888. case 7:
  889. self.listView.annotationType = CAnnotationType.link
  890. self.openRightPane()
  891. case 8:
  892. self.listView.annotationType = CAnnotationType.stamp
  893. self.openRightPane()
  894. case 9:
  895. self.listView.annotationType = CAnnotationType.signSignature
  896. self.openRightPane()
  897. default:
  898. break
  899. }
  900. } else {
  901. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  902. self.listView.toolMode = .noteToolMode
  903. }
  904. switch sender.tag {
  905. case 0:
  906. self.listView.toolMode = .noteToolMode
  907. self.listView.annotationType = CAnnotationType.ink
  908. case 1:
  909. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  910. if (pagePoint.x - defaultSize.width > 0){
  911. pagePoint.x -= defaultSize.width;
  912. }else{
  913. pagePoint.x = 0;
  914. }
  915. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  916. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  917. if ((annotation) != nil) {
  918. self.listView.edit(annotation)
  919. }
  920. case 2:
  921. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  922. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  923. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  924. self.listView.edit(annotation)
  925. case 3:
  926. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  927. if (pagePoint.x - defaultSize.width > 0){
  928. pagePoint.x -= defaultSize.width;
  929. }else{
  930. pagePoint.x = 0;
  931. }
  932. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  933. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  934. case 4:
  935. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  936. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  937. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  938. case 5:
  939. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  940. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  941. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  942. case 6:
  943. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  944. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  945. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  946. case 7:
  947. self.listView.annotationType = CAnnotationType.link
  948. self.openRightPane()
  949. case 8:
  950. self.listView.annotationType = CAnnotationType.stamp
  951. self.openRightPane()
  952. case 9:
  953. self.listView.annotationType = CAnnotationType.signSignature
  954. self.openRightPane()
  955. case 10:
  956. self.addImgAnnotationToView(center: pagePoint)
  957. default:
  958. break
  959. }
  960. if annotation != nil{
  961. self.listView.activeAnnotations.removeAllObjects()
  962. var newAnnonations : [CPDFAnnotation] = []
  963. newAnnonations.append(annotation!)
  964. self.listView.updateActiveAnnotations(newAnnonations)
  965. }
  966. }
  967. }
  968. }
  969. func addImgAnnotationToView(center: NSPoint) {
  970. let accessoryCtr = KMImageAccessoryController()
  971. let openPanel = NSOpenPanel()
  972. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  973. openPanel.allowsMultipleSelection = false
  974. openPanel.accessoryView = accessoryCtr.view
  975. openPanel.isAccessoryViewDisclosed = true
  976. openPanel.beginSheetModal(for: self.view.window!) { result in
  977. if result == .OK {
  978. let fileURL = openPanel.urls.first
  979. let filePath = fileURL!.path
  980. if filePath.pathExtension == "pdf" {
  981. let pdf = CPDFDocument(url: fileURL)
  982. if pdf!.isEncrypted {
  983. NSSound.beep()
  984. return
  985. }
  986. }
  987. let img = NSImage(contentsOfFile: filePath)
  988. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  989. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  990. }
  991. }
  992. }
  993. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  994. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  995. let index = self.listView.currentPageIndex
  996. self.listView.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  997. self.listView.setNeedsDisplayForVisiblePages()
  998. } else {
  999. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1000. self.listView.setNeedsDisplayForVisiblePages()
  1001. }
  1002. self.setDocumentEditedState(window: self.view.window)
  1003. if viewManager.isPDFReadMode {
  1004. } else {
  1005. self.leftSideViewController.showBookmarkTab()
  1006. }
  1007. }
  1008. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  1009. self.leftSideViewController.refreshMethodType(methodType: .Search)
  1010. }
  1011. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  1012. let rect = listView.currentSelectionRect()
  1013. let page = listView.currentPage()
  1014. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  1015. copyPage.setBounds(rect, for: .cropBox)
  1016. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  1017. // 执行右键操作后,需要取消框选区域
  1018. if self.listView.toolMode == .selectToolMode {
  1019. objc_sync_enter(self)
  1020. self.listView.selectionRect = NSZeroRect
  1021. self.listView.selectionPageIndex = UInt(NSNotFound)
  1022. objc_sync_exit(self)
  1023. }
  1024. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1025. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1026. if (result == .cancel) {
  1027. return
  1028. }
  1029. // 解除权限
  1030. self?.model.isSaveKeyChain = false
  1031. self?.listView.document.unlock(withPassword: password)
  1032. // 隐藏提示
  1033. self?.hiddenSecureLimitTip()
  1034. // 去打印
  1035. KMPrintWindowController.printImage(image: image)
  1036. }
  1037. return
  1038. }
  1039. KMPrintWindowController.printImage(image: image)
  1040. }
  1041. // MARK: - Measure
  1042. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  1043. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1044. return
  1045. }
  1046. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1047. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1048. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1049. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1050. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1051. areaMeasureInfoWindowController?.hideFloatingWindow()
  1052. }
  1053. self.listView.updateActiveAnnotations([anno])
  1054. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1055. self.listView.setNeedsDisplayForVisiblePages()
  1056. }
  1057. @objc func menuItemActionMeasureEditNote(sender: NSMenuItem) {
  1058. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1059. return
  1060. }
  1061. self.listView.edit(anno)
  1062. }
  1063. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  1064. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1065. return
  1066. }
  1067. self.listView.updateActiveAnnotations([anno])
  1068. self.listView.setNeedsDisplayForVisiblePages()
  1069. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  1070. self.showMeasureDistanceSettingWindow(measureInfo: data.measureInfo)
  1071. } else if let data = anno as? CPDFPolylineAnnotation {
  1072. self.showMeasurePerimeterSettingWindow(measureInfo: data.measureInfo)
  1073. } else if let data = anno as? CPDFPolygonAnnotation {
  1074. self.showMeasureAreaSettingWindow(measureInfo: data.measureInfo)
  1075. }
  1076. }
  1077. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  1078. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1079. return
  1080. }
  1081. self.listView.remove(anno)
  1082. }
  1083. func showMeasureDistanceSettingWindow(measureInfo: CPDFDistanceMeasureInfo?, hideInfoWindow: Bool = true) {
  1084. guard let mInfo = measureInfo else {
  1085. return
  1086. }
  1087. let winC = CDistanceSettingWindowController(distanceMeasureInfo: mInfo)
  1088. if hideInfoWindow {
  1089. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  1090. }
  1091. winC.delegate = self
  1092. winC.startModal("")
  1093. }
  1094. func showMeasurePerimeterSettingWindow(measureInfo: CPDFPerimeterMeasureInfo?, hideInfoWindow: Bool = true) {
  1095. guard let mInfo = measureInfo else {
  1096. return
  1097. }
  1098. let winC = CDistanceSettingWindowController(perimeterMeasureInfo: mInfo)
  1099. if hideInfoWindow {
  1100. self.perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1101. }
  1102. winC.delegate = self
  1103. winC.startModal("")
  1104. }
  1105. func showMeasureAreaSettingWindow(measureInfo: CPDFAreaMeasureInfo?, hideInfoWindow: Bool = true) {
  1106. guard let mInfo = measureInfo else {
  1107. return
  1108. }
  1109. let winC = CAreaSettingWindowController(measureInfo: mInfo)
  1110. if hideInfoWindow {
  1111. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  1112. }
  1113. winC.delegate = self
  1114. winC.startModal("")
  1115. }
  1116. func splitView(withTag tag: Int) {
  1117. if tag == 0 {
  1118. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1119. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1120. } else if tag == 1 {
  1121. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1122. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1123. } else if tag == 2 {
  1124. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1125. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1126. }
  1127. self.listView.needsDisplay = true
  1128. }
  1129. // MARK: - 幻灯片
  1130. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1131. let view: NSView = self.view.window!.firstResponder as! NSView
  1132. if view.isDescendant(of: pdfSplitView){
  1133. self.view.window?.makeFirstResponder(nil)
  1134. }
  1135. self.mainWindow = self.view.window
  1136. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1137. fullScreenWindow.interactionParent = self.view.window
  1138. self.mainWindow?.delegate = nil
  1139. fullScreenWindow.fadeInBlocking()
  1140. self.browserWindowController?.window = fullScreenWindow
  1141. fullScreenWindow.makeKey()
  1142. let sel = NSSelectorFromString("setAnimationBehavior:")
  1143. if self.mainWindow?.responds(to: sel) ?? false{
  1144. self.mainWindow?.animationBehavior = .none
  1145. }
  1146. self.mainWindow?.orderOut(nil)
  1147. if self.mainWindow?.responds(to: sel) ?? false{
  1148. self.mainWindow?.animationBehavior = .default
  1149. }
  1150. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1151. fullScreenWindow.orderFront(nil)
  1152. }
  1153. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1154. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1155. return
  1156. }
  1157. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1158. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1159. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1160. fullScreenWindow.contentView?.addSubview(view)
  1161. self.listView.layoutDocumentView()
  1162. self.listView.requiresDisplay()
  1163. fullScreenWindow.makeFirstResponder(self.listView)
  1164. fullScreenWindow.recalculateKeyViewLoop()
  1165. fullScreenWindow.delegate = self.browserWindowController
  1166. fullScreenWindow.display()
  1167. fadeWindow.fadeOut()
  1168. }
  1169. // MARK: Redact 【密文标记】
  1170. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1171. self.listView.remove(self.listView.activeAnnotation)
  1172. }
  1173. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1174. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1175. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1176. self.view.window?.beginSheet(windowController.window!)
  1177. self.currentWindowController = windowController
  1178. windowController.itemClick = { [weak self] index, value in
  1179. if (index == 1) { /// 取消
  1180. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1181. self?.currentWindowController = nil
  1182. return
  1183. }
  1184. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1185. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1186. annotaton.setBorderColor(windowController_redact.outsideColor)
  1187. annotaton.setInteriorColor(windowController_redact.fillColor)
  1188. if (windowController_redact.isOver) {
  1189. annotaton.setFontColor(windowController_redact.fontColor)
  1190. annotaton.setAlignment(windowController_redact.aligement)
  1191. annotaton.setFont(windowController_redact.font)
  1192. annotaton.setOverlayText(windowController_redact.overText)
  1193. }
  1194. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1195. self?.currentWindowController = nil
  1196. }
  1197. }
  1198. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1199. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1200. return
  1201. }
  1202. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1203. let model = CPDFAnnotationModel(annotationType: .redact)
  1204. model?.setColor(annotation.borderColor())
  1205. model?.setInteriorColor(annotation.interiorColor())
  1206. let overlayText: String = annotation.overlayText()
  1207. if (overlayText.isEmpty) {
  1208. model?.setIsOverlayText(false)
  1209. } else {
  1210. model?.setIsOverlayText(true)
  1211. model?.setOverlayText(overlayText)
  1212. model?.setFontColor(annotation.fontColor())
  1213. model?.setAlignment(annotation.alignment())
  1214. model?.setFontName(annotation.font().fontName)
  1215. model?.setFontSize(annotation.font().pointSize)
  1216. }
  1217. }
  1218. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1219. let anno = self.listView.activeAnnotation
  1220. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1221. return
  1222. }
  1223. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1224. windowController.pageCount = Int(self.listView.document?.pageCount ?? 0)
  1225. self.currentWindowController = windowController
  1226. self.view.window?.beginSheet(windowController.window!)
  1227. windowController.itemClick = { [weak self] index, value in
  1228. if (index == 1) {
  1229. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1230. self!.currentWindowController = nil
  1231. return
  1232. }
  1233. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1234. let pageType = windowController_mutilPageFlag.pageType
  1235. let pageString = windowController_mutilPageFlag.pageString
  1236. if (pageType == 4) { /// 自定义页面
  1237. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1238. if (array.count == 0) {
  1239. let alert = NSAlert()
  1240. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1241. alert.runModal()
  1242. return
  1243. }
  1244. }
  1245. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1246. self!.currentWindowController = nil
  1247. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1248. if (indexs.count == 0) {
  1249. return
  1250. }
  1251. for i in indexs {
  1252. let page: CPDFPage = (self?.listView.document?.page(at: UInt(i)))!
  1253. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1254. self?.listView.add(redactAnno, to: page)
  1255. }
  1256. }
  1257. }
  1258. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1259. self.exeRedactConfirm(.redactOne) {}
  1260. }
  1261. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1262. self.exeRedactConfirm(.eraserOne) {}
  1263. }
  1264. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1265. }
  1266. @objc func exportStampImage(sender:NSMenuItem) {
  1267. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1268. var image : NSImage = NSImage()
  1269. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1270. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1271. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1272. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1273. } else {
  1274. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1275. }
  1276. let data = image.tiffRepresentation
  1277. if sender.tag == 0 {
  1278. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1279. imageRep.size = image.size
  1280. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1281. let savePanel = NSSavePanel()
  1282. savePanel.allowedFileTypes = ["png"]
  1283. savePanel.beginSheetModal(for: self.view.window!) { response in
  1284. if (response != .OK) {
  1285. return
  1286. }
  1287. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1288. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1289. }
  1290. }
  1291. } else {
  1292. let pdfdocument = CPDFDocument()
  1293. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1294. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1295. pdfdocument?.km_insertPage(image.size, withImage: signatureImagePath!, at: 0)
  1296. let savePanel = NSSavePanel()
  1297. savePanel.allowedFileTypes = ["pdf"]
  1298. savePanel.beginSheetModal(for: self.view.window!) { response in
  1299. if (response != .OK) {
  1300. return
  1301. }
  1302. if pdfdocument!.write(to: savePanel.url!) {
  1303. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1304. }
  1305. }
  1306. }
  1307. }
  1308. }
  1309. }
  1310. @objc func exportCorpImage(sender:NSMenuItem) {
  1311. let rect = NSIntegralRect(listView.currentSelectionRect())
  1312. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1313. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1314. page.setBounds(rect, for: .cropBox)
  1315. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1316. let data = image.tiffRepresentation
  1317. guard let data = data else { return }
  1318. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1319. imageRep.size = rect.size
  1320. let savePanel = NSSavePanel()
  1321. switch sender.tag {
  1322. case 0:
  1323. savePanel.allowedFileTypes = ["png"]
  1324. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1325. savePanel.beginSheetModal(for: self.view.window!) { response in
  1326. if (response != .OK) {
  1327. return
  1328. }
  1329. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1330. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1331. }
  1332. }
  1333. case 1:
  1334. savePanel.allowedFileTypes = ["jpg"]
  1335. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1336. savePanel.beginSheetModal(for: self.view.window!) { response in
  1337. if (response != .OK) {
  1338. return
  1339. }
  1340. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1341. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1342. }
  1343. }
  1344. case 2:
  1345. savePanel.allowedFileTypes = ["pdf"]
  1346. let pdfdocument = CPDFDocument()
  1347. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1348. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1349. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1350. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1351. savePanel.beginSheetModal(for: self.view.window!) { response in
  1352. if (response != .OK) {
  1353. return
  1354. }
  1355. if pdfdocument!.write(to: savePanel.url!) {
  1356. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1357. }
  1358. }
  1359. }
  1360. default:
  1361. break
  1362. }
  1363. // 执行右键操作后,需要取消框选区域
  1364. if self.listView.toolMode == .selectToolMode {
  1365. objc_sync_enter(self)
  1366. self.listView.selectionRect = NSZeroRect
  1367. self.listView.selectionPageIndex = UInt(NSNotFound)
  1368. objc_sync_exit(self)
  1369. }
  1370. }
  1371. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1372. let rect = listView.currentSelectionRect()
  1373. let page = listView.currentPage()
  1374. if NSIsEmptyRect(rect) == false && page != nil {
  1375. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1376. var bounds = listView.bounds
  1377. var scale = 1.0
  1378. if isLegacy {
  1379. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1380. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1381. }
  1382. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1383. scale = NSHeight(bounds) / NSHeight(rect)
  1384. } else {
  1385. scale = NSWidth(bounds) / NSWidth(rect)
  1386. }
  1387. listView.setScaleFactor(scale, animated: false)
  1388. let scrollView = listView.scroll()
  1389. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1390. if ((scrollView?.hasVerticalScroller) != nil) {
  1391. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1392. }
  1393. if ((scrollView?.hasHorizontalScroller) != nil) {
  1394. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1395. }
  1396. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1397. scale = NSHeight(bounds) / NSHeight(rect)
  1398. } else {
  1399. scale = NSWidth(bounds) / NSWidth(rect)
  1400. }
  1401. listView.setScaleFactor(scale, animated: false)
  1402. }
  1403. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1404. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1405. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1406. };
  1407. }
  1408. // 执行右键操作后,需要取消框选区域
  1409. if self.listView.toolMode == .selectToolMode {
  1410. objc_sync_enter(self)
  1411. self.listView.selectionRect = NSZeroRect
  1412. self.listView.selectionPageIndex = UInt(NSNotFound)
  1413. objc_sync_exit(self)
  1414. }
  1415. }
  1416. private func cropPagesToRects(rects:NSPointerArray) {
  1417. }
  1418. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1419. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1420. switch sender.tag {
  1421. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1422. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1423. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1424. var red: CGFloat = 0.0
  1425. var green: CGFloat = 0.0
  1426. var blue: CGFloat = 0.0
  1427. var alpha: CGFloat = 0.0
  1428. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1429. if sender.tag == CAnnotationType.highlight.rawValue {
  1430. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1431. } else if sender.tag == CAnnotationType.underline.rawValue {
  1432. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1433. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1434. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1435. }
  1436. case CAnnotationType.ink.rawValue:
  1437. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1438. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1439. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1440. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1441. var red: CGFloat = 0.0
  1442. var green: CGFloat = 0.0
  1443. var blue: CGFloat = 0.0
  1444. var alpha: CGFloat = 0.0
  1445. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1446. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1447. case CAnnotationType.freeText.rawValue:
  1448. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1449. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1450. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1451. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1452. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1453. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1454. var red: CGFloat = 0.0
  1455. var green: CGFloat = 0.0
  1456. var blue: CGFloat = 0.0
  1457. var alpha: CGFloat = 0.0
  1458. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1459. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1460. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1461. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1462. UserDefaults.standard.synchronize()
  1463. }
  1464. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1465. if (alignment == .left || alignment == .center || alignment == .right) {
  1466. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1467. UserDefaults.standard.synchronize()
  1468. }
  1469. case CAnnotationType.anchored.rawValue:
  1470. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1471. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1472. var red: CGFloat = 0.0
  1473. var green: CGFloat = 0.0
  1474. var blue: CGFloat = 0.0
  1475. var alpha: CGFloat = 0.0
  1476. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1477. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1478. case CAnnotationType.square.rawValue:
  1479. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1480. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1481. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1482. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1483. var red: CGFloat = 0.0
  1484. var green: CGFloat = 0.0
  1485. var blue: CGFloat = 0.0
  1486. var alpha: CGFloat = 0.0
  1487. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1488. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1489. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1490. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1491. case CAnnotationType.circle.rawValue:
  1492. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1493. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1494. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1495. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1496. var red: CGFloat = 0.0
  1497. var green: CGFloat = 0.0
  1498. var blue: CGFloat = 0.0
  1499. var alpha: CGFloat = 0.0
  1500. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1501. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1502. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1503. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1504. default:
  1505. break
  1506. }
  1507. }
  1508. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1509. self.showOrHideNotes()
  1510. }
  1511. //MARK: - action
  1512. @objc func cropCurrentPage() {
  1513. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1514. var page: CPDFPage?
  1515. if let data = self.listView.currentSelectionPage() {
  1516. page = data
  1517. } else {
  1518. page = self.listView.currentPage()
  1519. }
  1520. if (NSIsEmptyRect(rect)) {
  1521. rect = KMCropTools.getPageForegroundBox(page!)
  1522. }
  1523. let index: UInt = (page?.pageIndex()) ?? 0
  1524. self._cropPage(at: index, in: rect)
  1525. // 执行右键操作后,需要取消框选区域
  1526. if self.listView.toolMode == .selectToolMode {
  1527. objc_sync_enter(self)
  1528. self.listView.selectionRect = NSZeroRect
  1529. self.listView.selectionPageIndex = UInt(NSNotFound)
  1530. objc_sync_exit(self)
  1531. }
  1532. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1533. }
  1534. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1535. let oldRect = self.listView.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1536. let undoManager = self.listView.undoManager
  1537. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1538. let page = self.listView.document.page(at: index)
  1539. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1540. page?.setBounds(newRect, for: .cropBox)
  1541. /// 刷新预览视图
  1542. self.listView.layoutDocumentView()
  1543. self.listView.displayBox = .cropBox
  1544. }
  1545. func beginProgressSheet(with message: String, maxValue: UInt) {
  1546. let progress = SKProgressController()
  1547. progress.window?.contentView?.wantsLayer = true
  1548. progress.message = NSLocalizedString("Converting...", comment: "")
  1549. self.progressC = progress
  1550. self.progressC?.message = message
  1551. if maxValue > 0 {
  1552. progressC?.indeterminate = false
  1553. progressC?.maxValue = Double(maxValue)
  1554. } else {
  1555. progressC?.indeterminate = true
  1556. }
  1557. self.view.km_beginSheet(windowC: progressC!)
  1558. }
  1559. // 白边距
  1560. @objc func smart_cropAllPage() {
  1561. var size = NSZeroSize
  1562. for i in 0 ..< self.listView.document.pageCount {
  1563. let page = self.listView.document.page(at: i)
  1564. let rect = KMCropTools.getPageForegroundBox(page!)
  1565. size.width = fmax(size.width, NSWidth(rect))
  1566. size.height = fmax(size.height, NSHeight(rect))
  1567. }
  1568. beginProgressSheet(with: KMLocalizedString("Cropping Pages"), maxValue: min(18, self.listView.document.pageCount))
  1569. var rectArray: Array<NSRect> = []
  1570. for i in 0 ..< self.listView.document.pageCount {
  1571. progressC?.increment(by: Double(i))
  1572. progressC?.doubleValue = Double(i)
  1573. let page = self.listView.document.page(at: i)
  1574. var rect = KMCropTools.getPageForegroundBox(page!)
  1575. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1576. rectArray.append(rect)
  1577. }
  1578. cropPages(to: rectArray)
  1579. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1580. }
  1581. // 自动
  1582. @objc func auto_cropAllPage() {
  1583. var size = NSZeroSize
  1584. for i in 0 ..< self.listView.document.pageCount {
  1585. let page = self.listView.document.page(at: i)
  1586. let rect = KMCropTools.getPageForegroundBox(page!)
  1587. size.width = fmax(size.width, NSWidth(rect))
  1588. size.height = fmax(size.height, NSHeight(rect))
  1589. }
  1590. beginProgressSheet(with: KMLocalizedString("Cropping Pages"), maxValue: min(18, self.listView.document.pageCount))
  1591. var rectArray: Array<NSRect> = []
  1592. for i in 0 ..< self.listView.document.pageCount {
  1593. progressC?.increment(by: Double(i))
  1594. progressC?.doubleValue = Double(i)
  1595. let page = self.listView.document.page(at: i)
  1596. var rect = KMCropTools.getPageForegroundBox(page!)
  1597. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1598. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1599. rect.origin.x = rect.maxX-size.width
  1600. }
  1601. rect.origin.y = rect.maxY-size.height
  1602. rect.size = size
  1603. if (NSWidth(rect) > NSWidth(bounds)) {
  1604. rect.size.width = NSWidth(bounds)
  1605. }
  1606. if (NSHeight(rect) > NSHeight(bounds)) {
  1607. rect.size.height = NSHeight(bounds)
  1608. }
  1609. if (NSMinX(rect) < NSMinX(bounds)) {
  1610. rect.origin.x = NSMinX(bounds)
  1611. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1612. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1613. }
  1614. if (NSMinY(rect) < NSMinY(bounds)) {
  1615. rect.origin.y = NSMinY(bounds)
  1616. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1617. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1618. }
  1619. rectArray.append(rect)
  1620. }
  1621. cropPages(to: rectArray)
  1622. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1623. }
  1624. @objc func cropAllPage() {
  1625. var rect = [NSIntegralRect(self.listView.currentSelectionRect() ?? .zero), .zero]
  1626. var rectArray: Array<NSRect> = []
  1627. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1628. if (emptySelection) {
  1629. guard let count = self.listView.document?.pageCount, count > 0 else {
  1630. KMPrint("listView | document is nil.", beep: true)
  1631. return
  1632. }
  1633. rect[0] = .zero
  1634. rect[1] = .zero
  1635. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1636. if (count == 1) {
  1637. if let page = self.listView.document.page(at: 0) {
  1638. rect[0] = KMCropTools.getPageForegroundBox(page)
  1639. }
  1640. progressC?.increment(by: 1)
  1641. } else if (count < 19) {
  1642. for i in 0 ..< 19 {
  1643. if let page = self.listView.document.page(at: UInt(i)) {
  1644. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1645. progressC?.increment(by: Double(i))
  1646. }
  1647. }
  1648. } else {
  1649. let start = [1, (count - 5) / 2, count - 6]
  1650. var cnt = 0
  1651. for j in 0 ..< 3 {
  1652. for i in 0 ..< 6 {
  1653. let k = Int(start[j] + UInt(i))
  1654. if let page = self.listView.document.page(at: UInt(k)) {
  1655. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1656. cnt += 1
  1657. progressC?.increment(by: Double(cnt))
  1658. }
  1659. }
  1660. }
  1661. }
  1662. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  1663. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  1664. for j in 0 ..< 2 {
  1665. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  1666. }
  1667. rectArray.append(rect.first ?? .zero)
  1668. rectArray.append(rect.last ?? .zero)
  1669. } else {
  1670. rectArray.append(rect.first ?? .zero)
  1671. }
  1672. self.cropPages(to: rectArray)
  1673. // 执行右键操作后,需要取消框选区域
  1674. if self.listView.toolMode == .selectToolMode {
  1675. objc_sync_enter(self)
  1676. self.listView.selectionRect = NSZeroRect
  1677. self.listView.selectionPageIndex = UInt(NSNotFound)
  1678. objc_sync_exit(self)
  1679. }
  1680. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1681. }
  1682. func cropPages(to rects: Array<NSRect>) {
  1683. let currentPage = self.listView.currentPage()
  1684. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1685. var oldRectArray: Array<NSRect> = []
  1686. let rectCount = rects.count
  1687. for i in 0 ..< self.listView.document.pageCount {
  1688. let page = self.listView.document.page(at: i)
  1689. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  1690. let oldRect = page?.bounds(for: .cropBox)
  1691. oldRectArray.append(oldRect!)
  1692. page?.setBounds(rect, for: .cropBox)
  1693. }
  1694. let undoManager = self.listView.undoManager
  1695. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1696. /// 刷新预览视图
  1697. self.listView.layoutDocumentView()
  1698. self.listView.displayBox = .cropBox
  1699. self.listView.go(to: currentPage)
  1700. self.listView.go(to: visibleRect, on: currentPage)
  1701. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1702. self.dismissProgressSheet()
  1703. }
  1704. }
  1705. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1706. if (limit) {
  1707. let document = self.listView.document ?? CPDFDocument()
  1708. if document?.documentURL == nil {
  1709. return
  1710. }
  1711. var doucumentURL : URL = self.listView.document.documentURL
  1712. if doucumentURL.path.count > 0 {
  1713. let docDir = NSTemporaryDirectory()
  1714. let documentName : String = doucumentURL.path.lastPathComponent
  1715. let path = docDir.stringByAppendingPathComponent(documentName)
  1716. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1717. let writeSuccess = data != nil
  1718. if writeSuccess == false {
  1719. __NSBeep()
  1720. return;
  1721. }
  1722. doucumentURL = URL(fileURLWithPath: path)
  1723. }
  1724. let array = [doucumentURL]
  1725. let picker = NSSharingServicePicker.init(items: array)
  1726. if sender.shareButton.window != nil {
  1727. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1728. } else {
  1729. 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)
  1730. }
  1731. return
  1732. }
  1733. let document = self.listView.document ?? CPDFDocument()
  1734. if document?.documentURL == nil {
  1735. return
  1736. }
  1737. var doucumentURL : URL = self.listView.document.documentURL
  1738. if doucumentURL.path.count > 0 {
  1739. let docDir = NSTemporaryDirectory()
  1740. let documentName : String = doucumentURL.path.lastPathComponent
  1741. let path = docDir.stringByAppendingPathComponent(documentName)
  1742. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1743. if writeSuccess == false {
  1744. __NSBeep()
  1745. return;
  1746. }
  1747. doucumentURL = URL(fileURLWithPath: path)
  1748. }
  1749. let array = [doucumentURL]
  1750. let picker = NSSharingServicePicker.init(items: array)
  1751. if sender.shareButton.window != nil {
  1752. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1753. } else {
  1754. 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)
  1755. }
  1756. }
  1757. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1758. if (limit) {
  1759. let document = self.listView.document ?? CPDFDocument()
  1760. var path: String?
  1761. if document?.documentURL != nil {
  1762. path = document?.documentURL.path ?? ""
  1763. }
  1764. if path?.count ?? 0 > 0 {
  1765. let docDir = NSTemporaryDirectory()
  1766. let documentName : String = path?.lastPathComponent ?? ""
  1767. path = docDir.stringByAppendingPathComponent(documentName)
  1768. }
  1769. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1770. var tfileName = path?.deletingPathExtension.lastPathComponent
  1771. let tStdFileSuffix = "_flatten"
  1772. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1773. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1774. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path ?? ""))
  1775. let success = data != nil
  1776. if success {
  1777. let url = URL(fileURLWithPath: path ?? "")
  1778. let picker = NSSharingServicePicker.init(items: [url])
  1779. if sender.shareButton.window != nil {
  1780. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1781. } else {
  1782. 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)
  1783. }
  1784. }
  1785. return
  1786. }
  1787. let document = self.listView.document ?? CPDFDocument()
  1788. var path: String?
  1789. if document?.documentURL != nil {
  1790. path = document?.documentURL.path ?? ""
  1791. }
  1792. if path?.count ?? 0 > 0 {
  1793. let docDir = NSTemporaryDirectory()
  1794. let documentName : String = path?.lastPathComponent ?? ""
  1795. path = docDir.stringByAppendingPathComponent(documentName)
  1796. }
  1797. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1798. var tfileName = path?.deletingPathExtension.lastPathComponent
  1799. let tStdFileSuffix = "_flatten"
  1800. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1801. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1802. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  1803. if success {
  1804. let url = URL(fileURLWithPath: path ?? "")
  1805. let picker = NSSharingServicePicker.init(items: [url])
  1806. if sender.shareButton.window != nil {
  1807. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1808. } else {
  1809. 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)
  1810. }
  1811. }
  1812. }
  1813. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1814. guard let pdfDoc = self.listView.document else {
  1815. NSSound.beep()
  1816. return
  1817. }
  1818. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  1819. let alert = NSAlert()
  1820. alert.alertStyle = .critical
  1821. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1822. alert.runModal()
  1823. return
  1824. }
  1825. if (limit) {
  1826. let document = self.listView.document ?? CPDFDocument()
  1827. var path: String?
  1828. if document?.documentURL != nil {
  1829. path = document?.documentURL.path ?? ""
  1830. }
  1831. if path?.count ?? 0 > 0{
  1832. let docDir = NSTemporaryDirectory()
  1833. let documentName : String = path?.lastPathComponent ?? ""
  1834. path = docDir.stringByAppendingPathComponent(documentName)
  1835. }
  1836. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path ?? ""), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1837. var writeSuccess = data != nil
  1838. if writeSuccess == false {
  1839. __NSBeep()
  1840. return;
  1841. }
  1842. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  1843. let cnt = newDocument?.pageCount ?? 0
  1844. for i in 0 ..< cnt {
  1845. let page = newDocument?.page(at: i)
  1846. var annotations : [CPDFAnnotation] = []
  1847. for annotation in page!.annotations {
  1848. annotations.append(annotation)
  1849. }
  1850. for annotation in annotations {
  1851. annotation.page.removeAnnotation(annotation)
  1852. }
  1853. }
  1854. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? "")) ?? false
  1855. if writeSuccess {
  1856. let url = URL(fileURLWithPath: path ?? "")
  1857. let picker = NSSharingServicePicker.init(items: [url])
  1858. if sender.shareButton.window != nil {
  1859. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1860. } else {
  1861. 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)
  1862. }
  1863. }
  1864. return
  1865. }
  1866. let document = self.listView.document ?? CPDFDocument()
  1867. var path: String?
  1868. if document?.documentURL != nil {
  1869. path = document?.documentURL.path ?? ""
  1870. }
  1871. if path?.count ?? 0 > 0 {
  1872. let docDir = NSTemporaryDirectory()
  1873. let documentName : String = path?.lastPathComponent ?? ""
  1874. path = docDir.stringByAppendingPathComponent(documentName)
  1875. }
  1876. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  1877. if writeSuccess == false {
  1878. __NSBeep()
  1879. return;
  1880. }
  1881. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  1882. let cnt = newDocument?.pageCount ?? 0
  1883. for i in 0 ..< cnt {
  1884. let page = newDocument!.page(at: i)
  1885. var annotations : [CPDFAnnotation] = []
  1886. for annotation in page!.annotations {
  1887. annotations.append(annotation)
  1888. }
  1889. for annotation in annotations {
  1890. annotation.page.removeAnnotation(annotation)
  1891. }
  1892. }
  1893. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  1894. if writeSuccess ?? false {
  1895. let url = URL(fileURLWithPath: path ?? "")
  1896. let picker = NSSharingServicePicker.init(items: [url])
  1897. if sender.shareButton.window != nil {
  1898. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1899. } else {
  1900. 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)
  1901. }
  1902. }
  1903. }
  1904. // 开启/关闭左边栏
  1905. @objc func toggleLeftPane() -> Void {
  1906. self.model.leftPanelOpen = true
  1907. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1908. }
  1909. // 开启左边栏
  1910. @objc func openLeftPane() -> Void {
  1911. self.model.leftPanelOpen = true
  1912. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1913. }
  1914. // 关闭左边栏
  1915. @objc func closeLeftPane() -> Void {
  1916. self.model.leftPanelOpen = false
  1917. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1918. }
  1919. // 开启/关闭右边栏
  1920. @objc func toggleRightPane() -> Void {
  1921. }
  1922. func rename(_ sender: NSNotification) -> Void {
  1923. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1924. return
  1925. }
  1926. let tabController = sender.object as? CTTabController
  1927. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  1928. if let doc = self.myDocument, doc.isDocumentEdited {
  1929. Task {
  1930. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  1931. if resp != .alertFirstButtonReturn { // 取消
  1932. return
  1933. }
  1934. doc.updateChangeCount(.changeCleared)
  1935. self.document?.write(to: doc.fileURL)
  1936. Task { @MainActor in
  1937. self._renameForSavePanel(tabController)
  1938. }
  1939. }
  1940. return
  1941. }
  1942. self._renameForSavePanel(tabController)
  1943. }
  1944. }
  1945. func savePdfAlertView() {
  1946. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  1947. return
  1948. }
  1949. AutoSaveManager.manager.isSaveNoti = true
  1950. var num = 0
  1951. if self.listView.document != nil{
  1952. num = Int(self.listView.document.pageCount)
  1953. }
  1954. if Thread.current.isMainThread {
  1955. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1956. } else {
  1957. DispatchQueue.main.async {
  1958. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1959. }
  1960. }
  1961. }
  1962. func savePdfFinishAlertView() {
  1963. if !AutoSaveManager.manager.isSaveNoti{
  1964. return
  1965. }
  1966. AutoSaveManager.manager.isSaveNoti = false
  1967. if Thread.current.isMainThread {
  1968. self.dismissProgressSheet()
  1969. } else {
  1970. DispatchQueue.main.async {
  1971. self.dismissProgressSheet()
  1972. }
  1973. }
  1974. }
  1975. private func _renameForSavePanel(_ tabC: CTTabController?) {
  1976. let outputSavePanel = NSSavePanel()
  1977. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1978. outputSavePanel.allowedFileTypes = ["pdf"]
  1979. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1980. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1981. let resp = outputSavePanel.runModal()
  1982. if resp == .OK {
  1983. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1984. let fileURL = pdfDocument?.documentURL
  1985. let fileManager = FileManager.default
  1986. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1987. var result = true
  1988. do {
  1989. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1990. } catch {
  1991. result = false
  1992. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1993. }
  1994. if (result) {
  1995. tabC?.title = outputSavePanel.url!.lastPathComponent
  1996. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1997. self.model.isSaveKeyChain = false
  1998. newPdfDocument.unlock(withPassword: self.document?.password)
  1999. if (newPdfDocument.pageCount > 0) {
  2000. self.setDocument = newPdfDocument
  2001. }
  2002. }
  2003. }
  2004. } else {
  2005. outputSavePanel.close()
  2006. }
  2007. }
  2008. func showInFinder(_ sender: Any) -> Void {
  2009. if sender is NSNotification {
  2010. let tabController = (sender as! NSNotification).object as? CTTabController
  2011. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2012. if tabController?.title == path {
  2013. if let file = self.myDocument?.fileURL {
  2014. if FileManager.default.fileExists(atPath: file.path) {
  2015. NSWorkspace.shared.activateFileViewerSelecting([file])
  2016. }
  2017. }
  2018. }
  2019. } else {
  2020. guard let url = self.myDocument?.fileURL else { return }
  2021. let file: URL = url
  2022. if FileManager.default.fileExists(atPath: file.path) {
  2023. NSWorkspace.shared.activateFileViewerSelecting([file])
  2024. }
  2025. }
  2026. }
  2027. func showOrHideNotes() {
  2028. self.listView.hideNotes = !self.listView.hideNotes
  2029. for note in self.listView.notes as? [CPDFAnnotation] ?? [] {
  2030. if note.isForm() {
  2031. note.setAnnotationShouldDisplay(true)
  2032. note.setHidden(false)
  2033. }
  2034. }
  2035. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2036. self.leftSideViewController.note_reloadDataIfNeed()
  2037. }
  2038. func closeTab(_ sender: NSNotification) -> Void {
  2039. }
  2040. @IBAction func toggleSplitPDF(_ sender: Any) {
  2041. if let menuItem = sender as? NSMenuItem {
  2042. splitView(withTag: menuItem.tag)
  2043. }
  2044. }
  2045. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2046. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2047. if (displayChanged) {
  2048. self.listView.layoutDocumentView()
  2049. }
  2050. if (page != nil) {
  2051. let idx = page!.pageIndex()
  2052. if (displayChanged) {
  2053. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2054. }
  2055. } else {
  2056. if (displayChanged) {
  2057. self.leftSideViewController.allThumbnailsNeedUpdate()
  2058. }
  2059. }
  2060. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2061. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2062. }
  2063. }
  2064. func changeLineAttribute(_ sender: Any?) {
  2065. var inspector = sender as? KMLineInspector
  2066. if inspector == nil {
  2067. inspector = KMLineInspector.shared
  2068. }
  2069. let action = inspector?.currentLineChangeAction ?? .no
  2070. for annotation in self.listView.activeAnnotations {
  2071. guard let anno = annotation as? CPDFAnnotation else {
  2072. continue
  2073. }
  2074. if anno.hasBorder() {
  2075. switch (action) {
  2076. case .lineWidth:
  2077. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2078. break
  2079. case .style:
  2080. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2081. break
  2082. case .dashPattern:
  2083. anno.setDashPattern(inspector?.dashPattern ?? [])
  2084. break
  2085. case .startLineStyle:
  2086. if anno.isLine() {
  2087. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2088. }
  2089. break
  2090. case .endLineStyle:
  2091. if anno.isLine() {
  2092. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2093. }
  2094. break
  2095. case .no:
  2096. break
  2097. }
  2098. }
  2099. }
  2100. }
  2101. // MARK: -
  2102. // MARK: 显示窗口
  2103. internal func showCompressWindow(url: URL? = nil) {
  2104. self.compressWIndowControllerNew = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2105. self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  2106. self.compressWIndowControllerNew?.password = self.listView.document?.password ?? ""
  2107. self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  2108. self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  2109. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2110. }
  2111. self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  2112. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2113. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2114. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2115. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2116. batchWindowController.window?.makeKeyAndOrderFront("")
  2117. }
  2118. self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2119. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2120. if (result) {
  2121. if (openDocument) {
  2122. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2123. } else {
  2124. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2125. }
  2126. } else {
  2127. let alert = NSAlert()
  2128. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2129. alert.runModal()
  2130. }
  2131. }
  2132. }
  2133. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2134. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2135. KMPrint("转档窗口已显示")
  2136. return
  2137. }
  2138. var convertT: KMConvertType = .Word
  2139. var windowController: KMConvertBaseWindowController?
  2140. if (type == .word) { /// Word
  2141. convertT = .Word
  2142. windowController = KMConvertWordWindowController()
  2143. } else if (type == .excel) {
  2144. convertT = .Excel
  2145. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2146. if (type == .ppt) {
  2147. convertT = .PPT
  2148. } else if (type == .rtf) {
  2149. convertT = .RTF
  2150. } else if (type == .html) {
  2151. convertT = .HTML
  2152. } else if (type == .conversion_text) {
  2153. convertT = .Text
  2154. }
  2155. } else if (type == .csv) {
  2156. convertT = .CSV
  2157. } else if (type == .conversion_image) {
  2158. windowController = KMConvertImageWindowController()
  2159. convertT = .JPEG
  2160. } else if type == .json {
  2161. convertT = .Json
  2162. }
  2163. var url: URL?
  2164. if (documentUrl != nil) {
  2165. url = documentUrl
  2166. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2167. } else {
  2168. url = self.listView.document.documentURL
  2169. }
  2170. let model = KMDocumentModel(url: url!)
  2171. windowController?.documentModel = model
  2172. self.km_safe_beginSheet(windowC: windowController)
  2173. }
  2174. //MARK: 转档 -
  2175. func showAllConvertWindow(convertT: KMConvertType) {
  2176. self.ConvertTrackEvent(type: convertT)
  2177. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2178. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2179. var type: KMConvertWithPDFType = .WordAdvance
  2180. switch convertT {
  2181. case .Word:
  2182. break
  2183. case .Excel:
  2184. type = .Excel
  2185. case .PPT:
  2186. type = .PowerPoint
  2187. case .RTF:
  2188. type = .RTF
  2189. case .CSV:
  2190. type = .CSV
  2191. case .HTML:
  2192. type = .HTML
  2193. case .Text:
  2194. type = .Text
  2195. case .JPEG:
  2196. type = .JPEG
  2197. case .PNG:
  2198. type = .PNG
  2199. case .GIF:
  2200. type = .GIF
  2201. case .JPG:
  2202. type = .JPG
  2203. case .TIFF:
  2204. type = .TIFF
  2205. case .TGA:
  2206. type = .TGA
  2207. case .BMP:
  2208. type = .BMP
  2209. case .JP2:
  2210. type = .JPEG2000
  2211. case .AdvancedWord:
  2212. break
  2213. case .Json:
  2214. type = .Json
  2215. break
  2216. default:
  2217. break
  2218. }
  2219. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2220. var needShowHint = false
  2221. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2222. needShowHint = true
  2223. } else {
  2224. var needContinue = false
  2225. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2226. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2227. let ss = self.document?.documentURL.path
  2228. if arr.contains(ss!) {
  2229. needContinue = false
  2230. }else {
  2231. needContinue = true
  2232. }
  2233. }else {
  2234. needContinue = true
  2235. }
  2236. if needContinue {
  2237. let ss = self.document?.documentURL.path
  2238. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2239. file.password = document?.password ?? ""
  2240. KMBatchOperateManager.defaultManager.files?.append(file)
  2241. }
  2242. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2243. batchWindowController.switchToConvertType(convertType: type)
  2244. }
  2245. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2246. if needShowHint {
  2247. batchWindowController.showIsConvertingHint()
  2248. } else {
  2249. }
  2250. }
  2251. }
  2252. self.km_beginSheet(windowC: convertWC)
  2253. }
  2254. func ConvertTrackEvent(type: KMConvertType) {
  2255. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2256. switch type {
  2257. case .Word:
  2258. eventStr = "Btn_SubTbr_Converter_ToWord"
  2259. break
  2260. case .Excel:
  2261. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2262. case .PPT:
  2263. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2264. case .RTF:
  2265. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2266. case .CSV:
  2267. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2268. case .HTML:
  2269. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2270. case .Text:
  2271. eventStr = "Btn_SubTbr_Converter_ToText"
  2272. case .JPEG:
  2273. eventStr = "Btn_SubTbr_Converter_ToImage"
  2274. case .PNG:
  2275. eventStr = "Btn_SubTbr_Converter_ToImage"
  2276. case .GIF:
  2277. eventStr = "Btn_SubTbr_Converter_ToImage"
  2278. case .JPG:
  2279. eventStr = "Btn_SubTbr_Converter_ToImage"
  2280. case .TIFF:
  2281. eventStr = "Btn_SubTbr_Converter_ToImage"
  2282. case .TGA:
  2283. eventStr = "Btn_SubTbr_Converter_ToImage"
  2284. case .BMP:
  2285. eventStr = "Btn_SubTbr_Converter_ToImage"
  2286. case .JP2:
  2287. eventStr = "Btn_SubTbr_Converter_ToImage"
  2288. case .AdvancedWord:
  2289. eventStr = "Btn_SubTbr_Converter_ToWord"
  2290. break
  2291. default:
  2292. break
  2293. }
  2294. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2295. }
  2296. //MARK: 转档 - OCR
  2297. func showOCRWindow() {
  2298. if !IAPProductsManager.default().isAvailableAllFunction(){
  2299. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2300. winC?.showWindow(nil)
  2301. return
  2302. }
  2303. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  2304. com.currentIndexPage = self.listView.currentPageIndex
  2305. self.km_beginSheet(windowC: com)
  2306. }
  2307. //MARK: 导出图片
  2308. func extractImageAction(num: Int) {
  2309. if !IAPProductsManager.default().isAvailableAllFunction(){
  2310. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2311. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  2312. winC?.showWindow(nil)
  2313. return
  2314. }
  2315. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2316. let alert = NSAlert()
  2317. alert.alertStyle = .critical
  2318. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2319. alert.runModal()
  2320. return
  2321. }
  2322. let document = self.listView.document
  2323. var fileURL = document?.documentURL
  2324. if num == 1 {
  2325. let pageCount = document?.pageCount ?? 0
  2326. let indeSet = NSMutableIndexSet()
  2327. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2328. if indeSet.count == 0 {
  2329. return
  2330. }
  2331. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2332. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2333. let outputSavePanel = NSSavePanel()
  2334. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2335. outputSavePanel.allowsOtherFileTypes = true
  2336. outputSavePanel.isExtensionHidden = true
  2337. outputSavePanel.canCreateDirectories = true
  2338. outputSavePanel.nameFieldStringValue = tFileName
  2339. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2340. if result == NSApplication.ModalResponse.OK {
  2341. DispatchQueue.main.async {
  2342. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2343. let tDestFile = outputSavePanel.url!.path
  2344. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2345. let pdfconverter = PDFConvertObject()
  2346. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2347. self.dismissProgressSheet()
  2348. let fileManager = FileManager.default
  2349. if fileManager.fileExists(atPath: tDestFile) {
  2350. let workspace = NSWorkspace.shared
  2351. let url = URL(fileURLWithPath: tDestFile)
  2352. workspace.activateFileViewerSelecting([url])
  2353. }
  2354. }
  2355. }
  2356. })
  2357. return
  2358. }
  2359. if fileURL != nil {
  2360. self.myDocument?.save(nil)
  2361. } else {
  2362. let myDocument = self.myDocument
  2363. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2364. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2365. if writeSuccess {
  2366. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2367. fileURL = document?.documentURL
  2368. } else {
  2369. NSSound.beep()
  2370. return
  2371. }
  2372. }
  2373. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2374. extract?.docPath = fileURL?.path ?? ""
  2375. extract?.password = document?.password ?? ""
  2376. extract?.currentPage = self.listView.currentPageIndex
  2377. self.km_beginSheet(windowC: extract!)
  2378. extract?.selectCurrentPageBtn()
  2379. }
  2380. //MARK: 创建文字图章示例实际上不会在这里使用
  2381. func showCreateStamp() {
  2382. let stampCreaterWindowController = KMStampCreaterWindowController()
  2383. stampCreaterWindowController.window?.backgroundColor = .clear
  2384. self.km_beginSheet(windowC: stampCreaterWindowController)
  2385. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2386. if result == 1 {
  2387. }
  2388. }
  2389. }
  2390. //MARK: 添加签名示例实际上不会在这里使用
  2391. func showAddSignature() {
  2392. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  2393. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  2394. })
  2395. }
  2396. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2397. let progress = SKProgressController()
  2398. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2399. progress.window?.contentView?.wantsLayer = true
  2400. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2401. progress.progressField.textColor = NSColor.white
  2402. progress.message = NSLocalizedString("Converting...", comment: "")
  2403. progressC = progress
  2404. progressC?.message = message
  2405. if maxValue > 0 {
  2406. progressC?.indeterminate = false
  2407. progressC?.maxValue = Double(maxValue)
  2408. progressC?.progressBar.doubleValue = 0.3
  2409. } else {
  2410. progressC?.indeterminate = true
  2411. }
  2412. self.view.km_beginSheet(windowC: progressC!)
  2413. }
  2414. func dismissProgressSheet() {
  2415. progressC?.stopAnimation()
  2416. self.view.km_endSheet()
  2417. progressC = nil
  2418. }
  2419. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2420. let newArr = NSMutableArray()
  2421. for item in files {
  2422. newArr.add(item.filePath)
  2423. }
  2424. return newArr as! [String]
  2425. }
  2426. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2427. self.saveDocument()
  2428. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2429. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2430. if (result == .cancel) {
  2431. return
  2432. }
  2433. // 解除权限
  2434. self?.listView.document.unlock(withPassword: password)
  2435. // 隐藏提示
  2436. self?.hiddenSecureLimitTip()
  2437. // 去打印
  2438. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  2439. }
  2440. return
  2441. }
  2442. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  2443. }
  2444. // MARK: - 图片注释
  2445. @IBAction func imageAnnotation(_ sender: Any) {
  2446. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2447. changeAnnotationMode(sender)
  2448. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2449. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2450. return
  2451. }
  2452. let accessoryCtr = KMImageAccessoryController()
  2453. let openPanel = NSOpenPanel()
  2454. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2455. openPanel.allowsMultipleSelection = false
  2456. openPanel.accessoryView = accessoryCtr.view
  2457. openPanel.canSelectHiddenExtension = true
  2458. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2459. if result == .OK {
  2460. guard let url = openPanel.url else {
  2461. return
  2462. }
  2463. let filePath = url.path
  2464. if filePath.pathExtension.lowercased() == "pdf" {
  2465. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2466. NSSound.beep()
  2467. return
  2468. }
  2469. }
  2470. guard let image = NSImage(contentsOfFile: url.path) else {
  2471. let alert = NSAlert()
  2472. alert.alertStyle = .critical
  2473. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2474. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2475. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2476. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2477. if response == .alertFirstButtonReturn {
  2478. // Handle cancel button clicked
  2479. }
  2480. }
  2481. return
  2482. }
  2483. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  2484. if isDamageImage {
  2485. let alert = NSAlert()
  2486. alert.alertStyle = .critical
  2487. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2488. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2489. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2490. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2491. if response == .alertFirstButtonReturn {
  2492. // Handle cancel button clicked
  2493. }
  2494. }
  2495. return
  2496. }
  2497. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2498. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2499. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2500. }
  2501. }
  2502. }
  2503. }
  2504. @IBAction func tableAnnotation(_ sender: Any) {
  2505. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2506. changeAnnotationMode(sender)
  2507. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2508. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2509. winC?.kEventName = "Reading_Table_BuyNow"
  2510. winC?.showWindow(nil)
  2511. return
  2512. }
  2513. listView.addAnnotationWithTable()
  2514. openRightPane()
  2515. }
  2516. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2517. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2518. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2519. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2520. }
  2521. if let data = image.tiffRepresentation,
  2522. let imageRep = NSBitmapImageRep(data: data) {
  2523. imageRep.size = image.size
  2524. var imageData: Data?
  2525. if path.lowercased() == "png" {
  2526. imageData = imageRep.representation(using: .png, properties: [:])
  2527. } else {
  2528. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2529. }
  2530. if let imageData = imageData {
  2531. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2532. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2533. return true
  2534. } else {
  2535. return false
  2536. }
  2537. }
  2538. }
  2539. return false
  2540. }
  2541. func tagString() -> String {
  2542. let dateFormatter = DateFormatter()
  2543. dateFormatter.dateFormat = "yyMMddHHmmss"
  2544. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2545. }
  2546. // MARK: - Split View
  2547. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2548. }
  2549. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2550. }
  2551. func updateBackAndForwardButtonState() {
  2552. }
  2553. }
  2554. // MARK: -
  2555. // MARK: - KMToolbarViewControllerDelegate
  2556. extension KMMainViewController : KMToolbarViewControllerDelegate {
  2557. func changeModelAction(mode: CToolMode) {
  2558. self.listView.toolMode = mode
  2559. if mode == .editPDFToolMode {
  2560. }
  2561. }
  2562. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2563. switch selectedTag {
  2564. case 2:
  2565. if self.listView.scaleFactor != 1.0 {
  2566. self.listView.scaleFactor = 1.0
  2567. self.listView.autoScales = false
  2568. }
  2569. break
  2570. case 1:
  2571. let pageHeight = self.listView.currentPage()!.size.height
  2572. let pdfviewHeight = self.listView.bounds.size.height
  2573. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2574. self.listView.autoScales = false
  2575. break
  2576. case 0:
  2577. self.listView.autoScales = true
  2578. break
  2579. case 3:
  2580. self.listView.scaleFactor = 0.1
  2581. break
  2582. case 4:
  2583. self.listView.scaleFactor = 0.25
  2584. break
  2585. case 5:
  2586. self.listView.scaleFactor = 0.5
  2587. break
  2588. case 6:
  2589. self.listView.scaleFactor = 0.75
  2590. break
  2591. case 7:
  2592. self.listView.scaleFactor = 1.0
  2593. break
  2594. case 8:
  2595. self.listView.scaleFactor = 1.5
  2596. break
  2597. case 9:
  2598. self.listView.scaleFactor = 2.0
  2599. break
  2600. case 10:
  2601. self.listView.scaleFactor = 4.0
  2602. break
  2603. case 11:
  2604. self.listView.scaleFactor = 8.0
  2605. break
  2606. case 12:
  2607. self.listView.scaleFactor = 16.0
  2608. break
  2609. case 13:
  2610. self.listView.scaleFactor = 32.0
  2611. break
  2612. case 14:
  2613. self.listView.scaleFactor = 64.0
  2614. break
  2615. case 15:
  2616. self.listView.scaleFactor = 100.0
  2617. break
  2618. default:
  2619. break
  2620. }
  2621. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2622. if self.digitalSignController?.pdfView != nil {
  2623. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  2624. }
  2625. if self.redactController?.redactPdfView != nil {
  2626. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  2627. }
  2628. }
  2629. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2630. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2631. if scale > 100 {
  2632. scale = 100
  2633. }
  2634. if (scale <= 0.101) {
  2635. self.listView.scaleFactor = self.listView.minScaleFactor()
  2636. } else {
  2637. self.listView.scaleFactor = scale
  2638. }
  2639. if self.digitalSignController?.pdfView != nil {
  2640. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  2641. }
  2642. if self.redactController?.redactPdfView != nil {
  2643. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  2644. }
  2645. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2646. }
  2647. func changePDFViewZoomInAction() {
  2648. }
  2649. func changePDFViewZoomOutAction() {
  2650. }
  2651. func changePDFViewGotoNextPageAction() {
  2652. self.listView.km_goBack(nil)
  2653. if (self.listView.canGoToNextPage()) {
  2654. self.listView.goToNextPage(nil)
  2655. }
  2656. }
  2657. func changePDFViewGoToPreviousPageAction() {
  2658. if (self.listView.canGoToPreviousPage()) {
  2659. self.listView.goToPreviousPage(nil)
  2660. }
  2661. }
  2662. func changePDFViewGotoBackAction() {
  2663. self.listView.km_goBack(nil)
  2664. self.updateBackAndForwardButtonState()
  2665. }
  2666. func changePDFViewGoToForwardAction() {
  2667. self.listView.km_goForward(nil)
  2668. self.updateBackAndForwardButtonState()
  2669. }
  2670. func aiTranslationPDFFileAction() {
  2671. self.trackEvent_aiTranslate()
  2672. self._aiTranslationPDFFileAction()
  2673. }
  2674. private func _aiTranslationPDFFileAction() {
  2675. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2676. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2677. let alert = NSAlert()
  2678. alert.alertStyle = .critical
  2679. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2680. alert.runModal()
  2681. return
  2682. } else if isExceedsLimit {
  2683. let alert = NSAlert()
  2684. alert.alertStyle = .critical
  2685. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2686. alert.runModal()
  2687. return
  2688. }
  2689. let alert = NSAlert()
  2690. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2691. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2692. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2693. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2694. if (result == .alertFirstButtonReturn) {
  2695. } else if result == .alertSecondButtonReturn {
  2696. return
  2697. }
  2698. }
  2699. }
  2700. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2701. self.trackEvent_share()
  2702. }
  2703. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2704. self.shareDocument(sender: viewController)
  2705. }
  2706. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2707. if IAPProductsManager.default().isAvailableAllFunction() == false {
  2708. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2709. winC?.kEventName = "Reading_Flatten_BuyNow"
  2710. winC?.showWindow(nil)
  2711. return
  2712. }
  2713. self.shareFlatten(sender: viewController)
  2714. }
  2715. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2716. self.shareOriginalPDF(sender: viewController)
  2717. }
  2718. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2719. if(0 == selectedTag) {
  2720. } else {
  2721. }
  2722. }
  2723. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2724. if beforeType == .editPDF {
  2725. }
  2726. if(type != .Page) {
  2727. if (hasEnterPageEdit()) {
  2728. self.exitPageEdit()
  2729. }
  2730. }
  2731. if type != .redact {
  2732. if self.hasEnterRedact() {
  2733. self.exitRedact()
  2734. }
  2735. }
  2736. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  2737. if self.hasShowDigitalSign() {
  2738. self.exitDigitalSign()
  2739. }
  2740. }
  2741. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  2742. }
  2743. if(type != .Form) {
  2744. self.removeFromAlertView()
  2745. }
  2746. if (type == .Page) {
  2747. if (hasEnterPageEdit()) {
  2748. self.exitPageEdit()
  2749. } else {
  2750. self.enterPageEdit(pages)
  2751. }
  2752. } else if type == .editPDF {
  2753. self.enterEditPDF()
  2754. } else if type == .Annatiton {
  2755. } else if type == .redact {
  2756. if self.needSaveDocument() {
  2757. self.saveDocumentWithProgressAlert { [unowned self] params in
  2758. self.enterRedact()
  2759. }
  2760. return
  2761. }
  2762. let isEdited = self.listView.isEdited()
  2763. let isPDFTextImageEdited = self.model.isPDFTextImageEdited
  2764. if isEdited || isPDFTextImageEdited {
  2765. self.enterRedact()
  2766. } else {
  2767. self.enterRedact()
  2768. }
  2769. } else if type == .Tool {
  2770. if KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  2771. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  2772. } else if KMGuideInfoWindowController.availableShow(.measureGuide) {
  2773. self.loadOpenFileFunctionGuide(.measureGuide)
  2774. }
  2775. } else if type == . Conversion {
  2776. self.loadOpenFileFunctionGuide(.convertGuide)
  2777. }else if type == .Form {
  2778. self.showFormAlertView()
  2779. }else if type == .Select {
  2780. self.closeRightPane()
  2781. }
  2782. }
  2783. func clickChildTool(type: KMToolbarType, index: Int) {
  2784. if (type == .secure) {
  2785. if (index == 1) {
  2786. self.trackEvent_setPassword()
  2787. } else if (index == 2) {
  2788. self.trackEvent_removePassword()
  2789. }
  2790. } else {
  2791. self.trackEvent(toolBarType: type)
  2792. }
  2793. Task { @MainActor in
  2794. if (type == .compress) { /// 压缩
  2795. if !self.documentAllowsEdit() {
  2796. return
  2797. }
  2798. if (self.needSaveDocument()) {
  2799. self.saveDocumentWithProgressAlert { [unowned self] params in
  2800. self.showCompressWindow()
  2801. }
  2802. return
  2803. }
  2804. self.showCompressWindow()
  2805. return
  2806. }
  2807. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  2808. if type == .conversion_imageToPDF {
  2809. Task {
  2810. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  2811. }
  2812. return
  2813. }
  2814. var identifier: String?
  2815. if (type == .word) { /// Word
  2816. identifier = KMToolbarConversionWordItemIdentifier
  2817. } else if (type == .excel) {
  2818. identifier = KMToolbarConversionExcelItemIdentifier
  2819. } else if (type == .ppt) {
  2820. identifier = KMToolbarConversionPPTItemIdentifier
  2821. } else if (type == .rtf) {
  2822. identifier = KMToolbarConversionRTFItemIdentifier
  2823. } else if (type == .html) {
  2824. identifier = KMToolbarConversionHTMLItemIdentifier
  2825. } else if (type == .conversion_text) {
  2826. identifier = KMToolbarConversionTextItemIdentifier
  2827. } else if (type == .csv) {
  2828. identifier = KMToolbarConversionCSVItemIdentifier
  2829. } else if (type == .conversion_image) {
  2830. identifier = KMToolbarConversionImageItemIdentifier
  2831. }
  2832. if (self.needSaveDocument()) {
  2833. self.saveDocumentWithProgressAlert { [unowned self] params in
  2834. self.showConvertWindow(type: type, identifier: identifier)
  2835. }
  2836. return
  2837. }
  2838. self.showConvertWindow(type: type, identifier: identifier)
  2839. return
  2840. }
  2841. if (type == .merge) { /// 合并
  2842. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  2843. if !self.documentAllowsEdit() {
  2844. return
  2845. }
  2846. if (self.needSaveDocument()) {
  2847. self.saveDocumentWithProgressAlert { [unowned self] params in
  2848. self.showMergeWindow(self.listView.document.password)
  2849. }
  2850. return
  2851. }
  2852. self.showMergeWindow(self.listView.document.password)
  2853. return
  2854. }
  2855. if (type == .bates || type == .headerAndFooter) {
  2856. if !IAPProductsManager.default().isAvailableAllFunction(){
  2857. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2858. if type == .headerAndFooter {
  2859. if index == 1 {
  2860. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  2861. } else if index == 2 {
  2862. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  2863. }
  2864. } else if type == .bates {
  2865. if index == 1 {
  2866. winC?.kEventName = "Reading_AddBates_BuyNow"
  2867. } else if index == 2 {
  2868. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  2869. }
  2870. }
  2871. winC?.showWindow(nil)
  2872. return
  2873. }
  2874. if !self.documentAllowsEdit() {
  2875. return
  2876. }
  2877. if (index == 1) {
  2878. var windowController: KMBaseWindowController = KMBaseWindowController()
  2879. if (type == .bates) {
  2880. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2881. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2882. let fpath = self.document?.documentURL?.path ?? ""
  2883. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2884. }
  2885. windowController.isBates = true
  2886. } else if (type == .headerAndFooter) {
  2887. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  2888. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  2889. let fpath = self.document?.documentURL?.path ?? ""
  2890. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2891. }
  2892. } else if (type == .background) {
  2893. } else if (type == .watermark) {
  2894. }
  2895. windowController.pdfDocument = self.listView.document
  2896. windowController.cancelAction = { [unowned self] controller in
  2897. self.view.window?.endSheet((self.currentWindowController.window)!)
  2898. self.currentWindowController = nil
  2899. }
  2900. self.currentWindowController = windowController
  2901. await self.view.window?.beginSheet(windowController.window!)
  2902. return
  2903. }
  2904. if (index == 1) { /// 取消
  2905. ///
  2906. self.closeRightPane()
  2907. return
  2908. } else if index == 3 {
  2909. let fpath = self.document?.documentURL?.path ?? ""
  2910. if type == .bates {
  2911. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2912. } else {
  2913. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2914. }
  2915. } else if index == 4 {
  2916. let fpath = self.document?.documentURL?.path ?? ""
  2917. if type == .bates {
  2918. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  2919. } else {
  2920. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  2921. }
  2922. } else if (index == 2) { //// 移除
  2923. if type == .headerAndFooter {
  2924. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2925. let savePanel = NSSavePanel()
  2926. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2927. savePanel.allowedFileTypes = ["pdf"]
  2928. savePanel.accessoryView = savePanelAccessoryViewController.view
  2929. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2930. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2931. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2932. if success == 1 && savePanel.url?.path == self.listView.document?.documentURL.path {
  2933. self.setDocument = CPDFDocument(url: savePanel.url!)
  2934. return
  2935. }
  2936. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2937. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2938. }
  2939. } else {
  2940. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2941. }
  2942. }
  2943. }
  2944. }
  2945. } else if type == .bates {
  2946. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2947. let savePanel = NSSavePanel()
  2948. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2949. savePanel.allowedFileTypes = ["pdf"]
  2950. savePanel.accessoryView = savePanelAccessoryViewController.view
  2951. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2952. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2953. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  2954. if success == 1 && savePanel.url?.path == self.listView.document?.documentURL.path {
  2955. self.setDocument = CPDFDocument(url: savePanel.url!)
  2956. return
  2957. }
  2958. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  2959. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  2960. }
  2961. } else {
  2962. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  2963. }
  2964. }
  2965. }
  2966. }
  2967. }
  2968. } else if (index == 2) { /// 应用
  2969. } else if index == 5 {
  2970. self.openRightPane()
  2971. }
  2972. } else if (type == .redact) { /// 标记密文
  2973. if !IAPProductsManager.default().isAvailableAllFunction(){
  2974. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2975. return
  2976. }
  2977. if (index == 1) { /// 取消
  2978. if (self.model.hasAddRedact) {
  2979. let alert = NSAlert()
  2980. 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: "")
  2981. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2982. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2983. let result = alert.runModal()
  2984. if (result == .alertFirstButtonReturn) {
  2985. self.listView.toolMode = .moveToolMode
  2986. }
  2987. return
  2988. }
  2989. self.listView.toolMode = .moveToolMode
  2990. return
  2991. }
  2992. if (index == 2) { /// 擦除
  2993. self.exeRedactConfirm(.eraserAll) {}
  2994. return
  2995. }
  2996. if (index == 3) { /// 应用
  2997. self.exeRedactConfirm(.redactAll) {}
  2998. return
  2999. }
  3000. if (index == 4) { /// 文本&图像
  3001. self.listView.toolMode = .redactToolMode
  3002. return
  3003. }
  3004. if (index == 5) { /// 页面
  3005. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3006. await self.view.window?.beginSheet(windowController.window!)
  3007. self.currentWindowController = windowController
  3008. windowController.itemClick = { [weak self] index, value in
  3009. if (index == 1) {
  3010. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3011. self?.currentWindowController = nil
  3012. return
  3013. }
  3014. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3015. let pageType = windowController_pageRange.pageType
  3016. let pageString = windowController_pageRange.pageString
  3017. if (pageType == 5) { /// 自定义页面
  3018. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  3019. if (array.count == 0) {
  3020. let alert = NSAlert()
  3021. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3022. alert.runModal()
  3023. return
  3024. }
  3025. }
  3026. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3027. self!.currentWindowController = nil
  3028. var indexs: IndexSet = []
  3029. if (pageType == 1) { /// 当前页面
  3030. indexs.insert((self?.listView.currentPageIndex)!)
  3031. } else {
  3032. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  3033. }
  3034. if (indexs.count == 0) {
  3035. return
  3036. }
  3037. for i in indexs {
  3038. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3039. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3040. redactAnno.bounds = page.bounds
  3041. self?.listView.add(redactAnno, to: page)
  3042. }
  3043. }
  3044. return
  3045. }
  3046. } else if (type == .secure) { /// 安全
  3047. if (index == 1) { /// 设置密码
  3048. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3049. if !self.documentAllowsEdit() {
  3050. return
  3051. }
  3052. }
  3053. self.showSecureWindow(self.listView.document.documentURL)
  3054. return
  3055. } else if index == 2 {
  3056. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3057. let alert = NSAlert()
  3058. alert.alertStyle = .warning
  3059. alert.messageText = NSLocalizedString("Warning", comment: "")
  3060. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3061. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3062. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3063. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3064. if returnCode == .alertSecondButtonReturn {
  3065. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3066. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3067. if success {
  3068. self.document?.unlock(withPassword: resultPassword)
  3069. self.clickChildTool(type: .secure, index: 2)
  3070. }
  3071. }
  3072. }
  3073. }
  3074. }
  3075. } else {
  3076. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3077. controller.pdfDocument = self.document
  3078. self.currentWindowController = controller
  3079. controller.batchAction = { [unowned self] controller, files in
  3080. self.view.window?.endSheet((self.currentWindowController.window)!)
  3081. self.currentWindowController = nil
  3082. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3083. if #available(macOS 10.13, *) {
  3084. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3085. } else {
  3086. baseWindowController.showWindow(nil)
  3087. }
  3088. let arr = NSMutableArray()
  3089. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  3090. file.password = document?.password ?? ""
  3091. arr.add(file)
  3092. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  3093. }
  3094. controller.cancelAction = { [unowned self] controller in
  3095. self.view.window?.endSheet((self.currentWindowController.window)!)
  3096. self.currentWindowController = nil
  3097. }
  3098. controller.doneAction = { [unowned self] controller in
  3099. self.view.window?.endSheet((self.currentWindowController.window)!)
  3100. self.currentWindowController = nil
  3101. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  3102. if success {
  3103. let savePanel = NSSavePanel()
  3104. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3105. savePanel.allowedFileTypes = ["pdf"]
  3106. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3107. guard result == .OK else { return }
  3108. /// 删除安全性设置
  3109. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3110. self.model.isSaveKeyChain = false
  3111. self.listView.document.unlock(withPassword: resultPassword)
  3112. }
  3113. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3114. guard let document = document else { return }
  3115. document.unlock(withPassword: resultPassword)
  3116. let success = document.writeDecrypt(to: savePanel.url)
  3117. if success {
  3118. self.hiddenSecureLimitTip()
  3119. let tip = KMRemovePasswordResultTipView()
  3120. tip.result = .success
  3121. tip.showInView(superView: (self.listView.superview)!)
  3122. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3123. } else {
  3124. self.hiddenSecureLimitTip()
  3125. let tip = KMRemovePasswordResultTipView()
  3126. tip.result = .failure
  3127. tip.showInView(superView: (self.listView.superview)!)
  3128. }
  3129. }
  3130. }
  3131. }
  3132. }
  3133. await NSWindow.currentWindow().beginSheet(controller.window!)
  3134. }
  3135. return
  3136. }
  3137. } else if type == .comparison {
  3138. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3139. if !IAPProductsManager.default().isAvailableAllFunction(){
  3140. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3141. winC?.kEventName = "Reading_Compare_BuyNow"
  3142. winC?.showWindow(nil)
  3143. return
  3144. }
  3145. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3146. self.currentWindowController = controller
  3147. controller.password = self.document?.password ?? ""
  3148. controller.filePath = (self.document?.documentURL.path)!
  3149. controller.cancelAction = { [unowned self] controller in
  3150. self.view.window?.endSheet((self.currentWindowController.window)!)
  3151. self.currentWindowController = nil
  3152. }
  3153. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3154. self.view.window?.endSheet((self.currentWindowController.window)!)
  3155. self.currentWindowController = nil
  3156. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3157. }
  3158. controller.coveringComplete = { [unowned self] controller, document in
  3159. self.view.window?.endSheet((self.currentWindowController.window)!)
  3160. self.currentWindowController = nil
  3161. self.openCoveringCompareVC(with: document)
  3162. }
  3163. if index == 1 {
  3164. controller.fileType = .content
  3165. } else {
  3166. controller.fileType = .coverting
  3167. }
  3168. await NSWindow.currentWindow().beginSheet(controller.window!)
  3169. } else if type == .watermark {
  3170. if !IAPProductsManager.default().isAvailableAllFunction(){
  3171. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3172. if index == 1 {
  3173. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  3174. } else if index == 2 {
  3175. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  3176. }
  3177. winC?.showWindow(nil)
  3178. return
  3179. }
  3180. if !self.documentAllowsEdit() {
  3181. return
  3182. }
  3183. if index == 1 {
  3184. } else if index == 2 {
  3185. let watermarks = self.listView.document.watermarks()
  3186. if (watermarks == nil || watermarks!.count <= 0) {
  3187. let alert = NSAlert()
  3188. alert.alertStyle = .warning
  3189. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  3190. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  3191. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3192. alert.runModal()
  3193. return
  3194. }
  3195. let alert = NSAlert()
  3196. alert.alertStyle = .warning
  3197. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  3198. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  3199. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3200. let result = alert.runModal()
  3201. if (result != .alertFirstButtonReturn) {
  3202. return
  3203. }
  3204. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3205. let savePanel = NSSavePanel()
  3206. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  3207. savePanel.allowedFileTypes = ["pdf"]
  3208. savePanel.accessoryView = savePanelAccessoryViewController.view
  3209. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3210. guard result == .OK else { return }
  3211. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3212. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  3213. result in
  3214. DispatchQueue.main.async {
  3215. self.listView.layoutDocumentView()
  3216. self.listView.setNeedsDisplayForVisiblePages()
  3217. }
  3218. if (result) {
  3219. let alert = NSAlert()
  3220. alert.alertStyle = .warning
  3221. alert.messageText = NSLocalizedString("Finish", comment: "")
  3222. alert.runModal()
  3223. if savePanel.url?.path == self.listView.document?.documentURL.path {
  3224. self.setDocument = CPDFDocument(url: savePanel.url!)
  3225. return
  3226. }
  3227. let needOpen = savePanelAccessoryViewController.needOpen
  3228. if needOpen {
  3229. NSDocumentController.shared.km_safe_openDocument(withContentsOf: savePanel.url!, display: true) { document, hasOpen, err in }
  3230. } else {
  3231. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3232. }
  3233. } else {
  3234. let alert = NSAlert()
  3235. alert.alertStyle = .critical
  3236. alert.messageText = NSLocalizedString("Failed", comment: "")
  3237. alert.runModal()
  3238. }
  3239. }
  3240. }
  3241. } else if index == 3 {
  3242. let fpath = self.document?.documentURL?.path ?? ""
  3243. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  3244. } else if index == 4 {
  3245. let fpath = self.document?.documentURL?.path ?? ""
  3246. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  3247. } else if index == 5 {
  3248. self.openRightPane()
  3249. return
  3250. }
  3251. } else if type == .background {
  3252. if !IAPProductsManager.default().isAvailableAllFunction(){
  3253. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3254. if index == 1 {
  3255. winC?.kEventName = "Reading_AddBackground_BuyNow"
  3256. } else if index == 2 {
  3257. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  3258. }
  3259. winC?.showWindow(nil)
  3260. return
  3261. }
  3262. if !self.documentAllowsEdit() {
  3263. return
  3264. }
  3265. if index == 1 {
  3266. } else if index == 2 {
  3267. guard let document = self.document else { return }
  3268. if !document.allowsPrinting || !document.allowsCopying {
  3269. let alert = NSAlert()
  3270. alert.alertStyle = .critical
  3271. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3272. alert.runModal()
  3273. return
  3274. }
  3275. guard let documentURL = document.documentURL else { return }
  3276. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3277. let savePanel = NSSavePanel()
  3278. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  3279. savePanel.allowedFileTypes = ["pdf"]
  3280. savePanel.accessoryView = savePanelAccessoryViewController.view
  3281. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3282. guard result == .OK else { return }
  3283. }
  3284. } else if index == 3 {
  3285. let fpath = self.document?.documentURL?.path ?? ""
  3286. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  3287. } else if index == 4 {
  3288. let fpath = self.document?.documentURL?.path ?? ""
  3289. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  3290. } else if index == 5 {
  3291. self.openRightPane()
  3292. return
  3293. }
  3294. } else if type == .measure {
  3295. if !IAPProductsManager.default().isAvailableAllFunction(){
  3296. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3297. winC?.kEventName = "Reading_Measure_BuyNow"
  3298. winC?.showWindow(nil)
  3299. return
  3300. }
  3301. if !self.documentAllowsEdit() {
  3302. return
  3303. }
  3304. self.listView.toolMode = .measureToolMode
  3305. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  3306. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3307. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  3308. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3309. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  3310. areaMeasureInfoWindowController?.hideFloatingWindow()
  3311. }
  3312. if distanceMeasureInfoWindowController == nil {
  3313. let measureInfo = CPDFDistanceMeasureInfo()
  3314. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  3315. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  3316. distanceMeasureInfoWindowController?.delegate = self
  3317. }
  3318. if perimeterMeasureInfoWindowController == nil {
  3319. let measureInfo = CPDFPerimeterMeasureInfo()
  3320. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  3321. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  3322. perimeterMeasureInfoWindowController?.delegate = self
  3323. }
  3324. if areaMeasureInfoWindowController == nil {
  3325. let measureInfo = CPDFAreaMeasureInfo()
  3326. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  3327. areaMeasureInfoWindowController?.measureInfo = measureInfo
  3328. areaMeasureInfoWindowController?.delegate = self
  3329. }
  3330. if index == 1 {
  3331. self.listView.annotationType = .line
  3332. let winW: CGFloat = 300
  3333. let rightW: CGFloat = 270
  3334. var winFrame = self.view.window?.frame ?? .zero
  3335. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3336. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3337. distanceMeasureInfoWindowController?.showWindow(nil)
  3338. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3339. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  3340. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  3341. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  3342. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3343. self.trackEvent(toolMode: .measureToolMode)
  3344. } else if index == 2 {
  3345. self.listView.annotationType = .polyLine
  3346. let winW: CGFloat = 300
  3347. let rightW: CGFloat = 270
  3348. var winFrame = self.view.window?.frame ?? .zero
  3349. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3350. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3351. perimeterMeasureInfoWindowController?.showWindow(nil)
  3352. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3353. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  3354. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3355. self.trackEvent(toolMode: .measureToolMode)
  3356. } else if index == 3 {
  3357. self.listView.annotationType = .polyGon
  3358. let winW: CGFloat = 300
  3359. let rightW: CGFloat = 270
  3360. var winFrame = self.view.window?.frame ?? .zero
  3361. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3362. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3363. areaMeasureInfoWindowController?.showWindow(nil)
  3364. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3365. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3366. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3367. self.trackEvent(toolMode: .measureToolMode)
  3368. } else if index == 4 {
  3369. self.listView.annotationType = .square
  3370. let winW: CGFloat = 300
  3371. let rightW: CGFloat = 270
  3372. var winFrame = self.view.window?.frame ?? .zero
  3373. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3374. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3375. areaMeasureInfoWindowController?.showWindow(nil)
  3376. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3377. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3378. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  3379. self.trackEvent(toolMode: .measureToolMode)
  3380. } else {
  3381. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  3382. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3383. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  3384. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3385. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  3386. areaMeasureInfoWindowController?.hideFloatingWindow()
  3387. }
  3388. }
  3389. self.openRightPane()
  3390. }
  3391. }
  3392. }
  3393. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  3394. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3395. var array: [KMBatchOperateFile] = []
  3396. for fpath in filepaths ?? [] {
  3397. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  3398. array.append(batchOperateFile)
  3399. }
  3400. batchWindowController.switchToOperateType(type, files: array)
  3401. batchWindowController.window?.makeKeyAndOrderFront("")
  3402. }
  3403. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3404. self.toolbarItemClickForExitMode(toolbarItem)
  3405. if let itemID = toolbarItem.itemIdentifier {
  3406. if isMainToolItem(itemID) {
  3407. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3408. openNewWindowAlertWindow()
  3409. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3410. self.changePDFViewGoToPreviousPageAction()
  3411. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3412. let isSelected = toolbarItem.isSelected
  3413. toolbarItem.isSelected = !isSelected
  3414. if toolbarItem.isSelected {
  3415. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  3416. self.openRightPane()
  3417. }else{
  3418. closeRightPane()
  3419. }
  3420. if toolbarItem.isSelected {
  3421. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  3422. }
  3423. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  3424. toolbarItem.isSelected = !toolbarItem.isSelected
  3425. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  3426. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3427. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  3428. }
  3429. toolbarItem.isSelected = !toolbarItem.isSelected
  3430. self.toggleRightPane()
  3431. if self.listView.toolMode == .editPDFToolMode {
  3432. self.editPDFHanddler?.rightSideLastState = toolbarItem.isSelected ? .open : .close
  3433. }
  3434. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  3435. self.listView.toolMode = .redactToolMode
  3436. self.enterRedact()
  3437. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  3438. showOCRWindow()
  3439. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  3440. self.showAITypeChooseView(aiConfigType: .none)
  3441. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  3442. if self.canEnterDigitalSign() == false {
  3443. Task {
  3444. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3445. }
  3446. return
  3447. }
  3448. toolbarItem.isSelected = !toolbarItem.isSelected
  3449. if toolbarItem.isSelected {
  3450. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3451. }
  3452. self.enterDigitalSign()
  3453. } else if itemID == KMDocumentPrintToolbarItemIdentifier {
  3454. self.showPrintWindow()
  3455. } else if itemID == KMDocumentPresentationToolbarItemIdentifier {
  3456. self.togglePresentation(nil)
  3457. } else if itemID == KMDocumentSignToolbarItemIdentifier {
  3458. let isSelected = toolbarItem.isSelected
  3459. toolbarItem.isSelected = !isSelected
  3460. }
  3461. } else {
  3462. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  3463. toolbarItem.isSelected = false
  3464. let windowC = KMToolbarCustomWindowController()
  3465. windowC.resetCallback = { [weak self] in
  3466. }
  3467. self.km_beginSheet(windowC: windowC) { [weak self] resp, obj in
  3468. if resp == .OK {
  3469. }
  3470. }
  3471. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  3472. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  3473. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  3474. self.trackEvent_print()
  3475. self.showPrintWindow()
  3476. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  3477. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  3478. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  3479. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  3480. windowC.callBack = { [weak self] string in
  3481. if (string.isEmpty == false) {
  3482. self?.listView.addTextField(subType: .profile, string: string)
  3483. }
  3484. self?.km_endSheet()
  3485. }
  3486. self.km_beginSheet(windowC: windowC)
  3487. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  3488. toolbarItem.isSelected = !toolbarItem.isSelected
  3489. self.listView.annotationType = .unkown
  3490. if toolbarItem.isSelected {
  3491. self.openRightPane()
  3492. }else{
  3493. closeRightPane()
  3494. }
  3495. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  3496. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  3497. self.listView.takeSnapshot(nil)
  3498. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  3499. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  3500. self.listView.annotationType = .unkown
  3501. self.showTTSWindow()
  3502. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3503. self.showOCRWindow()
  3504. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  3505. toolbarItem.isSelected = false
  3506. self.imageAnnotation(toolbarItem)
  3507. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  3508. self.tableAnnotation(toolbarItem)
  3509. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  3510. self.leftSideViewController.insertPDF(nil)
  3511. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  3512. let windowC = SplitWindowController(document: self.listView.document)
  3513. self.km_beginSheet(windowC: windowC)
  3514. } else if itemID == KMSignDigitalSignToolbarItemIdentifier {
  3515. if self.canEnterDigitalSign() == false {
  3516. Task {
  3517. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3518. }
  3519. return
  3520. }
  3521. toolbarItem.isSelected = !toolbarItem.isSelected
  3522. if toolbarItem.isSelected {
  3523. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3524. }
  3525. self.enterDigitalSign()
  3526. } else if itemID == KMToolbarMeasureItemIdentifier {
  3527. if toolbarItem.isSelected {
  3528. toolbarItem.isSelected = false
  3529. self.listView.toolMode = .textToolMode
  3530. self.listView.annotationType = .unkown
  3531. }
  3532. }
  3533. }
  3534. }
  3535. }
  3536. func openNewWindowAlertWindow() {
  3537. var needShowChooseWindow = false
  3538. //#if VERSION_FREE
  3539. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  3540. needShowChooseWindow = true
  3541. }
  3542. //#endif
  3543. if needShowChooseWindow {
  3544. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  3545. if preferenceNoteShow {
  3546. menuItemAction_newTagPageToNewWindow("")
  3547. } else {
  3548. if !KMDataManager.default.isTabbingWin{
  3549. KMDataManager.default.isTabbingWin = true
  3550. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  3551. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  3552. KMDataManager.default.isTabbingWin = false
  3553. if continueOrNot {
  3554. self?.reopenDocument(forPaths: [])
  3555. } else {
  3556. }
  3557. }
  3558. self.km_beginSheet(windowC: tabbingWin)
  3559. }
  3560. }
  3561. }else{
  3562. handleTabbingLogic()
  3563. }
  3564. }
  3565. func reopenDocument(forPaths paths: [String]) -> Void {
  3566. let browser = KMBrowser.init() as KMBrowser
  3567. browser.windowController = KMBrowserWindowController.init(browser: browser)
  3568. browser.addHomeTabContents()
  3569. browser.windowController.showWindow(self)
  3570. }
  3571. func handleTabbingLogic() {
  3572. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  3573. }
  3574. func showTTSWindow() {
  3575. var lastPDFView: CPDFView?
  3576. let ttsView = KMTTSWindowController.share
  3577. if (ttsView.window?.isVisible ?? false) {
  3578. lastPDFView = ttsView.pdfView
  3579. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  3580. lastPDFView = nil
  3581. ttsView.window?.orderOut(nil)
  3582. } else {
  3583. ttsView.pdfView = self.listView
  3584. ttsView.showWindow(nil)
  3585. }
  3586. } else {
  3587. ttsView.pdfView = self.listView
  3588. ttsView.showWindow(nil)
  3589. }
  3590. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  3591. if isCloseWindow {
  3592. }
  3593. }
  3594. if let currentSelection = self.listView.currentSelection {
  3595. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  3596. ttsView.startSpeakingPDFSelection(currentSelection)
  3597. }
  3598. }
  3599. if let lastPDFView = lastPDFView {
  3600. lastPDFView.setHighlightedSelections([])
  3601. ttsView.stopSpeaking()
  3602. }
  3603. }
  3604. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3605. self.toolbarItemClickForExitMode(toolbarItem)
  3606. let itemId = toolbarItem.itemIdentifier
  3607. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3608. self.clickChildTool(type: .watermark, index: index)
  3609. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  3610. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3611. self.clickChildTool(type: .background, index: index)
  3612. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  3613. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3614. self.clickChildTool(type: .headerAndFooter, index: index)
  3615. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  3616. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3617. self.clickChildTool(type: .bates, index: index)
  3618. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  3619. } else if (toolbarItem.itemIdentifier == KMToolbarMeasureItemIdentifier) {
  3620. self.clickChildTool(type: .measure, index: index)
  3621. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3622. self.clickChildTool(type: .comparison, index: index)
  3623. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3624. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3625. convertToImg(index: index)
  3626. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  3627. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3628. extractImageAction(num: index)
  3629. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3630. self.createPdf(index: index)
  3631. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3632. if index == 2 { // 裁剪当前页面
  3633. self.cropCurrentPage()
  3634. } else if index == 3 { // Auto Crop – Separate
  3635. self.smart_cropAllPage()
  3636. } else if index == 4 { // Auto Crop – Combined
  3637. self.auto_cropAllPage()
  3638. } else if index == 5 { // Select Area
  3639. }
  3640. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  3641. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3642. self.clickChildTool(type: .secure, index: index)
  3643. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  3644. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  3645. if index == 11 {
  3646. self.view.window?.makeFirstResponder(nil)
  3647. let winC = KMSearchReplaceWindowController(with: self.listView, type: .search)
  3648. self.currentWindowController = winC
  3649. winC.replaceCallback = { [weak self] in
  3650. let toolMode = self?.listView.toolMode ?? .none
  3651. let isEditing = self?.listView.isEditing() ?? false
  3652. if toolMode == .editPDFToolMode && isEditing {
  3653. } else { // 进入内容编辑模式
  3654. }
  3655. }
  3656. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  3657. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  3658. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 248 - 16
  3659. let winFramePoint = NSPoint(x: x, y: y)
  3660. winC.window?.setFrameOrigin(winFramePoint)
  3661. winC.startModal(nil)
  3662. } else if index == 12 {
  3663. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3664. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3665. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  3666. winC?.showWindow(nil)
  3667. return
  3668. }
  3669. self.view.window?.makeFirstResponder(nil)
  3670. let toolMode = self.listView.toolMode ?? .none
  3671. let isEditing = self.listView.isEditing() ?? false
  3672. if toolMode == .editPDFToolMode && isEditing {
  3673. } else { // 进入内容编辑模式
  3674. }
  3675. self.trackEvent_replace()
  3676. let winC = KMSearchReplaceWindowController(with: self.listView, type: .replace)
  3677. self.currentWindowController = winC
  3678. winC.replaceCallback = { [weak self] in
  3679. let toolMode = self?.listView.toolMode ?? .none
  3680. let isEditing = self?.listView.isEditing() ?? false
  3681. if toolMode == .editPDFToolMode && isEditing {
  3682. } else { // 进入内容编辑模式
  3683. }
  3684. }
  3685. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  3686. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  3687. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 388
  3688. let winFramePoint = NSPoint(x: x, y: y)
  3689. winC.window?.setFrameOrigin(winFramePoint)
  3690. winC.startModal(nil)
  3691. } else {
  3692. }
  3693. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3694. toolbarItem.isSelected = !toolbarItem.isSelected
  3695. self.toggleRightPane()
  3696. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3697. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3698. self.showOCRWindow()
  3699. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  3700. if index == 1 {
  3701. self.showAITypeChooseView(aiConfigType: .summarize)
  3702. } else if index == 2 {
  3703. self.showAITypeChooseView(aiConfigType: .reWriting)
  3704. } else if index == 3 {
  3705. self.showAITypeChooseView(aiConfigType: .proofreading)
  3706. } else if index == 4 {
  3707. self.showAITypeChooseView(aiConfigType: .translate)
  3708. }
  3709. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  3710. self.showOCRWindow()
  3711. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  3712. self.enterEditPDF()
  3713. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  3714. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  3715. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  3716. if self.canEnterDigitalSign() == false {
  3717. Task {
  3718. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3719. }
  3720. return
  3721. }
  3722. toolbarItem.isSelected = !toolbarItem.isSelected
  3723. if toolbarItem.isSelected {
  3724. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3725. }
  3726. self.enterDigitalSign()
  3727. } else if itemId == KMSignDigitalSignToolbarItemIdentifier {
  3728. if self.canEnterDigitalSign() == false {
  3729. Task {
  3730. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3731. }
  3732. return
  3733. }
  3734. toolbarItem.isSelected = !toolbarItem.isSelected
  3735. if toolbarItem.isSelected {
  3736. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3737. }
  3738. self.enterDigitalSign()
  3739. } else if itemId == KMDocumentAIToolsToolbarItemIdentifier {
  3740. self.showAITypeChooseView(aiConfigType: .none)
  3741. } else if itemId == KMToolbarToolCompressItemIdentifier {
  3742. self.clickChildTool(type: .compress, index: 0)
  3743. } else if itemId == KMToolbarPageEditSplitItemIdentifier { // 拆分
  3744. let windowC = SplitWindowController(document: self.listView.document)
  3745. self.km_beginSheet(windowC: windowC)
  3746. } else if itemId == KMToolbarToolMergeItemIdentifier {
  3747. self.clickChildTool(type: .merge, index: 0)
  3748. } else if itemId == KMToolbarPageEditInsetItemIdentifier {
  3749. self.leftSideViewController.insertPDF(nil)
  3750. } else if itemId == KMToolbarShowToolbarItemIdentifier {
  3751. self.showOrHideNotes()
  3752. } else if itemId == KMAnnotationTableToolbarItemIdentifier {
  3753. self.tableAnnotation(toolbarItem)
  3754. } else if itemId == KMToolbarConversionTextItemIdentifier {
  3755. self.clickChildTool(type: .conversion_text, index: 0)
  3756. } else if itemId == KMToolbarConversionHTMLItemIdentifier {
  3757. self.clickChildTool(type: .html, index: 0)
  3758. } else if itemId == KMToolbarConversionCSVItemIdentifier {
  3759. self.clickChildTool(type: .csv, index: 0)
  3760. } else if itemId == KMToolbarConversionRTFItemIdentifier {
  3761. self.clickChildTool(type: .rtf, index: 0)
  3762. } else if itemId == KMToolbarConversionPPTItemIdentifier {
  3763. self.clickChildTool(type: .ppt, index: 0)
  3764. } else if itemId == KMToolbarConversionExcelItemIdentifier {
  3765. self.clickChildTool(type: .excel, index: 0)
  3766. } else if itemId == KMToolbarConversionWordItemIdentifier {
  3767. self.clickChildTool(type: .word, index: 0)
  3768. } else if itemId == KMToolbarConversionOtherItemIdentifier {
  3769. if index == KMPDFConvertType.text.rawValue {
  3770. self.clickChildTool(type: .conversion_text, index: 0)
  3771. } else if index == KMPDFConvertType.rtf.rawValue {
  3772. self.clickChildTool(type: .rtf, index: 0)
  3773. } else if index == KMPDFConvertType.html.rawValue {
  3774. self.clickChildTool(type: .html, index: 0)
  3775. } else if index == KMPDFConvertType.csv.rawValue {
  3776. self.clickChildTool(type: .csv, index: 0)
  3777. } else if index == KMPDFConvertType.json.rawValue {
  3778. self.clickChildTool(type: .json, index: 0)
  3779. }
  3780. }
  3781. }
  3782. func convertToImg(index: Int) {
  3783. var convertT: KMConvertType = .JPEG
  3784. switch index {
  3785. case 7:
  3786. convertT = .JPEG
  3787. case 8:
  3788. convertT = .JPG
  3789. case 9:
  3790. convertT = .PNG
  3791. case 10:
  3792. convertT = .GIF
  3793. case 11:
  3794. convertT = .TIFF
  3795. case 12:
  3796. convertT = .TGA
  3797. case 13:
  3798. convertT = .BMP
  3799. default:
  3800. convertT = .JPEG
  3801. }
  3802. showAllConvertWindow(convertT: convertT)
  3803. }
  3804. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  3805. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3806. self.search(searchString: searchString, isCase: caseInsensitive, display: false)
  3807. var row = max(searchIndex - 1, 0)
  3808. if forward {
  3809. row = searchIndex + 1
  3810. }
  3811. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  3812. let model = self.searchResults[row]
  3813. if model.selection != nil {
  3814. self.listView.setHighlightedSelections([])
  3815. self.listView.go(to: model.selection, animated: true)
  3816. self.listView.setHighlightedSelection(model.selection, animated: true)
  3817. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3818. searchIndex = row
  3819. }
  3820. }
  3821. self.leftSideViewController.showSearchMode(searchString)
  3822. }
  3823. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  3824. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3825. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  3826. var row = max(searchIndex - 1, 0)
  3827. if forward {
  3828. row = searchIndex + 1
  3829. }
  3830. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  3831. let model = self.searchResults[row]
  3832. if model.selection != nil {
  3833. self.listView.setHighlightedSelections([])
  3834. self.listView.go(to: model.selection, animated: true)
  3835. self.listView.setHighlightedSelection(model.selection, animated: true)
  3836. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3837. searchIndex = row
  3838. }
  3839. }
  3840. }
  3841. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  3842. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3843. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  3844. self.leftSideViewController.showSearchMode(searchString)
  3845. }
  3846. func toolbarViewController(_ viewController: KMToolbarViewController, viewItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3847. let itemId = toolbarItem.itemIdentifier
  3848. if itemId == KMDocumentFirstLastToolbarItemIdentifier {
  3849. if index == 1 {
  3850. if self.listView.canGoToFirstPage() {
  3851. self.listView.goToFirstPage(nil)
  3852. }
  3853. } else if index == 2 {
  3854. if self.listView.canGoToLastPage() {
  3855. self.listView.goToLastPage(nil)
  3856. }
  3857. }
  3858. } else if itemId == KMDocumentPageInputToolbarItemIdentifier {
  3859. var valid = false
  3860. if let number = Int(info as? String ?? "") {
  3861. let cnt = self.listView.document?.pageCount ?? 0
  3862. if number > 0 && number <= cnt {
  3863. self.listView.go(toPageIndex: number-1, animated: false)
  3864. valid = true
  3865. }
  3866. }
  3867. if valid == false {
  3868. Task {@MainActor in
  3869. _ = await KMAlertTool.runModel(message: NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))
  3870. }
  3871. }
  3872. }
  3873. }
  3874. }
  3875. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  3876. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  3877. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  3878. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  3879. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  3880. distanceSettingWC.delegate = self
  3881. distanceSettingWC.startModal("")
  3882. }
  3883. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  3884. }
  3885. }
  3886. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  3887. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  3888. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  3889. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  3890. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  3891. distanceSettingWC.delegate = self
  3892. distanceSettingWC.startModal("")
  3893. }
  3894. }
  3895. // MARK: CAreaMeasureInfoWindowControllerDelegate
  3896. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  3897. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  3898. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  3899. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  3900. areaSettingWC.delegate = self
  3901. areaSettingWC.startModal("")
  3902. }
  3903. }
  3904. // MARK: CDistanceSettingWindowControllerDelegate
  3905. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  3906. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  3907. if distanceMeasureInfo != nil {
  3908. if self.listView.activeAnnotations.count > 0 {
  3909. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  3910. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  3911. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3912. }
  3913. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  3914. } else {
  3915. distanceMeasureInfo?.leadLength = 0
  3916. self.listView.distanceMeasureInfo = distanceMeasureInfo
  3917. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  3918. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3919. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  3920. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  3921. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  3922. }
  3923. if let data = self.listView.activeAnnotation {
  3924. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  3925. }
  3926. }
  3927. self.distanceMeasureInfoWindowController?.showWindow(self)
  3928. }
  3929. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  3930. if perimeterMeasureInfo != nil {
  3931. if self.listView.activeAnnotations.count > 0 {
  3932. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  3933. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  3934. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3935. }
  3936. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  3937. } else {
  3938. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  3939. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  3940. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3941. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  3942. }
  3943. if let data = self.listView.activeAnnotation {
  3944. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  3945. }
  3946. }
  3947. self.perimeterMeasureInfoWindowController?.showWindow(self)
  3948. }
  3949. }
  3950. // MARK: CAreaSettingWindowControllerDelegate
  3951. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  3952. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  3953. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  3954. if measureInfo != nil {
  3955. if self.listView.activeAnnotations.count > 0 {
  3956. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  3957. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  3958. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3959. }
  3960. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  3961. } else {
  3962. self.listView.squareAreaMeasureInfo = measureInfo
  3963. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  3964. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3965. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3966. }
  3967. }
  3968. self.areaMeasureInfoWindowController?.showWindow(self)
  3969. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  3970. if measureInfo != nil {
  3971. if self.listView.activeAnnotations.count > 0 {
  3972. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  3973. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  3974. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3975. }
  3976. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  3977. } else {
  3978. self.listView.polygonAreaMeasureInfo = measureInfo
  3979. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  3980. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3981. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3982. }
  3983. }
  3984. self.areaMeasureInfoWindowController?.showWindow(self)
  3985. } else {
  3986. if measureInfo != nil {
  3987. if self.listView.activeAnnotations.count > 0 {
  3988. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  3989. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  3990. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3991. }
  3992. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  3993. }
  3994. }
  3995. self.areaMeasureInfoWindowController?.showWindow(self)
  3996. }
  3997. if measureInfo != nil {
  3998. if let data = self.listView.activeAnnotation {
  3999. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4000. }
  4001. }
  4002. }
  4003. }
  4004. //MARK: LeftSideViewController
  4005. extension KMMainViewController {
  4006. func leftSideViewCancelSelect() {
  4007. if self.listView.isEditing() == true {
  4008. if self.listView.editingAreas() != nil &&
  4009. self.listView.editingAreas().count != 0 {
  4010. let areas = self.listView.editingAreas().first
  4011. if areas is CPDFEditTextArea {
  4012. self.listView.clearEditingSelectCharItem()
  4013. self.listView.updateEditing([])
  4014. KMPrint("取消选中")
  4015. }
  4016. }
  4017. }
  4018. }
  4019. }
  4020. // MARK: - Analytics (埋点)
  4021. extension KMMainViewController {
  4022. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  4023. if (type == .Annatiton) {
  4024. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  4025. } else if (type == .editPDF) {
  4026. } else if (type == .Page) {
  4027. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  4028. } else if (type == .Conversion) {
  4029. } else if (type == .Tool) {
  4030. }
  4031. }
  4032. func trackEvent_aiTranslate() -> Void {
  4033. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  4034. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4035. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4036. }
  4037. func trackEvent_print() -> Void {
  4038. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  4039. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4040. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4041. }
  4042. func trackEvent_share() -> Void {
  4043. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  4044. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4045. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4046. }
  4047. func trackEvent_upgrade() -> Void {
  4048. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  4049. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4050. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4051. }
  4052. func trackEvent(annotationType type: CAnnotationType) -> Void {
  4053. if (type == .highlight) {
  4054. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  4055. } else if (type == .underline) {
  4056. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  4057. } else if (type == .strikeOut) {
  4058. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  4059. } else if (type == .ink) {
  4060. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  4061. } else if (type == .freeText) {
  4062. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  4063. } else if (type == .anchored) {
  4064. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  4065. } else if (type == .square) {
  4066. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  4067. } else if (type == .link) {
  4068. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  4069. } else if (type == .stamp) {
  4070. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  4071. } else if (type == .signSignature) {
  4072. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  4073. } else if (type == .circle) {
  4074. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  4075. } else if (type == .arrow) {
  4076. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  4077. } else if (type == .line) {
  4078. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  4079. } else if (type == .addText) {
  4080. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  4081. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4082. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4083. } else if (type == .addImage) {
  4084. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  4085. } else if (type == .textField) {
  4086. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  4087. } else if (type == .checkBox) {
  4088. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  4089. } else if (type == .radioButton) {
  4090. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  4091. } else if (type == .listMenu) {
  4092. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  4093. } else if (type == .comboBox) {
  4094. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  4095. } else if (type == .actionButton) {
  4096. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4097. } else if (type == .actionButton) {
  4098. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4099. } else if (type == .signature) {
  4100. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  4101. } else if (type == .squiggly) {
  4102. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  4103. } else if (type == .eraser) {
  4104. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  4105. }
  4106. }
  4107. func trackEvent(toolMode mode: CToolMode) -> Void {
  4108. if (mode == .selectToolMode) {
  4109. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  4110. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4111. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4112. } else if (mode == .moveToolMode) {
  4113. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  4114. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4115. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4116. } else if mode == .measureToolMode {
  4117. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  4118. }
  4119. }
  4120. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  4121. if (type == .word) {
  4122. } else if (type == .excel) {
  4123. } else if (type == .ppt) {
  4124. } else if (type == .rtf) {
  4125. } else if (type == .csv) {
  4126. } else if (type == .html) {
  4127. } else if (type == .conversion_text) {
  4128. } else if (type == .conversion_image) {
  4129. } else if (type == .compress) {
  4130. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  4131. } else if (type == .merge) {
  4132. } else if (type == .secure) {
  4133. } else if (type == .crop) {
  4134. } else if type == .json {
  4135. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  4136. }
  4137. }
  4138. func trackEvent_setPassword() -> Void {
  4139. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  4140. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4141. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4142. }
  4143. func trackEvent_removePassword() -> Void {
  4144. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  4145. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4146. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4147. }
  4148. func trackEvent_replace() -> Void {
  4149. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  4150. }
  4151. }
  4152. extension KMMainViewController {
  4153. //文件对比
  4154. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  4155. self.isCompareModel = true
  4156. let compareContentView = KMCompareContentView()
  4157. compareContentView.oldDocument = oldDocument
  4158. compareContentView.document = document
  4159. compareContentView.compareResults = results
  4160. compareContentView.saveHandle = { [unowned self] view in
  4161. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  4162. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  4163. self.currentWindowController = saveController
  4164. saveController.cancelHandle = { [unowned self] controller in
  4165. self.view.window!.endSheet(controller.window!)
  4166. self.currentWindowController = nil
  4167. }
  4168. saveController.saveHandle = { [unowned self] controller, saveType in
  4169. let folderPath = controller.fileSaveFolderPath
  4170. if folderPath != nil {
  4171. if !FileManager.default.fileExists(atPath: folderPath) {
  4172. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  4173. }
  4174. #if VERSION_DMG
  4175. #else
  4176. let url = URL(fileURLWithPath: folderPath)
  4177. let fileAccess = AppSandboxFileAccess()
  4178. fileAccess?.persistPermissionURL(url)
  4179. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  4180. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  4181. let urlString = url.path
  4182. let _url = URL(fileURLWithPath: urlString)
  4183. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  4184. }
  4185. #endif
  4186. var savePath: String
  4187. switch saveType {
  4188. case 0:
  4189. let filePath = oldDocument.documentURL.path
  4190. let fileName = filePath.deletingPathExtension.lastPathComponent
  4191. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4192. savePath = self.getValidFilePath(savePath)
  4193. oldDocument.write(to: URL(fileURLWithPath: savePath))
  4194. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4195. case 1:
  4196. let filePath = document.documentURL.path
  4197. let fileName = filePath.deletingPathExtension.lastPathComponent
  4198. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4199. savePath = self.getValidFilePath(savePath)
  4200. document.write(to: URL(fileURLWithPath: savePath))
  4201. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4202. case 2:
  4203. let filePath = oldDocument.documentURL.path
  4204. let fileName = filePath.deletingPathExtension.lastPathComponent
  4205. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  4206. savePath = self.getValidFilePath(savePath)
  4207. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  4208. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4209. default:
  4210. break
  4211. }
  4212. }
  4213. self.view.window!.endSheet(controller.window!)
  4214. self.currentWindowController = nil
  4215. }
  4216. NSWindow.currentWindow().beginSheet(saveController.window!)
  4217. }
  4218. }
  4219. compareContentView.closeHandle = { [unowned self] view in
  4220. self.isCompareModel = false
  4221. view.removeFromSuperview()
  4222. }
  4223. compareContentView.autoresizingMask = [.width,.height]
  4224. }
  4225. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  4226. self.isCompareModel = true
  4227. let coveringView = KMCompareCoveringView()
  4228. coveringView.pdfDocument = pdfDocument
  4229. coveringView.closeHandle = { [unowned self] view in
  4230. self.isCompareModel = false
  4231. view.removeFromSuperview()
  4232. }
  4233. coveringView.saveHandle = { [unowned self] view in
  4234. let savePanel = NSSavePanel()
  4235. savePanel.nameFieldStringValue = "untitled"
  4236. savePanel.allowedFileTypes = ["pdf"]
  4237. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  4238. if result == .OK {
  4239. pdfDocument.write(to: savePanel.url!)
  4240. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  4241. }
  4242. }
  4243. }
  4244. coveringView.autoresizingMask = [.width,.height]
  4245. }
  4246. func getValidFilePath(_ oldPath: String) -> String {
  4247. let fileManager = FileManager.default
  4248. do {
  4249. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  4250. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  4251. return oldPath
  4252. }
  4253. var i = 1
  4254. var newPath = oldPath
  4255. while fileManager.fileExists(atPath: newPath) {
  4256. if fileType == FileAttributeType.typeDirectory.rawValue {
  4257. newPath = oldPath + "(\(i))"
  4258. } else {
  4259. let fileExtension = (oldPath as NSString).pathExtension
  4260. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  4261. }
  4262. i += 1
  4263. }
  4264. return newPath
  4265. } catch {
  4266. print("Error getting file attributes: \(error)")
  4267. return oldPath
  4268. }
  4269. }
  4270. }
  4271. extension KMMainViewController {
  4272. func documentAllowsEdit() -> Bool {
  4273. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  4274. let alert = NSAlert()
  4275. alert.alertStyle = .critical
  4276. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  4277. alert.runModal()
  4278. return false
  4279. } else {
  4280. return true
  4281. }
  4282. }
  4283. func changeFont(_ sender: NSFontManager) {
  4284. KMPrint("changeFont ...")
  4285. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  4286. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  4287. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  4288. font = sender.convert(font!)
  4289. annotation.fontSize = font?.pointSize ?? 12
  4290. self.listView.commitEditAnnotationFreeText(annotation)
  4291. self.listView.setNeedsDisplay(annotation)
  4292. }
  4293. }
  4294. func currentSetup() -> [String: Any] {
  4295. var setup: [String: Any] = [:]
  4296. var point = NSZeroPoint
  4297. if listView == nil {
  4298. return setup
  4299. }
  4300. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  4301. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  4302. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  4303. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  4304. setup[KMMainModel.Key.pageIndex] = pageIndex
  4305. return setup
  4306. }
  4307. // MARK: - Recommond活动
  4308. func loadRecommondPopWindow() {
  4309. if IAPProductsManager.default().isAvailableAllFunction() {
  4310. return
  4311. }
  4312. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  4313. if recommondPopWindowVC == nil {
  4314. recommondPopWindowVC = KMRecommondPopWindow.default()
  4315. }
  4316. recommondPopWindowVC?.recommondInfo = info
  4317. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  4318. return
  4319. }
  4320. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  4321. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  4322. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  4323. recommondPopWindowVC?.window?.orderFront((Any).self)
  4324. recommondPopWindowVC?.window?.becomeMain()
  4325. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  4326. UserDefaults.standard.synchronize()
  4327. }
  4328. }
  4329. @objc func didAddContentViewNotification(_ sender: Notification) {
  4330. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  4331. return
  4332. }
  4333. if self.interactionMode == .presentation {
  4334. }
  4335. }
  4336. @objc func purchaseStateUpdateNoti() {
  4337. if IAPProductsManager.default().isAvailableAllFunction() {
  4338. }
  4339. }
  4340. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  4341. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  4342. guard let anno = sender.object as? CPDFAnnotation else {
  4343. return
  4344. }
  4345. if anno.page?.document != self.listView.document {
  4346. return
  4347. }
  4348. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  4349. }
  4350. // MARK: Split View
  4351. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  4352. let openPanel = NSOpenPanel()
  4353. openPanel.allowedFileTypes = ["pdf", "PDF"]
  4354. openPanel.allowsMultipleSelection = false
  4355. guard let mainWindow = NSApp.mainWindow else {
  4356. return
  4357. }
  4358. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  4359. if response == NSApplication.ModalResponse.OK {
  4360. guard let url = openPanel.url else {
  4361. return
  4362. }
  4363. if let document = CPDFDocument(url: url) {
  4364. replaceBlock(document.documentURL?.path ?? "")
  4365. } else {
  4366. let alert = NSAlert()
  4367. alert.alertStyle = .critical
  4368. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  4369. alert.runModal()
  4370. }
  4371. }
  4372. }
  4373. }
  4374. }