KMMainViewController+Action.swift 280 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679
  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. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  1347. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1348. return
  1349. }
  1350. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1351. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1352. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1353. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1354. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1355. areaMeasureInfoWindowController?.hideFloatingWindow()
  1356. }
  1357. self.listView.updateActiveAnnotations([anno])
  1358. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1359. self.listView.setNeedsDisplayForVisiblePages()
  1360. }
  1361. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  1362. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1363. return
  1364. }
  1365. self.listView.updateActiveAnnotations([anno])
  1366. self.pdfListViewAnnotationMeasureInfoChange(self.listView, with: anno)
  1367. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1368. self.listView.setNeedsDisplayForVisiblePages()
  1369. }
  1370. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  1371. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1372. return
  1373. }
  1374. self.listView.remove(anno)
  1375. }
  1376. func splitView(withTag tag: Int) {
  1377. if tag == 0 {
  1378. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1379. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1380. } else if tag == 1 {
  1381. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1382. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1383. } else if tag == 2 {
  1384. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1385. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1386. }
  1387. self.listView.needsDisplay = true
  1388. }
  1389. // MARK: - 幻灯片
  1390. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1391. let view: NSView = self.view.window!.firstResponder as! NSView
  1392. if view.isDescendant(of: pdfSplitView){
  1393. self.view.window?.makeFirstResponder(nil)
  1394. }
  1395. self.mainWindow = self.view.window
  1396. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1397. fullScreenWindow.interactionParent = self.view.window
  1398. self.mainWindow?.delegate = nil
  1399. fullScreenWindow.fadeInBlocking()
  1400. self.browserWindowController?.window = fullScreenWindow
  1401. fullScreenWindow.makeKey()
  1402. // NSApp.updatePresentationOptions(for: fullScreenWindow)
  1403. let sel = NSSelectorFromString("setAnimationBehavior:")
  1404. if self.mainWindow?.responds(to: sel) ?? false{
  1405. self.mainWindow?.animationBehavior = .none
  1406. }
  1407. self.mainWindow?.orderOut(nil)
  1408. if self.mainWindow?.responds(to: sel) ?? false{
  1409. self.mainWindow?.animationBehavior = .default
  1410. }
  1411. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1412. fullScreenWindow.orderFront(nil)
  1413. // NSApp.addWindowsItem(fullScreenWindow, title: windowTitleForDocumentDisplayName(self.document?.displayName) ?? "", filename: false)
  1414. }
  1415. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1416. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1417. return
  1418. }
  1419. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1420. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1421. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1422. fullScreenWindow.contentView?.addSubview(view)
  1423. self.listView.layoutDocumentView()
  1424. self.listView.requiresDisplay()
  1425. fullScreenWindow.makeFirstResponder(self.listView)
  1426. fullScreenWindow.recalculateKeyViewLoop()
  1427. fullScreenWindow.delegate = self.browserWindowController
  1428. // if (RUNNING_BEFORE(10_7))
  1429. // [fullScreenWindow display];
  1430. fullScreenWindow.display()
  1431. fadeWindow.fadeOut()
  1432. }
  1433. // MARK: Redact 【密文标记】
  1434. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1435. self.listView.remove(self.listView.activeAnnotation)
  1436. }
  1437. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1438. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1439. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1440. self.view.window?.beginSheet(windowController.window!)
  1441. self.currentWindowController = windowController
  1442. windowController.itemClick = { [weak self] index, value in
  1443. if (index == 1) { /// 取消
  1444. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1445. self?.currentWindowController = nil
  1446. return
  1447. }
  1448. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1449. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1450. annotaton.setBorderColor(windowController_redact.outsideColor)
  1451. annotaton.setInteriorColor(windowController_redact.fillColor)
  1452. if (windowController_redact.isOver) {
  1453. annotaton.setFontColor(windowController_redact.fontColor)
  1454. annotaton.setAlignment(windowController_redact.aligement)
  1455. annotaton.setFont(windowController_redact.font)
  1456. annotaton.setOverlayText(windowController_redact.overText)
  1457. }
  1458. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1459. self?.currentWindowController = nil
  1460. }
  1461. }
  1462. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1463. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1464. return
  1465. }
  1466. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1467. let model = CPDFAnnotationModel(annotationType: .redact)
  1468. model?.setColor(annotation.borderColor())
  1469. model?.setInteriorColor(annotation.interiorColor())
  1470. let overlayText: String = annotation.overlayText()
  1471. if (overlayText.isEmpty) {
  1472. model?.setIsOverlayText(false)
  1473. } else {
  1474. model?.setIsOverlayText(true)
  1475. model?.setOverlayText(overlayText)
  1476. model?.setFontColor(annotation.fontColor())
  1477. model?.setAlignment(annotation.alignment())
  1478. model?.setFontName(annotation.font().fontName)
  1479. model?.setFontSize(annotation.font().pointSize)
  1480. }
  1481. }
  1482. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1483. let anno = self.listView.activeAnnotation
  1484. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1485. return
  1486. }
  1487. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1488. windowController.pageCount = Int(self.listView.document.pageCount)
  1489. self.currentWindowController = windowController
  1490. self.view.window?.beginSheet(windowController.window!)
  1491. windowController.itemClick = { [weak self] index, value in
  1492. if (index == 1) {
  1493. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1494. self!.currentWindowController = nil
  1495. return
  1496. }
  1497. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1498. let pageType = windowController_mutilPageFlag.pageType
  1499. let pageString = windowController_mutilPageFlag.pageString
  1500. if (pageType == 4) { /// 自定义页面
  1501. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1502. if (array.count == 0) {
  1503. let alert = NSAlert()
  1504. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1505. alert.runModal()
  1506. return
  1507. }
  1508. }
  1509. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1510. self!.currentWindowController = nil
  1511. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  1512. if (indexs.count == 0) {
  1513. return
  1514. }
  1515. for i in indexs {
  1516. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1517. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1518. self?.listView.add(redactAnno, to: page)
  1519. }
  1520. }
  1521. }
  1522. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1523. self.exeRedactConfirm(.redactOne) {}
  1524. }
  1525. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1526. self.exeRedactConfirm(.eraserOne) {}
  1527. }
  1528. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1529. }
  1530. @objc func exportStampImage(sender:NSMenuItem) {
  1531. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1532. var image : NSImage = NSImage()
  1533. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1534. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1535. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1536. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1537. } else {
  1538. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1539. }
  1540. let data = image.tiffRepresentation
  1541. if sender.tag == 0 {
  1542. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1543. imageRep.size = image.size
  1544. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1545. let savePanel = NSSavePanel()
  1546. savePanel.allowedFileTypes = ["png"]
  1547. savePanel.beginSheetModal(for: self.view.window!) { response in
  1548. if (response != .OK) {
  1549. return
  1550. }
  1551. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1552. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1553. }
  1554. }
  1555. } else {
  1556. let pdfdocument = CPDFDocument()
  1557. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1558. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1559. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1560. let savePanel = NSSavePanel()
  1561. savePanel.allowedFileTypes = ["pdf"]
  1562. savePanel.beginSheetModal(for: self.view.window!) { response in
  1563. if (response != .OK) {
  1564. return
  1565. }
  1566. if pdfdocument!.write(to: savePanel.url!) {
  1567. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1568. }
  1569. }
  1570. }
  1571. }
  1572. }
  1573. }
  1574. @objc func exportCorpImage(sender:NSMenuItem) {
  1575. let rect = NSIntegralRect(listView.currentSelectionRect())
  1576. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1577. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1578. page.setBounds(rect, for: .cropBox)
  1579. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1580. let data = image.tiffRepresentation
  1581. guard let data = data else { return }
  1582. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1583. imageRep.size = rect.size
  1584. let savePanel = NSSavePanel()
  1585. switch sender.tag {
  1586. case 0:
  1587. savePanel.allowedFileTypes = ["png"]
  1588. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1589. savePanel.beginSheetModal(for: self.view.window!) { response in
  1590. if (response != .OK) {
  1591. return
  1592. }
  1593. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1594. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1595. }
  1596. }
  1597. case 1:
  1598. savePanel.allowedFileTypes = ["jpg"]
  1599. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1600. savePanel.beginSheetModal(for: self.view.window!) { response in
  1601. if (response != .OK) {
  1602. return
  1603. }
  1604. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1605. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1606. }
  1607. }
  1608. case 2:
  1609. savePanel.allowedFileTypes = ["pdf"]
  1610. let pdfdocument = CPDFDocument()
  1611. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1612. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1613. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1614. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1615. savePanel.beginSheetModal(for: self.view.window!) { response in
  1616. if (response != .OK) {
  1617. return
  1618. }
  1619. if pdfdocument!.write(to: savePanel.url!) {
  1620. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1621. }
  1622. }
  1623. }
  1624. default:
  1625. break
  1626. }
  1627. // 执行右键操作后,需要取消框选区域
  1628. if self.listView.toolMode == .selectToolMode {
  1629. objc_sync_enter(self)
  1630. self.listView.selectionRect = NSZeroRect
  1631. self.listView.selectionPageIndex = UInt(NSNotFound)
  1632. objc_sync_exit(self)
  1633. }
  1634. }
  1635. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1636. let rect = listView.currentSelectionRect()
  1637. let page = listView.currentPage()
  1638. if NSIsEmptyRect(rect) == false && page != nil {
  1639. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1640. var bounds = listView.bounds
  1641. var scale = 1.0
  1642. if isLegacy {
  1643. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1644. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1645. }
  1646. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1647. scale = NSHeight(bounds) / NSHeight(rect)
  1648. } else {
  1649. scale = NSWidth(bounds) / NSWidth(rect)
  1650. }
  1651. listView.setScaleFactor(scale, animated: false)
  1652. let scrollView = listView.scroll()
  1653. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1654. if ((scrollView?.hasVerticalScroller) != nil) {
  1655. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1656. }
  1657. if ((scrollView?.hasHorizontalScroller) != nil) {
  1658. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1659. }
  1660. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1661. scale = NSHeight(bounds) / NSHeight(rect)
  1662. } else {
  1663. scale = NSWidth(bounds) / NSWidth(rect)
  1664. }
  1665. listView.setScaleFactor(scale, animated: false)
  1666. }
  1667. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1668. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1669. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1670. };
  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. private func cropPagesToRects(rects:NSPointerArray) {
  1681. }
  1682. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1683. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1684. switch sender.tag {
  1685. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1686. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1687. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1688. var red: CGFloat = 0.0
  1689. var green: CGFloat = 0.0
  1690. var blue: CGFloat = 0.0
  1691. var alpha: CGFloat = 0.0
  1692. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1693. if sender.tag == CAnnotationType.highlight.rawValue {
  1694. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1695. } else if sender.tag == CAnnotationType.underline.rawValue {
  1696. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1697. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1698. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1699. }
  1700. case CAnnotationType.ink.rawValue:
  1701. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1702. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1703. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1704. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1705. var red: CGFloat = 0.0
  1706. var green: CGFloat = 0.0
  1707. var blue: CGFloat = 0.0
  1708. var alpha: CGFloat = 0.0
  1709. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1710. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1711. case CAnnotationType.freeText.rawValue:
  1712. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1713. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1714. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1715. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1716. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1717. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1718. var red: CGFloat = 0.0
  1719. var green: CGFloat = 0.0
  1720. var blue: CGFloat = 0.0
  1721. var alpha: CGFloat = 0.0
  1722. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1723. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1724. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1725. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1726. UserDefaults.standard.synchronize()
  1727. }
  1728. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1729. if (alignment == .left || alignment == .center || alignment == .right) {
  1730. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1731. UserDefaults.standard.synchronize()
  1732. }
  1733. case CAnnotationType.anchored.rawValue:
  1734. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1735. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1736. var red: CGFloat = 0.0
  1737. var green: CGFloat = 0.0
  1738. var blue: CGFloat = 0.0
  1739. var alpha: CGFloat = 0.0
  1740. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1741. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1742. case CAnnotationType.square.rawValue:
  1743. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1744. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1745. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1746. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1747. var red: CGFloat = 0.0
  1748. var green: CGFloat = 0.0
  1749. var blue: CGFloat = 0.0
  1750. var alpha: CGFloat = 0.0
  1751. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1752. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1753. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1754. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1755. case CAnnotationType.circle.rawValue:
  1756. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1757. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1758. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1759. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1760. var red: CGFloat = 0.0
  1761. var green: CGFloat = 0.0
  1762. var blue: CGFloat = 0.0
  1763. var alpha: CGFloat = 0.0
  1764. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1765. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1766. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1767. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1768. default:
  1769. break
  1770. }
  1771. }
  1772. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1773. self.showOrHideNotes()
  1774. }
  1775. //MARK: - action
  1776. @objc func cropCurrentPage() {
  1777. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1778. var page: CPDFPage?
  1779. if let data = self.listView.currentSelectionPage() {
  1780. page = data
  1781. } else {
  1782. page = self.listView.currentPage()
  1783. }
  1784. if (NSIsEmptyRect(rect)) {
  1785. rect = KMCropTools.getPageForegroundBox(page!)
  1786. }
  1787. let index: UInt = (page?.pageIndex()) ?? 0
  1788. self._cropPage(at: index, in: rect)
  1789. // 执行右键操作后,需要取消框选区域
  1790. if self.listView.toolMode == .selectToolMode {
  1791. objc_sync_enter(self)
  1792. self.listView.selectionRect = NSZeroRect
  1793. self.listView.selectionPageIndex = UInt(NSNotFound)
  1794. objc_sync_exit(self)
  1795. }
  1796. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1797. }
  1798. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1799. let oldRect = self.listView?.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1800. let undoManager = self.listView.undoManager
  1801. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1802. let page = self.listView.document.page(at: index)
  1803. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1804. page?.setBounds(newRect, for: .cropBox)
  1805. /// 刷新预览视图
  1806. self.listView.layoutDocumentView()
  1807. self.listView.displayBox = .cropBox
  1808. }
  1809. func beginProgressSheet(with message: String, maxValue: UInt) {
  1810. let progress = SKProgressController()
  1811. // progress.window?.backgroundColor = NSColor.km_init(hex: "#ffffff")
  1812. progress.window?.contentView?.wantsLayer = true
  1813. // progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#ffffff").cgColor
  1814. // progress.progressField.textColor = NSColor.black
  1815. progress.message = NSLocalizedString("Converting...", comment: "")
  1816. self.progressC = progress
  1817. self.progressC?.message = message
  1818. if maxValue > 0 {
  1819. progressC?.indeterminate = false
  1820. progressC?.maxValue = Double(maxValue)
  1821. } else {
  1822. progressC?.indeterminate = true
  1823. }
  1824. self.view.km_beginSheet(windowC: progressC!)
  1825. }
  1826. // 白边距
  1827. @objc func smart_cropAllPage() {
  1828. var size = NSZeroSize
  1829. for i in 0 ..< self.listView.document.pageCount {
  1830. let page = self.listView.document.page(at: i)
  1831. let rect = KMCropTools.getPageForegroundBox(page!)
  1832. size.width = fmax(size.width, NSWidth(rect))
  1833. size.height = fmax(size.height, NSHeight(rect))
  1834. }
  1835. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1836. var rectArray: Array<NSRect> = []
  1837. for i in 0 ..< self.listView.document.pageCount {
  1838. progressC?.increment(by: Double(i))
  1839. progressC?.doubleValue = Double(i)
  1840. let page = self.listView.document.page(at: i)
  1841. var rect = KMCropTools.getPageForegroundBox(page!)
  1842. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1843. // if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1844. // rect.origin.x = rect.maxX-size.width
  1845. // }
  1846. // rect.origin.y = rect.maxY-size.height
  1847. // rect.size = size
  1848. // if (NSWidth(rect) > NSWidth(bounds)) {
  1849. // rect.size.width = NSWidth(bounds)
  1850. // }
  1851. // if (NSHeight(rect) > NSHeight(bounds)) {
  1852. // rect.size.height = NSHeight(bounds)
  1853. // }
  1854. //
  1855. // if (NSMinX(rect) < NSMinX(bounds)) {
  1856. // rect.origin.x = NSMinX(bounds)
  1857. // } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1858. // rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1859. // }
  1860. //
  1861. // if (NSMinY(rect) < NSMinY(bounds)) {
  1862. // rect.origin.y = NSMinY(bounds)
  1863. // } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1864. // rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1865. // }
  1866. rectArray.append(rect)
  1867. }
  1868. cropPages(to: rectArray)
  1869. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1870. }
  1871. // 自动
  1872. @objc func auto_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. if (NSMinX(rect) < NSMinX(bounds)) {
  1900. rect.origin.x = NSMinX(bounds)
  1901. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1902. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1903. }
  1904. if (NSMinY(rect) < NSMinY(bounds)) {
  1905. rect.origin.y = NSMinY(bounds)
  1906. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1907. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1908. }
  1909. rectArray.append(rect)
  1910. }
  1911. cropPages(to: rectArray)
  1912. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1913. }
  1914. @objc func cropAllPage() {
  1915. var rect = [NSIntegralRect(self.listView?.currentSelectionRect() ?? .zero), .zero]
  1916. var rectArray: Array<NSRect> = []
  1917. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1918. if (emptySelection) {
  1919. guard let count = self.listView?.document?.pageCount, count > 0 else {
  1920. KMPrint("listView | document is nil.", beep: true)
  1921. return
  1922. }
  1923. rect[0] = .zero
  1924. rect[1] = .zero
  1925. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1926. if (count == 1) {
  1927. if let page = self.listView.document.page(at: 0) {
  1928. rect[0] = KMCropTools.getPageForegroundBox(page)
  1929. }
  1930. progressC?.increment(by: 1)
  1931. } else if (count < 19) {
  1932. for i in 0 ..< 19 {
  1933. if let page = self.listView.document.page(at: UInt(i)) {
  1934. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1935. progressC?.increment(by: Double(i))
  1936. }
  1937. }
  1938. } else {
  1939. let start = [1, (count - 5) / 2, count - 6]
  1940. var cnt = 0
  1941. for j in 0 ..< 3 {
  1942. for i in 0 ..< 6 {
  1943. let k = Int(start[j] + UInt(i))
  1944. if let page = self.listView.document.page(at: UInt(k)) {
  1945. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1946. cnt += 1
  1947. progressC?.increment(by: Double(cnt))
  1948. }
  1949. }
  1950. }
  1951. }
  1952. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  1953. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  1954. for j in 0 ..< 2 {
  1955. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  1956. }
  1957. rectArray.append(rect.first ?? .zero)
  1958. rectArray.append(rect.last ?? .zero)
  1959. } else {
  1960. rectArray.append(rect.first ?? .zero)
  1961. }
  1962. self.cropPages(to: rectArray)
  1963. // 执行右键操作后,需要取消框选区域
  1964. if self.listView.toolMode == .selectToolMode {
  1965. objc_sync_enter(self)
  1966. self.listView.selectionRect = NSZeroRect
  1967. self.listView.selectionPageIndex = UInt(NSNotFound)
  1968. objc_sync_exit(self)
  1969. }
  1970. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1971. }
  1972. func cropPages(to rects: Array<NSRect>) {
  1973. let currentPage = self.listView.currentPage()
  1974. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1975. var oldRectArray: Array<NSRect> = []
  1976. let rectCount = rects.count
  1977. for i in 0 ..< self.listView.document.pageCount {
  1978. let page = self.listView.document.page(at: i)
  1979. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  1980. let oldRect = page?.bounds(for: .cropBox)
  1981. oldRectArray.append(oldRect!)
  1982. page?.setBounds(rect, for: .cropBox)
  1983. }
  1984. let undoManager = self.listView.undoManager
  1985. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1986. /// 刷新预览视图
  1987. self.listView.layoutDocumentView()
  1988. self.listView.displayBox = .cropBox
  1989. self.listView.go(to: currentPage)
  1990. self.listView.go(to: visibleRect, on: currentPage)
  1991. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1992. self.dismissProgressSheet()
  1993. }
  1994. }
  1995. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1996. if (limit) {
  1997. let document = self.listView.document ?? CPDFDocument()
  1998. if document?.documentURL == nil {
  1999. return
  2000. }
  2001. var doucumentURL : URL = self.listView.document.documentURL
  2002. if doucumentURL.path.count > 0 {
  2003. let docDir = NSTemporaryDirectory()
  2004. let documentName : String = doucumentURL.path.lastPathComponent
  2005. let path = docDir.stringByAppendingPathComponent(documentName)
  2006. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2007. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2008. let writeSuccess = data != nil
  2009. if writeSuccess == false {
  2010. __NSBeep()
  2011. return;
  2012. }
  2013. doucumentURL = URL(fileURLWithPath: path)
  2014. }
  2015. let array = [doucumentURL]
  2016. let picker = NSSharingServicePicker.init(items: array)
  2017. if sender.shareButton.window != nil {
  2018. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2019. } else {
  2020. 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)
  2021. }
  2022. return
  2023. }
  2024. let document = self.listView.document ?? CPDFDocument()
  2025. if document?.documentURL == nil {
  2026. return
  2027. }
  2028. var doucumentURL : URL = self.listView.document.documentURL
  2029. if doucumentURL.path.count > 0 {
  2030. let docDir = NSTemporaryDirectory()
  2031. let documentName : String = doucumentURL.path.lastPathComponent
  2032. let path = docDir.stringByAppendingPathComponent(documentName)
  2033. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2034. if writeSuccess == false {
  2035. __NSBeep()
  2036. return;
  2037. }
  2038. doucumentURL = URL(fileURLWithPath: path)
  2039. }
  2040. let array = [doucumentURL]
  2041. let picker = NSSharingServicePicker.init(items: array)
  2042. if sender.shareButton.window != nil {
  2043. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2044. } else {
  2045. 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)
  2046. }
  2047. }
  2048. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  2049. if (limit) {
  2050. let document = self.listView.document ?? CPDFDocument()
  2051. var path: String?
  2052. if document?.documentURL != nil {
  2053. path = document?.documentURL.path ?? ""
  2054. }
  2055. if path?.count ?? 0 > 0 {
  2056. let docDir = NSTemporaryDirectory()
  2057. let documentName : String = path?.lastPathComponent ?? ""
  2058. path = docDir.stringByAppendingPathComponent(documentName)
  2059. }
  2060. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2061. var tfileName = path?.deletingPathExtension.lastPathComponent
  2062. let tStdFileSuffix = "_flatten"
  2063. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2064. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2065. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path ?? ""))
  2066. let success = data != nil
  2067. if success {
  2068. let url = URL(fileURLWithPath: path ?? "")
  2069. let picker = NSSharingServicePicker.init(items: [url])
  2070. if sender.shareButton.window != nil {
  2071. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2072. } else {
  2073. 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)
  2074. }
  2075. }
  2076. return
  2077. }
  2078. let document = self.listView.document ?? CPDFDocument()
  2079. var path: String?
  2080. if document?.documentURL != nil {
  2081. path = document?.documentURL.path ?? ""
  2082. }
  2083. if path?.count ?? 0 > 0 {
  2084. let docDir = NSTemporaryDirectory()
  2085. let documentName : String = path?.lastPathComponent ?? ""
  2086. path = docDir.stringByAppendingPathComponent(documentName)
  2087. }
  2088. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2089. var tfileName = path?.deletingPathExtension.lastPathComponent
  2090. let tStdFileSuffix = "_flatten"
  2091. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2092. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2093. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  2094. if success {
  2095. let url = URL(fileURLWithPath: path ?? "")
  2096. let picker = NSSharingServicePicker.init(items: [url])
  2097. if sender.shareButton.window != nil {
  2098. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2099. } else {
  2100. 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)
  2101. }
  2102. }
  2103. }
  2104. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  2105. guard let pdfDoc = self.listView.document else {
  2106. NSSound.beep()
  2107. return
  2108. }
  2109. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  2110. let alert = NSAlert()
  2111. alert.alertStyle = .critical
  2112. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2113. alert.runModal()
  2114. return
  2115. }
  2116. if (limit) {
  2117. let document = self.listView.document ?? CPDFDocument()
  2118. var path: String?
  2119. if document?.documentURL != nil {
  2120. path = document?.documentURL.path ?? ""
  2121. }
  2122. if path?.count ?? 0 > 0{
  2123. let docDir = NSTemporaryDirectory()
  2124. let documentName : String = path?.lastPathComponent ?? ""
  2125. path = docDir.stringByAppendingPathComponent(documentName)
  2126. }
  2127. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  2128. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path ?? ""), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2129. var writeSuccess = data != nil
  2130. if writeSuccess == false {
  2131. __NSBeep()
  2132. return;
  2133. }
  2134. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2135. let cnt = newDocument?.pageCount ?? 0
  2136. for i in 0 ..< cnt {
  2137. let page = newDocument?.page(at: i)
  2138. var annotations : [CPDFAnnotation] = []
  2139. for annotation in page!.annotations {
  2140. annotations.append(annotation)
  2141. }
  2142. for annotation in annotations {
  2143. annotation.page.removeAnnotation(annotation)
  2144. }
  2145. }
  2146. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? "")) ?? false
  2147. if writeSuccess {
  2148. let url = URL(fileURLWithPath: path ?? "")
  2149. let picker = NSSharingServicePicker.init(items: [url])
  2150. if sender.shareButton.window != nil {
  2151. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2152. } else {
  2153. 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)
  2154. }
  2155. }
  2156. return
  2157. }
  2158. let document = self.listView.document ?? CPDFDocument()
  2159. var path: String?
  2160. if document?.documentURL != nil {
  2161. path = document?.documentURL.path ?? ""
  2162. }
  2163. if path?.count ?? 0 > 0 {
  2164. let docDir = NSTemporaryDirectory()
  2165. let documentName : String = path?.lastPathComponent ?? ""
  2166. path = docDir.stringByAppendingPathComponent(documentName)
  2167. }
  2168. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2169. if writeSuccess == false {
  2170. __NSBeep()
  2171. return;
  2172. }
  2173. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2174. let cnt = newDocument?.pageCount ?? 0
  2175. for i in 0 ..< cnt {
  2176. let page = newDocument!.page(at: i)
  2177. var annotations : [CPDFAnnotation] = []
  2178. for annotation in page!.annotations {
  2179. annotations.append(annotation)
  2180. }
  2181. for annotation in annotations {
  2182. annotation.page.removeAnnotation(annotation)
  2183. }
  2184. }
  2185. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2186. if writeSuccess ?? false {
  2187. let url = URL(fileURLWithPath: path ?? "")
  2188. let picker = NSSharingServicePicker.init(items: [url])
  2189. if sender.shareButton.window != nil {
  2190. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2191. } else {
  2192. 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)
  2193. }
  2194. }
  2195. }
  2196. // 开启/关闭左边栏
  2197. @objc func toggleLeftPane() -> Void {
  2198. // if lastLeftPanWidth >= functionWidth {
  2199. self.model.leftPanelOpen = true
  2200. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2201. // } else {
  2202. // leftPanelOpen = false
  2203. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  2204. // }
  2205. }
  2206. // 开启左边栏
  2207. @objc func openLeftPane() -> Void {
  2208. self.model.leftPanelOpen = true
  2209. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2210. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  2211. }
  2212. // 关闭左边栏
  2213. @objc func closeLeftPane() -> Void {
  2214. self.model.leftPanelOpen = false
  2215. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2216. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = false
  2217. }
  2218. // 开启/关闭右边栏
  2219. @objc func toggleRightPane() -> Void {
  2220. if self.model.lastRightPanWidth > 5 {
  2221. self.model.rightPanelIsOpen = false
  2222. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2223. } else {
  2224. self.model.rightPanelIsOpen = true
  2225. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2226. }
  2227. }
  2228. @objc func openRightPane() -> Void {
  2229. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2230. if self.model.rightPanelIsOpen {
  2231. return
  2232. }
  2233. self.model.rightPanelIsOpen = true
  2234. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  2235. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2236. }
  2237. }
  2238. @objc func closeRightPane() -> Void {
  2239. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2240. self.model.rightPanelIsOpen = false
  2241. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  2242. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2243. cancelMeasureType()
  2244. }
  2245. }
  2246. func rename(_ sender: NSNotification) -> Void {
  2247. if (self.view.window == nil || self.view.window!.isVisible == false) {
  2248. return
  2249. }
  2250. let tabController = sender.object as? CTTabController
  2251. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  2252. if let doc = self.myDocument, doc.isDocumentEdited {
  2253. Task {
  2254. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  2255. if resp != .alertFirstButtonReturn { // 取消
  2256. return
  2257. }
  2258. doc.updateChangeCount(.changeCleared)
  2259. // doc.save(nil)
  2260. self.document?.write(to: doc.fileURL)
  2261. Task { @MainActor in
  2262. self._renameForSavePanel(tabController)
  2263. }
  2264. }
  2265. return
  2266. }
  2267. self._renameForSavePanel(tabController)
  2268. }
  2269. }
  2270. func savePdfAlertView() {
  2271. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  2272. return
  2273. }
  2274. AutoSaveManager.manager.isSaveNoti = true
  2275. var num = 0
  2276. if self.listView.document != nil{
  2277. num = Int(self.listView.document.pageCount)
  2278. }
  2279. if Thread.current.isMainThread {
  2280. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2281. } else {
  2282. DispatchQueue.main.async {
  2283. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2284. }
  2285. }
  2286. }
  2287. func savePdfFinishAlertView() {
  2288. if !AutoSaveManager.manager.isSaveNoti{
  2289. return
  2290. }
  2291. AutoSaveManager.manager.isSaveNoti = false
  2292. if Thread.current.isMainThread {
  2293. self.dismissProgressSheet()
  2294. } else {
  2295. DispatchQueue.main.async {
  2296. self.dismissProgressSheet()
  2297. }
  2298. }
  2299. }
  2300. private func _renameForSavePanel(_ tabC: CTTabController?) {
  2301. let outputSavePanel = NSSavePanel()
  2302. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  2303. outputSavePanel.allowedFileTypes = ["pdf"]
  2304. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  2305. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  2306. let resp = outputSavePanel.runModal()
  2307. if resp == .OK {
  2308. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  2309. let fileURL = pdfDocument?.documentURL
  2310. let fileManager = FileManager.default
  2311. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  2312. var result = true
  2313. do {
  2314. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  2315. } catch {
  2316. result = false
  2317. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  2318. }
  2319. if (result) {
  2320. tabC?.title = outputSavePanel.url!.lastPathComponent
  2321. // self.myDocument?.fileURL = newFileURL
  2322. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  2323. self.model.isSaveKeyChain = false
  2324. newPdfDocument.unlock(withPassword: self.document?.password)
  2325. if (newPdfDocument.pageCount > 0) {
  2326. self.setDocument = newPdfDocument
  2327. }
  2328. }
  2329. }
  2330. } else {
  2331. outputSavePanel.close()
  2332. }
  2333. }
  2334. func showInFinder(_ sender: Any) -> Void {
  2335. if sender is NSNotification {
  2336. let tabController = (sender as! NSNotification).object as? CTTabController
  2337. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2338. if tabController?.title == path {
  2339. if let file = self.myDocument?.fileURL {
  2340. if FileManager.default.fileExists(atPath: file.path) {
  2341. NSWorkspace.shared.activateFileViewerSelecting([file])
  2342. }
  2343. }
  2344. }
  2345. } else {
  2346. guard let url = self.myDocument?.fileURL else { return }
  2347. let file: URL = url
  2348. if FileManager.default.fileExists(atPath: file.path) {
  2349. NSWorkspace.shared.activateFileViewerSelecting([file])
  2350. }
  2351. }
  2352. }
  2353. func showOrHideNotes() {
  2354. self.listView.hideNotes = !self.listView.hideNotes
  2355. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  2356. //BOTA 注释列表显示隐藏
  2357. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2358. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2359. self.leftSideViewController.note_reloadDataIfNeed()
  2360. }
  2361. func closeTab(_ sender: NSNotification) -> Void {
  2362. // let tabController = sender.object as? CTTabController
  2363. // let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2364. // if tabController?.title == path {
  2365. // print("closeTab")
  2366. // self.leftSideViewController.clearAnnotationFilterData()
  2367. // self.leftSideViewController.clearNotification()
  2368. // }
  2369. }
  2370. @IBAction func toggleSplitPDF(_ sender: Any) {
  2371. if let menuItem = sender as? NSMenuItem {
  2372. splitView(withTag: menuItem.tag)
  2373. }
  2374. }
  2375. @IBAction func readMode(_ sender: Any) {
  2376. isReadMode = !isReadMode
  2377. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  2378. UserDefaults.standard.synchronize()
  2379. if isReadMode {
  2380. CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2381. } else {
  2382. CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2383. }
  2384. }
  2385. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2386. // NSDictionary *info = [notification userInfo];
  2387. // PDFPage *page = [info objectForKey:SKPDFPagePageKey];
  2388. // NSString *action = [info objectForKey:SKPDFPageActionKey];
  2389. // BOOL displayChanged = [action isEqualToString:SKPDFPageActionCrop] == NO || [pdfView displayBox] == kPDFDisplayBoxCropBox;
  2390. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2391. // if self.listView.displayBox == .cropBox {
  2392. // KMPrint("cropBox")
  2393. // } else if self.listView.displayBox == .artBox {
  2394. // KMPrint("artBox")
  2395. // } else if self.listView.displayBox == .trimBox {
  2396. // KMPrint("trimBox")
  2397. // } else if self.listView.displayBox == .bleedBox {
  2398. // KMPrint("bleedBox")
  2399. // } else if self.listView.displayBox == .mediaBox {
  2400. // KMPrint("mediaBox")
  2401. // } else {
  2402. // KMPrint("other \(self.listView.displayBox.rawValue)")
  2403. // }
  2404. if (displayChanged) {
  2405. self.listView.layoutDocumentView()
  2406. }
  2407. if (page != nil) {
  2408. let idx = page!.pageIndex()
  2409. if (displayChanged) {
  2410. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2411. }
  2412. } else {
  2413. if (displayChanged) {
  2414. self.leftSideViewController.allThumbnailsNeedUpdate()
  2415. }
  2416. }
  2417. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2418. // [secondaryPdfView requiresDisplay];
  2419. self.secondaryPdfView?.setNeedsDisplayForVisiblePages()
  2420. //
  2421. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2422. // [self updateRightStatus];
  2423. }
  2424. }
  2425. func changeLineAttribute(_ sender: Any?) {
  2426. var inspector = sender as? KMLineInspector
  2427. if inspector == nil {
  2428. inspector = KMLineInspector.shared
  2429. }
  2430. let action = inspector?.currentLineChangeAction ?? .no
  2431. for annotation in self.listView.activeAnnotations {
  2432. guard let anno = annotation as? CPDFAnnotation else {
  2433. continue
  2434. }
  2435. if anno.hasBorder() {
  2436. // if (mwcFlags.updatingLine == 0 && [annotation hasBorder]) {
  2437. // mwcFlags.updatingLine = 1;
  2438. switch (action) {
  2439. case .lineWidth:
  2440. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2441. break
  2442. case .style:
  2443. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2444. break
  2445. case .dashPattern:
  2446. anno.setDashPattern(inspector?.dashPattern ?? [])
  2447. break
  2448. case .startLineStyle:
  2449. if anno.isLine() {
  2450. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2451. }
  2452. break
  2453. case .endLineStyle:
  2454. if anno.isLine() {
  2455. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2456. }
  2457. break
  2458. case .no:
  2459. break
  2460. }
  2461. // mwcFlags.updatingLine = 0;
  2462. // in case one property changes another, e.g. when adding a dashPattern the borderStyle can change
  2463. }
  2464. }
  2465. // [self updateLineInspector];
  2466. }
  2467. // MARK: -
  2468. // MARK: 显示窗口
  2469. internal func showCompressWindow(url: URL? = nil) {
  2470. // if let wc = self.compressWIndowControllerNew, let _ = wc.window?.isSheet {
  2471. // KMPrint("压缩窗口已显示")
  2472. // return
  2473. // }
  2474. self.compressWIndowControllerNew = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2475. self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  2476. self.compressWIndowControllerNew?.password = self.listView?.document?.password ?? ""
  2477. // if let _url = url {
  2478. // windowController.oriDocumentUrl = self.listView.document.documentURL
  2479. // windowController.documentURL = _url
  2480. // } else {
  2481. self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  2482. // }
  2483. self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  2484. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2485. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2486. }
  2487. self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  2488. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2489. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2490. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2491. // batchWindowController.window?.makeKeyAndOrderFront("")
  2492. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2493. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2494. batchWindowController.window?.makeKeyAndOrderFront("")
  2495. }
  2496. self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2497. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2498. if (result) {
  2499. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2500. if (openDocument) {
  2501. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2502. } else {
  2503. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2504. }
  2505. } else {
  2506. let alert = NSAlert()
  2507. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2508. alert.runModal()
  2509. }
  2510. }
  2511. }
  2512. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2513. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2514. KMPrint("转档窗口已显示")
  2515. return
  2516. }
  2517. var convertT: KMConvertType = .Word
  2518. var windowController: KMConvertBaseWindowController?
  2519. if (type == .word) { /// Word
  2520. convertT = .Word
  2521. } else if (type == .excel) {
  2522. convertT = .Excel
  2523. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2524. if (type == .ppt) {
  2525. convertT = .PPT
  2526. } else if (type == .rtf) {
  2527. convertT = .RTF
  2528. } else if (type == .html) {
  2529. convertT = .HTML
  2530. } else if (type == .conversion_text) {
  2531. convertT = .Text
  2532. }
  2533. } else if (type == .csv) {
  2534. convertT = .CSV
  2535. } else if (type == .conversion_image) {
  2536. windowController = KMConvertImageWindowController()
  2537. convertT = .JPEG
  2538. }
  2539. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  2540. var url: URL?
  2541. if (documentUrl != nil) {
  2542. url = documentUrl
  2543. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2544. } else {
  2545. url = self.listView.document.documentURL
  2546. }
  2547. self.showAllConvertWindow(convertT: convertT)
  2548. }
  2549. //MARK: 转档 -
  2550. func showAllConvertWindow(convertT: KMConvertType) {
  2551. self.ConvertTrackEvent(type: convertT)
  2552. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2553. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2554. var type: KMConvertWithPDFType = .WordAdvance
  2555. switch convertT {
  2556. case .Word:
  2557. break
  2558. case .Excel:
  2559. type = .Excel
  2560. case .PPT:
  2561. type = .PowerPoint
  2562. case .RTF:
  2563. type = .RTF
  2564. case .CSV:
  2565. type = .CSV
  2566. case .HTML:
  2567. type = .HTML
  2568. case .Text:
  2569. type = .Text
  2570. case .JPEG:
  2571. type = .JPEG
  2572. case .PNG:
  2573. type = .PNG
  2574. case .GIF:
  2575. type = .GIF
  2576. case .JPG:
  2577. type = .JPG
  2578. case .TIFF:
  2579. type = .TIFF
  2580. case .TGA:
  2581. type = .TGA
  2582. case .BMP:
  2583. type = .BMP
  2584. case .JP2:
  2585. type = .JPEG2000
  2586. case .AdvancedWord:
  2587. break
  2588. default:
  2589. break
  2590. }
  2591. // let document = self.document
  2592. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2593. var needShowHint = false
  2594. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2595. needShowHint = true
  2596. } else {
  2597. var needContinue = false
  2598. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2599. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2600. let ss = self.document?.documentURL.path
  2601. if arr.contains(ss!) {
  2602. needContinue = false
  2603. }else {
  2604. needContinue = true
  2605. }
  2606. }else {
  2607. needContinue = true
  2608. }
  2609. if needContinue {
  2610. let ss = self.document?.documentURL.path
  2611. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2612. file.password = document?.password ?? ""
  2613. KMBatchOperateManager.defaultManager.files?.append(file)
  2614. }
  2615. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2616. batchWindowController.switchToConvertType(convertType: type)
  2617. }
  2618. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2619. if needShowHint {
  2620. batchWindowController.showIsConvertingHint()
  2621. } else {
  2622. }
  2623. }
  2624. }
  2625. self.km_beginSheet(windowC: convertWC)
  2626. }
  2627. func ConvertTrackEvent(type: KMConvertType) {
  2628. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2629. switch type {
  2630. case .Word:
  2631. eventStr = "Btn_SubTbr_Converter_ToWord"
  2632. break
  2633. case .Excel:
  2634. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2635. case .PPT:
  2636. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2637. case .RTF:
  2638. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2639. case .CSV:
  2640. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2641. case .HTML:
  2642. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2643. case .Text:
  2644. eventStr = "Btn_SubTbr_Converter_ToText"
  2645. case .JPEG:
  2646. eventStr = "Btn_SubTbr_Converter_ToImage"
  2647. case .PNG:
  2648. eventStr = "Btn_SubTbr_Converter_ToImage"
  2649. case .GIF:
  2650. eventStr = "Btn_SubTbr_Converter_ToImage"
  2651. case .JPG:
  2652. eventStr = "Btn_SubTbr_Converter_ToImage"
  2653. case .TIFF:
  2654. eventStr = "Btn_SubTbr_Converter_ToImage"
  2655. case .TGA:
  2656. eventStr = "Btn_SubTbr_Converter_ToImage"
  2657. case .BMP:
  2658. eventStr = "Btn_SubTbr_Converter_ToImage"
  2659. case .JP2:
  2660. eventStr = "Btn_SubTbr_Converter_ToImage"
  2661. case .AdvancedWord:
  2662. eventStr = "Btn_SubTbr_Converter_ToWord"
  2663. break
  2664. default:
  2665. break
  2666. }
  2667. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2668. }
  2669. //MARK: 转档 - OCR
  2670. func showOCRWindow() {
  2671. if !IAPProductsManager.default().isAvailableAllFunction(){
  2672. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2673. return
  2674. }
  2675. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  2676. com.currentIndexPage = self.listView.currentPageIndex
  2677. self.km_beginSheet(windowC: com)
  2678. }
  2679. //MARK: 导出图片
  2680. func extractImageAction(num: Int) {
  2681. if !IAPProductsManager.default().isAvailableAllFunction(){
  2682. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2683. return
  2684. }
  2685. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2686. let alert = NSAlert()
  2687. alert.alertStyle = .critical
  2688. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2689. alert.runModal()
  2690. return
  2691. }
  2692. // if sender is KMToolbarItem {
  2693. // (sender as! KMToolbarItem).isSelected = false
  2694. // }
  2695. let document = self.listView.document
  2696. var fileURL = document?.documentURL
  2697. if num == 1 {
  2698. let pageCount = document?.pageCount ?? 0
  2699. let indeSet = NSMutableIndexSet()
  2700. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2701. if indeSet.count == 0 {
  2702. return
  2703. }
  2704. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2705. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2706. let outputSavePanel = NSSavePanel()
  2707. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2708. outputSavePanel.allowsOtherFileTypes = true
  2709. outputSavePanel.isExtensionHidden = true
  2710. outputSavePanel.canCreateDirectories = true
  2711. outputSavePanel.nameFieldStringValue = tFileName
  2712. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2713. if result == NSApplication.ModalResponse.OK {
  2714. DispatchQueue.main.async {
  2715. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2716. let tDestFile = outputSavePanel.url!.path
  2717. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2718. let pdfconverter = PDFConvertObject()
  2719. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2720. self.dismissProgressSheet()
  2721. let fileManager = FileManager.default
  2722. if fileManager.fileExists(atPath: tDestFile) {
  2723. let workspace = NSWorkspace.shared
  2724. let url = URL(fileURLWithPath: tDestFile)
  2725. workspace.activateFileViewerSelecting([url])
  2726. }
  2727. }
  2728. }
  2729. })
  2730. return
  2731. }
  2732. if fileURL != nil {
  2733. self.myDocument?.save(nil)
  2734. } else {
  2735. let myDocument = self.myDocument
  2736. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2737. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2738. if writeSuccess {
  2739. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2740. fileURL = document?.documentURL
  2741. } else {
  2742. NSSound.beep()
  2743. return
  2744. }
  2745. }
  2746. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2747. extract?.docPath = fileURL?.path ?? ""
  2748. extract?.password = document?.password ?? ""
  2749. extract?.currentPage = self.listView.currentPageIndex
  2750. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2751. self.km_beginSheet(windowC: extract!)
  2752. extract?.selectCurrentPageBtn()
  2753. // self.showCreateStamp()
  2754. // self.showAddSignature()
  2755. }
  2756. //MARK: 创建文字图章示例实际上不会在这里使用
  2757. func showCreateStamp() {
  2758. let stampCreaterWindowController = KMStampCreaterWindowController()
  2759. stampCreaterWindowController.window?.backgroundColor = .clear
  2760. self.km_beginSheet(windowC: stampCreaterWindowController)
  2761. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2762. if result == 1 {
  2763. }
  2764. }
  2765. }
  2766. //MARK: 添加签名示例实际上不会在这里使用
  2767. func showAddSignature() {
  2768. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  2769. // signatureWindowController.window?.backgroundColor = .clear
  2770. // signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2771. //
  2772. // }
  2773. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  2774. })
  2775. }
  2776. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2777. // if progressController == nil {
  2778. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2779. // }
  2780. let progress = SKProgressController()
  2781. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2782. progress.window?.contentView?.wantsLayer = true
  2783. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2784. progress.progressField.textColor = NSColor.white
  2785. progress.message = NSLocalizedString("Converting...", comment: "")
  2786. progressC = progress
  2787. progressC?.message = message
  2788. if maxValue > 0 {
  2789. progressC?.indeterminate = false
  2790. progressC?.maxValue = Double(maxValue)
  2791. progressC?.progressBar.doubleValue = 0.3
  2792. } else {
  2793. progressC?.indeterminate = true
  2794. }
  2795. self.view.km_beginSheet(windowC: progressC!)
  2796. }
  2797. func dismissProgressSheet() {
  2798. progressC?.stopAnimation()
  2799. self.view.km_endSheet()
  2800. progressC = nil
  2801. }
  2802. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2803. let newArr = NSMutableArray()
  2804. for item in files {
  2805. newArr.add(item.filePath)
  2806. }
  2807. return newArr as! [String]
  2808. }
  2809. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2810. self.saveDocument()
  2811. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2812. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2813. if (result == .cancel) {
  2814. return
  2815. }
  2816. // 解除权限
  2817. self?.listView.document.unlock(withPassword: password)
  2818. // 隐藏提示
  2819. self?.hiddenSecureLimitTip()
  2820. // 去打印
  2821. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2822. }
  2823. return
  2824. }
  2825. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2826. }
  2827. // MARK: - 图片注释
  2828. @IBAction func imageAnnotation(_ sender: Any) {
  2829. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2830. changeAnnotationMode(sender)
  2831. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2832. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2833. return
  2834. }
  2835. let accessoryCtr = KMImageAccessoryController()
  2836. let openPanel = NSOpenPanel()
  2837. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2838. openPanel.allowsMultipleSelection = false
  2839. openPanel.accessoryView = accessoryCtr.view
  2840. // if #available(macOS 10.11, *) {
  2841. openPanel.canSelectHiddenExtension = true
  2842. // }
  2843. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2844. if result == .OK {
  2845. guard let url = openPanel.url else {
  2846. return
  2847. }
  2848. let filePath = url.path
  2849. if filePath.pathExtension.lowercased() == "pdf" {
  2850. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2851. NSSound.beep()
  2852. return
  2853. }
  2854. }
  2855. let image = NSImage(contentsOfFile: url.path)
  2856. let isDamageImage: Bool = self.isDamageImage(image!, imagePath: url.path)
  2857. if isDamageImage {
  2858. let alert = NSAlert()
  2859. alert.alertStyle = .critical
  2860. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2861. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2862. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2863. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2864. if response == .alertFirstButtonReturn {
  2865. // Handle cancel button clicked
  2866. }
  2867. }
  2868. }
  2869. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2870. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2871. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2872. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  2873. }
  2874. }
  2875. }
  2876. }
  2877. @IBAction func tableAnnotation(_ sender: Any) {
  2878. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2879. changeAnnotationMode(sender)
  2880. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2881. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2882. return
  2883. }
  2884. listView.addAnnotationWithTable()
  2885. openRightPane()
  2886. }
  2887. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2888. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2889. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2890. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2891. }
  2892. if let data = image.tiffRepresentation,
  2893. let imageRep = NSBitmapImageRep(data: data) {
  2894. imageRep.size = image.size
  2895. var imageData: Data?
  2896. if path.lowercased() == "png" {
  2897. imageData = imageRep.representation(using: .png, properties: [:])
  2898. } else {
  2899. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2900. }
  2901. if let imageData = imageData {
  2902. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2903. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2904. return true
  2905. } else {
  2906. return false
  2907. }
  2908. }
  2909. }
  2910. return false
  2911. }
  2912. func tagString() -> String {
  2913. let dateFormatter = DateFormatter()
  2914. dateFormatter.dateFormat = "yyMMddHHmmss"
  2915. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2916. }
  2917. // MARK: - Split View
  2918. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2919. }
  2920. @objc func removeSecondaryPdfContentView(_ sender: Notification?) {
  2921. if let _ = sender {
  2922. NotificationCenter.default.removeObserver(self, name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  2923. }
  2924. self.secondaryPdfContentView?.removeFromSuperview()
  2925. self.newPDFSplitView.adjustSubviews()
  2926. }
  2927. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2928. if !isSinglePage && isHorizontal {
  2929. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2930. }
  2931. if (!isSinglePage && !isHorizontal) {
  2932. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2933. }
  2934. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2935. }
  2936. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2937. if isSinglePage {
  2938. if self.newPDFSplitView.animating {
  2939. return
  2940. }
  2941. if self.secondaryPdfContentView?.window != nil {
  2942. self.lastSplitPDFHeight = self.lastSplitPDFHeightFloat(self.secondaryPdfContentView?.frame ?? .zero)
  2943. self.newPDFSplitView.setPosition(self.newPDFSplitView.maxPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: true)
  2944. if self.newPDFSplitView.animating {
  2945. NotificationCenter.default.addObserver(self, selector: #selector(removeSecondaryPdfContentView), name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  2946. } else {
  2947. self.removeSecondaryPdfContentView(nil)
  2948. }
  2949. }
  2950. self.view.window?.recalculateKeyViewLoop()
  2951. if self.interactionMode == .legacyFullScreen {
  2952. self.view.window?.makeFirstResponder(self.listView)
  2953. }
  2954. } else {
  2955. if self.newPDFSplitView.animating {
  2956. return
  2957. }
  2958. self.newPDFSplitView.dividerStyle = .paneSplitter
  2959. self.newPDFSplitView.isVertical = isHorizontal
  2960. if self.secondaryPdfView?.window == nil {
  2961. let frame = self.newPDFSplitView.bounds
  2962. if (self.lastSplitPDFHeight <= 0.0) {
  2963. var DEFAULT_SPLIT_PDF_FACTOR: Float = 0.3
  2964. self.lastSplitPDFHeight = floorf(DEFAULT_SPLIT_PDF_FACTOR * self.lastSplitPDFHeightFloat(frame))
  2965. }
  2966. var position = self.lastSplitPDFHeightFloat(frame)-self.lastSplitPDFHeight-Float(self.newPDFSplitView.dividerThickness)
  2967. var point: NSPoint = .zero
  2968. var page: CPDFPage?
  2969. self.newPDFSplitView.setPosition(position.cgFloat, ofDividerAt: 0, animate: true)
  2970. if (self.secondaryPdfContentView == nil) {
  2971. // secondaryPdfContentView = [[SKGradientView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 200.0, 20.0)];
  2972. self.secondaryPdfContentView = NSView(frame: NSMakeRect(0, 0, 200, 20))
  2973. self.secondaryPdfView = KMSecondaryPDFView(frame: self.secondaryPdfContentView?.bounds ?? .zero)
  2974. self.secondaryPdfView?.autoresizingMask = [.width, .height]
  2975. // self.secondaryPdfContentView?.isHidden = true
  2976. self.secondaryPdfContentView?.addSubview(self.secondaryPdfView!)
  2977. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  2978. // self.newPDFSplitView.addArrangedSubview(self.secondaryPdfContentView!)
  2979. // // Because of a PDFView bug, display properties can not be changed before it is placed in a window
  2980. self.secondaryPdfView?.synchronizedPDFView = self.listView
  2981. self.secondaryPdfView?.backgroundColor = self.listView.backgroundColor
  2982. // [secondaryPdfView applyDefaultPageBackgroundColor];
  2983. self.secondaryPdfView?.displaysPageBreaks = false
  2984. self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  2985. self.secondaryPdfView?.applyDefaultInterpolationQuality()
  2986. self.secondaryPdfView?.setGreekingThreshold(KMPreference.shared.greekThreshold.cgFloat)
  2987. self.secondaryPdfView?.setSynchronizeZoom(true)
  2988. // // [secondaryPdfView setDocument:[pdfView document]];
  2989. point = NSMakePoint(NSMinX(frame), NSMaxY(frame) - position.cgFloat - self.newPDFSplitView.dividerThickness)
  2990. page = self.listView.page(for: point, nearest: true)
  2991. //
  2992. let controlView = self.secondaryPdfView?.controlView
  2993. var color = NSColor(calibratedWhite: 0.97, alpha: 1.0)
  2994. if KMAppearance.isDarkMode() {
  2995. color = KMAppearance.Layout.l0Color()
  2996. }
  2997. // [(SKGradientView *)secondaryPdfContentView setGradient:[[[NSGradient alloc] initWithStartingColor:color endingColor:color] autorelease]];
  2998. // [(SKGradientView *)secondaryPdfContentView setAlternateGradient:nil];
  2999. var pdfRect: NSRect = .zero
  3000. var controlRect: NSRect = .zero
  3001. NSDivideRect(self.secondaryPdfContentView?.bounds ?? .zero, &controlRect, &pdfRect, NSHeight(controlView?.frame ?? .zero), .minY)
  3002. controlRect.size.width = NSWidth(controlView?.frame ?? .zero)
  3003. controlView?.frame = controlRect
  3004. controlView?.autoresizingMask = [.maxXMargin, .maxYMargin, .width]
  3005. // [(SKGradientView *)secondaryPdfContentView setMinSize:controlRect.size];
  3006. self.secondaryPdfView?.frame = pdfRect
  3007. self.secondaryPdfContentView?.addSubview(controlView!)
  3008. self.openSecondaryPdfView = KMSecondaryViewController()
  3009. self.openSecondaryPdfView?.view.frame = self.secondaryPdfContentView?.frame ?? .zero
  3010. self.secondaryPdfContentView?.addSubview(self.openSecondaryPdfView!.view)
  3011. self.openSecondaryPdfView?.secondaryView.receivedFileUrlBlock = { [weak self] fileUrl in
  3012. if let docUrl = fileUrl {
  3013. _ = self?.displaySecondaryPDFView(withUrl: docUrl)
  3014. self?.openSecondaryPdfView?.view.removeFromSuperview()
  3015. self?.openSecondaryPdfView = nil
  3016. }
  3017. }
  3018. self.openSecondaryPdfView?.delegate = self
  3019. if (!isHorizontal) {
  3020. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  3021. }
  3022. } else {
  3023. self.secondaryPdfContentView?.isHidden = true
  3024. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  3025. }
  3026. // self.newPDFSplitView.setPosition(self.secondaryPdfContentView?.bounds.size.width ?? 120, ofDividerAt: 1, animate: true)
  3027. if (page != nil) {
  3028. self.secondaryPdfView?.go(toPageIndex: Int(page!.pageIndex()), animated: false)
  3029. // point = [secondaryPdfView convertPoint:[secondaryPdfView convertPoint:[pdfView convertPoint:point toPage:page] fromPage:page] toView:[secondaryPdfView documentView]];
  3030. let tmpP = self.listView.convert(point, to: page)
  3031. let conP = self.secondaryPdfView?.convert(tmpP, from: page) ?? .zero
  3032. point = self.secondaryPdfView?.convert(conP, to: self.secondaryPdfView?.documentView()) ?? .zero
  3033. if let docView = self.secondaryPdfView?.documentView(), docView.contentView.isFlipped == false {
  3034. point.y -= docView.isFlipped ? -NSHeight(docView.visibleRect) : NSHeight(docView.visibleRect)
  3035. }
  3036. self.secondaryPdfView?.documentView()?.scroll(point)
  3037. self.secondaryPdfView?.layoutDocumentView()
  3038. }
  3039. }
  3040. self.view.window?.recalculateKeyViewLoop()
  3041. if self.interactionMode == .legacyFullScreen {
  3042. self.view.window?.makeFirstResponder(self.listView)
  3043. }
  3044. if self.secondaryPdfView?.document == nil {
  3045. self.openSecondaryPdfView?.viewHighlyAdaptive()
  3046. }
  3047. }
  3048. }
  3049. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  3050. if (self.newPDFSplitView.isVertical) {
  3051. return Float(NSWidth(rect))
  3052. } else {
  3053. return Float(NSHeight(rect))
  3054. }
  3055. }
  3056. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  3057. let document = CPDFDocument.init(url: url)
  3058. if document != nil {
  3059. self.secondaryPdfView?.document = nil
  3060. self.secondaryPdfView?.document = document
  3061. self.rightSideViewController.annotationProperties.openPropertiesType = .pageDisplay
  3062. return true
  3063. } else {
  3064. return false
  3065. }
  3066. }
  3067. func updateNextAndPreViousButtonState() {
  3068. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3069. let view = item?.customizeView as? KMToolbarPreviousNextItemView
  3070. if let can = self.listView?.canGoToPreviousPage() {
  3071. view?.previousButton.isEnabled = can
  3072. } else {
  3073. view?.previousButton.isEnabled = false
  3074. }
  3075. if let can = self.listView?.canGoToNextPage() {
  3076. view?.nextButton.isEnabled = can
  3077. } else {
  3078. view?.nextButton.isEnabled = false
  3079. }
  3080. }
  3081. func updateBackAndForwardButtonState() {
  3082. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3083. if self.listView.km_canGoForward() {
  3084. toItem?.unEnabled = false
  3085. } else {
  3086. toItem?.unEnabled = true
  3087. }
  3088. }
  3089. }
  3090. // MARK: -
  3091. // MARK: - KMSecondaryViewControllerDelegate
  3092. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  3093. func receivedFileUrl(_ url: URL!) {
  3094. let state = self.displaySecondaryPDFView(withUrl: url)
  3095. if !state {
  3096. let alert = NSAlert()
  3097. alert.alertStyle = .critical
  3098. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3099. alert.runModal()
  3100. return
  3101. } else {
  3102. self.openSecondaryPdfView?.view.removeFromSuperview()
  3103. self.openSecondaryPdfView = nil
  3104. }
  3105. }
  3106. func controllerDidClose(_ controller: KMSecondaryViewController!) {
  3107. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  3108. }
  3109. }
  3110. // MARK: -
  3111. // MARK: - KMMainToolbarControllerDelegate
  3112. extension KMMainViewController : KMMainToolbarControllerDelegate {
  3113. func changeModelAction(mode: CToolMode) {
  3114. self.listView.toolMode = mode
  3115. if mode == .editPDFToolMode {
  3116. self.childToolbarController.updateType(newType: .editPDF)
  3117. }
  3118. }
  3119. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  3120. switch selectedTag {
  3121. case 2:
  3122. if self.listView.scaleFactor != 1.0 {
  3123. self.listView.scaleFactor = 1.0
  3124. self.listView.autoScales = false
  3125. }
  3126. break
  3127. case 1:
  3128. let pageHeight = self.listView.currentPage()!.size.height
  3129. let pdfviewHeight = self.listView.bounds.size.height
  3130. self.listView.scaleFactor = pdfviewHeight/pageHeight
  3131. self.listView.autoScales = false
  3132. break
  3133. case 0:
  3134. // self.listView.autoScales = !self.listView.autoScales
  3135. self.listView.autoScales = true
  3136. break
  3137. case 3:
  3138. self.listView.scaleFactor = 0.1
  3139. break
  3140. case 4:
  3141. self.listView.scaleFactor = 0.25
  3142. break
  3143. case 5:
  3144. self.listView.scaleFactor = 0.5
  3145. break
  3146. case 6:
  3147. self.listView.scaleFactor = 0.75
  3148. break
  3149. case 7:
  3150. self.listView.scaleFactor = 1.0
  3151. break
  3152. case 8:
  3153. self.listView.scaleFactor = 1.5
  3154. break
  3155. case 9:
  3156. self.listView.scaleFactor = 2.0
  3157. break
  3158. case 10:
  3159. self.listView.scaleFactor = 4.0
  3160. break
  3161. case 11:
  3162. self.listView.scaleFactor = 8.0
  3163. break
  3164. case 12:
  3165. self.listView.scaleFactor = 16.0
  3166. break
  3167. case 13:
  3168. self.listView.scaleFactor = 32.0
  3169. break
  3170. case 14:
  3171. self.listView.scaleFactor = 64.0
  3172. break
  3173. case 15:
  3174. self.listView.scaleFactor = 100.0
  3175. break
  3176. default:
  3177. break
  3178. }
  3179. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3180. }
  3181. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  3182. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3183. if scale > 100 {
  3184. scale = 100
  3185. }
  3186. if (scale <= 0.101) {
  3187. self.listView.scaleFactor = self.listView.minScaleFactor()
  3188. } else {
  3189. self.listView.scaleFactor = scale
  3190. }
  3191. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3192. }
  3193. func changePDFViewZoomInAction() {
  3194. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3195. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3196. switch scale {
  3197. case 0...0.25:
  3198. scale += 0.25
  3199. case 0.25...3:
  3200. scale += 0.25
  3201. case 3.1...10:
  3202. scale += 0.4
  3203. case 10.1...100:
  3204. scale += 1
  3205. default:
  3206. scale += 1
  3207. }
  3208. self.listView.scaleFactor = scale
  3209. // nearbyint
  3210. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3211. // self.listView.zoomIn(nil)
  3212. if self.digitalSignController?.pdfView != nil {
  3213. self.digitalSignController?.pdfView.scaleFactor = scale
  3214. }
  3215. if self.redactController?.redactPdfView != nil {
  3216. self.redactController?.redactPdfView.scaleFactor = scale
  3217. }
  3218. }
  3219. func changePDFViewZoomOutAction() {
  3220. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3221. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3222. switch scale {
  3223. case 0...0.25:
  3224. scale = 0
  3225. case 0.25...3:
  3226. scale -= 0.25
  3227. case 3.1...10:
  3228. scale -= 0.4
  3229. case 10.1...100:
  3230. scale -= 1
  3231. default:
  3232. scale -= 1
  3233. }
  3234. self.listView.scaleFactor = scale
  3235. // nearbyint
  3236. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3237. // self.listView.zoomOut(nil)
  3238. if self.digitalSignController?.pdfView != nil {
  3239. self.digitalSignController?.pdfView.scaleFactor = scale
  3240. }
  3241. if self.redactController?.redactPdfView != nil {
  3242. self.redactController?.redactPdfView.scaleFactor = scale
  3243. }
  3244. self.savePageNumberIfNeed()
  3245. }
  3246. func changePDFViewGotoNextPageAction() {
  3247. self.listView.km_goBack(nil)
  3248. if (self.listView.canGoToNextPage()) {
  3249. self.listView.goToNextPage(nil)
  3250. }
  3251. self.updateNextAndPreViousButtonState()
  3252. }
  3253. func changePDFViewGoToPreviousPageAction() {
  3254. if (self.listView.canGoToPreviousPage()) {
  3255. self.listView.goToPreviousPage(nil)
  3256. }
  3257. self.updateNextAndPreViousButtonState()
  3258. }
  3259. func changePDFViewGotoBackAction() {
  3260. self.listView.km_goBack(nil)
  3261. self.updateBackAndForwardButtonState()
  3262. }
  3263. func changePDFViewGoToForwardAction() {
  3264. self.listView.km_goForward(nil)
  3265. self.updateBackAndForwardButtonState()
  3266. }
  3267. func aiTranslationPDFFileAction() {
  3268. #if VERSION_DMG
  3269. #else
  3270. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  3271. KMLoginWindowController.show(window: NSApp.mainWindow!)
  3272. return
  3273. }
  3274. #endif
  3275. self.trackEvent_aiTranslate()
  3276. self._aiTranslationPDFFileAction()
  3277. }
  3278. private func _aiTranslationPDFFileAction() {
  3279. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  3280. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  3281. let alert = NSAlert()
  3282. alert.alertStyle = .critical
  3283. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  3284. alert.runModal()
  3285. return
  3286. } else if isExceedsLimit {
  3287. let alert = NSAlert()
  3288. alert.alertStyle = .critical
  3289. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  3290. alert.runModal()
  3291. return
  3292. }
  3293. let alert = NSAlert()
  3294. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  3295. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  3296. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3297. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  3298. if (result == .alertFirstButtonReturn) {
  3299. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  3300. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  3301. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  3302. } else if result == .alertSecondButtonReturn {
  3303. return
  3304. }
  3305. }
  3306. }
  3307. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  3308. self.trackEvent_share()
  3309. }
  3310. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  3311. self.shareDocument(sender: viewController)
  3312. }
  3313. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  3314. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3315. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3316. return
  3317. }
  3318. self.shareFlatten(sender: viewController)
  3319. }
  3320. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  3321. self.shareOriginalPDF(sender: viewController)
  3322. }
  3323. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  3324. if(0 == selectedTag) {
  3325. // self.documentAIViewController?.enteredIncreaseAllPage()
  3326. // self.documentAIViewController?.updateToolState(false)
  3327. } else {
  3328. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  3329. // self.documentAIViewController?.recognitionPartModel(with: .english)
  3330. // self.documentAIViewController?.updateToolState(true)
  3331. }
  3332. // 0 : Scan 1:OCR Text
  3333. }
  3334. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  3335. if beforeType == .editPDF {
  3336. self.editPDFHanddler.enterEditPDF()
  3337. }
  3338. if(type != .Page) {
  3339. if (hasEnterPageEdit()) {
  3340. self.exitPageEdit()
  3341. }
  3342. }
  3343. if type != .redact {
  3344. if self.hasEnterRedact() {
  3345. self.exitRedact()
  3346. }
  3347. }
  3348. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  3349. if self.hasShowDigitalSign() {
  3350. self.exitDigitalSign()
  3351. }
  3352. }
  3353. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  3354. self.toolbarController.findItem(KMDocumentViewDisplayToolbarItemIdentifier)?.isSelected = false
  3355. }
  3356. if(type != .Form) {
  3357. self.removeFromAlertView()
  3358. }
  3359. if (type == .Page) {
  3360. if (hasEnterPageEdit()) {
  3361. self.exitPageEdit()
  3362. } else {
  3363. self.enterPageEdit(pages)
  3364. }
  3365. } else if type == .editPDF {
  3366. self.enterEditPDF()
  3367. } else if type == .Annatiton {
  3368. self.rightSideViewController.subViewType = .AnnotationProperts
  3369. } else if type == .redact {
  3370. if self.needSaveDocument() {
  3371. self.saveDocumentWithProgressAlert { [unowned self] params in
  3372. self.enterRedact()
  3373. }
  3374. return
  3375. }
  3376. self.enterRedact()
  3377. } else if type == .Tool {
  3378. if KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  3379. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  3380. } else if KMGuideInfoWindowController.availableShow(.measureGuide) {
  3381. self.loadOpenFileFunctionGuide(.measureGuide)
  3382. }
  3383. } else if type == . Conversion {
  3384. self.loadOpenFileFunctionGuide(.convertGuide)
  3385. }else if type == .Form {
  3386. self.showFormAlertView()
  3387. }else if type == .Select {
  3388. self.rightSideViewController.isHidden = true
  3389. self.closeRightPane()
  3390. }
  3391. }
  3392. func clickChildTool(type: KMToolbarType, index: Int) {
  3393. if (type == .secure) {
  3394. if (index == 1) {
  3395. self.trackEvent_setPassword()
  3396. } else if (index == 2) {
  3397. self.trackEvent_removePassword()
  3398. }
  3399. } else {
  3400. self.trackEvent(toolBarType: type)
  3401. }
  3402. Task { @MainActor in
  3403. if (type == .compress) { /// 压缩
  3404. if !self.documentAllowsEdit() {
  3405. return
  3406. }
  3407. if (self.needSaveDocument()) {
  3408. self.saveDocumentWithProgressAlert { [unowned self] params in
  3409. self.showCompressWindow()
  3410. }
  3411. return
  3412. }
  3413. self.showCompressWindow()
  3414. return
  3415. }
  3416. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  3417. var identifier: String?
  3418. if (type == .word) { /// Word
  3419. identifier = KMToolbarConversionWordItemIdentifier
  3420. } else if (type == .excel) {
  3421. identifier = KMToolbarConversionExcelItemIdentifier
  3422. } else if (type == .ppt) {
  3423. identifier = KMToolbarConversionPPTItemIdentifier
  3424. } else if (type == .rtf) {
  3425. identifier = KMToolbarConversionRTFItemIdentifier
  3426. } else if (type == .html) {
  3427. identifier = KMToolbarConversionHTMLItemIdentifier
  3428. } else if (type == .conversion_text) {
  3429. identifier = KMToolbarConversionTextItemIdentifier
  3430. } else if (type == .csv) {
  3431. identifier = KMToolbarConversionCSVItemIdentifier
  3432. } else if (type == .conversion_image) {
  3433. identifier = KMToolbarConversionImageItemIdentifier
  3434. }
  3435. if (self.needSaveDocument()) {
  3436. self.saveDocumentWithProgressAlert { [unowned self] params in
  3437. self.showConvertWindow(type: type, identifier: identifier)
  3438. }
  3439. return
  3440. }
  3441. self.showConvertWindow(type: type, identifier: identifier)
  3442. return
  3443. }
  3444. if (type == .merge) { /// 合并
  3445. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  3446. if !self.documentAllowsEdit() {
  3447. return
  3448. }
  3449. if (self.needSaveDocument()) {
  3450. self.saveDocumentWithProgressAlert { [unowned self] params in
  3451. self.showMergeWindow(self.listView.document.password)
  3452. }
  3453. return
  3454. }
  3455. self.showMergeWindow(self.listView.document.password)
  3456. return
  3457. }
  3458. if (type == .bates || type == .headerAndFooter) {
  3459. if !IAPProductsManager.default().isAvailableAllFunction(){
  3460. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3461. return
  3462. }
  3463. if !self.documentAllowsEdit() {
  3464. return
  3465. }
  3466. if (index == 1) {
  3467. var windowController: KMBaseWindowController = KMBaseWindowController()
  3468. if (type == .bates) {
  3469. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3470. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3471. let fpath = self.document?.documentURL?.path ?? ""
  3472. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3473. }
  3474. windowController.isBates = true
  3475. } else if (type == .headerAndFooter) {
  3476. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3477. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3478. let fpath = self.document?.documentURL?.path ?? ""
  3479. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3480. }
  3481. } else if (type == .background) {
  3482. } else if (type == .watermark) {
  3483. // controller = KMWatermarkViewController()
  3484. }
  3485. windowController.pdfDocument = self.listView.document
  3486. windowController.cancelAction = { [unowned self] controller in
  3487. self.view.window?.endSheet((self.currentWindowController.window)!)
  3488. self.currentWindowController = nil
  3489. }
  3490. self.currentWindowController = windowController
  3491. await self.view.window?.beginSheet(windowController.window!)
  3492. return
  3493. }
  3494. if (index == 1) { /// 取消
  3495. self.toolbarController.exitWatermarkAdjective()
  3496. // self.rightSideViewController.view.isHidden = true
  3497. self.rightSideViewController.isHidden = true
  3498. self.rightSideViewController.subViewType = .None
  3499. self.closeRightPane()
  3500. return
  3501. } else if index == 3 {
  3502. let fpath = self.document?.documentURL?.path ?? ""
  3503. if type == .bates {
  3504. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3505. } else {
  3506. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3507. }
  3508. } else if index == 4 {
  3509. let fpath = self.document?.documentURL?.path ?? ""
  3510. if type == .bates {
  3511. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  3512. } else {
  3513. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  3514. }
  3515. } else if (index == 2) { //// 移除
  3516. if type == .headerAndFooter {
  3517. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3518. let savePanel = NSSavePanel()
  3519. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3520. savePanel.allowedFileTypes = ["pdf"]
  3521. savePanel.accessoryView = savePanelAccessoryViewController.view
  3522. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3523. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3524. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3525. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3526. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3527. }
  3528. } else {
  3529. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3530. }
  3531. }
  3532. }
  3533. }
  3534. } else if type == .bates {
  3535. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3536. let savePanel = NSSavePanel()
  3537. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3538. savePanel.allowedFileTypes = ["pdf"]
  3539. savePanel.accessoryView = savePanelAccessoryViewController.view
  3540. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3541. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3542. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3543. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3544. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3545. }
  3546. } else {
  3547. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3548. }
  3549. }
  3550. }
  3551. }
  3552. }
  3553. return
  3554. } else if (index == 2) { /// 应用
  3555. let model = self.rightSideViewController.model
  3556. if (type == .bates || type == .headerAndFooter) {
  3557. if (model == nil || (model?.isKind(of: KMHeaderFooterObject.self) == false)) {
  3558. let alert = NSAlert()
  3559. alert.alertStyle = .critical
  3560. alert.messageText = "没有找到模型"
  3561. alert.runModal()
  3562. return
  3563. }
  3564. if ((model as! KMHeaderFooterObject).hasVaild == false) {
  3565. let alert = NSAlert()
  3566. alert.alertStyle = .critical
  3567. alert.messageText = "没有找到内容"
  3568. alert.runModal()
  3569. return
  3570. }
  3571. }
  3572. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  3573. result in
  3574. DispatchQueue.main.async {
  3575. self.listView.layoutDocumentView()
  3576. self.listView.setNeedsDisplayForVisiblePages()
  3577. }
  3578. if (result) {
  3579. let alert = NSAlert()
  3580. alert.alertStyle = .warning
  3581. alert.messageText = "成功"
  3582. alert.runModal()
  3583. } else {
  3584. let alert = NSAlert()
  3585. alert.alertStyle = .critical
  3586. alert.messageText = "失败"
  3587. alert.runModal()
  3588. }
  3589. }
  3590. return
  3591. } else if index == 5 {
  3592. self.rightSideViewController.isHidden = false
  3593. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3594. self.openRightPane()
  3595. }
  3596. } else if (type == .redact) { /// 标记密文
  3597. if !IAPProductsManager.default().isAvailableAllFunction(){
  3598. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3599. return
  3600. }
  3601. if (index == 1) { /// 取消
  3602. if (self.model.hasAddRedact) {
  3603. let alert = NSAlert()
  3604. 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: "")
  3605. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  3606. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3607. let result = alert.runModal()
  3608. if (result == .alertFirstButtonReturn) {
  3609. self.listView.toolMode = .moveToolMode
  3610. self.toolbarController.exitRedact()
  3611. }
  3612. return
  3613. }
  3614. self.listView.toolMode = .moveToolMode
  3615. self.toolbarController.exitRedact()
  3616. return
  3617. }
  3618. if (index == 2) { /// 擦除
  3619. self.exeRedactConfirm(.eraserAll) {}
  3620. return
  3621. }
  3622. if (index == 3) { /// 应用
  3623. self.exeRedactConfirm(.redactAll) {}
  3624. return
  3625. }
  3626. if (index == 4) { /// 文本&图像
  3627. self.listView.toolMode = .redactToolMode
  3628. return
  3629. }
  3630. if (index == 5) { /// 页面
  3631. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3632. await self.view.window?.beginSheet(windowController.window!)
  3633. self.currentWindowController = windowController
  3634. windowController.itemClick = { [weak self] index, value in
  3635. if (index == 1) {
  3636. let topBarView = self?.toolbarController.fetchTopBarView()
  3637. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3638. return
  3639. }
  3640. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3641. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3642. self?.currentWindowController = nil
  3643. return
  3644. }
  3645. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3646. let pageType = windowController_pageRange.pageType
  3647. let pageString = windowController_pageRange.pageString
  3648. if (pageType == 5) { /// 自定义页面
  3649. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  3650. if (array.count == 0) {
  3651. let alert = NSAlert()
  3652. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3653. alert.runModal()
  3654. return
  3655. }
  3656. }
  3657. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3658. self!.currentWindowController = nil
  3659. var indexs: IndexSet = []
  3660. if (pageType == 1) { /// 当前页面
  3661. indexs.insert((self?.listView.currentPageIndex)!)
  3662. } else {
  3663. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  3664. }
  3665. if (indexs.count == 0) {
  3666. return
  3667. }
  3668. for i in indexs {
  3669. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3670. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3671. redactAnno.bounds = page.bounds
  3672. self?.listView.add(redactAnno, to: page)
  3673. }
  3674. }
  3675. return
  3676. }
  3677. } else if (type == .secure) { /// 安全
  3678. if (index == 1) { /// 设置密码
  3679. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3680. if !self.documentAllowsEdit() {
  3681. return
  3682. }
  3683. // KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3684. // if (result == .cancel) {
  3685. // return
  3686. // }
  3687. //
  3688. // self?.isSaveKeyChain = false
  3689. // self?.listView.document.unlock(withPassword: password)
  3690. // self?.hiddenSecureLimitTip()
  3691. //
  3692. // self?.showSecureWindow((self?.listView.document.documentURL)!)
  3693. // }
  3694. // return
  3695. }
  3696. self.showSecureWindow(self.listView.document.documentURL)
  3697. return
  3698. } else if index == 2 {
  3699. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3700. let alert = NSAlert()
  3701. alert.alertStyle = .warning
  3702. alert.messageText = NSLocalizedString("Warning", comment: "")
  3703. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3704. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3705. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3706. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3707. if returnCode == .alertSecondButtonReturn {
  3708. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3709. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3710. if success {
  3711. self.document?.unlock(withPassword: resultPassword)
  3712. self.clickChildTool(type: .secure, index: 2)
  3713. }
  3714. }
  3715. }
  3716. }
  3717. }
  3718. } else {
  3719. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3720. controller.pdfDocument = self.document
  3721. self.currentWindowController = controller
  3722. controller.batchAction = { [unowned self] controller, files in
  3723. self.view.window?.endSheet((self.currentWindowController.window)!)
  3724. self.currentWindowController = nil
  3725. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3726. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3727. if #available(macOS 10.13, *) {
  3728. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3729. } else {
  3730. baseWindowController.showWindow(nil)
  3731. }
  3732. let arr = NSMutableArray()
  3733. let file = KMBatchOperateFile(filePath: self.listView!.document!.documentURL!.path, type: .RemovePassword)
  3734. file.password = document?.password ?? ""
  3735. arr.add(file)
  3736. // baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .RemovePassword, files: arr as! [KMBatchOperateFile])
  3737. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  3738. }
  3739. controller.cancelAction = { [unowned self] controller in
  3740. self.view.window?.endSheet((self.currentWindowController.window)!)
  3741. self.currentWindowController = nil
  3742. }
  3743. controller.doneAction = { [unowned self] controller in
  3744. self.view.window?.endSheet((self.currentWindowController.window)!)
  3745. self.currentWindowController = nil
  3746. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  3747. if success {
  3748. // let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3749. let savePanel = NSSavePanel()
  3750. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3751. savePanel.allowedFileTypes = ["pdf"]
  3752. // savePanel.accessoryView = savePanelAccessoryViewController.view
  3753. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3754. guard result == .OK else { return }
  3755. /// 删除安全性设置
  3756. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3757. self.model.isSaveKeyChain = false
  3758. self.listView.document.unlock(withPassword: resultPassword)
  3759. }
  3760. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3761. guard let document = document else { return }
  3762. document.unlock(withPassword: resultPassword)
  3763. let success = document.writeDecrypt(to: savePanel.url)
  3764. if success {
  3765. self.hiddenSecureLimitTip()
  3766. let tip = KMRemovePasswordResultTipView()
  3767. tip.result = .success
  3768. tip.showInView(superView: (self.listView.superview)!)
  3769. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3770. } else {
  3771. self.hiddenSecureLimitTip()
  3772. let tip = KMRemovePasswordResultTipView()
  3773. tip.result = .failure
  3774. tip.showInView(superView: (self.listView.superview)!)
  3775. }
  3776. }
  3777. }
  3778. }
  3779. }
  3780. await NSWindow.currentWindow().beginSheet(controller.window!)
  3781. }
  3782. return
  3783. }
  3784. } else if type == .comparison {
  3785. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3786. if !IAPProductsManager.default().isAvailableAllFunction(){
  3787. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3788. return
  3789. }
  3790. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3791. self.currentWindowController = controller
  3792. controller.password = self.document?.password ?? ""
  3793. controller.filePath = (self.document?.documentURL.path)!
  3794. controller.cancelAction = { [unowned self] controller in
  3795. self.view.window?.endSheet((self.currentWindowController.window)!)
  3796. self.currentWindowController = nil
  3797. }
  3798. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3799. self.view.window?.endSheet((self.currentWindowController.window)!)
  3800. self.currentWindowController = nil
  3801. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3802. }
  3803. controller.coveringComplete = { [unowned self] controller, document in
  3804. self.view.window?.endSheet((self.currentWindowController.window)!)
  3805. self.currentWindowController = nil
  3806. self.openCoveringCompareVC(with: document)
  3807. }
  3808. if index == 1 {
  3809. controller.fileType = .content
  3810. } else {
  3811. controller.fileType = .coverting
  3812. }
  3813. await NSWindow.currentWindow().beginSheet(controller.window!)
  3814. } else if type == .watermark {
  3815. if !IAPProductsManager.default().isAvailableAllFunction(){
  3816. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3817. return
  3818. }
  3819. if !self.documentAllowsEdit() {
  3820. return
  3821. }
  3822. if index == 1 {
  3823. self.watermarkWindowController = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  3824. self.watermarkWindowController!.pdfDocument = self.document
  3825. self.watermarkWindowController!.cancelAction = { [unowned self] controller in
  3826. // self.view.window?.endSheet((self.watermarkWindowController!.window)!)
  3827. self.km_endSheet()
  3828. }
  3829. self.watermarkWindowController!.operateCallBack = { [unowned self] controller, watermark, countType in
  3830. // self.view.window?.endSheet((self.watermarkWindowController!.window)!)
  3831. self.km_endSheet()
  3832. let fpath = self.document?.documentURL?.path ?? ""
  3833. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  3834. }
  3835. // NSWindow.currentWindow().beginSheet(controller.window!)
  3836. // NSWindow.currentWindow().beginSheet(self.watermarkWindowController!.window!, completionHandler: nil)
  3837. self.km_beginSheet(windowC: self.watermarkWindowController!)
  3838. } else if index == 2 {
  3839. let watermarks = self.listView.document.watermarks()
  3840. if (watermarks == nil || watermarks!.count <= 0) {
  3841. let alert = NSAlert()
  3842. alert.alertStyle = .warning
  3843. 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: "")
  3844. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  3845. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3846. alert.runModal()
  3847. return
  3848. }
  3849. let alert = NSAlert()
  3850. alert.alertStyle = .warning
  3851. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  3852. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  3853. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3854. let result = alert.runModal()
  3855. if (result != .alertFirstButtonReturn) {
  3856. return
  3857. }
  3858. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3859. let savePanel = NSSavePanel()
  3860. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  3861. savePanel.allowedFileTypes = ["pdf"]
  3862. savePanel.accessoryView = savePanelAccessoryViewController.view
  3863. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3864. guard result == .OK else { return }
  3865. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3866. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  3867. result in
  3868. DispatchQueue.main.async {
  3869. self.listView.layoutDocumentView()
  3870. self.listView.setNeedsDisplayForVisiblePages()
  3871. }
  3872. if (result) {
  3873. let alert = NSAlert()
  3874. alert.alertStyle = .warning
  3875. alert.messageText = "成功"
  3876. alert.runModal()
  3877. } else {
  3878. let alert = NSAlert()
  3879. alert.alertStyle = .critical
  3880. alert.messageText = "失败"
  3881. alert.runModal()
  3882. }
  3883. }
  3884. }
  3885. } else if index == 3 {
  3886. let fpath = self.document?.documentURL?.path ?? ""
  3887. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  3888. } else if index == 4 {
  3889. let fpath = self.document?.documentURL?.path ?? ""
  3890. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  3891. } else if index == 5 {
  3892. self.rightSideViewController.isHidden = false
  3893. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3894. self.openRightPane()
  3895. return
  3896. }
  3897. } else if type == .background {
  3898. if !IAPProductsManager.default().isAvailableAllFunction(){
  3899. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3900. return
  3901. }
  3902. if !self.documentAllowsEdit() {
  3903. return
  3904. }
  3905. if index == 1 {
  3906. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  3907. self.currentWindowController = controller
  3908. controller.pdfDocument = self.document
  3909. controller.cancelAction = { [unowned self] controller in
  3910. self.view.window?.endSheet((self.currentWindowController.window)!)
  3911. self.currentWindowController = nil
  3912. }
  3913. controller.operateCallBack = { [unowned self] controller, background, countType in
  3914. let fpath = self.document?.documentURL?.path ?? ""
  3915. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  3916. }
  3917. await NSWindow.currentWindow().beginSheet(controller.window!)
  3918. } else if index == 2 {
  3919. guard let document = self.document else { return }
  3920. if !document.allowsPrinting || !document.allowsCopying {
  3921. let alert = NSAlert()
  3922. alert.alertStyle = .critical
  3923. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3924. alert.runModal()
  3925. return
  3926. }
  3927. guard let documentURL = document.documentURL else { return }
  3928. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3929. let savePanel = NSSavePanel()
  3930. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  3931. savePanel.allowedFileTypes = ["pdf"]
  3932. savePanel.accessoryView = savePanelAccessoryViewController.view
  3933. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3934. guard result == .OK else { return }
  3935. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  3936. if success == 1 {
  3937. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3938. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  3939. } else {
  3940. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  3941. }
  3942. }
  3943. })
  3944. }
  3945. } else if index == 3 {
  3946. let fpath = self.document?.documentURL?.path ?? ""
  3947. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  3948. } else if index == 4 {
  3949. let fpath = self.document?.documentURL?.path ?? ""
  3950. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  3951. } else if index == 5 {
  3952. self.rightSideViewController.isHidden = false
  3953. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3954. self.openRightPane()
  3955. return
  3956. }
  3957. } else if type == .measure {
  3958. if !IAPProductsManager.default().isAvailableAllFunction(){
  3959. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3960. return
  3961. }
  3962. if !self.documentAllowsEdit() {
  3963. return
  3964. }
  3965. self.listView.toolMode = .measureToolMode
  3966. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  3967. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3968. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  3969. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3970. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  3971. areaMeasureInfoWindowController?.hideFloatingWindow()
  3972. }
  3973. if distanceMeasureInfoWindowController == nil {
  3974. let measureInfo = CPDFDistanceMeasureInfo()
  3975. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  3976. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  3977. distanceMeasureInfoWindowController?.delegate = self
  3978. }
  3979. if perimeterMeasureInfoWindowController == nil {
  3980. let measureInfo = CPDFPerimeterMeasureInfo()
  3981. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  3982. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  3983. perimeterMeasureInfoWindowController?.delegate = self
  3984. }
  3985. if areaMeasureInfoWindowController == nil {
  3986. let measureInfo = CPDFAreaMeasureInfo()
  3987. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  3988. areaMeasureInfoWindowController?.measureInfo = measureInfo
  3989. areaMeasureInfoWindowController?.delegate = self
  3990. }
  3991. if index == 1 {
  3992. self.listView.annotationType = .line
  3993. let winW: CGFloat = 300
  3994. let rightW: CGFloat = 270
  3995. var winFrame = self.view.window?.frame ?? .zero
  3996. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  3997. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  3998. distanceMeasureInfoWindowController?.showWindow(nil)
  3999. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4000. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4001. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4002. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4003. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4004. } else if index == 2 {
  4005. self.listView.annotationType = .polyLine
  4006. let winW: CGFloat = 300
  4007. let rightW: CGFloat = 270
  4008. var winFrame = self.view.window?.frame ?? .zero
  4009. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4010. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4011. perimeterMeasureInfoWindowController?.showWindow(nil)
  4012. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4013. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4014. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4015. } else if index == 3 {
  4016. self.listView.annotationType = .polyGon
  4017. let winW: CGFloat = 300
  4018. let rightW: CGFloat = 270
  4019. var winFrame = self.view.window?.frame ?? .zero
  4020. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4021. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4022. areaMeasureInfoWindowController?.showWindow(nil)
  4023. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4024. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4025. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4026. } else if index == 4 {
  4027. self.listView.annotationType = .square
  4028. let winW: CGFloat = 300
  4029. let rightW: CGFloat = 270
  4030. var winFrame = self.view.window?.frame ?? .zero
  4031. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4032. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4033. areaMeasureInfoWindowController?.showWindow(nil)
  4034. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4035. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4036. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4037. } else {
  4038. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  4039. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4040. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  4041. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4042. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  4043. areaMeasureInfoWindowController?.hideFloatingWindow()
  4044. }
  4045. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = false
  4046. }
  4047. self.rightSideViewController.reloadDataWithPDFView(pdfView: listView, isShow: true)
  4048. self.openRightPane()
  4049. }
  4050. }
  4051. }
  4052. // func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  4053. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4054. //// batchWindowController.window?.makeKeyAndOrderFront("")
  4055. //
  4056. // var array: [KMBatchOperateFile] = []
  4057. // for file in files ?? [] {
  4058. // let batchOperateFile = KMBatchOperateFile(filePath: file.filePath, type: type)
  4059. // array.append(batchOperateFile)
  4060. // }
  4061. // batchWindowController.switchToOperateType(type, files: array)
  4062. // batchWindowController.window?.makeKeyAndOrderFront("")
  4063. // }
  4064. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  4065. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4066. var array: [KMBatchOperateFile] = []
  4067. for fpath in filepaths ?? [] {
  4068. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  4069. array.append(batchOperateFile)
  4070. }
  4071. batchWindowController.switchToOperateType(type, files: array)
  4072. batchWindowController.window?.makeKeyAndOrderFront("")
  4073. }
  4074. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  4075. self.toolbarItemClickForExitMode(toolbarItem)
  4076. if let itemID = toolbarItem.itemIdentifier {
  4077. if isMainToolItem(itemID) {
  4078. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  4079. openNewWindowAlertWindow()
  4080. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  4081. self.changePDFViewGoToPreviousPageAction()
  4082. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4083. let isSelected = toolbarItem.isSelected
  4084. self.toolbarController.toolbarType = isSelected ? .None : .viewSetting
  4085. toolbarItem.isSelected = !isSelected
  4086. if toolbarItem.isSelected {
  4087. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  4088. self.rightSideViewController.isHidden = false
  4089. self.rightSideViewController.mainController = self
  4090. self.rightSideViewController.subViewType = .ViewSettings
  4091. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4092. self.openRightPane()
  4093. }else{
  4094. self.rightSideViewController.isHidden = true
  4095. self.rightSideViewController.subViewType = .AnnotationProperts
  4096. closeRightPane()
  4097. }
  4098. if toolbarItem.isSelected {
  4099. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  4100. }
  4101. let rightItem = self.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  4102. if isSelected {
  4103. rightItem?.isSelected = false
  4104. } else {
  4105. rightItem?.isSelected = true
  4106. }
  4107. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  4108. toolbarItem.isSelected = !toolbarItem.isSelected
  4109. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  4110. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4111. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  4112. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  4113. }
  4114. toolbarItem.isSelected = !toolbarItem.isSelected
  4115. self.toggleRightPane()
  4116. if self.listView.toolMode == .editPDFToolMode {
  4117. self.editPDFHanddler.rightSideLastState = toolbarItem.isSelected ? .open : .close
  4118. }
  4119. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  4120. self.listView.toolMode = .redactToolMode
  4121. self.enterRedact()
  4122. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  4123. showOCRWindow()
  4124. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  4125. self.showAITypeChooseView(aiConfigType: .none)
  4126. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  4127. if self.canEnterDigitalSign() == false {
  4128. Task {
  4129. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4130. }
  4131. return
  4132. }
  4133. toolbarItem.isSelected = !toolbarItem.isSelected
  4134. self.toolbarController.lastItemBox = toolbarItem
  4135. if toolbarItem.isSelected {
  4136. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4137. }
  4138. self.enterDigitalSign()
  4139. } else if itemID == KMDocumentPrintToolbarItemIdentifier {
  4140. self.showPrintWindow()
  4141. } else if itemID == KMDocumentPresentationToolbarItemIdentifier {
  4142. self.enterPresentation()
  4143. } else if itemID == KMDocumentSignToolbarItemIdentifier {
  4144. let isSelected = toolbarItem.isSelected
  4145. self.toolbarController.toolbarType = isSelected ? .None : .sign
  4146. toolbarItem.isSelected = !isSelected
  4147. self.toolbarController.lastItemBox = toolbarItem
  4148. }
  4149. } else {
  4150. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  4151. let windowC = KMToolbarCustomWindowController()
  4152. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  4153. windowC.resetCallback = { [weak self] in
  4154. let toolbar = self?.toolbarController.childToolBarView?.toolbar
  4155. toolbar?.reloadData()
  4156. }
  4157. self.km_beginSheet(windowC: windowC) { [weak self] resp, obj in
  4158. if resp == .OK {
  4159. let toolbar = self?.toolbarController.childToolBarView?.toolbar
  4160. toolbar?.reloadData()
  4161. }
  4162. }
  4163. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  4164. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  4165. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  4166. self.trackEvent_print()
  4167. self.showPrintWindow()
  4168. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  4169. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  4170. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  4171. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  4172. windowC.callBack = { [weak self] string in
  4173. if (string.isEmpty == false) {
  4174. self?.listView.addTextField(subType: .profile, string: string)
  4175. }
  4176. self?.km_endSheet()
  4177. }
  4178. self.km_beginSheet(windowC: windowC)
  4179. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  4180. toolbarItem.isSelected = !toolbarItem.isSelected
  4181. rightSideViewController.mainController = self
  4182. self.rightSideViewController.isHidden = toolbarItem.isSelected ? false : true
  4183. self.rightSideViewController.subViewType = .ViewSettings
  4184. // self.toggleRightPane()
  4185. self.listView.annotationType = .unkown
  4186. if toolbarItem.isSelected {
  4187. self.rightSideViewController.isHidden = false
  4188. self.rightSideViewController.mainController = self
  4189. self.rightSideViewController.subViewType = .ViewSettings
  4190. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4191. self.openRightPane()
  4192. }else{
  4193. self.rightSideViewController.isHidden = true
  4194. self.rightSideViewController.subViewType = .AnnotationProperts
  4195. closeRightPane()
  4196. }
  4197. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  4198. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  4199. self.listView.takeSnapshot(nil)
  4200. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  4201. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  4202. self.listView.annotationType = .unkown
  4203. self.showTTSWindow()
  4204. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4205. self.showOCRWindow()
  4206. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  4207. toolbarItem.isSelected = false
  4208. self.imageAnnotation(toolbarItem)
  4209. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  4210. self.tableAnnotation(toolbarItem)
  4211. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  4212. self.leftSideViewController.insertPDF(nil)
  4213. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  4214. let windowC = SplitWindowController(document: self.listView.document)
  4215. self.km_beginSheet(windowC: windowC)
  4216. } else if itemID == KMSignDigitalSignToolbarItemIdentifier {
  4217. if self.canEnterDigitalSign() == false {
  4218. Task {
  4219. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4220. }
  4221. return
  4222. }
  4223. toolbarItem.isSelected = !toolbarItem.isSelected
  4224. self.toolbarController.lastItemBox = toolbarItem
  4225. if toolbarItem.isSelected {
  4226. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4227. }
  4228. self.enterDigitalSign()
  4229. } else if itemID == KMToolbarMeasureItemIdentifier {
  4230. if toolbarItem.isSelected {
  4231. toolbarItem.isSelected = false
  4232. self.listView.toolMode = .textToolMode
  4233. self.listView.annotationType = .unkown
  4234. }
  4235. }
  4236. }
  4237. }
  4238. }
  4239. func openNewWindowAlertWindow() {
  4240. var needShowChooseWindow = false
  4241. //#if VERSION_FREE
  4242. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  4243. needShowChooseWindow = true
  4244. }
  4245. //#endif
  4246. if needShowChooseWindow {
  4247. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  4248. if preferenceNoteShow {
  4249. menuItemAction_newTagPageToNewWindow("")
  4250. } else {
  4251. if !KMDataManager.default.isTabbingWin{
  4252. KMDataManager.default.isTabbingWin = true
  4253. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  4254. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  4255. KMDataManager.default.isTabbingWin = false
  4256. if continueOrNot {
  4257. self?.reopenDocument(forPaths: [])
  4258. } else {
  4259. }
  4260. }
  4261. self.km_beginSheet(windowC: tabbingWin)
  4262. }
  4263. }
  4264. }else{
  4265. handleTabbingLogic()
  4266. }
  4267. }
  4268. func reopenDocument(forPaths paths: [String]) -> Void {
  4269. let browser = KMBrowser.init() as KMBrowser
  4270. browser.windowController = KMBrowserWindowController.init(browser: browser)
  4271. browser.addHomeTabContents()
  4272. browser.windowController.showWindow(self)
  4273. }
  4274. func handleTabbingLogic() {
  4275. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  4276. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  4277. }
  4278. func showTTSWindow() {
  4279. var lastPDFView: CPDFView?
  4280. let ttsView = KMTTSWindowController.share
  4281. if (ttsView.window?.isVisible ?? false) {
  4282. lastPDFView = ttsView.pdfView
  4283. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  4284. lastPDFView = nil
  4285. ttsView.window?.orderOut(nil)
  4286. } else {
  4287. ttsView.pdfView = self.listView
  4288. ttsView.showWindow(nil)
  4289. }
  4290. } else {
  4291. ttsView.pdfView = self.listView
  4292. ttsView.showWindow(nil)
  4293. }
  4294. // weak var blockSelf = self
  4295. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  4296. if isCloseWindow {
  4297. // for item in blockSelf?.toolbar.items ?? [] {
  4298. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  4299. // item.isSelected = false
  4300. // }
  4301. // }
  4302. }
  4303. }
  4304. if let currentSelection = self.listView.currentSelection {
  4305. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  4306. ttsView.startSpeakingPDFSelection(currentSelection)
  4307. }
  4308. }
  4309. if let lastPDFView = lastPDFView {
  4310. lastPDFView.setHighlightedSelections([])
  4311. ttsView.stopSpeaking()
  4312. }
  4313. }
  4314. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4315. self.toolbarItemClickForExitMode(toolbarItem)
  4316. let itemId = toolbarItem.itemIdentifier
  4317. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  4318. self.clickChildTool(type: .watermark, index: index)
  4319. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  4320. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  4321. self.clickChildTool(type: .background, index: index)
  4322. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  4323. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  4324. self.clickChildTool(type: .headerAndFooter, index: index)
  4325. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  4326. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  4327. self.clickChildTool(type: .bates, index: index)
  4328. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  4329. } else if (toolbarItem.itemIdentifier == KMToolbarMeasureItemIdentifier) {
  4330. self.clickChildTool(type: .measure, index: index)
  4331. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  4332. self.clickChildTool(type: .comparison, index: index)
  4333. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  4334. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  4335. convertToImg(index: index)
  4336. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  4337. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  4338. extractImageAction(num: index)
  4339. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  4340. self.createPdf(index: index)
  4341. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  4342. if index == 2 { // 裁剪当前页面
  4343. self.cropCurrentPage()
  4344. } else if index == 3 { // Auto Crop – Separate
  4345. self.smart_cropAllPage()
  4346. } else if index == 4 { // Auto Crop – Combined
  4347. self.auto_cropAllPage()
  4348. } else if index == 5 { // Select Area
  4349. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  4350. }
  4351. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  4352. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  4353. self.clickChildTool(type: .secure, index: index)
  4354. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  4355. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  4356. if index == 11 {
  4357. self.view.window?.makeFirstResponder(nil)
  4358. let winC = KMSearchReplaceWindowController(with: self.listView, type: .search)
  4359. self.currentWindowController = winC
  4360. winC.replaceCallback = { [weak self] in
  4361. let toolMode = self?.listView?.toolMode ?? .none
  4362. let isEditing = self?.listView?.isEditing() ?? false
  4363. if toolMode == .editPDFToolMode && isEditing {
  4364. } else { // 进入内容编辑模式
  4365. self?.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4366. }
  4367. }
  4368. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  4369. // - (winC.window?.frame.size.width ?? 0)
  4370. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  4371. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 248 - 16
  4372. let winFramePoint = NSPoint(x: x, y: y)
  4373. winC.window?.setFrameOrigin(winFramePoint)
  4374. winC.startModal(nil)
  4375. } else if index == 12 {
  4376. if IAPProductsManager.default().isAvailableAllFunction() == false {
  4377. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  4378. return
  4379. }
  4380. self.view.window?.makeFirstResponder(nil)
  4381. let toolMode = self.listView?.toolMode ?? .none
  4382. let isEditing = self.listView?.isEditing() ?? false
  4383. if toolMode == .editPDFToolMode && isEditing {
  4384. } else { // 进入内容编辑模式
  4385. self.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4386. }
  4387. let winC = KMSearchReplaceWindowController(with: self.listView, type: .replace)
  4388. self.currentWindowController = winC
  4389. winC.replaceCallback = { [weak self] in
  4390. let toolMode = self?.listView?.toolMode ?? .none
  4391. let isEditing = self?.listView?.isEditing() ?? false
  4392. if toolMode == .editPDFToolMode && isEditing {
  4393. } else { // 进入内容编辑模式
  4394. self?.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4395. }
  4396. }
  4397. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  4398. // - (winC.window?.frame.size.width ?? 0)
  4399. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  4400. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 388
  4401. let winFramePoint = NSPoint(x: x, y: y)
  4402. winC.window?.setFrameOrigin(winFramePoint)
  4403. winC.startModal(nil)
  4404. } else {
  4405. self.toolbarController.showFindBar()
  4406. }
  4407. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4408. toolbarItem.isSelected = !toolbarItem.isSelected
  4409. self.toggleRightPane()
  4410. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4411. self.toolbarController.toolbarType = .viewSetting
  4412. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4413. self.showOCRWindow()
  4414. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  4415. if index == 1 {
  4416. self.showAITypeChooseView(aiConfigType: .summarize)
  4417. } else if index == 2 {
  4418. self.showAITypeChooseView(aiConfigType: .reWriting)
  4419. } else if index == 3 {
  4420. self.showAITypeChooseView(aiConfigType: .proofreading)
  4421. } else if index == 4 {
  4422. self.showAITypeChooseView(aiConfigType: .translate)
  4423. }
  4424. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  4425. self.showOCRWindow()
  4426. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  4427. self.toolbarController.toolbarType = .editPDF
  4428. self.enterEditPDF()
  4429. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  4430. self.toolbarController.toolbarType = .FillSign
  4431. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  4432. self.toolbarController.toolbarType = .Form
  4433. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  4434. if self.canEnterDigitalSign() == false {
  4435. Task {
  4436. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4437. }
  4438. return
  4439. }
  4440. toolbarItem.isSelected = !toolbarItem.isSelected
  4441. self.toolbarController.lastItemBox = toolbarItem
  4442. if toolbarItem.isSelected {
  4443. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4444. }
  4445. self.enterDigitalSign()
  4446. } else if itemId == KMSignDigitalSignToolbarItemIdentifier {
  4447. if self.canEnterDigitalSign() == false {
  4448. Task {
  4449. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4450. }
  4451. return
  4452. }
  4453. toolbarItem.isSelected = !toolbarItem.isSelected
  4454. self.toolbarController.lastItemBox = toolbarItem
  4455. if toolbarItem.isSelected {
  4456. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4457. }
  4458. self.enterDigitalSign()
  4459. } else if itemId == KMDocumentAIToolsToolbarItemIdentifier {
  4460. self.showAITypeChooseView(aiConfigType: .none)
  4461. }
  4462. }
  4463. func convertToImg(index: Int) {
  4464. var convertT: KMConvertType = .JPEG
  4465. switch index {
  4466. case 7:
  4467. convertT = .JPEG
  4468. case 8:
  4469. convertT = .JPG
  4470. case 9:
  4471. convertT = .PNG
  4472. case 10:
  4473. convertT = .GIF
  4474. case 11:
  4475. convertT = .TIFF
  4476. case 12:
  4477. convertT = .TGA
  4478. case 13:
  4479. convertT = .BMP
  4480. default:
  4481. convertT = .JPEG
  4482. }
  4483. showAllConvertWindow(convertT: convertT)
  4484. }
  4485. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  4486. // if self.searchResults.count == 0 {
  4487. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4488. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4489. self.search(searchString: searchString, isCase: caseInsensitive, display: false)
  4490. // }
  4491. var row = max(searchIndex - 1, 0)
  4492. if forward {
  4493. row = searchIndex + 1
  4494. }
  4495. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4496. let model = self.searchResults[row]
  4497. if model.selection != nil {
  4498. self.listView.setHighlightedSelections([])
  4499. self.listView.go(to: model.selection, animated: true)
  4500. self.listView.setHighlightedSelection(model.selection, animated: true)
  4501. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4502. searchIndex = row
  4503. }
  4504. }
  4505. self.leftSideViewController.showSearchMode(searchString)
  4506. }
  4507. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  4508. // if self.searchResults.count == 0 {
  4509. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4510. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4511. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  4512. // }
  4513. var row = max(searchIndex - 1, 0)
  4514. if forward {
  4515. row = searchIndex + 1
  4516. }
  4517. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4518. let model = self.searchResults[row]
  4519. if model.selection != nil {
  4520. self.listView.setHighlightedSelections([])
  4521. self.listView.go(to: model.selection, animated: true)
  4522. self.listView.setHighlightedSelection(model.selection, animated: true)
  4523. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4524. searchIndex = row
  4525. }
  4526. }
  4527. }
  4528. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  4529. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4530. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  4531. self.leftSideViewController.showSearchMode(searchString)
  4532. }
  4533. func toolbarViewController(_ viewController: KMToolbarViewController, viewItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4534. let itemId = toolbarItem.itemIdentifier
  4535. if itemId == KMDocumentFirstLastToolbarItemIdentifier {
  4536. if index == 1 {
  4537. if self.listView.canGoToFirstPage() {
  4538. self.listView.goToFirstPage(nil)
  4539. }
  4540. } else if index == 2 {
  4541. if self.listView.canGoToLastPage() {
  4542. self.listView.goToLastPage(nil)
  4543. }
  4544. }
  4545. }
  4546. }
  4547. }
  4548. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  4549. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  4550. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  4551. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  4552. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4553. distanceSettingWC.delegate = self
  4554. distanceSettingWC.startModal("")
  4555. }
  4556. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  4557. }
  4558. }
  4559. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  4560. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  4561. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  4562. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  4563. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4564. distanceSettingWC.delegate = self
  4565. distanceSettingWC.startModal("")
  4566. }
  4567. }
  4568. // MARK: CAreaMeasureInfoWindowControllerDelegate
  4569. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  4570. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  4571. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  4572. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  4573. areaSettingWC.delegate = self
  4574. areaSettingWC.startModal("")
  4575. }
  4576. }
  4577. // MARK: CDistanceSettingWindowControllerDelegate
  4578. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  4579. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  4580. if distanceMeasureInfo != nil {
  4581. if self.listView.activeAnnotations.count > 0 {
  4582. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  4583. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  4584. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4585. }
  4586. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  4587. } else {
  4588. distanceMeasureInfo?.leadLength = 0
  4589. self.listView.distanceMeasureInfo = distanceMeasureInfo
  4590. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  4591. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4592. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4593. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4594. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4595. }
  4596. }
  4597. self.distanceMeasureInfoWindowController?.showWindow(self)
  4598. }
  4599. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  4600. if perimeterMeasureInfo != nil {
  4601. if self.listView.activeAnnotations.count > 0 {
  4602. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  4603. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  4604. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4605. }
  4606. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  4607. } else {
  4608. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  4609. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  4610. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4611. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4612. }
  4613. }
  4614. self.perimeterMeasureInfoWindowController?.showWindow(self)
  4615. }
  4616. }
  4617. // MARK: CAreaSettingWindowControllerDelegate
  4618. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  4619. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  4620. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  4621. if measureInfo != nil {
  4622. if self.listView.activeAnnotations.count > 0 {
  4623. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4624. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4625. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4626. }
  4627. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4628. } else {
  4629. self.listView.squareAreaMeasureInfo = measureInfo
  4630. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  4631. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4632. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4633. }
  4634. }
  4635. self.areaMeasureInfoWindowController?.showWindow(self)
  4636. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  4637. if measureInfo != nil {
  4638. if self.listView.activeAnnotations.count > 0 {
  4639. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4640. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4641. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4642. }
  4643. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4644. } else {
  4645. self.listView.polygonAreaMeasureInfo = measureInfo
  4646. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  4647. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4648. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4649. }
  4650. }
  4651. self.areaMeasureInfoWindowController?.showWindow(self)
  4652. } else {
  4653. if measureInfo != nil {
  4654. if self.listView.activeAnnotations.count > 0 {
  4655. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4656. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4657. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4658. }
  4659. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4660. }
  4661. }
  4662. self.areaMeasureInfoWindowController?.showWindow(self)
  4663. }
  4664. }
  4665. }
  4666. // MARK: -
  4667. // MARK: - Mouse
  4668. extension KMMainViewController {
  4669. override func mouseDown(with event: NSEvent) {
  4670. super.mouseDown(with: event)
  4671. // KMPrint("KMMainViewController mouseDown")
  4672. self.leftSideViewCancelSelect()
  4673. self.pageNumberDisplayView.isEdit = false
  4674. }
  4675. }
  4676. //MARK: LeftSideViewController
  4677. extension KMMainViewController {
  4678. func leftSideViewCancelSelect() {
  4679. // switch self.leftSideViewController.type.methodType {
  4680. // case .Thumbnail:
  4681. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  4682. // break
  4683. // case .Outline:
  4684. //// self.leftSideViewController.outlineViewController.cancelSelect()
  4685. // break
  4686. // case .BookMark:
  4687. //// self.leftSideViewController.bookViewController.cancelSelect()
  4688. // break
  4689. // case .Search:
  4690. //// self.leftSideViewController.searchViewController.cancelSelect()
  4691. // break
  4692. // case .Annotation:
  4693. //// self.leftSideViewController.annotationViewController.cancelSelect()
  4694. // break
  4695. // default:
  4696. if self.listView.isEditing() {
  4697. if self.listView.editingAreas() != nil &&
  4698. self.listView.editingAreas().count != 0 {
  4699. let areas = self.listView.editingAreas().first
  4700. if areas is CPDFEditTextArea {
  4701. self.listView.clearEditingSelectCharItem()
  4702. self.listView.updateEditing([])
  4703. KMPrint("取消选中")
  4704. }
  4705. }
  4706. }
  4707. // KMPrint("其他")
  4708. // }
  4709. }
  4710. }
  4711. extension KMMainViewController: KMReadModelViewDelegate {
  4712. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4713. self.listView.goToFirstPage(nil)
  4714. }
  4715. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  4716. self.listView.goToPreviousPage(nil)
  4717. }
  4718. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4719. self.listView.goToNextPage(nil)
  4720. }
  4721. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4722. self.listView.goToLastPage(nil)
  4723. }
  4724. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  4725. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  4726. }
  4727. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  4728. var scale: Double = 1.0
  4729. switch type {
  4730. case .fitWidth:
  4731. self.listView.autoScales = !self.listView.autoScales
  4732. scale = self.listView.scaleFactor
  4733. break
  4734. case .actualSize:
  4735. if self.listView.scaleFactor != 1.0 {
  4736. self.listView.scaleFactor = 1.0
  4737. self.listView.autoScales = false
  4738. }
  4739. scale = self.listView.scaleFactor
  4740. break
  4741. case .autoSize:
  4742. self.listView.autoScales = true
  4743. self.listView.autoScales = false
  4744. scale = self.listView.scaleFactor
  4745. break
  4746. case ._10:
  4747. scale = 0.1
  4748. break
  4749. case ._25:
  4750. scale = 0.25
  4751. break
  4752. case ._50:
  4753. scale = 0.5
  4754. break
  4755. case ._100:
  4756. scale = 1.0
  4757. break
  4758. case ._150:
  4759. scale = 1.5
  4760. break
  4761. case ._200:
  4762. scale = 2.0
  4763. break
  4764. case ._400:
  4765. scale = 4.0
  4766. break
  4767. case ._800:
  4768. scale = 8.0
  4769. break
  4770. default:
  4771. break
  4772. }
  4773. self.listView.scaleFactor = scale
  4774. self.toolbarController.mainViewController?.childToolbarController.zoomTextField?.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  4775. }
  4776. func cancelReadModel(view: KMReadModelView, sender: Any) {
  4777. if self.isReadMode {
  4778. self.closeReadModel()
  4779. }
  4780. }
  4781. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  4782. // if self.readModelViewWidthConstraint.constant != width {
  4783. self.readModelViewWidthConstraint.constant = width
  4784. // }
  4785. }
  4786. }
  4787. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  4788. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  4789. self.listView.go(toPageIndex: pageIndex, animated: true)
  4790. }
  4791. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  4792. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  4793. self.tipCurrentPageBoxWidthConstraint.constant = width
  4794. }
  4795. }
  4796. func commitEditingIfNeed() {
  4797. self.editPDFHanddler.commitEditing()
  4798. }
  4799. }
  4800. extension KMMainViewController: KMInteractionProviderProtocol {
  4801. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  4802. let view = self.listView
  4803. view?.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  4804. if let v = view {
  4805. fullScreenWindow.contentView?.addSubview(v)
  4806. }
  4807. return view
  4808. }
  4809. }
  4810. // MARK: - Analytics (埋点)
  4811. extension KMMainViewController {
  4812. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  4813. if (type == .Annatiton) {
  4814. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  4815. } else if (type == .editPDF) {
  4816. } else if (type == .Page) {
  4817. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  4818. } else if (type == .Conversion) {
  4819. } else if (type == .Tool) {
  4820. }
  4821. }
  4822. func trackEvent_aiTranslate() -> Void {
  4823. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  4824. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4825. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4826. }
  4827. func trackEvent_print() -> Void {
  4828. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  4829. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4830. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4831. }
  4832. func trackEvent_share() -> Void {
  4833. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  4834. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4835. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4836. }
  4837. func trackEvent_upgrade() -> Void {
  4838. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  4839. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4840. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4841. }
  4842. func trackEvent(annotationType type: CAnnotationType) -> Void {
  4843. if (type == .highlight) {
  4844. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  4845. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  4846. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4847. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4848. } else if (type == .underline) {
  4849. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  4850. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  4851. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4852. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4853. } else if (type == .strikeOut) {
  4854. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  4855. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  4856. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4857. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4858. } else if (type == .ink) {
  4859. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  4860. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  4861. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4862. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4863. } else if (type == .freeText) {
  4864. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  4865. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  4866. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4867. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4868. } else if (type == .anchored) {
  4869. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  4870. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  4871. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4872. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4873. } else if (type == .square) {
  4874. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  4875. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  4876. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4877. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4878. } else if (type == .link) {
  4879. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  4880. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  4881. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4882. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4883. } else if (type == .stamp) {
  4884. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  4885. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  4886. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4887. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4888. } else if (type == .signSignature) {
  4889. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  4890. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  4891. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4892. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4893. } else if (type == .circle) {
  4894. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  4895. } else if (type == .arrow) {
  4896. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  4897. } else if (type == .line) {
  4898. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  4899. } else if (type == .addText) {
  4900. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  4901. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4902. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4903. } else if (type == .addImage) {
  4904. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  4905. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  4906. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4907. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4908. } else if (type == .textField) {
  4909. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  4910. } else if (type == .checkBox) {
  4911. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  4912. } else if (type == .radioButton) {
  4913. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  4914. } else if (type == .listMenu) {
  4915. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  4916. } else if (type == .comboBox) {
  4917. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  4918. } else if (type == .actionButton) {
  4919. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4920. } else if (type == .actionButton) {
  4921. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4922. } else if (type == .signature) {
  4923. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  4924. } else {
  4925. }
  4926. }
  4927. func trackEvent(toolMode mode: CToolMode) -> Void {
  4928. if (mode == .selectToolMode) {
  4929. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  4930. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4931. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4932. } else if (mode == .moveToolMode) {
  4933. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  4934. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4935. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4936. }
  4937. }
  4938. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  4939. if (type == .word) {
  4940. } else if (type == .excel) {
  4941. } else if (type == .ppt) {
  4942. } else if (type == .rtf) {
  4943. } else if (type == .csv) {
  4944. } else if (type == .html) {
  4945. } else if (type == .conversion_text) {
  4946. } else if (type == .conversion_image) {
  4947. } else if (type == .compress) {
  4948. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  4949. } else if (type == .merge) {
  4950. } else if (type == .secure) {
  4951. } else if (type == .crop) {
  4952. }
  4953. }
  4954. func trackEvent_setPassword() -> Void {
  4955. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  4956. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4957. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4958. }
  4959. func trackEvent_removePassword() -> Void {
  4960. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  4961. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4962. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4963. }
  4964. }
  4965. extension KMMainViewController {
  4966. //文件对比
  4967. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  4968. self.isCompareModel = true
  4969. let compareContentView = KMCompareContentView()
  4970. compareContentView.oldDocument = oldDocument
  4971. compareContentView.document = document
  4972. compareContentView.compareResults = results
  4973. compareContentView.saveHandle = { [unowned self] view in
  4974. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  4975. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  4976. self.currentWindowController = saveController
  4977. saveController.cancelHandle = { [unowned self] controller in
  4978. self.view.window!.endSheet(controller.window!)
  4979. self.currentWindowController = nil
  4980. }
  4981. saveController.saveHandle = { [unowned self] controller, saveType in
  4982. let folderPath = controller.fileSaveFolderPath
  4983. if folderPath != nil {
  4984. if !FileManager.default.fileExists(atPath: folderPath) {
  4985. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  4986. }
  4987. #if VERSION_DMG
  4988. #else
  4989. let url = URL(fileURLWithPath: folderPath)
  4990. let fileAccess = AppSandboxFileAccess()
  4991. fileAccess?.persistPermissionURL(url)
  4992. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  4993. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  4994. let urlString = url.path
  4995. let _url = URL(fileURLWithPath: urlString)
  4996. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  4997. }
  4998. #endif
  4999. var savePath: String
  5000. switch saveType {
  5001. case 0:
  5002. let filePath = oldDocument.documentURL.path
  5003. let fileName = filePath.deletingPathExtension.lastPathComponent
  5004. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  5005. savePath = self.getValidFilePath(savePath)
  5006. oldDocument.write(to: URL(fileURLWithPath: savePath))
  5007. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5008. case 1:
  5009. let filePath = document.documentURL.path
  5010. let fileName = filePath.deletingPathExtension.lastPathComponent
  5011. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  5012. savePath = self.getValidFilePath(savePath)
  5013. document.write(to: URL(fileURLWithPath: savePath))
  5014. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5015. case 2:
  5016. let filePath = oldDocument.documentURL.path
  5017. let fileName = filePath.deletingPathExtension.lastPathComponent
  5018. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  5019. savePath = self.getValidFilePath(savePath)
  5020. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  5021. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5022. default:
  5023. break
  5024. }
  5025. }
  5026. self.view.window!.endSheet(controller.window!)
  5027. self.currentWindowController = nil
  5028. }
  5029. NSWindow.currentWindow().beginSheet(saveController.window!)
  5030. }
  5031. }
  5032. compareContentView.closeHandle = { [unowned self] view in
  5033. // self.view.window!.endSheet(controller.window!)
  5034. self.isCompareModel = false
  5035. view.removeFromSuperview()
  5036. }
  5037. self.PDFContendView.addSubview(compareContentView)
  5038. compareContentView.frame = self.PDFContendView.bounds
  5039. compareContentView.autoresizingMask = [.width,.height]
  5040. }
  5041. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  5042. self.isCompareModel = true
  5043. let coveringView = KMCompareCoveringView()
  5044. coveringView.pdfDocument = pdfDocument
  5045. coveringView.closeHandle = { [unowned self] view in
  5046. self.isCompareModel = false
  5047. view.removeFromSuperview()
  5048. }
  5049. coveringView.saveHandle = { [unowned self] view in
  5050. let savePanel = NSSavePanel()
  5051. savePanel.nameFieldStringValue = "untitled"
  5052. savePanel.allowedFileTypes = ["pdf"]
  5053. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  5054. if result == .OK {
  5055. pdfDocument.write(to: savePanel.url!)
  5056. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  5057. }
  5058. }
  5059. }
  5060. self.PDFContendView.addSubview(coveringView)
  5061. coveringView.frame = self.PDFContendView.bounds
  5062. coveringView.autoresizingMask = [.width,.height]
  5063. }
  5064. func getValidFilePath(_ oldPath: String) -> String {
  5065. let fileManager = FileManager.default
  5066. do {
  5067. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  5068. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  5069. return oldPath
  5070. }
  5071. var i = 1
  5072. var newPath = oldPath
  5073. while fileManager.fileExists(atPath: newPath) {
  5074. if fileType == FileAttributeType.typeDirectory.rawValue {
  5075. newPath = oldPath + "(\(i))"
  5076. } else {
  5077. let fileExtension = (oldPath as NSString).pathExtension
  5078. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  5079. }
  5080. i += 1
  5081. }
  5082. return newPath
  5083. } catch {
  5084. print("Error getting file attributes: \(error)")
  5085. return oldPath
  5086. }
  5087. }
  5088. }
  5089. extension KMMainViewController {
  5090. func documentAllowsEdit() -> Bool {
  5091. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  5092. let alert = NSAlert()
  5093. alert.alertStyle = .critical
  5094. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  5095. alert.runModal()
  5096. return false
  5097. } else {
  5098. return true
  5099. }
  5100. }
  5101. }