KMMainViewController+Action.swift 210 KB

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