KMMainViewController+Action.swift 239 KB

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