KMMainViewController+Action.swift 260 KB

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