KMMainViewController+Action.swift 258 KB

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