KMMainViewController+Action.swift 255 KB

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