KMMainViewController+Action.swift 255 KB

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