KMMainViewController+Action.swift 281 KB

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