KMMainViewController+Action.swift 258 KB

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