KMMainViewController+Action.swift 271 KB

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