KMMainViewController+Action.swift 254 KB

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