KMMainViewController+Action.swift 287 KB

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