KMMainViewController+Action.swift 209 KB

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