KMMainViewController+Action.swift 254 KB

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