KMMainViewController+Action.swift 277 KB

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