KMMainViewController+Action.swift 256 KB

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