KMMainViewController+Action.swift 258 KB

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