KMMainViewController+Action.swift 253 KB

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