KMMainViewController+Action.swift 266 KB

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