KMMainViewController+Action.swift 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let isEditing = self.listView.isEditing() ?? false
  11. if isEditing {
  12. if searchString.isEmpty {
  13. self.listView.setHighlightedSelection(nil, animated: false)
  14. self.leftSideViewController.searchResults = []
  15. if display {
  16. if self.leftSideViewController.findPaneState == .singular {
  17. self.leftSideViewController.displayFindViewAnimating(true)
  18. } else {
  19. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  20. }
  21. }
  22. return
  23. }
  24. let isWholeWord = self.leftSideViewController.mwcFlags.wholeWordSearch == 1
  25. var opt = CPDFSearchOptions()
  26. if isCase == false {
  27. opt.insert(.caseSensitive)
  28. }
  29. if isWholeWord {
  30. opt.insert(.matchWholeWord)
  31. }
  32. let datas = self.listView.document.findEditAllPageString(searchString, with: opt) ?? []
  33. // if let sel = datas.first?.first {
  34. // self.srHanddler.showSelection(sel)
  35. // }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in datas {
  39. for selection in selections {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = selection
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  43. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  44. self.searchResults.insert(mode, at: self.searchResults.count)
  45. _selections.append(selection)
  46. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  47. }
  48. }
  49. if needShowAll {
  50. self.listView.setHighlightedSelections(_selections)
  51. }
  52. if _selections.isEmpty {
  53. self.listView.setHighlightedSelection(nil, animated: false)
  54. }
  55. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  56. self.leftSideViewController.searchResults = self.searchResults
  57. if display {
  58. if self.leftSideViewController.findPaneState == .singular {
  59. self.leftSideViewController.displayFindViewAnimating(true)
  60. } else {
  61. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  62. }
  63. }
  64. return
  65. }
  66. let document = self.listView.document
  67. if let data = document?.isFinding, data {
  68. document?.cancelFindString()
  69. }
  70. if searchString == "" {
  71. self.searchResults = []
  72. self.leftSideViewController.searchResults = self.searchResults
  73. self.listView.setHighlightedSelections([])
  74. self.listView.setHighlightedSelection(nil, animated: false)
  75. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  76. } else {
  77. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  78. var findArray : [[CPDFSelection]]
  79. if isCase {
  80. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  81. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  82. } else {
  83. findArray = self.listView.document.findString(searchString) ?? []
  84. }
  85. } else {
  86. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  87. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  88. } else {
  89. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  90. }
  91. }
  92. self.searchResults.removeAll()
  93. var _selections: [CPDFSelection] = []
  94. for selections in findArray {
  95. for selection in selections {
  96. let mode : KMSearchMode = KMSearchMode()
  97. mode.selection = selection
  98. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  99. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  100. self.searchResults.insert(mode, at: self.searchResults.count)
  101. _selections.append(selection)
  102. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  103. }
  104. }
  105. if needShowAll {
  106. self.listView.setHighlightedSelections(_selections)
  107. }
  108. if _selections.isEmpty {
  109. self.listView.setHighlightedSelection(nil, animated: false)
  110. }
  111. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  112. self.leftSideViewController.searchResults = self.searchResults
  113. }
  114. if display {
  115. if self.leftSideViewController.findPaneState == .singular {
  116. self.leftSideViewController.displayFindViewAnimating(true)
  117. } else {
  118. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  119. }
  120. }
  121. }
  122. func removeSignatures(signatures:[CPDFSignature]) {
  123. for signature in signatures {
  124. self.listView.document.removeSignature(signature)
  125. }
  126. for i in 0..<self.listView.document.pageCount {
  127. guard let page = self.listView.document.page(at: i) else {
  128. continue
  129. }
  130. let annotations : [CPDFAnnotation] = page.annotations
  131. for j in 0..<annotations.count {
  132. let annotation = annotations[j]
  133. if annotation is CPDFSignatureWidgetAnnotation {
  134. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  135. }
  136. }
  137. }
  138. self.listView.setNeedsDisplayForVisiblePages()
  139. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  140. var mSignatures : [CPDFSignature] = []
  141. for sign in tSignatures {
  142. if sign.signers.count > 0 {
  143. mSignatures.append(sign)
  144. }
  145. }
  146. }
  147. //MARK: menu菜单
  148. func fontColorMenuItem()->NSMenuItem {
  149. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  150. return fontColorItem;
  151. }
  152. func fontSizeMenuItem()->NSMenuItem {
  153. let currentFontSize = self.listView.editingTextFontSize()
  154. let fontSizes = self.fontSizes()
  155. let submenu = NSMenu(title: "")
  156. for i in 0 ... fontSizes.count - 1 {
  157. let fontSize : String = fontSizes.object(at: i) as! String
  158. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  159. item.target = self
  160. item.tag = i
  161. submenu.addItem(item)
  162. if (Int(currentFontSize) == Int(fontSize)) {
  163. item.state = .on
  164. }
  165. }
  166. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  167. fontSizeItem.submenu = submenu
  168. return fontSizeItem;
  169. }
  170. func corpImageMenuItem()->NSMenuItem {
  171. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  172. return corpImageItem
  173. }
  174. func cancelCorpImageMenuItem()->NSMenuItem {
  175. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  176. return cancelCorpImageItem
  177. }
  178. func restoreCorpImageMenuItem()->NSMenuItem {
  179. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  180. return cancelCorpImageItem
  181. }
  182. func cutImageArea()->NSMenuItem {
  183. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  184. return deleteItem
  185. }
  186. func editAddBlanMenu(menu:NSMenu){
  187. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  188. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  189. }
  190. func addText() -> NSMenuItem {
  191. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  192. return addTextItem
  193. }
  194. func addImage() -> NSMenuItem {
  195. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  196. return addImageItem
  197. }
  198. func replaceImageArea()->NSMenuItem {
  199. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  200. return replaceItem
  201. }
  202. func exportImageArea()->NSMenuItem {
  203. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  204. let menu = NSMenu()
  205. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  206. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(menuItemEditingClick_ExportImage), target: self, tag:1, at: 1)
  207. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 2)
  208. exportItem.submenu = menu
  209. return exportItem
  210. }
  211. func exportImageStampItem()->NSMenuItem {
  212. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  213. let menu = NSMenu()
  214. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  215. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  216. exportItem.submenu = menu
  217. return exportItem
  218. }
  219. func exportMenu() -> NSMenu {
  220. let menu = NSMenu()
  221. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  222. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  223. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  224. return menu
  225. }
  226. func cropMenu() -> NSMenu {
  227. let menu = NSMenu()
  228. return menu
  229. }
  230. func zoomSelectionMenuItem() -> NSMenuItem {
  231. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  232. return item
  233. }
  234. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  235. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  236. return item
  237. }
  238. func enterAnnotationStype() -> NSMenuItem {
  239. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  240. let stypeMenu = NSMenu()
  241. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  242. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  243. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  244. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  245. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  246. stypeMenu.addItem(NSMenuItem.separator())
  247. }
  248. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  249. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  250. stypeMenu.addItem(NSMenuItem.separator())
  251. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  252. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  253. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  254. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  255. if viewManager.isPDFReadMode {
  256. } else {
  257. stypeMenu.addItem(NSMenuItem.separator())
  258. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  259. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  260. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  261. }
  262. stypItem.submenu = stypeMenu
  263. if self.listView.annotationType == .ink {
  264. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  265. } else if self.listView.annotationType == .freeText {
  266. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  267. } else if self.listView.annotationType == .anchored {
  268. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  269. } else if self.listView.annotationType == .square {
  270. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  271. } else if self.listView.annotationType == .circle {
  272. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  273. } else if self.listView.annotationType == .arrow {
  274. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  275. } else if self.listView.annotationType == .line {
  276. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  277. } else if self.listView.annotationType == .link {
  278. stypeMenu.item(at: 7)?.state = .on
  279. } else if self.listView.annotationType == .stamp {
  280. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  281. } else if self.listView.annotationType == .signSignature {
  282. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  283. }
  284. return stypItem
  285. }
  286. func setAnnotationToolStype() -> NSMenuItem {
  287. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  288. let stypeMenu = NSMenu()
  289. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CTextToolMode.rawValue)
  290. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CMoveToolMode.rawValue)
  291. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CMagnifyToolMode.rawValue)
  292. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.CSelectToolMode.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: nil , 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 = .CNoteToolMode
  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 = .CNoteToolMode
  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 = .CNoteToolMode
  860. }
  861. switch sender.tag {
  862. case 0:
  863. self.listView.toolMode = .CNoteToolMode
  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.listView.undoManager?.setActionName("")//添加undo事件就可删除
  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 == .CSelectToolMode {
  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 == .CSelectToolMode {
  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 == .CSelectToolMode {
  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. case CAnnotationType.ink.rawValue:
  1387. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1388. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1389. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1390. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1391. var red: CGFloat = 0.0
  1392. var green: CGFloat = 0.0
  1393. var blue: CGFloat = 0.0
  1394. var alpha: CGFloat = 0.0
  1395. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1396. case CAnnotationType.freeText.rawValue:
  1397. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1398. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1399. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1400. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1401. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1402. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1403. var red: CGFloat = 0.0
  1404. var green: CGFloat = 0.0
  1405. var blue: CGFloat = 0.0
  1406. var alpha: CGFloat = 0.0
  1407. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1408. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1409. }
  1410. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1411. if (alignment == .left || alignment == .center || alignment == .right) {
  1412. }
  1413. case CAnnotationType.anchored.rawValue:
  1414. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1415. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1416. var red: CGFloat = 0.0
  1417. var green: CGFloat = 0.0
  1418. var blue: CGFloat = 0.0
  1419. var alpha: CGFloat = 0.0
  1420. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1421. case CAnnotationType.square.rawValue:
  1422. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1423. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1424. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1425. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1426. var red: CGFloat = 0.0
  1427. var green: CGFloat = 0.0
  1428. var blue: CGFloat = 0.0
  1429. var alpha: CGFloat = 0.0
  1430. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1431. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1432. case CAnnotationType.circle.rawValue:
  1433. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1434. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1435. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1436. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1437. var red: CGFloat = 0.0
  1438. var green: CGFloat = 0.0
  1439. var blue: CGFloat = 0.0
  1440. var alpha: CGFloat = 0.0
  1441. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1442. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1443. default:
  1444. break
  1445. }
  1446. }
  1447. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1448. self.showOrHideNotes()
  1449. }
  1450. //MARK: - action
  1451. // 开启/关闭左边栏
  1452. @objc func toggleLeftPane() -> Void {
  1453. self.model.leftPanelOpen = true
  1454. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1455. }
  1456. // 开启左边栏
  1457. @objc func openLeftPane() -> Void {
  1458. self.model.leftPanelOpen = true
  1459. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1460. }
  1461. // 关闭左边栏
  1462. @objc func closeLeftPane() -> Void {
  1463. self.model.leftPanelOpen = false
  1464. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1465. }
  1466. func rename(_ sender: NSNotification) -> Void {
  1467. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1468. return
  1469. }
  1470. let tabController = sender.object as? CTTabController
  1471. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  1472. if let doc = self.myDocument, doc.isDocumentEdited {
  1473. Task {
  1474. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  1475. if resp != .alertFirstButtonReturn { // 取消
  1476. return
  1477. }
  1478. doc.updateChangeCount(.changeCleared)
  1479. self.document?.write(to: doc.fileURL)
  1480. Task { @MainActor in
  1481. self._renameForSavePanel(tabController)
  1482. }
  1483. }
  1484. return
  1485. }
  1486. self._renameForSavePanel(tabController)
  1487. }
  1488. }
  1489. func savePdfAlertView() {
  1490. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  1491. return
  1492. }
  1493. AutoSaveManager.manager.isSaveNoti = true
  1494. var num = 0
  1495. if self.listView.document != nil{
  1496. num = Int(self.listView.document.pageCount)
  1497. }
  1498. if Thread.current.isMainThread {
  1499. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1500. } else {
  1501. DispatchQueue.main.async {
  1502. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1503. }
  1504. }
  1505. }
  1506. func savePdfFinishAlertView() {
  1507. if !AutoSaveManager.manager.isSaveNoti{
  1508. return
  1509. }
  1510. AutoSaveManager.manager.isSaveNoti = false
  1511. if Thread.current.isMainThread {
  1512. self.dismissProgressSheet()
  1513. } else {
  1514. DispatchQueue.main.async {
  1515. self.dismissProgressSheet()
  1516. }
  1517. }
  1518. }
  1519. private func _renameForSavePanel(_ tabC: CTTabController?) {
  1520. let outputSavePanel = NSSavePanel()
  1521. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1522. outputSavePanel.allowedFileTypes = ["pdf"]
  1523. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1524. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1525. let resp = outputSavePanel.runModal()
  1526. if resp == .OK {
  1527. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1528. let fileURL = pdfDocument?.documentURL
  1529. let fileManager = FileManager.default
  1530. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1531. var result = true
  1532. do {
  1533. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1534. } catch {
  1535. result = false
  1536. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1537. }
  1538. if (result) {
  1539. tabC?.title = outputSavePanel.url!.lastPathComponent
  1540. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1541. self.model.isSaveKeyChain = false
  1542. newPdfDocument.unlock(withPassword: self.document?.password)
  1543. if (newPdfDocument.pageCount > 0) {
  1544. self.setDocument = newPdfDocument
  1545. }
  1546. }
  1547. }
  1548. } else {
  1549. outputSavePanel.close()
  1550. }
  1551. }
  1552. func showInFinder(_ sender: Any) -> Void {
  1553. if sender is NSNotification {
  1554. let tabController = (sender as! NSNotification).object as? CTTabController
  1555. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  1556. if tabController?.title == path {
  1557. if let file = self.myDocument?.fileURL {
  1558. if FileManager.default.fileExists(atPath: file.path) {
  1559. NSWorkspace.shared.activateFileViewerSelecting([file])
  1560. }
  1561. }
  1562. }
  1563. } else {
  1564. guard let url = self.myDocument?.fileURL else { return }
  1565. let file: URL = url
  1566. if FileManager.default.fileExists(atPath: file.path) {
  1567. NSWorkspace.shared.activateFileViewerSelecting([file])
  1568. }
  1569. }
  1570. }
  1571. func closeTab(_ sender: NSNotification) -> Void {
  1572. }
  1573. @IBAction func toggleSplitPDF(_ sender: Any) {
  1574. if let menuItem = sender as? NSMenuItem {
  1575. splitView(withTag: menuItem.tag)
  1576. }
  1577. }
  1578. func changeLineAttribute(_ sender: Any?) {
  1579. var inspector = sender as? KMLineInspector
  1580. if inspector == nil {
  1581. inspector = KMLineInspector.shared
  1582. }
  1583. let action = inspector?.currentLineChangeAction ?? .no
  1584. for annotation in self.listView.activeAnnotations {
  1585. guard let anno = annotation as? CPDFAnnotation else {
  1586. continue
  1587. }
  1588. if anno.hasBorder() {
  1589. switch (action) {
  1590. case .lineWidth:
  1591. anno.setLineWidth(inspector?.lineWidth ?? 0)
  1592. break
  1593. case .style:
  1594. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  1595. break
  1596. case .dashPattern:
  1597. anno.setDashPattern(inspector?.dashPattern ?? [])
  1598. break
  1599. case .startLineStyle:
  1600. if anno.isLine() {
  1601. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  1602. }
  1603. break
  1604. case .endLineStyle:
  1605. if anno.isLine() {
  1606. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  1607. }
  1608. break
  1609. case .no:
  1610. break
  1611. }
  1612. }
  1613. }
  1614. }
  1615. // MARK: -
  1616. // MARK: 显示窗口
  1617. // internal func showCompressWindow(url: URL? = nil) {
  1618. //
  1619. // self.compressWIndowControllerNew = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1620. // self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  1621. // self.compressWIndowControllerNew?.password = self.listView.document?.password ?? ""
  1622. //
  1623. // self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  1624. //
  1625. //
  1626. // self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  1627. // self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1628. //
  1629. // }
  1630. //
  1631. // self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  1632. // self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1633. //
  1634. //
  1635. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1636. // let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  1637. // batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1638. // batchWindowController.window?.makeKeyAndOrderFront("")
  1639. // }
  1640. //
  1641. // self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  1642. // self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1643. // if (result) {
  1644. //
  1645. // if (openDocument) {
  1646. // NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1647. // } else {
  1648. // NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1649. // }
  1650. // } else {
  1651. // let alert = NSAlert()
  1652. // alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1653. // alert.runModal()
  1654. // }
  1655. // }
  1656. // }
  1657. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1658. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1659. KMPrint("转档窗口已显示")
  1660. return
  1661. }
  1662. var convertT: KMConvertType = .Word
  1663. var windowController: KMConvertBaseWindowController?
  1664. if (type == .word) { /// Word
  1665. convertT = .Word
  1666. windowController = KMConvertWordWindowController()
  1667. } else if (type == .excel) {
  1668. convertT = .Excel
  1669. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1670. if (type == .ppt) {
  1671. convertT = .PPT
  1672. } else if (type == .rtf) {
  1673. convertT = .RTF
  1674. } else if (type == .html) {
  1675. convertT = .HTML
  1676. } else if (type == .conversion_text) {
  1677. convertT = .Text
  1678. }
  1679. } else if (type == .csv) {
  1680. convertT = .CSV
  1681. } else if (type == .conversion_image) {
  1682. windowController = KMConvertImageWindowController()
  1683. convertT = .JPEG
  1684. } else if type == .json {
  1685. convertT = .Json
  1686. }
  1687. var url: URL?
  1688. if (documentUrl != nil) {
  1689. url = documentUrl
  1690. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1691. } else {
  1692. url = self.listView.document.documentURL
  1693. }
  1694. let model = KMDocumentModel(url: url!)
  1695. windowController?.documentModel = model
  1696. self.km_safe_beginSheet(windowC: windowController)
  1697. }
  1698. //MARK: 转档 -
  1699. func showAllConvertWindow(convertT: KMConvertType) {
  1700. self.ConvertTrackEvent(type: convertT)
  1701. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1702. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1703. var type: KMConvertWithPDFType = .WordAdvance
  1704. switch convertT {
  1705. case .Word:
  1706. break
  1707. case .Excel:
  1708. type = .Excel
  1709. case .PPT:
  1710. type = .PowerPoint
  1711. case .RTF:
  1712. type = .RTF
  1713. case .CSV:
  1714. type = .CSV
  1715. case .HTML:
  1716. type = .HTML
  1717. case .Text:
  1718. type = .Text
  1719. case .JPEG:
  1720. type = .JPEG
  1721. case .PNG:
  1722. type = .PNG
  1723. case .GIF:
  1724. type = .GIF
  1725. case .JPG:
  1726. type = .JPG
  1727. case .TIFF:
  1728. type = .TIFF
  1729. case .TGA:
  1730. type = .TGA
  1731. case .BMP:
  1732. type = .BMP
  1733. case .JP2:
  1734. type = .JPEG2000
  1735. case .AdvancedWord:
  1736. break
  1737. case .Json:
  1738. type = .Json
  1739. break
  1740. default:
  1741. break
  1742. }
  1743. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1744. var needShowHint = false
  1745. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1746. needShowHint = true
  1747. } else {
  1748. var needContinue = false
  1749. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1750. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1751. let ss = self.document?.documentURL.path
  1752. if arr.contains(ss!) {
  1753. needContinue = false
  1754. }else {
  1755. needContinue = true
  1756. }
  1757. }else {
  1758. needContinue = true
  1759. }
  1760. if needContinue {
  1761. let ss = self.document?.documentURL.path
  1762. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1763. file.password = document?.password ?? ""
  1764. KMBatchOperateManager.defaultManager.files?.append(file)
  1765. }
  1766. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1767. batchWindowController.switchToConvertType(convertType: type)
  1768. }
  1769. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1770. if needShowHint {
  1771. batchWindowController.showIsConvertingHint()
  1772. } else {
  1773. }
  1774. }
  1775. }
  1776. self.km_beginSheet(windowC: convertWC)
  1777. }
  1778. func ConvertTrackEvent(type: KMConvertType) {
  1779. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  1780. switch type {
  1781. case .Word:
  1782. eventStr = "Btn_SubTbr_Converter_ToWord"
  1783. break
  1784. case .Excel:
  1785. eventStr = "Btn_SubTbr_Converter_ToExcel"
  1786. case .PPT:
  1787. eventStr = "Btn_SubTbr_Converter_ToPPT"
  1788. case .RTF:
  1789. eventStr = "Btn_SubTbr_Converter_ToRTF"
  1790. case .CSV:
  1791. eventStr = "Btn_SubTbr_Converter_ToCSV"
  1792. case .HTML:
  1793. eventStr = "Btn_SubTbr_Converter_ToHTML"
  1794. case .Text:
  1795. eventStr = "Btn_SubTbr_Converter_ToText"
  1796. case .JPEG:
  1797. eventStr = "Btn_SubTbr_Converter_ToImage"
  1798. case .PNG:
  1799. eventStr = "Btn_SubTbr_Converter_ToImage"
  1800. case .GIF:
  1801. eventStr = "Btn_SubTbr_Converter_ToImage"
  1802. case .JPG:
  1803. eventStr = "Btn_SubTbr_Converter_ToImage"
  1804. case .TIFF:
  1805. eventStr = "Btn_SubTbr_Converter_ToImage"
  1806. case .TGA:
  1807. eventStr = "Btn_SubTbr_Converter_ToImage"
  1808. case .BMP:
  1809. eventStr = "Btn_SubTbr_Converter_ToImage"
  1810. case .JP2:
  1811. eventStr = "Btn_SubTbr_Converter_ToImage"
  1812. case .AdvancedWord:
  1813. eventStr = "Btn_SubTbr_Converter_ToWord"
  1814. break
  1815. default:
  1816. break
  1817. }
  1818. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  1819. }
  1820. //MARK: 转档 - OCR
  1821. func showOCRWindow() {
  1822. if !IAPProductsManager.default().isAvailableAllFunction(){
  1823. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1824. winC?.showWindow(nil)
  1825. return
  1826. }
  1827. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  1828. com.currentIndexPage = self.listView.currentPageIndex
  1829. self.km_beginSheet(windowC: com)
  1830. }
  1831. // MARK: - 图片注释
  1832. @IBAction func imageAnnotation(_ sender: Any) {
  1833. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  1834. changeAnnotationMode(sender)
  1835. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1836. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1837. return
  1838. }
  1839. let accessoryCtr = KMImageAccessoryController()
  1840. let openPanel = NSOpenPanel()
  1841. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1842. openPanel.allowsMultipleSelection = false
  1843. openPanel.accessoryView = accessoryCtr.view
  1844. openPanel.canSelectHiddenExtension = true
  1845. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  1846. if result == .OK {
  1847. guard let url = openPanel.url else {
  1848. return
  1849. }
  1850. let filePath = url.path
  1851. if filePath.pathExtension.lowercased() == "pdf" {
  1852. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  1853. NSSound.beep()
  1854. return
  1855. }
  1856. }
  1857. guard let image = NSImage(contentsOfFile: url.path) else {
  1858. let alert = NSAlert()
  1859. alert.alertStyle = .critical
  1860. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  1861. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  1862. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1863. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  1864. if response == .alertFirstButtonReturn {
  1865. // Handle cancel button clicked
  1866. }
  1867. }
  1868. return
  1869. }
  1870. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  1871. if isDamageImage {
  1872. let alert = NSAlert()
  1873. alert.alertStyle = .critical
  1874. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  1875. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  1876. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1877. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  1878. if response == .alertFirstButtonReturn {
  1879. // Handle cancel button clicked
  1880. }
  1881. }
  1882. return
  1883. }
  1884. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1885. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  1886. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  1887. }
  1888. }
  1889. }
  1890. }
  1891. @IBAction func tableAnnotation(_ sender: Any) {
  1892. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  1893. changeAnnotationMode(sender)
  1894. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1895. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1896. winC?.kEventName = "Reading_Table_BuyNow"
  1897. winC?.showWindow(nil)
  1898. return
  1899. }
  1900. listView.addAnnotationWithTable()
  1901. toggleOpenRightSide()
  1902. }
  1903. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  1904. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  1905. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  1906. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  1907. }
  1908. if let data = image.tiffRepresentation,
  1909. let imageRep = NSBitmapImageRep(data: data) {
  1910. imageRep.size = image.size
  1911. var imageData: Data?
  1912. if path.lowercased() == "png" {
  1913. imageData = imageRep.representation(using: .png, properties: [:])
  1914. } else {
  1915. imageData = imageRep.representation(using: .jpeg, properties: [:])
  1916. }
  1917. if let imageData = imageData {
  1918. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  1919. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  1920. return true
  1921. } else {
  1922. return false
  1923. }
  1924. }
  1925. }
  1926. return false
  1927. }
  1928. func tagString() -> String {
  1929. let dateFormatter = DateFormatter()
  1930. dateFormatter.dateFormat = "yyMMddHHmmss"
  1931. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  1932. }
  1933. // MARK: - Split View
  1934. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  1935. }
  1936. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  1937. }
  1938. func updateBackAndForwardButtonState() {
  1939. }
  1940. }
  1941. extension KMMainViewController {
  1942. func changeModelAction(mode: CToolMode) {
  1943. self.listView.toolMode = mode
  1944. if mode == .CEditPDFToolMode {
  1945. }
  1946. }
  1947. func changePDFViewZoomInAction() {
  1948. }
  1949. func changePDFViewZoomOutAction() {
  1950. }
  1951. func changePDFViewGotoNextPageAction() {
  1952. self.listView.km_goBack(nil)
  1953. if (self.listView.canGoToNextPage()) {
  1954. self.listView.goToNextPage(nil)
  1955. }
  1956. }
  1957. func changePDFViewGoToPreviousPageAction() {
  1958. if (self.listView.canGoToPreviousPage()) {
  1959. self.listView.goToPreviousPage(nil)
  1960. }
  1961. }
  1962. func changePDFViewGotoBackAction() {
  1963. self.listView.km_goBack(nil)
  1964. self.updateBackAndForwardButtonState()
  1965. }
  1966. func changePDFViewGoToForwardAction() {
  1967. self.listView.km_goForward(nil)
  1968. self.updateBackAndForwardButtonState()
  1969. }
  1970. func aiTranslationPDFFileAction() {
  1971. self.trackEvent_aiTranslate()
  1972. self._aiTranslationPDFFileAction()
  1973. }
  1974. private func _aiTranslationPDFFileAction() {
  1975. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  1976. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  1977. let alert = NSAlert()
  1978. alert.alertStyle = .critical
  1979. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  1980. alert.runModal()
  1981. return
  1982. } else if isExceedsLimit {
  1983. let alert = NSAlert()
  1984. alert.alertStyle = .critical
  1985. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  1986. alert.runModal()
  1987. return
  1988. }
  1989. let alert = NSAlert()
  1990. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  1991. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  1992. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1993. alert.beginSheetModal(for: view.window!) { [weak self] result in
  1994. if (result == .alertFirstButtonReturn) {
  1995. } else if result == .alertSecondButtonReturn {
  1996. return
  1997. }
  1998. }
  1999. }
  2000. func clickChildTool(type: KMToolbarType, index: Int) {
  2001. if (type == .secure) {
  2002. if (index == 1) {
  2003. self.trackEvent_setPassword()
  2004. } else if (index == 2) {
  2005. self.trackEvent_removePassword()
  2006. }
  2007. } else {
  2008. self.trackEvent(toolBarType: type)
  2009. }
  2010. Task { @MainActor in
  2011. if (type == .compress) { /// 压缩
  2012. if !self.documentAllowsEdit() {
  2013. return
  2014. }
  2015. if (self.needSaveDocument()) {
  2016. self.saveDocumentWithProgressAlert { [unowned self] params in
  2017. // self.showCompressWindow()
  2018. }
  2019. return
  2020. }
  2021. // self.showCompressWindow()
  2022. return
  2023. }
  2024. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  2025. if type == .conversion_imageToPDF {
  2026. Task {
  2027. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  2028. }
  2029. return
  2030. }
  2031. var identifier: String?
  2032. if (type == .word) { /// Word
  2033. identifier = KMToolbarConversionWordItemIdentifier
  2034. } else if (type == .excel) {
  2035. identifier = KMToolbarConversionExcelItemIdentifier
  2036. } else if (type == .ppt) {
  2037. identifier = KMToolbarConversionPPTItemIdentifier
  2038. } else if (type == .rtf) {
  2039. identifier = KMToolbarConversionRTFItemIdentifier
  2040. } else if (type == .html) {
  2041. identifier = KMToolbarConversionHTMLItemIdentifier
  2042. } else if (type == .conversion_text) {
  2043. identifier = KMToolbarConversionTextItemIdentifier
  2044. } else if (type == .csv) {
  2045. identifier = KMToolbarConversionCSVItemIdentifier
  2046. } else if (type == .conversion_image) {
  2047. identifier = KMToolbarConversionImageItemIdentifier
  2048. }
  2049. if (self.needSaveDocument()) {
  2050. self.saveDocumentWithProgressAlert { [unowned self] params in
  2051. self.showConvertWindow(type: type, identifier: identifier)
  2052. }
  2053. return
  2054. }
  2055. self.showConvertWindow(type: type, identifier: identifier)
  2056. return
  2057. }
  2058. if (type == .merge) { /// 合并
  2059. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  2060. if !self.documentAllowsEdit() {
  2061. return
  2062. }
  2063. if (self.needSaveDocument()) {
  2064. self.saveDocumentWithProgressAlert { [unowned self] params in
  2065. self.showMergeWindow(self.listView.document.password)
  2066. }
  2067. return
  2068. }
  2069. self.showMergeWindow(self.listView.document.password)
  2070. return
  2071. }
  2072. if (type == .bates || type == .headerAndFooter) {
  2073. if !IAPProductsManager.default().isAvailableAllFunction(){
  2074. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2075. if type == .headerAndFooter {
  2076. if index == 1 {
  2077. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  2078. } else if index == 2 {
  2079. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  2080. }
  2081. } else if type == .bates {
  2082. if index == 1 {
  2083. winC?.kEventName = "Reading_AddBates_BuyNow"
  2084. } else if index == 2 {
  2085. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  2086. }
  2087. }
  2088. winC?.showWindow(nil)
  2089. return
  2090. }
  2091. if !self.documentAllowsEdit() {
  2092. return
  2093. }
  2094. if (index == 1) {
  2095. var windowController: KMBaseWindowController = KMBaseWindowController()
  2096. if (type == .bates) {
  2097. } else if (type == .headerAndFooter) {
  2098. } else if (type == .background) {
  2099. } else if (type == .watermark) {
  2100. }
  2101. windowController.pdfDocument = self.listView.document
  2102. windowController.cancelAction = { [unowned self] controller in
  2103. self.view.window?.endSheet((self.currentWindowController.window)!)
  2104. self.currentWindowController = nil
  2105. }
  2106. self.currentWindowController = windowController
  2107. await self.view.window?.beginSheet(windowController.window!)
  2108. return
  2109. }
  2110. if (index == 1) { /// 取消
  2111. ///
  2112. toggleCloseRightSide()
  2113. return
  2114. } else if index == 3 {
  2115. let fpath = self.document?.documentURL?.path ?? ""
  2116. if type == .bates {
  2117. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2118. } else {
  2119. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2120. }
  2121. } else if index == 4 {
  2122. let fpath = self.document?.documentURL?.path ?? ""
  2123. if type == .bates {
  2124. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  2125. } else {
  2126. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  2127. }
  2128. } else if (index == 2) { //// 移除
  2129. if type == .headerAndFooter {
  2130. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2131. let savePanel = NSSavePanel()
  2132. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2133. savePanel.allowedFileTypes = ["pdf"]
  2134. savePanel.accessoryView = savePanelAccessoryViewController.view
  2135. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2136. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2137. }
  2138. }
  2139. } else if type == .bates {
  2140. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2141. let savePanel = NSSavePanel()
  2142. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2143. savePanel.allowedFileTypes = ["pdf"]
  2144. savePanel.accessoryView = savePanelAccessoryViewController.view
  2145. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2146. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2147. }
  2148. }
  2149. }
  2150. } else if (index == 2) { /// 应用
  2151. } else if index == 5 {
  2152. self.toggleOpenRightSide()
  2153. }
  2154. } else if (type == .redact) { /// 标记密文
  2155. if !IAPProductsManager.default().isAvailableAllFunction(){
  2156. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2157. return
  2158. }
  2159. if (index == 1) { /// 取消
  2160. if (self.model.hasAddRedact) {
  2161. let alert = NSAlert()
  2162. 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: "")
  2163. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2164. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2165. let result = alert.runModal()
  2166. if (result == .alertFirstButtonReturn) {
  2167. self.listView.toolMode = .CMoveToolMode
  2168. }
  2169. return
  2170. }
  2171. self.listView.toolMode = .CMoveToolMode
  2172. return
  2173. }
  2174. if (index == 2) { /// 擦除
  2175. self.exeRedactConfirm(.eraserAll) {}
  2176. return
  2177. }
  2178. if (index == 3) { /// 应用
  2179. self.exeRedactConfirm(.redactAll) {}
  2180. return
  2181. }
  2182. if (index == 4) { /// 文本&图像
  2183. self.listView.toolMode = .CRedactToolMode
  2184. return
  2185. }
  2186. if (index == 5) { /// 页面
  2187. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2188. await self.view.window?.beginSheet(windowController.window!)
  2189. self.currentWindowController = windowController
  2190. windowController.itemClick = { [weak self] index, value in
  2191. if (index == 1) {
  2192. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2193. self?.currentWindowController = nil
  2194. return
  2195. }
  2196. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2197. let pageType = windowController_pageRange.pageType
  2198. let pageString = windowController_pageRange.pageString
  2199. if (pageType == 5) { /// 自定义页面
  2200. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  2201. if (array.count == 0) {
  2202. let alert = NSAlert()
  2203. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2204. alert.runModal()
  2205. return
  2206. }
  2207. }
  2208. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2209. self!.currentWindowController = nil
  2210. var indexs: IndexSet = []
  2211. if (pageType == 1) { /// 当前页面
  2212. indexs.insert((self?.listView.currentPageIndex)!)
  2213. } else {
  2214. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  2215. }
  2216. if (indexs.count == 0) {
  2217. return
  2218. }
  2219. for i in indexs {
  2220. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2221. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2222. redactAnno.bounds = page.bounds
  2223. self?.listView.add(redactAnno, to: page)
  2224. }
  2225. }
  2226. return
  2227. }
  2228. } else if (type == .secure) { /// 安全
  2229. if (index == 1) { /// 设置密码
  2230. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2231. if !self.documentAllowsEdit() {
  2232. return
  2233. }
  2234. }
  2235. self.showSecureWindow(self.listView.document.documentURL)
  2236. return
  2237. } else if index == 2 {
  2238. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  2239. let alert = NSAlert()
  2240. alert.alertStyle = .warning
  2241. alert.messageText = NSLocalizedString("Warning", comment: "")
  2242. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2243. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  2244. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  2245. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  2246. if returnCode == .alertSecondButtonReturn {
  2247. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2248. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  2249. if success {
  2250. self.document?.unlock(withPassword: resultPassword)
  2251. self.clickChildTool(type: .secure, index: 2)
  2252. }
  2253. }
  2254. }
  2255. }
  2256. }
  2257. } else {
  2258. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  2259. controller.pdfDocument = self.document
  2260. self.currentWindowController = controller
  2261. controller.batchAction = { [unowned self] controller, files in
  2262. self.view.window?.endSheet((self.currentWindowController.window)!)
  2263. self.currentWindowController = nil
  2264. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  2265. if #available(macOS 10.13, *) {
  2266. baseWindowController.window?.makeKeyAndOrderFront(nil)
  2267. } else {
  2268. baseWindowController.showWindow(nil)
  2269. }
  2270. let arr = NSMutableArray()
  2271. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  2272. file.password = document?.password ?? ""
  2273. arr.add(file)
  2274. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  2275. }
  2276. controller.cancelAction = { [unowned self] controller in
  2277. self.view.window?.endSheet((self.currentWindowController.window)!)
  2278. self.currentWindowController = nil
  2279. }
  2280. controller.doneAction = { [unowned self] controller in
  2281. self.view.window?.endSheet((self.currentWindowController.window)!)
  2282. self.currentWindowController = nil
  2283. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  2284. if success {
  2285. let savePanel = NSSavePanel()
  2286. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  2287. savePanel.allowedFileTypes = ["pdf"]
  2288. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  2289. guard result == .OK else { return }
  2290. /// 删除安全性设置
  2291. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2292. self.model.isSaveKeyChain = false
  2293. self.listView.document.unlock(withPassword: resultPassword)
  2294. }
  2295. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  2296. guard let document = document else { return }
  2297. document.unlock(withPassword: resultPassword)
  2298. let success = document.writeDecrypt(to: savePanel.url)
  2299. if success {
  2300. self.hiddenSecureLimitTip()
  2301. let tip = KMRemovePasswordResultTipView()
  2302. tip.result = .success
  2303. tip.showInView(superView: (self.listView.superview)!)
  2304. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2305. } else {
  2306. self.hiddenSecureLimitTip()
  2307. let tip = KMRemovePasswordResultTipView()
  2308. tip.result = .failure
  2309. tip.showInView(superView: (self.listView.superview)!)
  2310. }
  2311. }
  2312. }
  2313. }
  2314. }
  2315. await NSWindow.currentWindow().beginSheet(controller.window!)
  2316. }
  2317. return
  2318. }
  2319. } else if type == .comparison {
  2320. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  2321. if !IAPProductsManager.default().isAvailableAllFunction(){
  2322. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2323. winC?.kEventName = "Reading_Compare_BuyNow"
  2324. winC?.showWindow(nil)
  2325. return
  2326. }
  2327. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2328. self.currentWindowController = controller
  2329. controller.password = self.document?.password ?? ""
  2330. controller.filePath = (self.document?.documentURL.path)!
  2331. controller.cancelAction = { [unowned self] controller in
  2332. self.view.window?.endSheet((self.currentWindowController.window)!)
  2333. self.currentWindowController = nil
  2334. }
  2335. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  2336. self.view.window?.endSheet((self.currentWindowController.window)!)
  2337. self.currentWindowController = nil
  2338. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  2339. }
  2340. controller.coveringComplete = { [unowned self] controller, document in
  2341. self.view.window?.endSheet((self.currentWindowController.window)!)
  2342. self.currentWindowController = nil
  2343. self.openCoveringCompareVC(with: document)
  2344. }
  2345. if index == 1 {
  2346. controller.fileType = .content
  2347. } else {
  2348. controller.fileType = .coverting
  2349. }
  2350. await NSWindow.currentWindow().beginSheet(controller.window!)
  2351. } else if type == .watermark {
  2352. if !IAPProductsManager.default().isAvailableAllFunction(){
  2353. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2354. if index == 1 {
  2355. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  2356. } else if index == 2 {
  2357. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  2358. }
  2359. winC?.showWindow(nil)
  2360. return
  2361. }
  2362. if !self.documentAllowsEdit() {
  2363. return
  2364. }
  2365. if index == 1 {
  2366. } else if index == 2 {
  2367. let watermarks = self.listView.document.watermarks()
  2368. if (watermarks == nil || watermarks!.count <= 0) {
  2369. let alert = NSAlert()
  2370. alert.alertStyle = .warning
  2371. 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: "")
  2372. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  2373. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2374. alert.runModal()
  2375. return
  2376. }
  2377. let alert = NSAlert()
  2378. alert.alertStyle = .warning
  2379. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  2380. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2381. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2382. let result = alert.runModal()
  2383. if (result != .alertFirstButtonReturn) {
  2384. return
  2385. }
  2386. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2387. let savePanel = NSSavePanel()
  2388. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  2389. savePanel.allowedFileTypes = ["pdf"]
  2390. savePanel.accessoryView = savePanelAccessoryViewController.view
  2391. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2392. guard result == .OK else { return }
  2393. }
  2394. } else if index == 3 {
  2395. let fpath = self.document?.documentURL?.path ?? ""
  2396. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  2397. } else if index == 4 {
  2398. let fpath = self.document?.documentURL?.path ?? ""
  2399. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  2400. } else if index == 5 {
  2401. toggleOpenRightSide()
  2402. return
  2403. }
  2404. } else if type == .background {
  2405. if !IAPProductsManager.default().isAvailableAllFunction(){
  2406. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2407. if index == 1 {
  2408. winC?.kEventName = "Reading_AddBackground_BuyNow"
  2409. } else if index == 2 {
  2410. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  2411. }
  2412. winC?.showWindow(nil)
  2413. return
  2414. }
  2415. if !self.documentAllowsEdit() {
  2416. return
  2417. }
  2418. if index == 1 {
  2419. } else if index == 2 {
  2420. guard let document = self.document else { return }
  2421. if !document.allowsPrinting || !document.allowsCopying {
  2422. let alert = NSAlert()
  2423. alert.alertStyle = .critical
  2424. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2425. alert.runModal()
  2426. return
  2427. }
  2428. guard let documentURL = document.documentURL else { return }
  2429. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2430. let savePanel = NSSavePanel()
  2431. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  2432. savePanel.allowedFileTypes = ["pdf"]
  2433. savePanel.accessoryView = savePanelAccessoryViewController.view
  2434. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2435. guard result == .OK else { return }
  2436. }
  2437. } else if index == 3 {
  2438. let fpath = self.document?.documentURL?.path ?? ""
  2439. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  2440. } else if index == 4 {
  2441. let fpath = self.document?.documentURL?.path ?? ""
  2442. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  2443. } else if index == 5 {
  2444. toggleOpenRightSide()
  2445. return
  2446. }
  2447. } else if type == .measure {
  2448. if !IAPProductsManager.default().isAvailableAllFunction(){
  2449. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2450. winC?.kEventName = "Reading_Measure_BuyNow"
  2451. winC?.showWindow(nil)
  2452. return
  2453. }
  2454. if !self.documentAllowsEdit() {
  2455. return
  2456. }
  2457. self.listView.toolMode = .CNoteToolMode
  2458. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2459. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2460. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2461. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2462. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2463. areaMeasureInfoWindowController?.hideFloatingWindow()
  2464. }
  2465. if distanceMeasureInfoWindowController == nil {
  2466. let measureInfo = CPDFDistanceMeasureInfo()
  2467. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2468. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2469. distanceMeasureInfoWindowController?.delegate = self
  2470. }
  2471. if perimeterMeasureInfoWindowController == nil {
  2472. let measureInfo = CPDFPerimeterMeasureInfo()
  2473. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2474. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2475. perimeterMeasureInfoWindowController?.delegate = self
  2476. }
  2477. if areaMeasureInfoWindowController == nil {
  2478. let measureInfo = CPDFAreaMeasureInfo()
  2479. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2480. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2481. areaMeasureInfoWindowController?.delegate = self
  2482. }
  2483. if index == 1 {
  2484. self.listView.annotationType = .measureLine
  2485. let winW: CGFloat = 300
  2486. let rightW: CGFloat = 270
  2487. var winFrame = self.view.window?.frame ?? .zero
  2488. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2489. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2490. distanceMeasureInfoWindowController?.showWindow(nil)
  2491. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2492. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2493. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2494. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2495. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2496. self.trackEvent(toolMode: .CNoteToolMode)
  2497. } else if index == 2 {
  2498. self.listView.annotationType = .measurePolyLine
  2499. let winW: CGFloat = 300
  2500. let rightW: CGFloat = 270
  2501. var winFrame = self.view.window?.frame ?? .zero
  2502. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2503. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2504. perimeterMeasureInfoWindowController?.showWindow(nil)
  2505. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2506. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2507. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2508. self.trackEvent(toolMode: .CNoteToolMode)
  2509. } else if index == 3 {
  2510. self.listView.annotationType = .measurePolyGon
  2511. let winW: CGFloat = 300
  2512. let rightW: CGFloat = 270
  2513. var winFrame = self.view.window?.frame ?? .zero
  2514. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2515. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2516. areaMeasureInfoWindowController?.showWindow(nil)
  2517. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2518. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2519. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2520. self.trackEvent(toolMode: .CNoteToolMode)
  2521. } else if index == 4 {
  2522. self.listView.annotationType = .measureSquare
  2523. let winW: CGFloat = 300
  2524. let rightW: CGFloat = 270
  2525. var winFrame = self.view.window?.frame ?? .zero
  2526. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2527. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2528. areaMeasureInfoWindowController?.showWindow(nil)
  2529. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2530. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2531. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2532. self.trackEvent(toolMode: .CNoteToolMode)
  2533. } else {
  2534. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  2535. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2536. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  2537. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2538. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  2539. areaMeasureInfoWindowController?.hideFloatingWindow()
  2540. }
  2541. }
  2542. toggleOpenRightSide()
  2543. }
  2544. }
  2545. }
  2546. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  2547. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2548. var array: [KMBatchOperateFile] = []
  2549. for fpath in filepaths ?? [] {
  2550. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  2551. array.append(batchOperateFile)
  2552. }
  2553. batchWindowController.switchToOperateType(type, files: array)
  2554. batchWindowController.window?.makeKeyAndOrderFront("")
  2555. }
  2556. func openNewWindowAlertWindow() {
  2557. var needShowChooseWindow = false
  2558. //#if VERSION_FREE
  2559. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  2560. needShowChooseWindow = true
  2561. }
  2562. //#endif
  2563. if needShowChooseWindow {
  2564. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  2565. if preferenceNoteShow {
  2566. menuItemAction_newTagPageToNewWindow("")
  2567. } else {
  2568. if !KMDataManager.default.isTabbingWin{
  2569. KMDataManager.default.isTabbingWin = true
  2570. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  2571. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  2572. KMDataManager.default.isTabbingWin = false
  2573. if continueOrNot {
  2574. self?.reopenDocument(forPaths: [])
  2575. } else {
  2576. }
  2577. }
  2578. self.km_beginSheet(windowC: tabbingWin)
  2579. }
  2580. }
  2581. }else{
  2582. handleTabbingLogic()
  2583. }
  2584. }
  2585. func reopenDocument(forPaths paths: [String]) -> Void {
  2586. let browser = KMBrowser.init() as KMBrowser
  2587. browser.windowController = KMBrowserWindowController.init(browser: browser)
  2588. browser.addHomeTabContents()
  2589. browser.windowController.showWindow(self)
  2590. }
  2591. func handleTabbingLogic() {
  2592. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  2593. }
  2594. func convertToImg(index: Int) {
  2595. var convertT: KMConvertType = .JPEG
  2596. switch index {
  2597. case 7:
  2598. convertT = .JPEG
  2599. case 8:
  2600. convertT = .JPG
  2601. case 9:
  2602. convertT = .PNG
  2603. case 10:
  2604. convertT = .GIF
  2605. case 11:
  2606. convertT = .TIFF
  2607. case 12:
  2608. convertT = .TGA
  2609. case 13:
  2610. convertT = .BMP
  2611. default:
  2612. convertT = .JPEG
  2613. }
  2614. showAllConvertWindow(convertT: convertT)
  2615. }
  2616. }
  2617. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  2618. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  2619. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2620. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  2621. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2622. distanceSettingWC.delegate = self
  2623. distanceSettingWC.startModal("")
  2624. }
  2625. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2626. }
  2627. }
  2628. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  2629. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  2630. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  2631. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  2632. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2633. distanceSettingWC.delegate = self
  2634. distanceSettingWC.startModal("")
  2635. }
  2636. }
  2637. // MARK: CAreaMeasureInfoWindowControllerDelegate
  2638. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  2639. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  2640. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  2641. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  2642. areaSettingWC.delegate = self
  2643. areaSettingWC.startModal("")
  2644. }
  2645. }
  2646. // MARK: CDistanceSettingWindowControllerDelegate
  2647. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  2648. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  2649. if distanceMeasureInfo != nil {
  2650. if self.listView.activeAnnotations.count > 0 {
  2651. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  2652. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  2653. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2654. }
  2655. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  2656. } else {
  2657. distanceMeasureInfo?.leadLength = 0
  2658. self.listView.distanceMeasureInfo = distanceMeasureInfo
  2659. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  2660. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2661. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2662. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2663. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2664. }
  2665. if let data = self.listView.activeAnnotation {
  2666. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2667. }
  2668. }
  2669. self.distanceMeasureInfoWindowController?.showWindow(self)
  2670. }
  2671. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  2672. if perimeterMeasureInfo != nil {
  2673. if self.listView.activeAnnotations.count > 0 {
  2674. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  2675. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  2676. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2677. }
  2678. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  2679. } else {
  2680. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  2681. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  2682. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2683. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2684. }
  2685. if let data = self.listView.activeAnnotation {
  2686. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2687. }
  2688. }
  2689. self.perimeterMeasureInfoWindowController?.showWindow(self)
  2690. }
  2691. }
  2692. // MARK: CAreaSettingWindowControllerDelegate
  2693. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  2694. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  2695. if self.listView.annotationType == .measureSquare && self.listView.toolMode == .CNoteToolMode {
  2696. if measureInfo != nil {
  2697. if self.listView.activeAnnotations.count > 0 {
  2698. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2699. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2700. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2701. }
  2702. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2703. } else {
  2704. self.listView.squareAreaMeasureInfo = measureInfo
  2705. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  2706. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2707. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2708. }
  2709. }
  2710. self.areaMeasureInfoWindowController?.showWindow(self)
  2711. } else if self.listView.annotationType == .measurePolyGon && self.listView.toolMode == .CNoteToolMode {
  2712. if measureInfo != nil {
  2713. if self.listView.activeAnnotations.count > 0 {
  2714. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2715. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2716. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2717. }
  2718. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2719. } else {
  2720. self.listView.polygonAreaMeasureInfo = measureInfo
  2721. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  2722. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2723. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2724. }
  2725. }
  2726. self.areaMeasureInfoWindowController?.showWindow(self)
  2727. } else {
  2728. if measureInfo != nil {
  2729. if self.listView.activeAnnotations.count > 0 {
  2730. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2731. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2732. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2733. }
  2734. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2735. }
  2736. }
  2737. self.areaMeasureInfoWindowController?.showWindow(self)
  2738. }
  2739. if measureInfo != nil {
  2740. if let data = self.listView.activeAnnotation {
  2741. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2742. }
  2743. }
  2744. }
  2745. }
  2746. //MARK: LeftSideViewController
  2747. extension KMMainViewController {
  2748. func leftSideViewCancelSelect() {
  2749. if self.listView.isEditing() == true {
  2750. if self.listView.editingAreas() != nil &&
  2751. self.listView.editingAreas().count != 0 {
  2752. let areas = self.listView.editingAreas().first
  2753. if areas is CPDFEditTextArea {
  2754. self.listView.clearEditingSelectCharItem()
  2755. self.listView.updateEditing([])
  2756. KMPrint("取消选中")
  2757. }
  2758. }
  2759. }
  2760. }
  2761. }
  2762. // MARK: - Analytics (埋点)
  2763. extension KMMainViewController {
  2764. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  2765. if (type == .Annatiton) {
  2766. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  2767. } else if (type == .editPDF) {
  2768. } else if (type == .Page) {
  2769. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  2770. } else if (type == .Conversion) {
  2771. } else if (type == .Tool) {
  2772. }
  2773. }
  2774. func trackEvent_aiTranslate() -> Void {
  2775. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  2776. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2777. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2778. }
  2779. func trackEvent_print() -> Void {
  2780. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  2781. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2782. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2783. }
  2784. func trackEvent_share() -> Void {
  2785. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  2786. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2787. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2788. }
  2789. func trackEvent_upgrade() -> Void {
  2790. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  2791. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2792. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2793. }
  2794. func trackEvent(annotationType type: CAnnotationType) -> Void {
  2795. if (type == .highlight) {
  2796. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  2797. } else if (type == .underline) {
  2798. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  2799. } else if (type == .strikeOut) {
  2800. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  2801. } else if (type == .ink) {
  2802. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  2803. } else if (type == .freeText) {
  2804. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  2805. } else if (type == .anchored) {
  2806. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  2807. } else if (type == .square) {
  2808. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  2809. } else if (type == .link) {
  2810. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  2811. } else if (type == .stamp) {
  2812. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  2813. } else if (type == .signSignature) {
  2814. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  2815. } else if (type == .circle) {
  2816. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  2817. } else if (type == .arrow) {
  2818. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  2819. } else if (type == .line) {
  2820. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  2821. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .text) {
  2822. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  2823. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  2824. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2825. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .image) {
  2826. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  2827. } else if (type == .textField) {
  2828. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  2829. } else if (type == .checkBox) {
  2830. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  2831. } else if (type == .radioButton) {
  2832. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  2833. } else if (type == .listMenu) {
  2834. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  2835. } else if (type == .comboBox) {
  2836. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  2837. } else if (type == .actionButton) {
  2838. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  2839. } else if (type == .actionButton) {
  2840. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  2841. } else if (type == .signature) {
  2842. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  2843. } else if (type == .squiggly) {
  2844. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  2845. } else if (type == .eraser) {
  2846. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  2847. }
  2848. }
  2849. func trackEvent(toolMode mode: CToolMode) -> Void {
  2850. if (mode == .CSelectToolMode) {
  2851. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  2852. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2853. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2854. } else if (mode == .CMoveToolMode) {
  2855. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  2856. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  2857. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2858. } else if mode == .CNoteToolMode {
  2859. if CPDFListView.isMeasure(self.listView.annotationType) == true {
  2860. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  2861. }
  2862. }
  2863. }
  2864. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  2865. if (type == .word) {
  2866. } else if (type == .excel) {
  2867. } else if (type == .ppt) {
  2868. } else if (type == .rtf) {
  2869. } else if (type == .csv) {
  2870. } else if (type == .html) {
  2871. } else if (type == .conversion_text) {
  2872. } else if (type == .conversion_image) {
  2873. } else if (type == .compress) {
  2874. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  2875. } else if (type == .merge) {
  2876. } else if (type == .secure) {
  2877. } else if (type == .crop) {
  2878. } else if type == .json {
  2879. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  2880. }
  2881. }
  2882. func trackEvent_setPassword() -> Void {
  2883. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  2884. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2885. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2886. }
  2887. func trackEvent_removePassword() -> Void {
  2888. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  2889. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  2890. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2891. }
  2892. func trackEvent_replace() -> Void {
  2893. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  2894. }
  2895. }
  2896. extension KMMainViewController {
  2897. //文件对比
  2898. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  2899. self.isCompareModel = true
  2900. let compareContentView = KMCompareContentView()
  2901. compareContentView.oldDocument = oldDocument
  2902. compareContentView.document = document
  2903. compareContentView.compareResults = results
  2904. compareContentView.saveHandle = { [unowned self] view in
  2905. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2906. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  2907. self.currentWindowController = saveController
  2908. saveController.cancelHandle = { [unowned self] controller in
  2909. self.view.window!.endSheet(controller.window!)
  2910. self.currentWindowController = nil
  2911. }
  2912. saveController.saveHandle = { [unowned self] controller, saveType in
  2913. let folderPath = controller.fileSaveFolderPath
  2914. if folderPath != nil {
  2915. if !FileManager.default.fileExists(atPath: folderPath) {
  2916. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  2917. }
  2918. #if VERSION_DMG
  2919. #else
  2920. let url = URL(fileURLWithPath: folderPath)
  2921. let fileAccess = AppSandboxFileAccess()
  2922. fileAccess?.persistPermissionURL(url)
  2923. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  2924. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  2925. let urlString = url.path
  2926. let _url = URL(fileURLWithPath: urlString)
  2927. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  2928. }
  2929. #endif
  2930. var savePath: String
  2931. switch saveType {
  2932. case 0:
  2933. let filePath = oldDocument.documentURL.path
  2934. let fileName = filePath.deletingPathExtension.lastPathComponent
  2935. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  2936. savePath = self.getValidFilePath(savePath)
  2937. oldDocument.write(to: URL(fileURLWithPath: savePath))
  2938. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2939. case 1:
  2940. let filePath = document.documentURL.path
  2941. let fileName = filePath.deletingPathExtension.lastPathComponent
  2942. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  2943. savePath = self.getValidFilePath(savePath)
  2944. document.write(to: URL(fileURLWithPath: savePath))
  2945. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2946. case 2:
  2947. let filePath = oldDocument.documentURL.path
  2948. let fileName = filePath.deletingPathExtension.lastPathComponent
  2949. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  2950. savePath = self.getValidFilePath(savePath)
  2951. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  2952. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2953. default:
  2954. break
  2955. }
  2956. }
  2957. self.view.window!.endSheet(controller.window!)
  2958. self.currentWindowController = nil
  2959. }
  2960. NSWindow.currentWindow().beginSheet(saveController.window!)
  2961. }
  2962. }
  2963. compareContentView.closeHandle = { [unowned self] view in
  2964. self.isCompareModel = false
  2965. view.removeFromSuperview()
  2966. }
  2967. compareContentView.autoresizingMask = [.width,.height]
  2968. }
  2969. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  2970. self.isCompareModel = true
  2971. let coveringView = KMCompareCoveringView()
  2972. coveringView.pdfDocument = pdfDocument
  2973. coveringView.closeHandle = { [unowned self] view in
  2974. self.isCompareModel = false
  2975. view.removeFromSuperview()
  2976. }
  2977. coveringView.saveHandle = { [unowned self] view in
  2978. let savePanel = NSSavePanel()
  2979. savePanel.nameFieldStringValue = "untitled"
  2980. savePanel.allowedFileTypes = ["pdf"]
  2981. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  2982. if result == .OK {
  2983. pdfDocument.write(to: savePanel.url!)
  2984. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2985. }
  2986. }
  2987. }
  2988. coveringView.autoresizingMask = [.width,.height]
  2989. }
  2990. func getValidFilePath(_ oldPath: String) -> String {
  2991. let fileManager = FileManager.default
  2992. do {
  2993. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  2994. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  2995. return oldPath
  2996. }
  2997. var i = 1
  2998. var newPath = oldPath
  2999. while fileManager.fileExists(atPath: newPath) {
  3000. if fileType == FileAttributeType.typeDirectory.rawValue {
  3001. newPath = oldPath + "(\(i))"
  3002. } else {
  3003. let fileExtension = (oldPath as NSString).pathExtension
  3004. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3005. }
  3006. i += 1
  3007. }
  3008. return newPath
  3009. } catch {
  3010. print("Error getting file attributes: \(error)")
  3011. return oldPath
  3012. }
  3013. }
  3014. }
  3015. extension KMMainViewController {
  3016. func documentAllowsEdit() -> Bool {
  3017. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  3018. let alert = NSAlert()
  3019. alert.alertStyle = .critical
  3020. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3021. alert.runModal()
  3022. return false
  3023. } else {
  3024. return true
  3025. }
  3026. }
  3027. func changeFont(_ sender: NSFontManager) {
  3028. KMPrint("changeFont ...")
  3029. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  3030. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  3031. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  3032. font = sender.convert(font!)
  3033. annotation.fontSize = font?.pointSize ?? 12
  3034. self.listView.commitEditAnnotationFreeText(annotation)
  3035. self.listView.setNeedsDisplay(annotation)
  3036. }
  3037. }
  3038. func currentSetup() -> [String: Any] {
  3039. var setup: [String: Any] = [:]
  3040. var point = NSZeroPoint
  3041. if listView == nil {
  3042. return setup
  3043. }
  3044. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  3045. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  3046. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  3047. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  3048. setup[KMMainModel.Key.pageIndex] = pageIndex
  3049. return setup
  3050. }
  3051. // MARK: - Recommond活动
  3052. func loadRecommondPopWindow() {
  3053. if IAPProductsManager.default().isAvailableAllFunction() {
  3054. return
  3055. }
  3056. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  3057. if recommondPopWindowVC == nil {
  3058. recommondPopWindowVC = KMRecommondPopWindow.default()
  3059. }
  3060. recommondPopWindowVC?.recommondInfo = info
  3061. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  3062. return
  3063. }
  3064. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  3065. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  3066. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  3067. recommondPopWindowVC?.window?.orderFront((Any).self)
  3068. recommondPopWindowVC?.window?.becomeMain()
  3069. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  3070. UserDefaults.standard.synchronize()
  3071. }
  3072. }
  3073. @objc func didAddContentViewNotification(_ sender: Notification) {
  3074. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3075. return
  3076. }
  3077. if self.interactionMode == .presentation {
  3078. }
  3079. }
  3080. @objc func purchaseStateUpdateNoti() {
  3081. if IAPProductsManager.default().isAvailableAllFunction() {
  3082. }
  3083. }
  3084. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  3085. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  3086. guard let anno = sender.object as? CPDFAnnotation else {
  3087. return
  3088. }
  3089. if anno.page?.document != self.listView.document {
  3090. return
  3091. }
  3092. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  3093. }
  3094. // MARK: Split View
  3095. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  3096. let openPanel = NSOpenPanel()
  3097. openPanel.allowedFileTypes = ["pdf", "PDF"]
  3098. openPanel.allowsMultipleSelection = false
  3099. guard let mainWindow = NSApp.mainWindow else {
  3100. return
  3101. }
  3102. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  3103. if response == NSApplication.ModalResponse.OK {
  3104. guard let url = openPanel.url else {
  3105. return
  3106. }
  3107. if let document = CPDFDocument(url: url) {
  3108. replaceBlock(document.documentURL?.path ?? "")
  3109. } else {
  3110. let alert = NSAlert()
  3111. alert.alertStyle = .critical
  3112. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3113. alert.runModal()
  3114. }
  3115. }
  3116. }
  3117. }
  3118. }