KMMainViewController+Action.swift 261 KB

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