KMMainViewController+Action.swift 254 KB

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