KMMainViewController+Action.swift 245 KB

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