KMMainViewController+Action.swift 210 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let isEditing = self.listView.isEditing() ?? false
  11. if isEditing {
  12. if searchString.isEmpty {
  13. self.listView.setHighlightedSelection(nil, animated: false)
  14. self.leftSideViewController.searchResults = []
  15. if display {
  16. if self.leftSideViewController.findPaneState == .singular {
  17. self.leftSideViewController.displayFindViewAnimating(true)
  18. } else {
  19. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  20. }
  21. }
  22. return
  23. }
  24. let isWholeWord = self.leftSideViewController.mwcFlags.wholeWordSearch == 1
  25. var opt = CPDFSearchOptions()
  26. if isCase == false {
  27. opt.insert(.caseSensitive)
  28. }
  29. if isWholeWord {
  30. opt.insert(.matchWholeWord)
  31. }
  32. let datas = self.srHanddler.pdfView?.document.findEditAllPageString(searchString, with: opt) ?? []
  33. if let sel = datas.first?.first {
  34. self.srHanddler.showSelection(sel)
  35. }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in datas {
  39. for selection in selections {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = selection
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  43. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  44. self.searchResults.insert(mode, at: self.searchResults.count)
  45. _selections.append(selection)
  46. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  47. }
  48. }
  49. if needShowAll {
  50. self.listView.setHighlightedSelections(_selections)
  51. }
  52. if _selections.isEmpty {
  53. self.listView.setHighlightedSelection(nil, animated: false)
  54. }
  55. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  56. self.leftSideViewController.searchResults = self.searchResults
  57. if display {
  58. if self.leftSideViewController.findPaneState == .singular {
  59. self.leftSideViewController.displayFindViewAnimating(true)
  60. } else {
  61. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  62. }
  63. }
  64. return
  65. }
  66. let document = self.listView.document
  67. if let data = document?.isFinding, data {
  68. document?.cancelFindString()
  69. }
  70. if searchString == "" {
  71. self.searchResults = []
  72. self.leftSideViewController.searchResults = self.searchResults
  73. self.listView.setHighlightedSelections([])
  74. self.listView.setHighlightedSelection(nil, animated: false)
  75. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  76. } else {
  77. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  78. var findArray : [[CPDFSelection]]
  79. if isCase {
  80. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  81. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  82. } else {
  83. findArray = self.listView.document.findString(searchString) ?? []
  84. }
  85. } else {
  86. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  87. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  88. } else {
  89. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  90. }
  91. }
  92. self.searchResults.removeAll()
  93. var _selections: [CPDFSelection] = []
  94. for selections in findArray {
  95. for selection in selections {
  96. let mode : KMSearchMode = KMSearchMode()
  97. mode.selection = selection
  98. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  99. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  100. self.searchResults.insert(mode, at: self.searchResults.count)
  101. _selections.append(selection)
  102. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  103. }
  104. }
  105. if needShowAll {
  106. self.listView.setHighlightedSelections(_selections)
  107. }
  108. if _selections.isEmpty {
  109. self.listView.setHighlightedSelection(nil, animated: false)
  110. }
  111. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  112. self.leftSideViewController.searchResults = self.searchResults
  113. }
  114. if display {
  115. if self.leftSideViewController.findPaneState == .singular {
  116. self.leftSideViewController.displayFindViewAnimating(true)
  117. } else {
  118. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  119. }
  120. }
  121. }
  122. func removeSignatures(signatures:[CPDFSignature]) {
  123. for signature in signatures {
  124. self.listView.document.removeSignature(signature)
  125. }
  126. for i in 0..<self.listView.document.pageCount {
  127. 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. // 开启/关闭右边栏
  1485. @objc func toggleRightPane() -> Void {
  1486. }
  1487. func rename(_ sender: NSNotification) -> Void {
  1488. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1489. return
  1490. }
  1491. let tabController = sender.object as? CTTabController
  1492. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  1493. if let doc = self.myDocument, doc.isDocumentEdited {
  1494. Task {
  1495. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  1496. if resp != .alertFirstButtonReturn { // 取消
  1497. return
  1498. }
  1499. doc.updateChangeCount(.changeCleared)
  1500. self.document?.write(to: doc.fileURL)
  1501. Task { @MainActor in
  1502. self._renameForSavePanel(tabController)
  1503. }
  1504. }
  1505. return
  1506. }
  1507. self._renameForSavePanel(tabController)
  1508. }
  1509. }
  1510. func savePdfAlertView() {
  1511. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  1512. return
  1513. }
  1514. AutoSaveManager.manager.isSaveNoti = true
  1515. var num = 0
  1516. if self.listView.document != nil{
  1517. num = Int(self.listView.document.pageCount)
  1518. }
  1519. if Thread.current.isMainThread {
  1520. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1521. } else {
  1522. DispatchQueue.main.async {
  1523. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1524. }
  1525. }
  1526. }
  1527. func savePdfFinishAlertView() {
  1528. if !AutoSaveManager.manager.isSaveNoti{
  1529. return
  1530. }
  1531. AutoSaveManager.manager.isSaveNoti = false
  1532. if Thread.current.isMainThread {
  1533. self.dismissProgressSheet()
  1534. } else {
  1535. DispatchQueue.main.async {
  1536. self.dismissProgressSheet()
  1537. }
  1538. }
  1539. }
  1540. private func _renameForSavePanel(_ tabC: CTTabController?) {
  1541. let outputSavePanel = NSSavePanel()
  1542. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1543. outputSavePanel.allowedFileTypes = ["pdf"]
  1544. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1545. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1546. let resp = outputSavePanel.runModal()
  1547. if resp == .OK {
  1548. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1549. let fileURL = pdfDocument?.documentURL
  1550. let fileManager = FileManager.default
  1551. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1552. var result = true
  1553. do {
  1554. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1555. } catch {
  1556. result = false
  1557. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1558. }
  1559. if (result) {
  1560. tabC?.title = outputSavePanel.url!.lastPathComponent
  1561. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1562. self.model.isSaveKeyChain = false
  1563. newPdfDocument.unlock(withPassword: self.document?.password)
  1564. if (newPdfDocument.pageCount > 0) {
  1565. self.setDocument = newPdfDocument
  1566. }
  1567. }
  1568. }
  1569. } else {
  1570. outputSavePanel.close()
  1571. }
  1572. }
  1573. func showInFinder(_ sender: Any) -> Void {
  1574. if sender is NSNotification {
  1575. let tabController = (sender as! NSNotification).object as? CTTabController
  1576. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  1577. if tabController?.title == path {
  1578. if let file = self.myDocument?.fileURL {
  1579. if FileManager.default.fileExists(atPath: file.path) {
  1580. NSWorkspace.shared.activateFileViewerSelecting([file])
  1581. }
  1582. }
  1583. }
  1584. } else {
  1585. guard let url = self.myDocument?.fileURL else { return }
  1586. let file: URL = url
  1587. if FileManager.default.fileExists(atPath: file.path) {
  1588. NSWorkspace.shared.activateFileViewerSelecting([file])
  1589. }
  1590. }
  1591. }
  1592. func showOrHideNotes() {
  1593. self.listView.hideNotes = !self.listView.hideNotes
  1594. for note in self.listView.notes as? [CPDFAnnotation] ?? [] {
  1595. if note.isForm() {
  1596. note.setAnnotationShouldDisplay(true)
  1597. note.setHidden(false)
  1598. }
  1599. }
  1600. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  1601. self.leftSideViewController.note_reloadDataIfNeed()
  1602. }
  1603. func closeTab(_ sender: NSNotification) -> Void {
  1604. }
  1605. @IBAction func toggleSplitPDF(_ sender: Any) {
  1606. if let menuItem = sender as? NSMenuItem {
  1607. splitView(withTag: menuItem.tag)
  1608. }
  1609. }
  1610. func changeLineAttribute(_ sender: Any?) {
  1611. var inspector = sender as? KMLineInspector
  1612. if inspector == nil {
  1613. inspector = KMLineInspector.shared
  1614. }
  1615. let action = inspector?.currentLineChangeAction ?? .no
  1616. for annotation in self.listView.activeAnnotations {
  1617. guard let anno = annotation as? CPDFAnnotation else {
  1618. continue
  1619. }
  1620. if anno.hasBorder() {
  1621. switch (action) {
  1622. case .lineWidth:
  1623. anno.setLineWidth(inspector?.lineWidth ?? 0)
  1624. break
  1625. case .style:
  1626. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  1627. break
  1628. case .dashPattern:
  1629. anno.setDashPattern(inspector?.dashPattern ?? [])
  1630. break
  1631. case .startLineStyle:
  1632. if anno.isLine() {
  1633. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  1634. }
  1635. break
  1636. case .endLineStyle:
  1637. if anno.isLine() {
  1638. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  1639. }
  1640. break
  1641. case .no:
  1642. break
  1643. }
  1644. }
  1645. }
  1646. }
  1647. // MARK: -
  1648. // MARK: 显示窗口
  1649. internal func showCompressWindow(url: URL? = nil) {
  1650. self.compressWIndowControllerNew = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  1651. self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  1652. self.compressWIndowControllerNew?.password = self.listView.document?.password ?? ""
  1653. self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  1654. self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  1655. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1656. }
  1657. self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  1658. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1659. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1660. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  1661. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1662. batchWindowController.window?.makeKeyAndOrderFront("")
  1663. }
  1664. self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  1665. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1666. if (result) {
  1667. if (openDocument) {
  1668. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1669. } else {
  1670. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1671. }
  1672. } else {
  1673. let alert = NSAlert()
  1674. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1675. alert.runModal()
  1676. }
  1677. }
  1678. }
  1679. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1680. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1681. KMPrint("转档窗口已显示")
  1682. return
  1683. }
  1684. var convertT: KMConvertType = .Word
  1685. var windowController: KMConvertBaseWindowController?
  1686. if (type == .word) { /// Word
  1687. convertT = .Word
  1688. windowController = KMConvertWordWindowController()
  1689. } else if (type == .excel) {
  1690. convertT = .Excel
  1691. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1692. if (type == .ppt) {
  1693. convertT = .PPT
  1694. } else if (type == .rtf) {
  1695. convertT = .RTF
  1696. } else if (type == .html) {
  1697. convertT = .HTML
  1698. } else if (type == .conversion_text) {
  1699. convertT = .Text
  1700. }
  1701. } else if (type == .csv) {
  1702. convertT = .CSV
  1703. } else if (type == .conversion_image) {
  1704. windowController = KMConvertImageWindowController()
  1705. convertT = .JPEG
  1706. } else if type == .json {
  1707. convertT = .Json
  1708. }
  1709. var url: URL?
  1710. if (documentUrl != nil) {
  1711. url = documentUrl
  1712. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1713. } else {
  1714. url = self.listView.document.documentURL
  1715. }
  1716. let model = KMDocumentModel(url: url!)
  1717. windowController?.documentModel = model
  1718. self.km_safe_beginSheet(windowC: windowController)
  1719. }
  1720. //MARK: 转档 -
  1721. func showAllConvertWindow(convertT: KMConvertType) {
  1722. self.ConvertTrackEvent(type: convertT)
  1723. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1724. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1725. var type: KMConvertWithPDFType = .WordAdvance
  1726. switch convertT {
  1727. case .Word:
  1728. break
  1729. case .Excel:
  1730. type = .Excel
  1731. case .PPT:
  1732. type = .PowerPoint
  1733. case .RTF:
  1734. type = .RTF
  1735. case .CSV:
  1736. type = .CSV
  1737. case .HTML:
  1738. type = .HTML
  1739. case .Text:
  1740. type = .Text
  1741. case .JPEG:
  1742. type = .JPEG
  1743. case .PNG:
  1744. type = .PNG
  1745. case .GIF:
  1746. type = .GIF
  1747. case .JPG:
  1748. type = .JPG
  1749. case .TIFF:
  1750. type = .TIFF
  1751. case .TGA:
  1752. type = .TGA
  1753. case .BMP:
  1754. type = .BMP
  1755. case .JP2:
  1756. type = .JPEG2000
  1757. case .AdvancedWord:
  1758. break
  1759. case .Json:
  1760. type = .Json
  1761. break
  1762. default:
  1763. break
  1764. }
  1765. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1766. var needShowHint = false
  1767. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1768. needShowHint = true
  1769. } else {
  1770. var needContinue = false
  1771. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1772. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1773. let ss = self.document?.documentURL.path
  1774. if arr.contains(ss!) {
  1775. needContinue = false
  1776. }else {
  1777. needContinue = true
  1778. }
  1779. }else {
  1780. needContinue = true
  1781. }
  1782. if needContinue {
  1783. let ss = self.document?.documentURL.path
  1784. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1785. file.password = document?.password ?? ""
  1786. KMBatchOperateManager.defaultManager.files?.append(file)
  1787. }
  1788. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1789. batchWindowController.switchToConvertType(convertType: type)
  1790. }
  1791. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1792. if needShowHint {
  1793. batchWindowController.showIsConvertingHint()
  1794. } else {
  1795. }
  1796. }
  1797. }
  1798. self.km_beginSheet(windowC: convertWC)
  1799. }
  1800. func ConvertTrackEvent(type: KMConvertType) {
  1801. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  1802. switch type {
  1803. case .Word:
  1804. eventStr = "Btn_SubTbr_Converter_ToWord"
  1805. break
  1806. case .Excel:
  1807. eventStr = "Btn_SubTbr_Converter_ToExcel"
  1808. case .PPT:
  1809. eventStr = "Btn_SubTbr_Converter_ToPPT"
  1810. case .RTF:
  1811. eventStr = "Btn_SubTbr_Converter_ToRTF"
  1812. case .CSV:
  1813. eventStr = "Btn_SubTbr_Converter_ToCSV"
  1814. case .HTML:
  1815. eventStr = "Btn_SubTbr_Converter_ToHTML"
  1816. case .Text:
  1817. eventStr = "Btn_SubTbr_Converter_ToText"
  1818. case .JPEG:
  1819. eventStr = "Btn_SubTbr_Converter_ToImage"
  1820. case .PNG:
  1821. eventStr = "Btn_SubTbr_Converter_ToImage"
  1822. case .GIF:
  1823. eventStr = "Btn_SubTbr_Converter_ToImage"
  1824. case .JPG:
  1825. eventStr = "Btn_SubTbr_Converter_ToImage"
  1826. case .TIFF:
  1827. eventStr = "Btn_SubTbr_Converter_ToImage"
  1828. case .TGA:
  1829. eventStr = "Btn_SubTbr_Converter_ToImage"
  1830. case .BMP:
  1831. eventStr = "Btn_SubTbr_Converter_ToImage"
  1832. case .JP2:
  1833. eventStr = "Btn_SubTbr_Converter_ToImage"
  1834. case .AdvancedWord:
  1835. eventStr = "Btn_SubTbr_Converter_ToWord"
  1836. break
  1837. default:
  1838. break
  1839. }
  1840. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  1841. }
  1842. //MARK: 转档 - OCR
  1843. func showOCRWindow() {
  1844. if !IAPProductsManager.default().isAvailableAllFunction(){
  1845. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1846. winC?.showWindow(nil)
  1847. return
  1848. }
  1849. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  1850. com.currentIndexPage = self.listView.currentPageIndex
  1851. self.km_beginSheet(windowC: com)
  1852. }
  1853. //MARK: 导出图片
  1854. func extractImageAction(num: Int) {
  1855. if !IAPProductsManager.default().isAvailableAllFunction(){
  1856. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1857. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  1858. winC?.showWindow(nil)
  1859. return
  1860. }
  1861. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  1862. let alert = NSAlert()
  1863. alert.alertStyle = .critical
  1864. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1865. alert.runModal()
  1866. return
  1867. }
  1868. let document = self.listView.document
  1869. var fileURL = document?.documentURL
  1870. if num == 1 {
  1871. let pageCount = document?.pageCount ?? 0
  1872. let indeSet = NSMutableIndexSet()
  1873. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  1874. if indeSet.count == 0 {
  1875. return
  1876. }
  1877. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  1878. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  1879. let outputSavePanel = NSSavePanel()
  1880. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  1881. outputSavePanel.allowsOtherFileTypes = true
  1882. outputSavePanel.isExtensionHidden = true
  1883. outputSavePanel.canCreateDirectories = true
  1884. outputSavePanel.nameFieldStringValue = tFileName
  1885. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  1886. if result == NSApplication.ModalResponse.OK {
  1887. DispatchQueue.main.async {
  1888. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  1889. let tDestFile = outputSavePanel.url!.path
  1890. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  1891. let pdfconverter = PDFConvertObject()
  1892. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  1893. self.dismissProgressSheet()
  1894. let fileManager = FileManager.default
  1895. if fileManager.fileExists(atPath: tDestFile) {
  1896. let workspace = NSWorkspace.shared
  1897. let url = URL(fileURLWithPath: tDestFile)
  1898. workspace.activateFileViewerSelecting([url])
  1899. }
  1900. }
  1901. }
  1902. })
  1903. return
  1904. }
  1905. if fileURL != nil {
  1906. self.myDocument?.save(nil)
  1907. } else {
  1908. let myDocument = self.myDocument
  1909. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  1910. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1911. if writeSuccess {
  1912. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1913. fileURL = document?.documentURL
  1914. } else {
  1915. NSSound.beep()
  1916. return
  1917. }
  1918. }
  1919. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  1920. extract?.docPath = fileURL?.path ?? ""
  1921. extract?.password = document?.password ?? ""
  1922. extract?.currentPage = self.listView.currentPageIndex
  1923. self.km_beginSheet(windowC: extract!)
  1924. extract?.selectCurrentPageBtn()
  1925. }
  1926. //MARK: 创建文字图章示例实际上不会在这里使用
  1927. func showCreateStamp() {
  1928. let stampCreaterWindowController = KMStampCreaterWindowController()
  1929. stampCreaterWindowController.window?.backgroundColor = .clear
  1930. self.km_beginSheet(windowC: stampCreaterWindowController)
  1931. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  1932. if result == 1 {
  1933. }
  1934. }
  1935. }
  1936. //MARK: 添加签名示例实际上不会在这里使用
  1937. func showAddSignature() {
  1938. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  1939. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  1940. })
  1941. }
  1942. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  1943. let progress = SKProgressController()
  1944. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  1945. progress.window?.contentView?.wantsLayer = true
  1946. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1947. progress.progressField.textColor = NSColor.white
  1948. progress.message = NSLocalizedString("Converting...", comment: "")
  1949. progressC = progress
  1950. progressC?.message = message
  1951. if maxValue > 0 {
  1952. progressC?.indeterminate = false
  1953. progressC?.maxValue = Double(maxValue)
  1954. progressC?.progressBar.doubleValue = 0.3
  1955. } else {
  1956. progressC?.indeterminate = true
  1957. }
  1958. self.view.km_beginSheet(windowC: progressC!)
  1959. }
  1960. func dismissProgressSheet() {
  1961. progressC?.stopAnimation()
  1962. self.view.km_endSheet()
  1963. progressC = nil
  1964. }
  1965. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  1966. let newArr = NSMutableArray()
  1967. for item in files {
  1968. newArr.add(item.filePath)
  1969. }
  1970. return newArr as! [String]
  1971. }
  1972. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1973. self.saveDocument()
  1974. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1975. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1976. if (result == .cancel) {
  1977. return
  1978. }
  1979. // 解除权限
  1980. self?.listView.document.unlock(withPassword: password)
  1981. // 隐藏提示
  1982. self?.hiddenSecureLimitTip()
  1983. // 去打印
  1984. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  1985. }
  1986. return
  1987. }
  1988. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  1989. }
  1990. // MARK: - 图片注释
  1991. @IBAction func imageAnnotation(_ sender: Any) {
  1992. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  1993. changeAnnotationMode(sender)
  1994. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1995. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1996. return
  1997. }
  1998. let accessoryCtr = KMImageAccessoryController()
  1999. let openPanel = NSOpenPanel()
  2000. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2001. openPanel.allowsMultipleSelection = false
  2002. openPanel.accessoryView = accessoryCtr.view
  2003. openPanel.canSelectHiddenExtension = true
  2004. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2005. if result == .OK {
  2006. guard let url = openPanel.url else {
  2007. return
  2008. }
  2009. let filePath = url.path
  2010. if filePath.pathExtension.lowercased() == "pdf" {
  2011. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2012. NSSound.beep()
  2013. return
  2014. }
  2015. }
  2016. guard let image = NSImage(contentsOfFile: url.path) else {
  2017. let alert = NSAlert()
  2018. alert.alertStyle = .critical
  2019. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2020. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2021. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2022. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2023. if response == .alertFirstButtonReturn {
  2024. // Handle cancel button clicked
  2025. }
  2026. }
  2027. return
  2028. }
  2029. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  2030. if isDamageImage {
  2031. let alert = NSAlert()
  2032. alert.alertStyle = .critical
  2033. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2034. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2035. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2036. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2037. if response == .alertFirstButtonReturn {
  2038. // Handle cancel button clicked
  2039. }
  2040. }
  2041. return
  2042. }
  2043. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2044. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2045. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2046. }
  2047. }
  2048. }
  2049. }
  2050. @IBAction func tableAnnotation(_ sender: Any) {
  2051. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2052. changeAnnotationMode(sender)
  2053. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2054. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2055. winC?.kEventName = "Reading_Table_BuyNow"
  2056. winC?.showWindow(nil)
  2057. return
  2058. }
  2059. listView.addAnnotationWithTable()
  2060. toggleOpenRightSide()
  2061. }
  2062. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2063. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2064. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2065. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2066. }
  2067. if let data = image.tiffRepresentation,
  2068. let imageRep = NSBitmapImageRep(data: data) {
  2069. imageRep.size = image.size
  2070. var imageData: Data?
  2071. if path.lowercased() == "png" {
  2072. imageData = imageRep.representation(using: .png, properties: [:])
  2073. } else {
  2074. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2075. }
  2076. if let imageData = imageData {
  2077. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2078. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2079. return true
  2080. } else {
  2081. return false
  2082. }
  2083. }
  2084. }
  2085. return false
  2086. }
  2087. func tagString() -> String {
  2088. let dateFormatter = DateFormatter()
  2089. dateFormatter.dateFormat = "yyMMddHHmmss"
  2090. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2091. }
  2092. // MARK: - Split View
  2093. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2094. }
  2095. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2096. }
  2097. func updateBackAndForwardButtonState() {
  2098. }
  2099. }
  2100. // MARK: -
  2101. // MARK: - KMToolbarViewControllerDelegate
  2102. extension KMMainViewController : KMToolbarViewControllerDelegate {
  2103. func changeModelAction(mode: CToolMode) {
  2104. self.listView.toolMode = mode
  2105. if mode == .editPDFToolMode {
  2106. }
  2107. }
  2108. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2109. switch selectedTag {
  2110. case 2:
  2111. if self.listView.scaleFactor != 1.0 {
  2112. self.listView.scaleFactor = 1.0
  2113. self.listView.autoScales = false
  2114. }
  2115. break
  2116. case 1:
  2117. let pageHeight = self.listView.currentPage()!.size.height
  2118. let pdfviewHeight = self.listView.bounds.size.height
  2119. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2120. self.listView.autoScales = false
  2121. break
  2122. case 0:
  2123. self.listView.autoScales = true
  2124. break
  2125. case 3:
  2126. self.listView.scaleFactor = 0.1
  2127. break
  2128. case 4:
  2129. self.listView.scaleFactor = 0.25
  2130. break
  2131. case 5:
  2132. self.listView.scaleFactor = 0.5
  2133. break
  2134. case 6:
  2135. self.listView.scaleFactor = 0.75
  2136. break
  2137. case 7:
  2138. self.listView.scaleFactor = 1.0
  2139. break
  2140. case 8:
  2141. self.listView.scaleFactor = 1.5
  2142. break
  2143. case 9:
  2144. self.listView.scaleFactor = 2.0
  2145. break
  2146. case 10:
  2147. self.listView.scaleFactor = 4.0
  2148. break
  2149. case 11:
  2150. self.listView.scaleFactor = 8.0
  2151. break
  2152. case 12:
  2153. self.listView.scaleFactor = 16.0
  2154. break
  2155. case 13:
  2156. self.listView.scaleFactor = 32.0
  2157. break
  2158. case 14:
  2159. self.listView.scaleFactor = 64.0
  2160. break
  2161. case 15:
  2162. self.listView.scaleFactor = 100.0
  2163. break
  2164. default:
  2165. break
  2166. }
  2167. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2168. if self.digitalSignController?.pdfView != nil {
  2169. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  2170. }
  2171. if self.redactController?.redactPdfView != nil {
  2172. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  2173. }
  2174. }
  2175. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2176. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2177. if scale > 100 {
  2178. scale = 100
  2179. }
  2180. if (scale <= 0.101) {
  2181. self.listView.scaleFactor = self.listView.minScaleFactor()
  2182. } else {
  2183. self.listView.scaleFactor = scale
  2184. }
  2185. if self.digitalSignController?.pdfView != nil {
  2186. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  2187. }
  2188. if self.redactController?.redactPdfView != nil {
  2189. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  2190. }
  2191. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2192. }
  2193. func changePDFViewZoomInAction() {
  2194. }
  2195. func changePDFViewZoomOutAction() {
  2196. }
  2197. func changePDFViewGotoNextPageAction() {
  2198. self.listView.km_goBack(nil)
  2199. if (self.listView.canGoToNextPage()) {
  2200. self.listView.goToNextPage(nil)
  2201. }
  2202. }
  2203. func changePDFViewGoToPreviousPageAction() {
  2204. if (self.listView.canGoToPreviousPage()) {
  2205. self.listView.goToPreviousPage(nil)
  2206. }
  2207. }
  2208. func changePDFViewGotoBackAction() {
  2209. self.listView.km_goBack(nil)
  2210. self.updateBackAndForwardButtonState()
  2211. }
  2212. func changePDFViewGoToForwardAction() {
  2213. self.listView.km_goForward(nil)
  2214. self.updateBackAndForwardButtonState()
  2215. }
  2216. func aiTranslationPDFFileAction() {
  2217. self.trackEvent_aiTranslate()
  2218. self._aiTranslationPDFFileAction()
  2219. }
  2220. private func _aiTranslationPDFFileAction() {
  2221. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2222. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2223. let alert = NSAlert()
  2224. alert.alertStyle = .critical
  2225. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2226. alert.runModal()
  2227. return
  2228. } else if isExceedsLimit {
  2229. let alert = NSAlert()
  2230. alert.alertStyle = .critical
  2231. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2232. alert.runModal()
  2233. return
  2234. }
  2235. let alert = NSAlert()
  2236. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2237. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2238. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2239. alert.beginSheetModal(for: view.window!) { [weak self] result in
  2240. if (result == .alertFirstButtonReturn) {
  2241. } else if result == .alertSecondButtonReturn {
  2242. return
  2243. }
  2244. }
  2245. }
  2246. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2247. self.trackEvent_share()
  2248. }
  2249. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2250. if(0 == selectedTag) {
  2251. } else {
  2252. }
  2253. }
  2254. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2255. if beforeType == .editPDF {
  2256. }
  2257. if(type != .Page) {
  2258. if (hasEnterPageEdit()) {
  2259. self.exitPageEdit()
  2260. }
  2261. }
  2262. if type != .redact {
  2263. if self.hasEnterRedact() {
  2264. self.exitRedact()
  2265. }
  2266. }
  2267. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  2268. if self.hasShowDigitalSign() {
  2269. self.exitDigitalSign()
  2270. }
  2271. }
  2272. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  2273. }
  2274. if(type != .Form) {
  2275. self.removeFromAlertView()
  2276. }
  2277. if (type == .Page) {
  2278. if (hasEnterPageEdit()) {
  2279. self.exitPageEdit()
  2280. } else {
  2281. self.enterPageEdit(pages)
  2282. }
  2283. } else if type == .editPDF {
  2284. } else if type == .Annatiton {
  2285. } else if type == .redact {
  2286. if self.needSaveDocument() {
  2287. self.saveDocumentWithProgressAlert { [unowned self] params in
  2288. self.enterRedact()
  2289. }
  2290. return
  2291. }
  2292. let isEdited = self.listView.isEdited()
  2293. let isPDFTextImageEdited = self.model.isPDFTextImageEdited
  2294. if isEdited || isPDFTextImageEdited {
  2295. self.enterRedact()
  2296. } else {
  2297. self.enterRedact()
  2298. }
  2299. } else if type == .Tool {
  2300. if KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  2301. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  2302. } else if KMGuideInfoWindowController.availableShow(.measureGuide) {
  2303. self.loadOpenFileFunctionGuide(.measureGuide)
  2304. }
  2305. } else if type == . Conversion {
  2306. self.loadOpenFileFunctionGuide(.convertGuide)
  2307. }else if type == .Form {
  2308. self.showFormAlertView()
  2309. }else if type == .Select {
  2310. toggleCloseRightSide()
  2311. }
  2312. }
  2313. func clickChildTool(type: KMToolbarType, index: Int) {
  2314. if (type == .secure) {
  2315. if (index == 1) {
  2316. self.trackEvent_setPassword()
  2317. } else if (index == 2) {
  2318. self.trackEvent_removePassword()
  2319. }
  2320. } else {
  2321. self.trackEvent(toolBarType: type)
  2322. }
  2323. Task { @MainActor in
  2324. if (type == .compress) { /// 压缩
  2325. if !self.documentAllowsEdit() {
  2326. return
  2327. }
  2328. if (self.needSaveDocument()) {
  2329. self.saveDocumentWithProgressAlert { [unowned self] params in
  2330. self.showCompressWindow()
  2331. }
  2332. return
  2333. }
  2334. self.showCompressWindow()
  2335. return
  2336. }
  2337. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  2338. if type == .conversion_imageToPDF {
  2339. Task {
  2340. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  2341. }
  2342. return
  2343. }
  2344. var identifier: String?
  2345. if (type == .word) { /// Word
  2346. identifier = KMToolbarConversionWordItemIdentifier
  2347. } else if (type == .excel) {
  2348. identifier = KMToolbarConversionExcelItemIdentifier
  2349. } else if (type == .ppt) {
  2350. identifier = KMToolbarConversionPPTItemIdentifier
  2351. } else if (type == .rtf) {
  2352. identifier = KMToolbarConversionRTFItemIdentifier
  2353. } else if (type == .html) {
  2354. identifier = KMToolbarConversionHTMLItemIdentifier
  2355. } else if (type == .conversion_text) {
  2356. identifier = KMToolbarConversionTextItemIdentifier
  2357. } else if (type == .csv) {
  2358. identifier = KMToolbarConversionCSVItemIdentifier
  2359. } else if (type == .conversion_image) {
  2360. identifier = KMToolbarConversionImageItemIdentifier
  2361. }
  2362. if (self.needSaveDocument()) {
  2363. self.saveDocumentWithProgressAlert { [unowned self] params in
  2364. self.showConvertWindow(type: type, identifier: identifier)
  2365. }
  2366. return
  2367. }
  2368. self.showConvertWindow(type: type, identifier: identifier)
  2369. return
  2370. }
  2371. if (type == .merge) { /// 合并
  2372. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  2373. if !self.documentAllowsEdit() {
  2374. return
  2375. }
  2376. if (self.needSaveDocument()) {
  2377. self.saveDocumentWithProgressAlert { [unowned self] params in
  2378. self.showMergeWindow(self.listView.document.password)
  2379. }
  2380. return
  2381. }
  2382. self.showMergeWindow(self.listView.document.password)
  2383. return
  2384. }
  2385. if (type == .bates || type == .headerAndFooter) {
  2386. if !IAPProductsManager.default().isAvailableAllFunction(){
  2387. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2388. if type == .headerAndFooter {
  2389. if index == 1 {
  2390. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  2391. } else if index == 2 {
  2392. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  2393. }
  2394. } else if type == .bates {
  2395. if index == 1 {
  2396. winC?.kEventName = "Reading_AddBates_BuyNow"
  2397. } else if index == 2 {
  2398. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  2399. }
  2400. }
  2401. winC?.showWindow(nil)
  2402. return
  2403. }
  2404. if !self.documentAllowsEdit() {
  2405. return
  2406. }
  2407. if (index == 1) {
  2408. var windowController: KMBaseWindowController = KMBaseWindowController()
  2409. if (type == .bates) {
  2410. } else if (type == .headerAndFooter) {
  2411. } else if (type == .background) {
  2412. } else if (type == .watermark) {
  2413. }
  2414. windowController.pdfDocument = self.listView.document
  2415. windowController.cancelAction = { [unowned self] controller in
  2416. self.view.window?.endSheet((self.currentWindowController.window)!)
  2417. self.currentWindowController = nil
  2418. }
  2419. self.currentWindowController = windowController
  2420. await self.view.window?.beginSheet(windowController.window!)
  2421. return
  2422. }
  2423. if (index == 1) { /// 取消
  2424. ///
  2425. toggleCloseRightSide()
  2426. return
  2427. } else if index == 3 {
  2428. let fpath = self.document?.documentURL?.path ?? ""
  2429. if type == .bates {
  2430. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2431. } else {
  2432. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2433. }
  2434. } else if index == 4 {
  2435. let fpath = self.document?.documentURL?.path ?? ""
  2436. if type == .bates {
  2437. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  2438. } else {
  2439. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  2440. }
  2441. } else if (index == 2) { //// 移除
  2442. if type == .headerAndFooter {
  2443. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2444. let savePanel = NSSavePanel()
  2445. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2446. savePanel.allowedFileTypes = ["pdf"]
  2447. savePanel.accessoryView = savePanelAccessoryViewController.view
  2448. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2449. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2450. }
  2451. }
  2452. } else if type == .bates {
  2453. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2454. let savePanel = NSSavePanel()
  2455. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2456. savePanel.allowedFileTypes = ["pdf"]
  2457. savePanel.accessoryView = savePanelAccessoryViewController.view
  2458. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2459. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2460. }
  2461. }
  2462. }
  2463. } else if (index == 2) { /// 应用
  2464. } else if index == 5 {
  2465. self.toggleOpenRightSide()
  2466. }
  2467. } else if (type == .redact) { /// 标记密文
  2468. if !IAPProductsManager.default().isAvailableAllFunction(){
  2469. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2470. return
  2471. }
  2472. if (index == 1) { /// 取消
  2473. if (self.model.hasAddRedact) {
  2474. let alert = NSAlert()
  2475. 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: "")
  2476. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2477. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2478. let result = alert.runModal()
  2479. if (result == .alertFirstButtonReturn) {
  2480. self.listView.toolMode = .moveToolMode
  2481. }
  2482. return
  2483. }
  2484. self.listView.toolMode = .moveToolMode
  2485. return
  2486. }
  2487. if (index == 2) { /// 擦除
  2488. self.exeRedactConfirm(.eraserAll) {}
  2489. return
  2490. }
  2491. if (index == 3) { /// 应用
  2492. self.exeRedactConfirm(.redactAll) {}
  2493. return
  2494. }
  2495. if (index == 4) { /// 文本&图像
  2496. self.listView.toolMode = .redactToolMode
  2497. return
  2498. }
  2499. if (index == 5) { /// 页面
  2500. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2501. await self.view.window?.beginSheet(windowController.window!)
  2502. self.currentWindowController = windowController
  2503. windowController.itemClick = { [weak self] index, value in
  2504. if (index == 1) {
  2505. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2506. self?.currentWindowController = nil
  2507. return
  2508. }
  2509. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2510. let pageType = windowController_pageRange.pageType
  2511. let pageString = windowController_pageRange.pageString
  2512. if (pageType == 5) { /// 自定义页面
  2513. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  2514. if (array.count == 0) {
  2515. let alert = NSAlert()
  2516. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2517. alert.runModal()
  2518. return
  2519. }
  2520. }
  2521. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2522. self!.currentWindowController = nil
  2523. var indexs: IndexSet = []
  2524. if (pageType == 1) { /// 当前页面
  2525. indexs.insert((self?.listView.currentPageIndex)!)
  2526. } else {
  2527. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  2528. }
  2529. if (indexs.count == 0) {
  2530. return
  2531. }
  2532. for i in indexs {
  2533. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2534. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2535. redactAnno.bounds = page.bounds
  2536. self?.listView.add(redactAnno, to: page)
  2537. }
  2538. }
  2539. return
  2540. }
  2541. } else if (type == .secure) { /// 安全
  2542. if (index == 1) { /// 设置密码
  2543. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2544. if !self.documentAllowsEdit() {
  2545. return
  2546. }
  2547. }
  2548. self.showSecureWindow(self.listView.document.documentURL)
  2549. return
  2550. } else if index == 2 {
  2551. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  2552. let alert = NSAlert()
  2553. alert.alertStyle = .warning
  2554. alert.messageText = NSLocalizedString("Warning", comment: "")
  2555. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2556. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  2557. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  2558. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  2559. if returnCode == .alertSecondButtonReturn {
  2560. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2561. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  2562. if success {
  2563. self.document?.unlock(withPassword: resultPassword)
  2564. self.clickChildTool(type: .secure, index: 2)
  2565. }
  2566. }
  2567. }
  2568. }
  2569. }
  2570. } else {
  2571. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  2572. controller.pdfDocument = self.document
  2573. self.currentWindowController = controller
  2574. controller.batchAction = { [unowned self] controller, files in
  2575. self.view.window?.endSheet((self.currentWindowController.window)!)
  2576. self.currentWindowController = nil
  2577. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  2578. if #available(macOS 10.13, *) {
  2579. baseWindowController.window?.makeKeyAndOrderFront(nil)
  2580. } else {
  2581. baseWindowController.showWindow(nil)
  2582. }
  2583. let arr = NSMutableArray()
  2584. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  2585. file.password = document?.password ?? ""
  2586. arr.add(file)
  2587. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  2588. }
  2589. controller.cancelAction = { [unowned self] controller in
  2590. self.view.window?.endSheet((self.currentWindowController.window)!)
  2591. self.currentWindowController = nil
  2592. }
  2593. controller.doneAction = { [unowned self] controller in
  2594. self.view.window?.endSheet((self.currentWindowController.window)!)
  2595. self.currentWindowController = nil
  2596. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  2597. if success {
  2598. let savePanel = NSSavePanel()
  2599. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  2600. savePanel.allowedFileTypes = ["pdf"]
  2601. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  2602. guard result == .OK else { return }
  2603. /// 删除安全性设置
  2604. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2605. self.model.isSaveKeyChain = false
  2606. self.listView.document.unlock(withPassword: resultPassword)
  2607. }
  2608. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  2609. guard let document = document else { return }
  2610. document.unlock(withPassword: resultPassword)
  2611. let success = document.writeDecrypt(to: savePanel.url)
  2612. if success {
  2613. self.hiddenSecureLimitTip()
  2614. let tip = KMRemovePasswordResultTipView()
  2615. tip.result = .success
  2616. tip.showInView(superView: (self.listView.superview)!)
  2617. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2618. } else {
  2619. self.hiddenSecureLimitTip()
  2620. let tip = KMRemovePasswordResultTipView()
  2621. tip.result = .failure
  2622. tip.showInView(superView: (self.listView.superview)!)
  2623. }
  2624. }
  2625. }
  2626. }
  2627. }
  2628. await NSWindow.currentWindow().beginSheet(controller.window!)
  2629. }
  2630. return
  2631. }
  2632. } else if type == .comparison {
  2633. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  2634. if !IAPProductsManager.default().isAvailableAllFunction(){
  2635. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2636. winC?.kEventName = "Reading_Compare_BuyNow"
  2637. winC?.showWindow(nil)
  2638. return
  2639. }
  2640. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2641. self.currentWindowController = controller
  2642. controller.password = self.document?.password ?? ""
  2643. controller.filePath = (self.document?.documentURL.path)!
  2644. controller.cancelAction = { [unowned self] controller in
  2645. self.view.window?.endSheet((self.currentWindowController.window)!)
  2646. self.currentWindowController = nil
  2647. }
  2648. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  2649. self.view.window?.endSheet((self.currentWindowController.window)!)
  2650. self.currentWindowController = nil
  2651. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  2652. }
  2653. controller.coveringComplete = { [unowned self] controller, document in
  2654. self.view.window?.endSheet((self.currentWindowController.window)!)
  2655. self.currentWindowController = nil
  2656. self.openCoveringCompareVC(with: document)
  2657. }
  2658. if index == 1 {
  2659. controller.fileType = .content
  2660. } else {
  2661. controller.fileType = .coverting
  2662. }
  2663. await NSWindow.currentWindow().beginSheet(controller.window!)
  2664. } else if type == .watermark {
  2665. if !IAPProductsManager.default().isAvailableAllFunction(){
  2666. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2667. if index == 1 {
  2668. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  2669. } else if index == 2 {
  2670. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  2671. }
  2672. winC?.showWindow(nil)
  2673. return
  2674. }
  2675. if !self.documentAllowsEdit() {
  2676. return
  2677. }
  2678. if index == 1 {
  2679. } else if index == 2 {
  2680. let watermarks = self.listView.document.watermarks()
  2681. if (watermarks == nil || watermarks!.count <= 0) {
  2682. let alert = NSAlert()
  2683. alert.alertStyle = .warning
  2684. 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: "")
  2685. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  2686. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2687. alert.runModal()
  2688. return
  2689. }
  2690. let alert = NSAlert()
  2691. alert.alertStyle = .warning
  2692. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  2693. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2694. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2695. let result = alert.runModal()
  2696. if (result != .alertFirstButtonReturn) {
  2697. return
  2698. }
  2699. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2700. let savePanel = NSSavePanel()
  2701. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  2702. savePanel.allowedFileTypes = ["pdf"]
  2703. savePanel.accessoryView = savePanelAccessoryViewController.view
  2704. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2705. guard result == .OK else { return }
  2706. }
  2707. } else if index == 3 {
  2708. let fpath = self.document?.documentURL?.path ?? ""
  2709. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  2710. } else if index == 4 {
  2711. let fpath = self.document?.documentURL?.path ?? ""
  2712. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  2713. } else if index == 5 {
  2714. toggleOpenRightSide()
  2715. return
  2716. }
  2717. } else if type == .background {
  2718. if !IAPProductsManager.default().isAvailableAllFunction(){
  2719. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2720. if index == 1 {
  2721. winC?.kEventName = "Reading_AddBackground_BuyNow"
  2722. } else if index == 2 {
  2723. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  2724. }
  2725. winC?.showWindow(nil)
  2726. return
  2727. }
  2728. if !self.documentAllowsEdit() {
  2729. return
  2730. }
  2731. if index == 1 {
  2732. } else if index == 2 {
  2733. guard let document = self.document else { return }
  2734. if !document.allowsPrinting || !document.allowsCopying {
  2735. let alert = NSAlert()
  2736. alert.alertStyle = .critical
  2737. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2738. alert.runModal()
  2739. return
  2740. }
  2741. guard let documentURL = document.documentURL else { return }
  2742. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2743. let savePanel = NSSavePanel()
  2744. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  2745. savePanel.allowedFileTypes = ["pdf"]
  2746. savePanel.accessoryView = savePanelAccessoryViewController.view
  2747. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2748. guard result == .OK else { return }
  2749. }
  2750. } else if index == 3 {
  2751. let fpath = self.document?.documentURL?.path ?? ""
  2752. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  2753. } else if index == 4 {
  2754. let fpath = self.document?.documentURL?.path ?? ""
  2755. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  2756. } else if index == 5 {
  2757. toggleOpenRightSide()
  2758. return
  2759. }
  2760. } else if type == .measure {
  2761. if !IAPProductsManager.default().isAvailableAllFunction(){
  2762. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2763. winC?.kEventName = "Reading_Measure_BuyNow"
  2764. winC?.showWindow(nil)
  2765. return
  2766. }
  2767. if !self.documentAllowsEdit() {
  2768. return
  2769. }
  2770. self.listView.toolMode = .measureToolMode
  2771. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2772. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2773. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2774. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2775. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2776. areaMeasureInfoWindowController?.hideFloatingWindow()
  2777. }
  2778. if distanceMeasureInfoWindowController == nil {
  2779. let measureInfo = CPDFDistanceMeasureInfo()
  2780. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2781. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2782. distanceMeasureInfoWindowController?.delegate = self
  2783. }
  2784. if perimeterMeasureInfoWindowController == nil {
  2785. let measureInfo = CPDFPerimeterMeasureInfo()
  2786. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2787. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2788. perimeterMeasureInfoWindowController?.delegate = self
  2789. }
  2790. if areaMeasureInfoWindowController == nil {
  2791. let measureInfo = CPDFAreaMeasureInfo()
  2792. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2793. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2794. areaMeasureInfoWindowController?.delegate = self
  2795. }
  2796. if index == 1 {
  2797. self.listView.annotationType = .line
  2798. let winW: CGFloat = 300
  2799. let rightW: CGFloat = 270
  2800. var winFrame = self.view.window?.frame ?? .zero
  2801. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2802. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2803. distanceMeasureInfoWindowController?.showWindow(nil)
  2804. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2805. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2806. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2807. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2808. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2809. self.trackEvent(toolMode: .measureToolMode)
  2810. } else if index == 2 {
  2811. self.listView.annotationType = .polyLine
  2812. let winW: CGFloat = 300
  2813. let rightW: CGFloat = 270
  2814. var winFrame = self.view.window?.frame ?? .zero
  2815. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2816. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2817. perimeterMeasureInfoWindowController?.showWindow(nil)
  2818. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2819. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2820. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2821. self.trackEvent(toolMode: .measureToolMode)
  2822. } else if index == 3 {
  2823. self.listView.annotationType = .polyGon
  2824. let winW: CGFloat = 300
  2825. let rightW: CGFloat = 270
  2826. var winFrame = self.view.window?.frame ?? .zero
  2827. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2828. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2829. areaMeasureInfoWindowController?.showWindow(nil)
  2830. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2831. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2832. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2833. self.trackEvent(toolMode: .measureToolMode)
  2834. } else if index == 4 {
  2835. self.listView.annotationType = .square
  2836. let winW: CGFloat = 300
  2837. let rightW: CGFloat = 270
  2838. var winFrame = self.view.window?.frame ?? .zero
  2839. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2840. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2841. areaMeasureInfoWindowController?.showWindow(nil)
  2842. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2843. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2844. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2845. self.trackEvent(toolMode: .measureToolMode)
  2846. } else {
  2847. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  2848. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2849. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  2850. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2851. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  2852. areaMeasureInfoWindowController?.hideFloatingWindow()
  2853. }
  2854. }
  2855. toggleOpenRightSide()
  2856. }
  2857. }
  2858. }
  2859. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  2860. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2861. var array: [KMBatchOperateFile] = []
  2862. for fpath in filepaths ?? [] {
  2863. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  2864. array.append(batchOperateFile)
  2865. }
  2866. batchWindowController.switchToOperateType(type, files: array)
  2867. batchWindowController.window?.makeKeyAndOrderFront("")
  2868. }
  2869. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  2870. self.toolbarItemClickForExitMode(toolbarItem)
  2871. if let itemID = toolbarItem.itemIdentifier {
  2872. if isMainToolItem(itemID) {
  2873. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  2874. openNewWindowAlertWindow()
  2875. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  2876. self.changePDFViewGoToPreviousPageAction()
  2877. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  2878. let isSelected = toolbarItem.isSelected
  2879. toolbarItem.isSelected = !isSelected
  2880. if toolbarItem.isSelected {
  2881. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  2882. toggleOpenRightSide()
  2883. }else{
  2884. toggleCloseRightSide()
  2885. }
  2886. if toolbarItem.isSelected {
  2887. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  2888. }
  2889. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  2890. toolbarItem.isSelected = !toolbarItem.isSelected
  2891. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  2892. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  2893. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2894. }
  2895. toolbarItem.isSelected = !toolbarItem.isSelected
  2896. self.toggleRightPane()
  2897. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  2898. self.listView.toolMode = .redactToolMode
  2899. self.enterRedact()
  2900. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  2901. showOCRWindow()
  2902. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  2903. self.showAITypeChooseView(aiConfigType: .none)
  2904. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  2905. if self.canEnterDigitalSign() == false {
  2906. Task {
  2907. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  2908. }
  2909. return
  2910. }
  2911. toolbarItem.isSelected = !toolbarItem.isSelected
  2912. if toolbarItem.isSelected {
  2913. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  2914. }
  2915. self.enterDigitalSign()
  2916. } else if itemID == KMDocumentPrintToolbarItemIdentifier {
  2917. self.showPrintWindow()
  2918. } else if itemID == KMDocumentPresentationToolbarItemIdentifier {
  2919. self.togglePresentation(nil)
  2920. } else if itemID == KMDocumentSignToolbarItemIdentifier {
  2921. let isSelected = toolbarItem.isSelected
  2922. toolbarItem.isSelected = !isSelected
  2923. }
  2924. } else {
  2925. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  2926. toolbarItem.isSelected = false
  2927. let windowC = KMToolbarCustomWindowController()
  2928. windowC.resetCallback = { [weak self] in
  2929. }
  2930. self.km_beginSheet(windowC: windowC) { [weak self] resp, obj in
  2931. if resp == .OK {
  2932. }
  2933. }
  2934. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  2935. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  2936. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  2937. self.trackEvent_print()
  2938. self.showPrintWindow()
  2939. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  2940. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  2941. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  2942. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  2943. windowC.callBack = { [weak self] string in
  2944. if (string.isEmpty == false) {
  2945. self?.listView.addTextField(subType: .profile, string: string)
  2946. }
  2947. self?.km_endSheet()
  2948. }
  2949. self.km_beginSheet(windowC: windowC)
  2950. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  2951. toolbarItem.isSelected = !toolbarItem.isSelected
  2952. self.listView.annotationType = .unkown
  2953. if toolbarItem.isSelected {
  2954. toggleOpenRightSide()
  2955. }else{
  2956. toggleCloseRightSide()
  2957. }
  2958. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  2959. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  2960. self.listView.takeSnapshot(nil)
  2961. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  2962. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  2963. self.listView.annotationType = .unkown
  2964. self.showTTSWindow()
  2965. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  2966. self.showOCRWindow()
  2967. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  2968. toolbarItem.isSelected = false
  2969. self.imageAnnotation(toolbarItem)
  2970. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  2971. self.tableAnnotation(toolbarItem)
  2972. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  2973. self.leftSideViewController.insertPDF(nil)
  2974. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  2975. let windowC = SplitWindowController(document: self.listView.document)
  2976. self.km_beginSheet(windowC: windowC)
  2977. } else if itemID == KMSignDigitalSignToolbarItemIdentifier {
  2978. if self.canEnterDigitalSign() == false {
  2979. Task {
  2980. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  2981. }
  2982. return
  2983. }
  2984. toolbarItem.isSelected = !toolbarItem.isSelected
  2985. if toolbarItem.isSelected {
  2986. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  2987. }
  2988. self.enterDigitalSign()
  2989. } else if itemID == KMToolbarMeasureItemIdentifier {
  2990. if toolbarItem.isSelected {
  2991. toolbarItem.isSelected = false
  2992. self.listView.toolMode = .textToolMode
  2993. self.listView.annotationType = .unkown
  2994. }
  2995. }
  2996. }
  2997. }
  2998. }
  2999. func openNewWindowAlertWindow() {
  3000. var needShowChooseWindow = false
  3001. //#if VERSION_FREE
  3002. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  3003. needShowChooseWindow = true
  3004. }
  3005. //#endif
  3006. if needShowChooseWindow {
  3007. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  3008. if preferenceNoteShow {
  3009. menuItemAction_newTagPageToNewWindow("")
  3010. } else {
  3011. if !KMDataManager.default.isTabbingWin{
  3012. KMDataManager.default.isTabbingWin = true
  3013. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  3014. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  3015. KMDataManager.default.isTabbingWin = false
  3016. if continueOrNot {
  3017. self?.reopenDocument(forPaths: [])
  3018. } else {
  3019. }
  3020. }
  3021. self.km_beginSheet(windowC: tabbingWin)
  3022. }
  3023. }
  3024. }else{
  3025. handleTabbingLogic()
  3026. }
  3027. }
  3028. func reopenDocument(forPaths paths: [String]) -> Void {
  3029. let browser = KMBrowser.init() as KMBrowser
  3030. browser.windowController = KMBrowserWindowController.init(browser: browser)
  3031. browser.addHomeTabContents()
  3032. browser.windowController.showWindow(self)
  3033. }
  3034. func handleTabbingLogic() {
  3035. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  3036. }
  3037. func showTTSWindow() {
  3038. var lastPDFView: CPDFView?
  3039. let ttsView = KMTTSWindowController.share
  3040. if (ttsView.window?.isVisible ?? false) {
  3041. lastPDFView = ttsView.pdfView
  3042. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  3043. lastPDFView = nil
  3044. ttsView.window?.orderOut(nil)
  3045. } else {
  3046. ttsView.pdfView = self.listView
  3047. ttsView.showWindow(nil)
  3048. }
  3049. } else {
  3050. ttsView.pdfView = self.listView
  3051. ttsView.showWindow(nil)
  3052. }
  3053. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  3054. if isCloseWindow {
  3055. }
  3056. }
  3057. if let currentSelection = self.listView.currentSelection {
  3058. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  3059. ttsView.startSpeakingPDFSelection(currentSelection)
  3060. }
  3061. }
  3062. if let lastPDFView = lastPDFView {
  3063. lastPDFView.setHighlightedSelections([])
  3064. ttsView.stopSpeaking()
  3065. }
  3066. }
  3067. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3068. self.toolbarItemClickForExitMode(toolbarItem)
  3069. let itemId = toolbarItem.itemIdentifier
  3070. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3071. self.clickChildTool(type: .watermark, index: index)
  3072. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  3073. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3074. self.clickChildTool(type: .background, index: index)
  3075. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  3076. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3077. self.clickChildTool(type: .headerAndFooter, index: index)
  3078. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  3079. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3080. self.clickChildTool(type: .bates, index: index)
  3081. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  3082. } else if (toolbarItem.itemIdentifier == KMToolbarMeasureItemIdentifier) {
  3083. self.clickChildTool(type: .measure, index: index)
  3084. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3085. self.clickChildTool(type: .comparison, index: index)
  3086. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3087. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3088. convertToImg(index: index)
  3089. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  3090. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3091. extractImageAction(num: index)
  3092. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3093. self.createPdf(index: index)
  3094. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3095. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3096. self.clickChildTool(type: .secure, index: index)
  3097. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  3098. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  3099. if index == 11 {
  3100. self.view.window?.makeFirstResponder(nil)
  3101. let winC = KMSearchReplaceWindowController(with: self.listView, type: .search)
  3102. self.currentWindowController = winC
  3103. winC.replaceCallback = { [weak self] in
  3104. let toolMode = self?.listView.toolMode ?? .none
  3105. let isEditing = self?.listView.isEditing() ?? false
  3106. if toolMode == .editPDFToolMode && isEditing {
  3107. } else { // 进入内容编辑模式
  3108. }
  3109. }
  3110. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  3111. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  3112. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 248 - 16
  3113. let winFramePoint = NSPoint(x: x, y: y)
  3114. winC.window?.setFrameOrigin(winFramePoint)
  3115. winC.startModal(nil)
  3116. } else if index == 12 {
  3117. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3118. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3119. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  3120. winC?.showWindow(nil)
  3121. return
  3122. }
  3123. self.view.window?.makeFirstResponder(nil)
  3124. let toolMode = self.listView.toolMode ?? .none
  3125. let isEditing = self.listView.isEditing() ?? false
  3126. if toolMode == .editPDFToolMode && isEditing {
  3127. } else { // 进入内容编辑模式
  3128. }
  3129. self.trackEvent_replace()
  3130. let winC = KMSearchReplaceWindowController(with: self.listView, type: .replace)
  3131. self.currentWindowController = winC
  3132. winC.replaceCallback = { [weak self] in
  3133. let toolMode = self?.listView.toolMode ?? .none
  3134. let isEditing = self?.listView.isEditing() ?? false
  3135. if toolMode == .editPDFToolMode && isEditing {
  3136. } else { // 进入内容编辑模式
  3137. }
  3138. }
  3139. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  3140. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  3141. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 388
  3142. let winFramePoint = NSPoint(x: x, y: y)
  3143. winC.window?.setFrameOrigin(winFramePoint)
  3144. winC.startModal(nil)
  3145. } else {
  3146. }
  3147. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3148. toolbarItem.isSelected = !toolbarItem.isSelected
  3149. self.toggleRightPane()
  3150. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3151. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  3152. self.showOCRWindow()
  3153. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  3154. if index == 1 {
  3155. self.showAITypeChooseView(aiConfigType: .summarize)
  3156. } else if index == 2 {
  3157. self.showAITypeChooseView(aiConfigType: .reWriting)
  3158. } else if index == 3 {
  3159. self.showAITypeChooseView(aiConfigType: .proofreading)
  3160. } else if index == 4 {
  3161. self.showAITypeChooseView(aiConfigType: .translate)
  3162. }
  3163. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  3164. self.showOCRWindow()
  3165. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  3166. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  3167. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  3168. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  3169. if self.canEnterDigitalSign() == false {
  3170. Task {
  3171. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3172. }
  3173. return
  3174. }
  3175. toolbarItem.isSelected = !toolbarItem.isSelected
  3176. if toolbarItem.isSelected {
  3177. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3178. }
  3179. self.enterDigitalSign()
  3180. } else if itemId == KMSignDigitalSignToolbarItemIdentifier {
  3181. if self.canEnterDigitalSign() == false {
  3182. Task {
  3183. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  3184. }
  3185. return
  3186. }
  3187. toolbarItem.isSelected = !toolbarItem.isSelected
  3188. if toolbarItem.isSelected {
  3189. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  3190. }
  3191. self.enterDigitalSign()
  3192. } else if itemId == KMDocumentAIToolsToolbarItemIdentifier {
  3193. self.showAITypeChooseView(aiConfigType: .none)
  3194. } else if itemId == KMToolbarToolCompressItemIdentifier {
  3195. self.clickChildTool(type: .compress, index: 0)
  3196. } else if itemId == KMToolbarPageEditSplitItemIdentifier { // 拆分
  3197. let windowC = SplitWindowController(document: self.listView.document)
  3198. self.km_beginSheet(windowC: windowC)
  3199. } else if itemId == KMToolbarToolMergeItemIdentifier {
  3200. self.clickChildTool(type: .merge, index: 0)
  3201. } else if itemId == KMToolbarPageEditInsetItemIdentifier {
  3202. self.leftSideViewController.insertPDF(nil)
  3203. } else if itemId == KMToolbarShowToolbarItemIdentifier {
  3204. self.showOrHideNotes()
  3205. } else if itemId == KMAnnotationTableToolbarItemIdentifier {
  3206. self.tableAnnotation(toolbarItem)
  3207. } else if itemId == KMToolbarConversionTextItemIdentifier {
  3208. self.clickChildTool(type: .conversion_text, index: 0)
  3209. } else if itemId == KMToolbarConversionHTMLItemIdentifier {
  3210. self.clickChildTool(type: .html, index: 0)
  3211. } else if itemId == KMToolbarConversionCSVItemIdentifier {
  3212. self.clickChildTool(type: .csv, index: 0)
  3213. } else if itemId == KMToolbarConversionRTFItemIdentifier {
  3214. self.clickChildTool(type: .rtf, index: 0)
  3215. } else if itemId == KMToolbarConversionPPTItemIdentifier {
  3216. self.clickChildTool(type: .ppt, index: 0)
  3217. } else if itemId == KMToolbarConversionExcelItemIdentifier {
  3218. self.clickChildTool(type: .excel, index: 0)
  3219. } else if itemId == KMToolbarConversionWordItemIdentifier {
  3220. self.clickChildTool(type: .word, index: 0)
  3221. } else if itemId == KMToolbarConversionOtherItemIdentifier {
  3222. if index == KMPDFConvertType.text.rawValue {
  3223. self.clickChildTool(type: .conversion_text, index: 0)
  3224. } else if index == KMPDFConvertType.rtf.rawValue {
  3225. self.clickChildTool(type: .rtf, index: 0)
  3226. } else if index == KMPDFConvertType.html.rawValue {
  3227. self.clickChildTool(type: .html, index: 0)
  3228. } else if index == KMPDFConvertType.csv.rawValue {
  3229. self.clickChildTool(type: .csv, index: 0)
  3230. } else if index == KMPDFConvertType.json.rawValue {
  3231. self.clickChildTool(type: .json, index: 0)
  3232. }
  3233. }
  3234. }
  3235. func convertToImg(index: Int) {
  3236. var convertT: KMConvertType = .JPEG
  3237. switch index {
  3238. case 7:
  3239. convertT = .JPEG
  3240. case 8:
  3241. convertT = .JPG
  3242. case 9:
  3243. convertT = .PNG
  3244. case 10:
  3245. convertT = .GIF
  3246. case 11:
  3247. convertT = .TIFF
  3248. case 12:
  3249. convertT = .TGA
  3250. case 13:
  3251. convertT = .BMP
  3252. default:
  3253. convertT = .JPEG
  3254. }
  3255. showAllConvertWindow(convertT: convertT)
  3256. }
  3257. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  3258. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3259. self.search(searchString: searchString, isCase: caseInsensitive, display: false)
  3260. var row = max(searchIndex - 1, 0)
  3261. if forward {
  3262. row = searchIndex + 1
  3263. }
  3264. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  3265. let model = self.searchResults[row]
  3266. if model.selection != nil {
  3267. self.listView.setHighlightedSelections([])
  3268. self.listView.go(to: model.selection, animated: true)
  3269. self.listView.setHighlightedSelection(model.selection, animated: true)
  3270. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3271. searchIndex = row
  3272. }
  3273. }
  3274. self.leftSideViewController.showSearchMode(searchString)
  3275. }
  3276. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  3277. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3278. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  3279. var row = max(searchIndex - 1, 0)
  3280. if forward {
  3281. row = searchIndex + 1
  3282. }
  3283. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  3284. let model = self.searchResults[row]
  3285. if model.selection != nil {
  3286. self.listView.setHighlightedSelections([])
  3287. self.listView.go(to: model.selection, animated: true)
  3288. self.listView.setHighlightedSelection(model.selection, animated: true)
  3289. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3290. searchIndex = row
  3291. }
  3292. }
  3293. }
  3294. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  3295. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  3296. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  3297. self.leftSideViewController.showSearchMode(searchString)
  3298. }
  3299. func toolbarViewController(_ viewController: KMToolbarViewController, viewItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3300. let itemId = toolbarItem.itemIdentifier
  3301. if itemId == KMDocumentFirstLastToolbarItemIdentifier {
  3302. if index == 1 {
  3303. if self.listView.canGoToFirstPage() {
  3304. self.listView.goToFirstPage(nil)
  3305. }
  3306. } else if index == 2 {
  3307. if self.listView.canGoToLastPage() {
  3308. self.listView.goToLastPage(nil)
  3309. }
  3310. }
  3311. } else if itemId == KMDocumentPageInputToolbarItemIdentifier {
  3312. var valid = false
  3313. if let number = Int(info as? String ?? "") {
  3314. let cnt = self.listView.document?.pageCount ?? 0
  3315. if number > 0 && number <= cnt {
  3316. self.listView.go(toPageIndex: number-1, animated: false)
  3317. valid = true
  3318. }
  3319. }
  3320. if valid == false {
  3321. Task {@MainActor in
  3322. _ = await KMAlertTool.runModel(message: NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))
  3323. }
  3324. }
  3325. }
  3326. }
  3327. }
  3328. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  3329. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  3330. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  3331. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  3332. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  3333. distanceSettingWC.delegate = self
  3334. distanceSettingWC.startModal("")
  3335. }
  3336. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  3337. }
  3338. }
  3339. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  3340. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  3341. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  3342. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  3343. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  3344. distanceSettingWC.delegate = self
  3345. distanceSettingWC.startModal("")
  3346. }
  3347. }
  3348. // MARK: CAreaMeasureInfoWindowControllerDelegate
  3349. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  3350. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  3351. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  3352. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  3353. areaSettingWC.delegate = self
  3354. areaSettingWC.startModal("")
  3355. }
  3356. }
  3357. // MARK: CDistanceSettingWindowControllerDelegate
  3358. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  3359. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  3360. if distanceMeasureInfo != nil {
  3361. if self.listView.activeAnnotations.count > 0 {
  3362. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  3363. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  3364. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3365. }
  3366. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  3367. } else {
  3368. distanceMeasureInfo?.leadLength = 0
  3369. self.listView.distanceMeasureInfo = distanceMeasureInfo
  3370. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  3371. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3372. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  3373. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  3374. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  3375. }
  3376. if let data = self.listView.activeAnnotation {
  3377. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  3378. }
  3379. }
  3380. self.distanceMeasureInfoWindowController?.showWindow(self)
  3381. }
  3382. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  3383. if perimeterMeasureInfo != nil {
  3384. if self.listView.activeAnnotations.count > 0 {
  3385. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  3386. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  3387. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3388. }
  3389. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  3390. } else {
  3391. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  3392. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  3393. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  3394. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  3395. }
  3396. if let data = self.listView.activeAnnotation {
  3397. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  3398. }
  3399. }
  3400. self.perimeterMeasureInfoWindowController?.showWindow(self)
  3401. }
  3402. }
  3403. // MARK: CAreaSettingWindowControllerDelegate
  3404. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  3405. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  3406. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  3407. if measureInfo != nil {
  3408. if self.listView.activeAnnotations.count > 0 {
  3409. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  3410. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  3411. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3412. }
  3413. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  3414. } else {
  3415. self.listView.squareAreaMeasureInfo = measureInfo
  3416. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  3417. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3418. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3419. }
  3420. }
  3421. self.areaMeasureInfoWindowController?.showWindow(self)
  3422. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  3423. if measureInfo != nil {
  3424. if self.listView.activeAnnotations.count > 0 {
  3425. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  3426. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  3427. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3428. }
  3429. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  3430. } else {
  3431. self.listView.polygonAreaMeasureInfo = measureInfo
  3432. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  3433. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  3434. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  3435. }
  3436. }
  3437. self.areaMeasureInfoWindowController?.showWindow(self)
  3438. } else {
  3439. if measureInfo != nil {
  3440. if self.listView.activeAnnotations.count > 0 {
  3441. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  3442. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  3443. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  3444. }
  3445. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  3446. }
  3447. }
  3448. self.areaMeasureInfoWindowController?.showWindow(self)
  3449. }
  3450. if measureInfo != nil {
  3451. if let data = self.listView.activeAnnotation {
  3452. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  3453. }
  3454. }
  3455. }
  3456. }
  3457. //MARK: LeftSideViewController
  3458. extension KMMainViewController {
  3459. func leftSideViewCancelSelect() {
  3460. if self.listView.isEditing() == true {
  3461. if self.listView.editingAreas() != nil &&
  3462. self.listView.editingAreas().count != 0 {
  3463. let areas = self.listView.editingAreas().first
  3464. if areas is CPDFEditTextArea {
  3465. self.listView.clearEditingSelectCharItem()
  3466. self.listView.updateEditing([])
  3467. KMPrint("取消选中")
  3468. }
  3469. }
  3470. }
  3471. }
  3472. }
  3473. // MARK: - Analytics (埋点)
  3474. extension KMMainViewController {
  3475. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  3476. if (type == .Annatiton) {
  3477. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  3478. } else if (type == .editPDF) {
  3479. } else if (type == .Page) {
  3480. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  3481. } else if (type == .Conversion) {
  3482. } else if (type == .Tool) {
  3483. }
  3484. }
  3485. func trackEvent_aiTranslate() -> Void {
  3486. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  3487. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3488. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3489. }
  3490. func trackEvent_print() -> Void {
  3491. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  3492. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3493. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3494. }
  3495. func trackEvent_share() -> Void {
  3496. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  3497. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3498. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3499. }
  3500. func trackEvent_upgrade() -> Void {
  3501. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  3502. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3503. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3504. }
  3505. func trackEvent(annotationType type: CAnnotationType) -> Void {
  3506. if (type == .highlight) {
  3507. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  3508. } else if (type == .underline) {
  3509. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  3510. } else if (type == .strikeOut) {
  3511. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  3512. } else if (type == .ink) {
  3513. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  3514. } else if (type == .freeText) {
  3515. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  3516. } else if (type == .anchored) {
  3517. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  3518. } else if (type == .square) {
  3519. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  3520. } else if (type == .link) {
  3521. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  3522. } else if (type == .stamp) {
  3523. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  3524. } else if (type == .signSignature) {
  3525. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  3526. } else if (type == .circle) {
  3527. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  3528. } else if (type == .arrow) {
  3529. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  3530. } else if (type == .line) {
  3531. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  3532. } else if (type == .addText) {
  3533. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  3534. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3535. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3536. } else if (type == .addImage) {
  3537. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  3538. } else if (type == .textField) {
  3539. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  3540. } else if (type == .checkBox) {
  3541. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  3542. } else if (type == .radioButton) {
  3543. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  3544. } else if (type == .listMenu) {
  3545. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  3546. } else if (type == .comboBox) {
  3547. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  3548. } else if (type == .actionButton) {
  3549. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  3550. } else if (type == .actionButton) {
  3551. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  3552. } else if (type == .signature) {
  3553. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  3554. } else if (type == .squiggly) {
  3555. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  3556. } else if (type == .eraser) {
  3557. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  3558. }
  3559. }
  3560. func trackEvent(toolMode mode: CToolMode) -> Void {
  3561. if (mode == .selectToolMode) {
  3562. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3563. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3564. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3565. } else if (mode == .moveToolMode) {
  3566. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3567. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3568. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3569. } else if mode == .measureToolMode {
  3570. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  3571. }
  3572. }
  3573. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3574. if (type == .word) {
  3575. } else if (type == .excel) {
  3576. } else if (type == .ppt) {
  3577. } else if (type == .rtf) {
  3578. } else if (type == .csv) {
  3579. } else if (type == .html) {
  3580. } else if (type == .conversion_text) {
  3581. } else if (type == .conversion_image) {
  3582. } else if (type == .compress) {
  3583. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  3584. } else if (type == .merge) {
  3585. } else if (type == .secure) {
  3586. } else if (type == .crop) {
  3587. } else if type == .json {
  3588. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  3589. }
  3590. }
  3591. func trackEvent_setPassword() -> Void {
  3592. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3593. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3594. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3595. }
  3596. func trackEvent_removePassword() -> Void {
  3597. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3598. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3599. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3600. }
  3601. func trackEvent_replace() -> Void {
  3602. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  3603. }
  3604. }
  3605. extension KMMainViewController {
  3606. //文件对比
  3607. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3608. self.isCompareModel = true
  3609. let compareContentView = KMCompareContentView()
  3610. compareContentView.oldDocument = oldDocument
  3611. compareContentView.document = document
  3612. compareContentView.compareResults = results
  3613. compareContentView.saveHandle = { [unowned self] view in
  3614. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3615. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3616. self.currentWindowController = saveController
  3617. saveController.cancelHandle = { [unowned self] controller in
  3618. self.view.window!.endSheet(controller.window!)
  3619. self.currentWindowController = nil
  3620. }
  3621. saveController.saveHandle = { [unowned self] controller, saveType in
  3622. let folderPath = controller.fileSaveFolderPath
  3623. if folderPath != nil {
  3624. if !FileManager.default.fileExists(atPath: folderPath) {
  3625. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3626. }
  3627. #if VERSION_DMG
  3628. #else
  3629. let url = URL(fileURLWithPath: folderPath)
  3630. let fileAccess = AppSandboxFileAccess()
  3631. fileAccess?.persistPermissionURL(url)
  3632. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  3633. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  3634. let urlString = url.path
  3635. let _url = URL(fileURLWithPath: urlString)
  3636. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  3637. }
  3638. #endif
  3639. var savePath: String
  3640. switch saveType {
  3641. case 0:
  3642. let filePath = oldDocument.documentURL.path
  3643. let fileName = filePath.deletingPathExtension.lastPathComponent
  3644. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3645. savePath = self.getValidFilePath(savePath)
  3646. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3647. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3648. case 1:
  3649. let filePath = document.documentURL.path
  3650. let fileName = filePath.deletingPathExtension.lastPathComponent
  3651. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3652. savePath = self.getValidFilePath(savePath)
  3653. document.write(to: URL(fileURLWithPath: savePath))
  3654. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3655. case 2:
  3656. let filePath = oldDocument.documentURL.path
  3657. let fileName = filePath.deletingPathExtension.lastPathComponent
  3658. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  3659. savePath = self.getValidFilePath(savePath)
  3660. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  3661. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3662. default:
  3663. break
  3664. }
  3665. }
  3666. self.view.window!.endSheet(controller.window!)
  3667. self.currentWindowController = nil
  3668. }
  3669. NSWindow.currentWindow().beginSheet(saveController.window!)
  3670. }
  3671. }
  3672. compareContentView.closeHandle = { [unowned self] view in
  3673. self.isCompareModel = false
  3674. view.removeFromSuperview()
  3675. }
  3676. compareContentView.autoresizingMask = [.width,.height]
  3677. }
  3678. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3679. self.isCompareModel = true
  3680. let coveringView = KMCompareCoveringView()
  3681. coveringView.pdfDocument = pdfDocument
  3682. coveringView.closeHandle = { [unowned self] view in
  3683. self.isCompareModel = false
  3684. view.removeFromSuperview()
  3685. }
  3686. coveringView.saveHandle = { [unowned self] view in
  3687. let savePanel = NSSavePanel()
  3688. savePanel.nameFieldStringValue = "untitled"
  3689. savePanel.allowedFileTypes = ["pdf"]
  3690. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  3691. if result == .OK {
  3692. pdfDocument.write(to: savePanel.url!)
  3693. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3694. }
  3695. }
  3696. }
  3697. coveringView.autoresizingMask = [.width,.height]
  3698. }
  3699. func getValidFilePath(_ oldPath: String) -> String {
  3700. let fileManager = FileManager.default
  3701. do {
  3702. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3703. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3704. return oldPath
  3705. }
  3706. var i = 1
  3707. var newPath = oldPath
  3708. while fileManager.fileExists(atPath: newPath) {
  3709. if fileType == FileAttributeType.typeDirectory.rawValue {
  3710. newPath = oldPath + "(\(i))"
  3711. } else {
  3712. let fileExtension = (oldPath as NSString).pathExtension
  3713. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3714. }
  3715. i += 1
  3716. }
  3717. return newPath
  3718. } catch {
  3719. print("Error getting file attributes: \(error)")
  3720. return oldPath
  3721. }
  3722. }
  3723. }
  3724. extension KMMainViewController {
  3725. func documentAllowsEdit() -> Bool {
  3726. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  3727. let alert = NSAlert()
  3728. alert.alertStyle = .critical
  3729. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3730. alert.runModal()
  3731. return false
  3732. } else {
  3733. return true
  3734. }
  3735. }
  3736. func changeFont(_ sender: NSFontManager) {
  3737. KMPrint("changeFont ...")
  3738. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  3739. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  3740. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  3741. font = sender.convert(font!)
  3742. annotation.fontSize = font?.pointSize ?? 12
  3743. self.listView.commitEditAnnotationFreeText(annotation)
  3744. self.listView.setNeedsDisplay(annotation)
  3745. }
  3746. }
  3747. func currentSetup() -> [String: Any] {
  3748. var setup: [String: Any] = [:]
  3749. var point = NSZeroPoint
  3750. if listView == nil {
  3751. return setup
  3752. }
  3753. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  3754. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  3755. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  3756. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  3757. setup[KMMainModel.Key.pageIndex] = pageIndex
  3758. return setup
  3759. }
  3760. // MARK: - Recommond活动
  3761. func loadRecommondPopWindow() {
  3762. if IAPProductsManager.default().isAvailableAllFunction() {
  3763. return
  3764. }
  3765. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  3766. if recommondPopWindowVC == nil {
  3767. recommondPopWindowVC = KMRecommondPopWindow.default()
  3768. }
  3769. recommondPopWindowVC?.recommondInfo = info
  3770. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  3771. return
  3772. }
  3773. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  3774. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  3775. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  3776. recommondPopWindowVC?.window?.orderFront((Any).self)
  3777. recommondPopWindowVC?.window?.becomeMain()
  3778. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  3779. UserDefaults.standard.synchronize()
  3780. }
  3781. }
  3782. @objc func didAddContentViewNotification(_ sender: Notification) {
  3783. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3784. return
  3785. }
  3786. if self.interactionMode == .presentation {
  3787. }
  3788. }
  3789. @objc func purchaseStateUpdateNoti() {
  3790. if IAPProductsManager.default().isAvailableAllFunction() {
  3791. }
  3792. }
  3793. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  3794. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  3795. guard let anno = sender.object as? CPDFAnnotation else {
  3796. return
  3797. }
  3798. if anno.page?.document != self.listView.document {
  3799. return
  3800. }
  3801. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  3802. }
  3803. // MARK: Split View
  3804. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  3805. let openPanel = NSOpenPanel()
  3806. openPanel.allowedFileTypes = ["pdf", "PDF"]
  3807. openPanel.allowsMultipleSelection = false
  3808. guard let mainWindow = NSApp.mainWindow else {
  3809. return
  3810. }
  3811. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  3812. if response == NSApplication.ModalResponse.OK {
  3813. guard let url = openPanel.url else {
  3814. return
  3815. }
  3816. if let document = CPDFDocument(url: url) {
  3817. replaceBlock(document.documentURL?.path ?? "")
  3818. } else {
  3819. let alert = NSAlert()
  3820. alert.alertStyle = .critical
  3821. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3822. alert.runModal()
  3823. }
  3824. }
  3825. }
  3826. }
  3827. }