KMMainViewController+Action.swift 257 KB

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