KMMainViewController+Action.swift 263 KB

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