KMMainViewController+Action.swift 259 KB

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