KMMainViewController+Action.swift 259 KB

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