KMMainViewController+Action.swift 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782
  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: #selector(showTTSView), target: self)
  322. return stypItem
  323. }
  324. func setShareStype() -> NSMenuItem {
  325. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  326. var string = ""
  327. if listView.activeAnnotation != nil {
  328. string = self.listView.activeAnnotation?.contents ?? ""
  329. }
  330. if string.count < 1{
  331. string = self.listView.currentSelection?.string() ?? ""
  332. }
  333. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  334. return stypItem
  335. }
  336. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  337. var number = 0
  338. var indexN = 0
  339. guard str.count > 0 else {return (0, 0)}
  340. for i in 0...str.count - 1 {
  341. let c: unichar = (str as NSString).character(at: i)
  342. if (c >= 0x4E00) {
  343. number += 2
  344. }else {
  345. number += 1
  346. }
  347. if number > 56{
  348. indexN = i
  349. number = 100
  350. break
  351. }
  352. }
  353. return (number, indexN)
  354. }
  355. func setLookUpStype() -> NSMenuItem {
  356. guard let str = listView.currentSelection?.string() else {
  357. return NSMenuItem.separator()
  358. }//String(format: "Look Up %@", listView.currentSelection?.string() ?? "")
  359. let dic = numberOfChars(str)
  360. var newStr = str
  361. if dic.num == 100{
  362. newStr = str.prefix(dic.indexN) + "..."
  363. }
  364. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  365. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  366. return stypItem
  367. }
  368. func setSearchBaiduStype() -> NSMenuItem {
  369. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  370. return stypItem
  371. }
  372. func setCutStype() -> NSMenuItem {
  373. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  374. return stypItem
  375. }
  376. func setDeleteStype() -> NSMenuItem {
  377. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  378. return stypItem
  379. }
  380. func setColorsStype() -> NSMenuItem {
  381. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  382. return stypItem
  383. }
  384. func setLinesStype() -> NSMenuItem {
  385. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  386. return stypItem
  387. }
  388. func setEditNoteStype() -> NSMenuItem {
  389. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  390. return stypItem
  391. }
  392. func setRotateStype() -> NSMenuItem {
  393. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  394. let stypeMenu = NSMenu()
  395. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  396. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  397. stypItem.submenu = stypeMenu
  398. return stypItem
  399. }
  400. func setNextPageStype() -> NSMenuItem {
  401. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  402. stypItem.isEnabled = false
  403. if listView.canGoToNextPage() {
  404. stypItem.isEnabled = true
  405. }
  406. return stypItem
  407. }
  408. func setPreviousPageStype() -> NSMenuItem {
  409. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  410. stypItem.isEnabled = false
  411. if listView.canGoToPreviousPage() {
  412. stypItem.isEnabled = true
  413. }
  414. return stypItem
  415. }
  416. func setTranslateStype() -> NSMenuItem {
  417. let str = listView.currentSelection?.string() ?? ""//String(format: "Translate %@", listView.currentSelection?.string() ?? "")
  418. let dic = numberOfChars(str)
  419. var newStr = str
  420. if dic.num == 100{
  421. newStr = str.prefix(dic.indexN) + "..."
  422. }
  423. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  424. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  425. return stypItem
  426. }
  427. func setAutoScrollStype() -> NSMenuItem {
  428. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  429. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  430. return stypItem
  431. }
  432. func setSnapshotStype() -> NSMenuItem {
  433. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  434. let stypeMenu = NSMenu()
  435. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  436. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  437. stypItem.submenu = stypeMenu
  438. return stypItem
  439. }
  440. func setServicesStype() -> NSMenuItem {
  441. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  442. let stypeMenu = NSMenu()
  443. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  444. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  445. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  446. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  447. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  448. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  449. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  450. stypItem.submenu = stypeMenu
  451. return stypItem
  452. }
  453. func setCropStype() -> NSMenuItem {
  454. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  455. let stypeMenu = NSMenu()
  456. if NSIsEmptyRect(listView.selectionRect){
  457. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  458. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  459. }
  460. stypItem.submenu = stypeMenu
  461. return stypItem
  462. }
  463. func setAITranslateStype() -> NSMenuItem {
  464. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  465. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  466. return stypItem
  467. }
  468. func setAIProofreadStype() -> NSMenuItem {
  469. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  470. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  471. return stypItem
  472. }
  473. func setAIRewriteStype() -> NSMenuItem {
  474. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  475. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  476. return stypItem
  477. }
  478. func addHighlightLinksStype() -> NSMenuItem {
  479. let highlightLink = KMPreferenceManager.shared.highlightLinks
  480. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  481. if highlightLink {
  482. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  483. }
  484. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  485. return highlightLinksItem
  486. }
  487. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  488. if item == nil {
  489. return
  490. }
  491. let menu = NSMenu()
  492. item?.submenu = menu
  493. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  494. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  495. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  496. let wavyLine = NSMenuItem(title: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  497. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  498. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  499. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  500. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  501. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  502. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  503. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  504. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  505. if listView.currentSelection.selectionType() != .image {
  506. menu.insertItem(height, at: menu.items.count)
  507. menu.insertItem(underline, at: menu.items.count)
  508. menu.insertItem(strickout, at: menu.items.count)
  509. menu.insertItem(wavyLine, at: menu.items.count)
  510. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  511. }
  512. if viewManager.isPDFReadMode {
  513. } else {
  514. if listView.currentSelection.selectionType() != .image &&
  515. listView.currentSelection.selectionType() != .text {
  516. menu.insertItem(text, at: menu.items.count)
  517. menu.insertItem(note, at: menu.items.count)
  518. }
  519. }
  520. if viewManager.isPDFReadMode {
  521. } else {
  522. if listView.currentSelection.selectionType() != .image {
  523. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  524. menu.insertItem(rectangle, at: menu.items.count)
  525. menu.insertItem(oval, at: menu.items.count)
  526. }
  527. }
  528. if viewManager.isPDFReadMode {
  529. } else {
  530. if listView.currentSelection.selectionType() != .image &&
  531. listView.currentSelection.selectionType() != .text {
  532. menu.insertItem(line, at: menu.items.count)
  533. }
  534. }
  535. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  536. if viewManager.isPDFReadMode {
  537. } else {
  538. menu.insertItem(link, at: menu.items.count)
  539. }
  540. if viewManager.isPDFReadMode {
  541. } else {
  542. if listView.currentSelection.selectionType() != .image {
  543. menu.insertItem(outline, at: menu.items.count)
  544. }
  545. }
  546. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  547. if viewManager.isPDFReadMode {
  548. } else {
  549. if (listView.currentSelection.selectionType() != .image) {
  550. }
  551. }
  552. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  553. }
  554. func addBookmarkMenu() -> NSMenuItem {
  555. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  556. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  557. return bookMarkItem
  558. } else {
  559. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  560. return bookMarkItem
  561. }
  562. }
  563. func findStringMenu() -> NSMenuItem {
  564. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  565. menuItem.keyEquivalent = "f"
  566. return menuItem
  567. }
  568. func printingMenu() -> NSMenuItem {
  569. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  570. return menuItem
  571. }
  572. func fontSizes()->NSArray {
  573. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  574. }
  575. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  576. if interactionMode == .presentation {
  577. listView.goToPreviousPage(nil)
  578. return true
  579. }
  580. return false
  581. }
  582. func useNativeFullScreen() -> Bool {
  583. var isFull = false
  584. let sel = NSSelectorFromString("toggleFullscreen:")
  585. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  586. isFull = true
  587. }
  588. return isFull
  589. }
  590. func forceSubwindowsOnTop(_ flag: Bool) {
  591. }
  592. //MARK: menuItem Action
  593. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  594. let color = listView.editingSelectionFontColor()
  595. let panel = NSColorPanel.shared
  596. panel.setTarget(self)
  597. panel.setAction(#selector(fontColorChangeAction))
  598. panel.orderFront(nil)
  599. panel.showsAlpha = false
  600. panel.color = color ?? NSColor.black
  601. }
  602. @objc func fontColorChangeAction(sender: NSColorPanel) {
  603. self.listView.setEditingSelectionFontColor(sender.color)
  604. }
  605. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  606. let fontSize = self.fontSizes().object(at: sender.tag)
  607. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  608. }
  609. @objc func addImageText(sender: NSMenuItem) {
  610. let event = NSApp.currentEvent
  611. let clickLocation = event?.locationInWindow
  612. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  613. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  614. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  615. point = point2
  616. if sender.tag == 0 {
  617. KMPrint("添加文字")
  618. } else if sender.tag == 1 {
  619. } else if sender.tag == 2 {
  620. KMPrint("粘贴")
  621. }
  622. }
  623. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  624. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  625. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  626. }
  627. }
  628. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  629. self.listView.exitCrop(with: self.listView.selectImageAreas)
  630. self.listView.cropAreas = nil
  631. self.listView.isEditImage = false
  632. }
  633. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  634. self.listView.resetCrop(with: self.listView.selectImageAreas)
  635. }
  636. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  637. }
  638. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  639. if self.listView.selectImageAreas == nil {
  640. return
  641. }
  642. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  643. let panel = NSOpenPanel()
  644. panel.allowsMultipleSelection = false
  645. panel.allowedFileTypes = ["png","jpg"]
  646. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  647. if response == .OK {
  648. let openPath = panel.url?.path
  649. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  650. if s {
  651. }
  652. }
  653. }
  654. }
  655. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  656. if self.listView.selectImageAreas == nil {
  657. return
  658. }
  659. let panel = NSSavePanel()
  660. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  661. panel.isExtensionHidden = true
  662. let response = panel.runModal()
  663. if response == .OK {
  664. let url = panel.url
  665. if FileManager.default.fileExists(atPath: url!.path) {
  666. try?FileManager.default.removeItem(atPath: url!.path)
  667. }
  668. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  669. if result {
  670. NSWorkspace.shared.activateFileViewerSelecting([url!])
  671. }
  672. }
  673. }
  674. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  675. }
  676. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  677. }
  678. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  679. }
  680. @objc func OpenItemAction(sender: NSMenuItem) {
  681. }
  682. @objc func customCropModel(sender: NSMenuItem) {
  683. }
  684. @objc func rotateRightAction(sender: NSMenuItem) {
  685. }
  686. @objc func rotateLeftAction(sender: NSMenuItem) {
  687. }
  688. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  689. self.listView.toolMode = .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.setDocumentEditedState(window: self.view.window)
  960. if viewManager.isPDFReadMode {
  961. } else {
  962. self.leftSideViewController.showBookmarkTab()
  963. }
  964. }
  965. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  966. self.leftSideViewController.refreshMethodType(methodType: .Search)
  967. }
  968. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  969. let rect = listView.currentSelectionRect()
  970. let page = listView.currentPage()
  971. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  972. copyPage.setBounds(rect, for: .cropBox)
  973. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  974. // 执行右键操作后,需要取消框选区域
  975. if self.listView.toolMode == .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. func extractImageAction(num: Int) {
  1833. if !IAPProductsManager.default().isAvailableAllFunction(){
  1834. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1835. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  1836. winC?.showWindow(nil)
  1837. return
  1838. }
  1839. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  1840. let alert = NSAlert()
  1841. alert.alertStyle = .critical
  1842. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1843. alert.runModal()
  1844. return
  1845. }
  1846. let document = self.listView.document
  1847. var fileURL = document?.documentURL
  1848. if num == 1 {
  1849. let pageCount = document?.pageCount ?? 0
  1850. let indeSet = NSMutableIndexSet()
  1851. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  1852. if indeSet.count == 0 {
  1853. return
  1854. }
  1855. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  1856. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  1857. let outputSavePanel = NSSavePanel()
  1858. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  1859. outputSavePanel.allowsOtherFileTypes = true
  1860. outputSavePanel.isExtensionHidden = true
  1861. outputSavePanel.canCreateDirectories = true
  1862. outputSavePanel.nameFieldStringValue = tFileName
  1863. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  1864. if result == NSApplication.ModalResponse.OK {
  1865. DispatchQueue.main.async {
  1866. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  1867. let tDestFile = outputSavePanel.url!.path
  1868. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  1869. let pdfconverter = PDFConvertObject()
  1870. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  1871. self.dismissProgressSheet()
  1872. let fileManager = FileManager.default
  1873. if fileManager.fileExists(atPath: tDestFile) {
  1874. let workspace = NSWorkspace.shared
  1875. let url = URL(fileURLWithPath: tDestFile)
  1876. workspace.activateFileViewerSelecting([url])
  1877. }
  1878. }
  1879. }
  1880. })
  1881. return
  1882. }
  1883. if fileURL != nil {
  1884. self.myDocument?.save(nil)
  1885. } else {
  1886. let myDocument = self.myDocument
  1887. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  1888. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1889. if writeSuccess {
  1890. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1891. fileURL = document?.documentURL
  1892. } else {
  1893. NSSound.beep()
  1894. return
  1895. }
  1896. }
  1897. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  1898. extract?.docPath = fileURL?.path ?? ""
  1899. extract?.password = document?.password ?? ""
  1900. extract?.currentPage = self.listView.currentPageIndex
  1901. self.km_beginSheet(windowC: extract!)
  1902. extract?.selectCurrentPageBtn()
  1903. }
  1904. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  1905. let progress = SKProgressController()
  1906. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  1907. progress.window?.contentView?.wantsLayer = true
  1908. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1909. progress.progressField.textColor = NSColor.white
  1910. progress.message = NSLocalizedString("Converting...", comment: "")
  1911. progressC = progress
  1912. progressC?.message = message
  1913. if maxValue > 0 {
  1914. progressC?.indeterminate = false
  1915. progressC?.maxValue = Double(maxValue)
  1916. progressC?.progressBar.doubleValue = 0.3
  1917. } else {
  1918. progressC?.indeterminate = true
  1919. }
  1920. self.view.km_beginSheet(windowC: progressC!)
  1921. }
  1922. func dismissProgressSheet() {
  1923. progressC?.stopAnimation()
  1924. self.view.km_endSheet()
  1925. progressC = nil
  1926. }
  1927. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  1928. let newArr = NSMutableArray()
  1929. for item in files {
  1930. newArr.add(item.filePath)
  1931. }
  1932. return newArr as! [String]
  1933. }
  1934. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1935. self.saveDocument()
  1936. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1937. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1938. if (result == .cancel) {
  1939. return
  1940. }
  1941. // 解除权限
  1942. self?.listView.document.unlock(withPassword: password)
  1943. // 隐藏提示
  1944. self?.hiddenSecureLimitTip()
  1945. // 去打印
  1946. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  1947. }
  1948. return
  1949. }
  1950. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  1951. }
  1952. // MARK: - 图片注释
  1953. @IBAction func imageAnnotation(_ sender: Any) {
  1954. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  1955. changeAnnotationMode(sender)
  1956. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1957. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1958. return
  1959. }
  1960. let accessoryCtr = KMImageAccessoryController()
  1961. let openPanel = NSOpenPanel()
  1962. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1963. openPanel.allowsMultipleSelection = false
  1964. openPanel.accessoryView = accessoryCtr.view
  1965. openPanel.canSelectHiddenExtension = true
  1966. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  1967. if result == .OK {
  1968. guard let url = openPanel.url else {
  1969. return
  1970. }
  1971. let filePath = url.path
  1972. if filePath.pathExtension.lowercased() == "pdf" {
  1973. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  1974. NSSound.beep()
  1975. return
  1976. }
  1977. }
  1978. guard let image = NSImage(contentsOfFile: url.path) else {
  1979. let alert = NSAlert()
  1980. alert.alertStyle = .critical
  1981. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  1982. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  1983. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1984. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  1985. if response == .alertFirstButtonReturn {
  1986. // Handle cancel button clicked
  1987. }
  1988. }
  1989. return
  1990. }
  1991. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  1992. if isDamageImage {
  1993. let alert = NSAlert()
  1994. alert.alertStyle = .critical
  1995. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  1996. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  1997. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1998. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  1999. if response == .alertFirstButtonReturn {
  2000. // Handle cancel button clicked
  2001. }
  2002. }
  2003. return
  2004. }
  2005. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2006. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2007. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2008. }
  2009. }
  2010. }
  2011. }
  2012. @IBAction func tableAnnotation(_ sender: Any) {
  2013. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2014. changeAnnotationMode(sender)
  2015. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2016. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2017. winC?.kEventName = "Reading_Table_BuyNow"
  2018. winC?.showWindow(nil)
  2019. return
  2020. }
  2021. listView.addAnnotationWithTable()
  2022. toggleOpenRightSide()
  2023. }
  2024. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2025. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2026. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2027. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2028. }
  2029. if let data = image.tiffRepresentation,
  2030. let imageRep = NSBitmapImageRep(data: data) {
  2031. imageRep.size = image.size
  2032. var imageData: Data?
  2033. if path.lowercased() == "png" {
  2034. imageData = imageRep.representation(using: .png, properties: [:])
  2035. } else {
  2036. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2037. }
  2038. if let imageData = imageData {
  2039. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2040. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2041. return true
  2042. } else {
  2043. return false
  2044. }
  2045. }
  2046. }
  2047. return false
  2048. }
  2049. func tagString() -> String {
  2050. let dateFormatter = DateFormatter()
  2051. dateFormatter.dateFormat = "yyMMddHHmmss"
  2052. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2053. }
  2054. // MARK: - Split View
  2055. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2056. }
  2057. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2058. }
  2059. func updateBackAndForwardButtonState() {
  2060. }
  2061. }
  2062. extension KMMainViewController {
  2063. func changeModelAction(mode: CToolMode) {
  2064. self.listView.toolMode = mode
  2065. if mode == .CEditPDFToolMode {
  2066. }
  2067. }
  2068. func changePDFViewZoomInAction() {
  2069. }
  2070. func changePDFViewZoomOutAction() {
  2071. }
  2072. func changePDFViewGotoNextPageAction() {
  2073. self.listView.km_goBack(nil)
  2074. if (self.listView.canGoToNextPage()) {
  2075. self.listView.goToNextPage(nil)
  2076. }
  2077. }
  2078. func changePDFViewGoToPreviousPageAction() {
  2079. if (self.listView.canGoToPreviousPage()) {
  2080. self.listView.goToPreviousPage(nil)
  2081. }
  2082. }
  2083. func changePDFViewGotoBackAction() {
  2084. self.listView.km_goBack(nil)
  2085. self.updateBackAndForwardButtonState()
  2086. }
  2087. func changePDFViewGoToForwardAction() {
  2088. self.listView.km_goForward(nil)
  2089. self.updateBackAndForwardButtonState()
  2090. }
  2091. func aiTranslationPDFFileAction() {
  2092. self.trackEvent_aiTranslate()
  2093. self._aiTranslationPDFFileAction()
  2094. }
  2095. private func _aiTranslationPDFFileAction() {
  2096. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2097. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2098. let alert = NSAlert()
  2099. alert.alertStyle = .critical
  2100. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2101. alert.runModal()
  2102. return
  2103. } else if isExceedsLimit {
  2104. let alert = NSAlert()
  2105. alert.alertStyle = .critical
  2106. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2107. alert.runModal()
  2108. return
  2109. }
  2110. let alert = NSAlert()
  2111. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2112. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2113. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2114. alert.beginSheetModal(for: view.window!) { [weak self] result in
  2115. if (result == .alertFirstButtonReturn) {
  2116. } else if result == .alertSecondButtonReturn {
  2117. return
  2118. }
  2119. }
  2120. }
  2121. func clickChildTool(type: KMToolbarType, index: Int) {
  2122. if (type == .secure) {
  2123. if (index == 1) {
  2124. self.trackEvent_setPassword()
  2125. } else if (index == 2) {
  2126. self.trackEvent_removePassword()
  2127. }
  2128. } else {
  2129. self.trackEvent(toolBarType: type)
  2130. }
  2131. Task { @MainActor in
  2132. if (type == .compress) { /// 压缩
  2133. if !self.documentAllowsEdit() {
  2134. return
  2135. }
  2136. if (self.needSaveDocument()) {
  2137. self.saveDocumentWithProgressAlert { [unowned self] params in
  2138. // self.showCompressWindow()
  2139. }
  2140. return
  2141. }
  2142. // self.showCompressWindow()
  2143. return
  2144. }
  2145. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  2146. if type == .conversion_imageToPDF {
  2147. Task {
  2148. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  2149. }
  2150. return
  2151. }
  2152. var identifier: String?
  2153. if (type == .word) { /// Word
  2154. identifier = KMToolbarConversionWordItemIdentifier
  2155. } else if (type == .excel) {
  2156. identifier = KMToolbarConversionExcelItemIdentifier
  2157. } else if (type == .ppt) {
  2158. identifier = KMToolbarConversionPPTItemIdentifier
  2159. } else if (type == .rtf) {
  2160. identifier = KMToolbarConversionRTFItemIdentifier
  2161. } else if (type == .html) {
  2162. identifier = KMToolbarConversionHTMLItemIdentifier
  2163. } else if (type == .conversion_text) {
  2164. identifier = KMToolbarConversionTextItemIdentifier
  2165. } else if (type == .csv) {
  2166. identifier = KMToolbarConversionCSVItemIdentifier
  2167. } else if (type == .conversion_image) {
  2168. identifier = KMToolbarConversionImageItemIdentifier
  2169. }
  2170. if (self.needSaveDocument()) {
  2171. self.saveDocumentWithProgressAlert { [unowned self] params in
  2172. self.showConvertWindow(type: type, identifier: identifier)
  2173. }
  2174. return
  2175. }
  2176. self.showConvertWindow(type: type, identifier: identifier)
  2177. return
  2178. }
  2179. if (type == .merge) { /// 合并
  2180. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  2181. if !self.documentAllowsEdit() {
  2182. return
  2183. }
  2184. if (self.needSaveDocument()) {
  2185. self.saveDocumentWithProgressAlert { [unowned self] params in
  2186. self.showMergeWindow(self.listView.document.password)
  2187. }
  2188. return
  2189. }
  2190. self.showMergeWindow(self.listView.document.password)
  2191. return
  2192. }
  2193. if (type == .bates || type == .headerAndFooter) {
  2194. if !IAPProductsManager.default().isAvailableAllFunction(){
  2195. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2196. if type == .headerAndFooter {
  2197. if index == 1 {
  2198. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  2199. } else if index == 2 {
  2200. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  2201. }
  2202. } else if type == .bates {
  2203. if index == 1 {
  2204. winC?.kEventName = "Reading_AddBates_BuyNow"
  2205. } else if index == 2 {
  2206. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  2207. }
  2208. }
  2209. winC?.showWindow(nil)
  2210. return
  2211. }
  2212. if !self.documentAllowsEdit() {
  2213. return
  2214. }
  2215. if (index == 1) {
  2216. var windowController: KMBaseWindowController = KMBaseWindowController()
  2217. if (type == .bates) {
  2218. } else if (type == .headerAndFooter) {
  2219. } else if (type == .background) {
  2220. } else if (type == .watermark) {
  2221. }
  2222. windowController.pdfDocument = self.listView.document
  2223. windowController.cancelAction = { [unowned self] controller in
  2224. self.view.window?.endSheet((self.currentWindowController.window)!)
  2225. self.currentWindowController = nil
  2226. }
  2227. self.currentWindowController = windowController
  2228. await self.view.window?.beginSheet(windowController.window!)
  2229. return
  2230. }
  2231. if (index == 1) { /// 取消
  2232. ///
  2233. toggleCloseRightSide()
  2234. return
  2235. } else if index == 3 {
  2236. let fpath = self.document?.documentURL?.path ?? ""
  2237. if type == .bates {
  2238. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2239. } else {
  2240. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2241. }
  2242. } else if index == 4 {
  2243. let fpath = self.document?.documentURL?.path ?? ""
  2244. if type == .bates {
  2245. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  2246. } else {
  2247. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  2248. }
  2249. } else if (index == 2) { //// 移除
  2250. if type == .headerAndFooter {
  2251. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2252. let savePanel = NSSavePanel()
  2253. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2254. savePanel.allowedFileTypes = ["pdf"]
  2255. savePanel.accessoryView = savePanelAccessoryViewController.view
  2256. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2257. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2258. }
  2259. }
  2260. } else if type == .bates {
  2261. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2262. let savePanel = NSSavePanel()
  2263. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2264. savePanel.allowedFileTypes = ["pdf"]
  2265. savePanel.accessoryView = savePanelAccessoryViewController.view
  2266. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2267. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2268. }
  2269. }
  2270. }
  2271. } else if (index == 2) { /// 应用
  2272. } else if index == 5 {
  2273. self.toggleOpenRightSide()
  2274. }
  2275. } else if (type == .redact) { /// 标记密文
  2276. if !IAPProductsManager.default().isAvailableAllFunction(){
  2277. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2278. return
  2279. }
  2280. if (index == 1) { /// 取消
  2281. if (self.model.hasAddRedact) {
  2282. let alert = NSAlert()
  2283. 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: "")
  2284. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2285. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2286. let result = alert.runModal()
  2287. if (result == .alertFirstButtonReturn) {
  2288. self.listView.toolMode = .CMoveToolMode
  2289. }
  2290. return
  2291. }
  2292. self.listView.toolMode = .CMoveToolMode
  2293. return
  2294. }
  2295. if (index == 2) { /// 擦除
  2296. self.exeRedactConfirm(.eraserAll) {}
  2297. return
  2298. }
  2299. if (index == 3) { /// 应用
  2300. self.exeRedactConfirm(.redactAll) {}
  2301. return
  2302. }
  2303. if (index == 4) { /// 文本&图像
  2304. self.listView.toolMode = .CRedactToolMode
  2305. return
  2306. }
  2307. if (index == 5) { /// 页面
  2308. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2309. await self.view.window?.beginSheet(windowController.window!)
  2310. self.currentWindowController = windowController
  2311. windowController.itemClick = { [weak self] index, value in
  2312. if (index == 1) {
  2313. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2314. self?.currentWindowController = nil
  2315. return
  2316. }
  2317. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2318. let pageType = windowController_pageRange.pageType
  2319. let pageString = windowController_pageRange.pageString
  2320. if (pageType == 5) { /// 自定义页面
  2321. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  2322. if (array.count == 0) {
  2323. let alert = NSAlert()
  2324. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2325. alert.runModal()
  2326. return
  2327. }
  2328. }
  2329. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2330. self!.currentWindowController = nil
  2331. var indexs: IndexSet = []
  2332. if (pageType == 1) { /// 当前页面
  2333. indexs.insert((self?.listView.currentPageIndex)!)
  2334. } else {
  2335. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  2336. }
  2337. if (indexs.count == 0) {
  2338. return
  2339. }
  2340. for i in indexs {
  2341. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2342. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2343. redactAnno.bounds = page.bounds
  2344. self?.listView.add(redactAnno, to: page)
  2345. }
  2346. }
  2347. return
  2348. }
  2349. } else if (type == .secure) { /// 安全
  2350. if (index == 1) { /// 设置密码
  2351. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2352. if !self.documentAllowsEdit() {
  2353. return
  2354. }
  2355. }
  2356. self.showSecureWindow(self.listView.document.documentURL)
  2357. return
  2358. } else if index == 2 {
  2359. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  2360. let alert = NSAlert()
  2361. alert.alertStyle = .warning
  2362. alert.messageText = NSLocalizedString("Warning", comment: "")
  2363. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2364. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  2365. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  2366. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  2367. if returnCode == .alertSecondButtonReturn {
  2368. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2369. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  2370. if success {
  2371. self.document?.unlock(withPassword: resultPassword)
  2372. self.clickChildTool(type: .secure, index: 2)
  2373. }
  2374. }
  2375. }
  2376. }
  2377. }
  2378. } else {
  2379. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  2380. controller.pdfDocument = self.document
  2381. self.currentWindowController = controller
  2382. controller.batchAction = { [unowned self] controller, files in
  2383. self.view.window?.endSheet((self.currentWindowController.window)!)
  2384. self.currentWindowController = nil
  2385. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  2386. if #available(macOS 10.13, *) {
  2387. baseWindowController.window?.makeKeyAndOrderFront(nil)
  2388. } else {
  2389. baseWindowController.showWindow(nil)
  2390. }
  2391. let arr = NSMutableArray()
  2392. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  2393. file.password = document?.password ?? ""
  2394. arr.add(file)
  2395. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  2396. }
  2397. controller.cancelAction = { [unowned self] controller in
  2398. self.view.window?.endSheet((self.currentWindowController.window)!)
  2399. self.currentWindowController = nil
  2400. }
  2401. controller.doneAction = { [unowned self] controller in
  2402. self.view.window?.endSheet((self.currentWindowController.window)!)
  2403. self.currentWindowController = nil
  2404. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  2405. if success {
  2406. let savePanel = NSSavePanel()
  2407. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  2408. savePanel.allowedFileTypes = ["pdf"]
  2409. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  2410. guard result == .OK else { return }
  2411. /// 删除安全性设置
  2412. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2413. self.model.isSaveKeyChain = false
  2414. self.listView.document.unlock(withPassword: resultPassword)
  2415. }
  2416. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  2417. guard let document = document else { return }
  2418. document.unlock(withPassword: resultPassword)
  2419. let success = document.writeDecrypt(to: savePanel.url)
  2420. if success {
  2421. self.hiddenSecureLimitTip()
  2422. let tip = KMRemovePasswordResultTipView()
  2423. tip.result = .success
  2424. tip.showInView(superView: (self.listView.superview)!)
  2425. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2426. } else {
  2427. self.hiddenSecureLimitTip()
  2428. let tip = KMRemovePasswordResultTipView()
  2429. tip.result = .failure
  2430. tip.showInView(superView: (self.listView.superview)!)
  2431. }
  2432. }
  2433. }
  2434. }
  2435. }
  2436. await NSWindow.currentWindow().beginSheet(controller.window!)
  2437. }
  2438. return
  2439. }
  2440. } else if type == .comparison {
  2441. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  2442. if !IAPProductsManager.default().isAvailableAllFunction(){
  2443. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2444. winC?.kEventName = "Reading_Compare_BuyNow"
  2445. winC?.showWindow(nil)
  2446. return
  2447. }
  2448. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2449. self.currentWindowController = controller
  2450. controller.password = self.document?.password ?? ""
  2451. controller.filePath = (self.document?.documentURL.path)!
  2452. controller.cancelAction = { [unowned self] controller in
  2453. self.view.window?.endSheet((self.currentWindowController.window)!)
  2454. self.currentWindowController = nil
  2455. }
  2456. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  2457. self.view.window?.endSheet((self.currentWindowController.window)!)
  2458. self.currentWindowController = nil
  2459. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  2460. }
  2461. controller.coveringComplete = { [unowned self] controller, document in
  2462. self.view.window?.endSheet((self.currentWindowController.window)!)
  2463. self.currentWindowController = nil
  2464. self.openCoveringCompareVC(with: document)
  2465. }
  2466. if index == 1 {
  2467. controller.fileType = .content
  2468. } else {
  2469. controller.fileType = .coverting
  2470. }
  2471. await NSWindow.currentWindow().beginSheet(controller.window!)
  2472. } else if type == .watermark {
  2473. if !IAPProductsManager.default().isAvailableAllFunction(){
  2474. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2475. if index == 1 {
  2476. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  2477. } else if index == 2 {
  2478. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  2479. }
  2480. winC?.showWindow(nil)
  2481. return
  2482. }
  2483. if !self.documentAllowsEdit() {
  2484. return
  2485. }
  2486. if index == 1 {
  2487. } else if index == 2 {
  2488. let watermarks = self.listView.document.watermarks()
  2489. if (watermarks == nil || watermarks!.count <= 0) {
  2490. let alert = NSAlert()
  2491. alert.alertStyle = .warning
  2492. 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: "")
  2493. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  2494. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2495. alert.runModal()
  2496. return
  2497. }
  2498. let alert = NSAlert()
  2499. alert.alertStyle = .warning
  2500. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  2501. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2502. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2503. let result = alert.runModal()
  2504. if (result != .alertFirstButtonReturn) {
  2505. return
  2506. }
  2507. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2508. let savePanel = NSSavePanel()
  2509. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  2510. savePanel.allowedFileTypes = ["pdf"]
  2511. savePanel.accessoryView = savePanelAccessoryViewController.view
  2512. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2513. guard result == .OK else { return }
  2514. }
  2515. } else if index == 3 {
  2516. let fpath = self.document?.documentURL?.path ?? ""
  2517. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  2518. } else if index == 4 {
  2519. let fpath = self.document?.documentURL?.path ?? ""
  2520. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  2521. } else if index == 5 {
  2522. toggleOpenRightSide()
  2523. return
  2524. }
  2525. } else if type == .background {
  2526. if !IAPProductsManager.default().isAvailableAllFunction(){
  2527. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2528. if index == 1 {
  2529. winC?.kEventName = "Reading_AddBackground_BuyNow"
  2530. } else if index == 2 {
  2531. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  2532. }
  2533. winC?.showWindow(nil)
  2534. return
  2535. }
  2536. if !self.documentAllowsEdit() {
  2537. return
  2538. }
  2539. if index == 1 {
  2540. } else if index == 2 {
  2541. guard let document = self.document else { return }
  2542. if !document.allowsPrinting || !document.allowsCopying {
  2543. let alert = NSAlert()
  2544. alert.alertStyle = .critical
  2545. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2546. alert.runModal()
  2547. return
  2548. }
  2549. guard let documentURL = document.documentURL else { return }
  2550. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2551. let savePanel = NSSavePanel()
  2552. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  2553. savePanel.allowedFileTypes = ["pdf"]
  2554. savePanel.accessoryView = savePanelAccessoryViewController.view
  2555. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2556. guard result == .OK else { return }
  2557. }
  2558. } else if index == 3 {
  2559. let fpath = self.document?.documentURL?.path ?? ""
  2560. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  2561. } else if index == 4 {
  2562. let fpath = self.document?.documentURL?.path ?? ""
  2563. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  2564. } else if index == 5 {
  2565. toggleOpenRightSide()
  2566. return
  2567. }
  2568. } else if type == .measure {
  2569. if !IAPProductsManager.default().isAvailableAllFunction(){
  2570. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2571. winC?.kEventName = "Reading_Measure_BuyNow"
  2572. winC?.showWindow(nil)
  2573. return
  2574. }
  2575. if !self.documentAllowsEdit() {
  2576. return
  2577. }
  2578. self.listView.toolMode = .CNoteToolMode
  2579. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2580. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2581. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2582. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2583. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2584. areaMeasureInfoWindowController?.hideFloatingWindow()
  2585. }
  2586. if distanceMeasureInfoWindowController == nil {
  2587. let measureInfo = CPDFDistanceMeasureInfo()
  2588. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2589. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2590. distanceMeasureInfoWindowController?.delegate = self
  2591. }
  2592. if perimeterMeasureInfoWindowController == nil {
  2593. let measureInfo = CPDFPerimeterMeasureInfo()
  2594. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2595. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2596. perimeterMeasureInfoWindowController?.delegate = self
  2597. }
  2598. if areaMeasureInfoWindowController == nil {
  2599. let measureInfo = CPDFAreaMeasureInfo()
  2600. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2601. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2602. areaMeasureInfoWindowController?.delegate = self
  2603. }
  2604. if index == 1 {
  2605. self.listView.annotationType = .measureLine
  2606. let winW: CGFloat = 300
  2607. let rightW: CGFloat = 270
  2608. var winFrame = self.view.window?.frame ?? .zero
  2609. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2610. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2611. distanceMeasureInfoWindowController?.showWindow(nil)
  2612. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2613. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2614. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2615. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2616. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2617. self.trackEvent(toolMode: .CNoteToolMode)
  2618. } else if index == 2 {
  2619. self.listView.annotationType = .measurePolyLine
  2620. let winW: CGFloat = 300
  2621. let rightW: CGFloat = 270
  2622. var winFrame = self.view.window?.frame ?? .zero
  2623. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2624. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2625. perimeterMeasureInfoWindowController?.showWindow(nil)
  2626. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2627. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2628. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2629. self.trackEvent(toolMode: .CNoteToolMode)
  2630. } else if index == 3 {
  2631. self.listView.annotationType = .measurePolyGon
  2632. let winW: CGFloat = 300
  2633. let rightW: CGFloat = 270
  2634. var winFrame = self.view.window?.frame ?? .zero
  2635. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2636. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2637. areaMeasureInfoWindowController?.showWindow(nil)
  2638. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2639. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2640. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2641. self.trackEvent(toolMode: .CNoteToolMode)
  2642. } else if index == 4 {
  2643. self.listView.annotationType = .measureSquare
  2644. let winW: CGFloat = 300
  2645. let rightW: CGFloat = 270
  2646. var winFrame = self.view.window?.frame ?? .zero
  2647. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2648. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2649. areaMeasureInfoWindowController?.showWindow(nil)
  2650. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2651. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2652. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2653. self.trackEvent(toolMode: .CNoteToolMode)
  2654. } else {
  2655. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  2656. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2657. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  2658. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2659. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  2660. areaMeasureInfoWindowController?.hideFloatingWindow()
  2661. }
  2662. }
  2663. toggleOpenRightSide()
  2664. }
  2665. }
  2666. }
  2667. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  2668. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2669. var array: [KMBatchOperateFile] = []
  2670. for fpath in filepaths ?? [] {
  2671. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  2672. array.append(batchOperateFile)
  2673. }
  2674. batchWindowController.switchToOperateType(type, files: array)
  2675. batchWindowController.window?.makeKeyAndOrderFront("")
  2676. }
  2677. func openNewWindowAlertWindow() {
  2678. var needShowChooseWindow = false
  2679. //#if VERSION_FREE
  2680. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  2681. needShowChooseWindow = true
  2682. }
  2683. //#endif
  2684. if needShowChooseWindow {
  2685. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  2686. if preferenceNoteShow {
  2687. menuItemAction_newTagPageToNewWindow("")
  2688. } else {
  2689. if !KMDataManager.default.isTabbingWin{
  2690. KMDataManager.default.isTabbingWin = true
  2691. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  2692. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  2693. KMDataManager.default.isTabbingWin = false
  2694. if continueOrNot {
  2695. self?.reopenDocument(forPaths: [])
  2696. } else {
  2697. }
  2698. }
  2699. self.km_beginSheet(windowC: tabbingWin)
  2700. }
  2701. }
  2702. }else{
  2703. handleTabbingLogic()
  2704. }
  2705. }
  2706. func reopenDocument(forPaths paths: [String]) -> Void {
  2707. let browser = KMBrowser.init() as KMBrowser
  2708. browser.windowController = KMBrowserWindowController.init(browser: browser)
  2709. browser.addHomeTabContents()
  2710. browser.windowController.showWindow(self)
  2711. }
  2712. func handleTabbingLogic() {
  2713. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  2714. }
  2715. func showTTSWindow() {
  2716. var lastPDFView: CPDFView?
  2717. let ttsView = KMTTSWindowController.share
  2718. if (ttsView.window?.isVisible ?? false) {
  2719. lastPDFView = ttsView.pdfView
  2720. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  2721. lastPDFView = nil
  2722. ttsView.window?.orderOut(nil)
  2723. } else {
  2724. ttsView.pdfView = self.listView
  2725. ttsView.showWindow(nil)
  2726. }
  2727. } else {
  2728. ttsView.pdfView = self.listView
  2729. ttsView.showWindow(nil)
  2730. }
  2731. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  2732. if isCloseWindow {
  2733. }
  2734. }
  2735. if let currentSelection = self.listView.currentSelection {
  2736. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  2737. ttsView.startSpeakingPDFSelection(currentSelection)
  2738. }
  2739. }
  2740. if let lastPDFView = lastPDFView {
  2741. lastPDFView.setHighlightedSelections([])
  2742. ttsView.stopSpeaking()
  2743. }
  2744. }
  2745. func convertToImg(index: Int) {
  2746. var convertT: KMConvertType = .JPEG
  2747. switch index {
  2748. case 7:
  2749. convertT = .JPEG
  2750. case 8:
  2751. convertT = .JPG
  2752. case 9:
  2753. convertT = .PNG
  2754. case 10:
  2755. convertT = .GIF
  2756. case 11:
  2757. convertT = .TIFF
  2758. case 12:
  2759. convertT = .TGA
  2760. case 13:
  2761. convertT = .BMP
  2762. default:
  2763. convertT = .JPEG
  2764. }
  2765. showAllConvertWindow(convertT: convertT)
  2766. }
  2767. }
  2768. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  2769. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  2770. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2771. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  2772. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2773. distanceSettingWC.delegate = self
  2774. distanceSettingWC.startModal("")
  2775. }
  2776. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2777. }
  2778. }
  2779. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  2780. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  2781. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  2782. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  2783. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2784. distanceSettingWC.delegate = self
  2785. distanceSettingWC.startModal("")
  2786. }
  2787. }
  2788. // MARK: CAreaMeasureInfoWindowControllerDelegate
  2789. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  2790. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  2791. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  2792. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  2793. areaSettingWC.delegate = self
  2794. areaSettingWC.startModal("")
  2795. }
  2796. }
  2797. // MARK: CDistanceSettingWindowControllerDelegate
  2798. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  2799. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  2800. if distanceMeasureInfo != nil {
  2801. if self.listView.activeAnnotations.count > 0 {
  2802. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  2803. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  2804. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2805. }
  2806. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  2807. } else {
  2808. distanceMeasureInfo?.leadLength = 0
  2809. self.listView.distanceMeasureInfo = distanceMeasureInfo
  2810. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  2811. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2812. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2813. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2814. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2815. }
  2816. if let data = self.listView.activeAnnotation {
  2817. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2818. }
  2819. }
  2820. self.distanceMeasureInfoWindowController?.showWindow(self)
  2821. }
  2822. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  2823. if perimeterMeasureInfo != nil {
  2824. if self.listView.activeAnnotations.count > 0 {
  2825. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  2826. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  2827. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2828. }
  2829. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  2830. } else {
  2831. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  2832. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  2833. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2834. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2835. }
  2836. if let data = self.listView.activeAnnotation {
  2837. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2838. }
  2839. }
  2840. self.perimeterMeasureInfoWindowController?.showWindow(self)
  2841. }
  2842. }
  2843. // MARK: CAreaSettingWindowControllerDelegate
  2844. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  2845. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  2846. if self.listView.annotationType == .measureSquare && self.listView.toolMode == .CNoteToolMode {
  2847. if measureInfo != nil {
  2848. if self.listView.activeAnnotations.count > 0 {
  2849. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2850. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2851. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2852. }
  2853. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2854. } else {
  2855. self.listView.squareAreaMeasureInfo = measureInfo
  2856. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  2857. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2858. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2859. }
  2860. }
  2861. self.areaMeasureInfoWindowController?.showWindow(self)
  2862. } else if self.listView.annotationType == .measurePolyGon && self.listView.toolMode == .CNoteToolMode {
  2863. if measureInfo != nil {
  2864. if self.listView.activeAnnotations.count > 0 {
  2865. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2866. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2867. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2868. }
  2869. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2870. } else {
  2871. self.listView.polygonAreaMeasureInfo = measureInfo
  2872. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  2873. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2874. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2875. }
  2876. }
  2877. self.areaMeasureInfoWindowController?.showWindow(self)
  2878. } else {
  2879. if measureInfo != nil {
  2880. if self.listView.activeAnnotations.count > 0 {
  2881. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2882. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2883. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2884. }
  2885. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2886. }
  2887. }
  2888. self.areaMeasureInfoWindowController?.showWindow(self)
  2889. }
  2890. if measureInfo != nil {
  2891. if let data = self.listView.activeAnnotation {
  2892. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2893. }
  2894. }
  2895. }
  2896. }
  2897. //MARK: LeftSideViewController
  2898. extension KMMainViewController {
  2899. func leftSideViewCancelSelect() {
  2900. if self.listView.isEditing() == true {
  2901. if self.listView.editingAreas() != nil &&
  2902. self.listView.editingAreas().count != 0 {
  2903. let areas = self.listView.editingAreas().first
  2904. if areas is CPDFEditTextArea {
  2905. self.listView.clearEditingSelectCharItem()
  2906. self.listView.updateEditing([])
  2907. KMPrint("取消选中")
  2908. }
  2909. }
  2910. }
  2911. }
  2912. }
  2913. // MARK: - Analytics (埋点)
  2914. extension KMMainViewController {
  2915. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  2916. if (type == .Annatiton) {
  2917. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  2918. } else if (type == .editPDF) {
  2919. } else if (type == .Page) {
  2920. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  2921. } else if (type == .Conversion) {
  2922. } else if (type == .Tool) {
  2923. }
  2924. }
  2925. func trackEvent_aiTranslate() -> Void {
  2926. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  2927. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2928. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2929. }
  2930. func trackEvent_print() -> Void {
  2931. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  2932. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2933. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2934. }
  2935. func trackEvent_share() -> Void {
  2936. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  2937. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2938. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2939. }
  2940. func trackEvent_upgrade() -> Void {
  2941. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  2942. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2943. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2944. }
  2945. func trackEvent(annotationType type: CAnnotationType) -> Void {
  2946. if (type == .highlight) {
  2947. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  2948. } else if (type == .underline) {
  2949. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  2950. } else if (type == .strikeOut) {
  2951. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  2952. } else if (type == .ink) {
  2953. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  2954. } else if (type == .freeText) {
  2955. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  2956. } else if (type == .anchored) {
  2957. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  2958. } else if (type == .square) {
  2959. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  2960. } else if (type == .link) {
  2961. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  2962. } else if (type == .stamp) {
  2963. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  2964. } else if (type == .signSignature) {
  2965. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  2966. } else if (type == .circle) {
  2967. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  2968. } else if (type == .arrow) {
  2969. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  2970. } else if (type == .line) {
  2971. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  2972. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .text) {
  2973. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  2974. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  2975. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2976. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .image) {
  2977. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  2978. } else if (type == .textField) {
  2979. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  2980. } else if (type == .checkBox) {
  2981. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  2982. } else if (type == .radioButton) {
  2983. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  2984. } else if (type == .listMenu) {
  2985. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  2986. } else if (type == .comboBox) {
  2987. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  2988. } else if (type == .actionButton) {
  2989. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  2990. } else if (type == .actionButton) {
  2991. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  2992. } else if (type == .signature) {
  2993. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  2994. } else if (type == .squiggly) {
  2995. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  2996. } else if (type == .eraser) {
  2997. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  2998. }
  2999. }
  3000. func trackEvent(toolMode mode: CToolMode) -> Void {
  3001. if (mode == .CSelectToolMode) {
  3002. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3003. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3004. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3005. } else if (mode == .CMoveToolMode) {
  3006. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3007. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3008. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3009. } else if mode == .CNoteToolMode {
  3010. if CPDFListView.isMeasure(self.listView.annotationType) == true {
  3011. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  3012. }
  3013. }
  3014. }
  3015. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3016. if (type == .word) {
  3017. } else if (type == .excel) {
  3018. } else if (type == .ppt) {
  3019. } else if (type == .rtf) {
  3020. } else if (type == .csv) {
  3021. } else if (type == .html) {
  3022. } else if (type == .conversion_text) {
  3023. } else if (type == .conversion_image) {
  3024. } else if (type == .compress) {
  3025. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  3026. } else if (type == .merge) {
  3027. } else if (type == .secure) {
  3028. } else if (type == .crop) {
  3029. } else if type == .json {
  3030. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  3031. }
  3032. }
  3033. func trackEvent_setPassword() -> Void {
  3034. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3035. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3036. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3037. }
  3038. func trackEvent_removePassword() -> Void {
  3039. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3040. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3041. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3042. }
  3043. func trackEvent_replace() -> Void {
  3044. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  3045. }
  3046. }
  3047. extension KMMainViewController {
  3048. //文件对比
  3049. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3050. self.isCompareModel = true
  3051. let compareContentView = KMCompareContentView()
  3052. compareContentView.oldDocument = oldDocument
  3053. compareContentView.document = document
  3054. compareContentView.compareResults = results
  3055. compareContentView.saveHandle = { [unowned self] view in
  3056. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3057. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3058. self.currentWindowController = saveController
  3059. saveController.cancelHandle = { [unowned self] controller in
  3060. self.view.window!.endSheet(controller.window!)
  3061. self.currentWindowController = nil
  3062. }
  3063. saveController.saveHandle = { [unowned self] controller, saveType in
  3064. let folderPath = controller.fileSaveFolderPath
  3065. if folderPath != nil {
  3066. if !FileManager.default.fileExists(atPath: folderPath) {
  3067. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3068. }
  3069. #if VERSION_DMG
  3070. #else
  3071. let url = URL(fileURLWithPath: folderPath)
  3072. let fileAccess = AppSandboxFileAccess()
  3073. fileAccess?.persistPermissionURL(url)
  3074. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  3075. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  3076. let urlString = url.path
  3077. let _url = URL(fileURLWithPath: urlString)
  3078. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  3079. }
  3080. #endif
  3081. var savePath: String
  3082. switch saveType {
  3083. case 0:
  3084. let filePath = oldDocument.documentURL.path
  3085. let fileName = filePath.deletingPathExtension.lastPathComponent
  3086. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3087. savePath = self.getValidFilePath(savePath)
  3088. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3089. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3090. case 1:
  3091. let filePath = document.documentURL.path
  3092. let fileName = filePath.deletingPathExtension.lastPathComponent
  3093. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3094. savePath = self.getValidFilePath(savePath)
  3095. document.write(to: URL(fileURLWithPath: savePath))
  3096. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3097. case 2:
  3098. let filePath = oldDocument.documentURL.path
  3099. let fileName = filePath.deletingPathExtension.lastPathComponent
  3100. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  3101. savePath = self.getValidFilePath(savePath)
  3102. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  3103. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3104. default:
  3105. break
  3106. }
  3107. }
  3108. self.view.window!.endSheet(controller.window!)
  3109. self.currentWindowController = nil
  3110. }
  3111. NSWindow.currentWindow().beginSheet(saveController.window!)
  3112. }
  3113. }
  3114. compareContentView.closeHandle = { [unowned self] view in
  3115. self.isCompareModel = false
  3116. view.removeFromSuperview()
  3117. }
  3118. compareContentView.autoresizingMask = [.width,.height]
  3119. }
  3120. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3121. self.isCompareModel = true
  3122. let coveringView = KMCompareCoveringView()
  3123. coveringView.pdfDocument = pdfDocument
  3124. coveringView.closeHandle = { [unowned self] view in
  3125. self.isCompareModel = false
  3126. view.removeFromSuperview()
  3127. }
  3128. coveringView.saveHandle = { [unowned self] view in
  3129. let savePanel = NSSavePanel()
  3130. savePanel.nameFieldStringValue = "untitled"
  3131. savePanel.allowedFileTypes = ["pdf"]
  3132. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  3133. if result == .OK {
  3134. pdfDocument.write(to: savePanel.url!)
  3135. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3136. }
  3137. }
  3138. }
  3139. coveringView.autoresizingMask = [.width,.height]
  3140. }
  3141. func getValidFilePath(_ oldPath: String) -> String {
  3142. let fileManager = FileManager.default
  3143. do {
  3144. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3145. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3146. return oldPath
  3147. }
  3148. var i = 1
  3149. var newPath = oldPath
  3150. while fileManager.fileExists(atPath: newPath) {
  3151. if fileType == FileAttributeType.typeDirectory.rawValue {
  3152. newPath = oldPath + "(\(i))"
  3153. } else {
  3154. let fileExtension = (oldPath as NSString).pathExtension
  3155. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3156. }
  3157. i += 1
  3158. }
  3159. return newPath
  3160. } catch {
  3161. print("Error getting file attributes: \(error)")
  3162. return oldPath
  3163. }
  3164. }
  3165. }
  3166. extension KMMainViewController {
  3167. func documentAllowsEdit() -> Bool {
  3168. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  3169. let alert = NSAlert()
  3170. alert.alertStyle = .critical
  3171. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3172. alert.runModal()
  3173. return false
  3174. } else {
  3175. return true
  3176. }
  3177. }
  3178. func changeFont(_ sender: NSFontManager) {
  3179. KMPrint("changeFont ...")
  3180. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  3181. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  3182. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  3183. font = sender.convert(font!)
  3184. annotation.fontSize = font?.pointSize ?? 12
  3185. self.listView.commitEditAnnotationFreeText(annotation)
  3186. self.listView.setNeedsDisplay(annotation)
  3187. }
  3188. }
  3189. func currentSetup() -> [String: Any] {
  3190. var setup: [String: Any] = [:]
  3191. var point = NSZeroPoint
  3192. if listView == nil {
  3193. return setup
  3194. }
  3195. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  3196. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  3197. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  3198. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  3199. setup[KMMainModel.Key.pageIndex] = pageIndex
  3200. return setup
  3201. }
  3202. // MARK: - Recommond活动
  3203. func loadRecommondPopWindow() {
  3204. if IAPProductsManager.default().isAvailableAllFunction() {
  3205. return
  3206. }
  3207. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  3208. if recommondPopWindowVC == nil {
  3209. recommondPopWindowVC = KMRecommondPopWindow.default()
  3210. }
  3211. recommondPopWindowVC?.recommondInfo = info
  3212. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  3213. return
  3214. }
  3215. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  3216. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  3217. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  3218. recommondPopWindowVC?.window?.orderFront((Any).self)
  3219. recommondPopWindowVC?.window?.becomeMain()
  3220. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  3221. UserDefaults.standard.synchronize()
  3222. }
  3223. }
  3224. @objc func didAddContentViewNotification(_ sender: Notification) {
  3225. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3226. return
  3227. }
  3228. if self.interactionMode == .presentation {
  3229. }
  3230. }
  3231. @objc func purchaseStateUpdateNoti() {
  3232. if IAPProductsManager.default().isAvailableAllFunction() {
  3233. }
  3234. }
  3235. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  3236. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  3237. guard let anno = sender.object as? CPDFAnnotation else {
  3238. return
  3239. }
  3240. if anno.page?.document != self.listView.document {
  3241. return
  3242. }
  3243. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  3244. }
  3245. // MARK: Split View
  3246. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  3247. let openPanel = NSOpenPanel()
  3248. openPanel.allowedFileTypes = ["pdf", "PDF"]
  3249. openPanel.allowsMultipleSelection = false
  3250. guard let mainWindow = NSApp.mainWindow else {
  3251. return
  3252. }
  3253. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  3254. if response == NSApplication.ModalResponse.OK {
  3255. guard let url = openPanel.url else {
  3256. return
  3257. }
  3258. if let document = CPDFDocument(url: url) {
  3259. replaceBlock(document.documentURL?.path ?? "")
  3260. } else {
  3261. let alert = NSAlert()
  3262. alert.alertStyle = .critical
  3263. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3264. alert.runModal()
  3265. }
  3266. }
  3267. }
  3268. }
  3269. }