KMMainViewController+Action.swift 296 KB

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