KMMainViewController+Action.swift 254 KB

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