KMLeftSideViewController.swift 302 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969
  1. //
  2. // KMLeftSideViewController.swift
  3. // PDF Master
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. @objc protocol KMLeftSideViewControllerDelegate {
  9. @objc optional func controlStateChange(_ obj: KMLeftSideViewController,show:Bool)
  10. @objc optional func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int])
  11. @objc optional func searchAction(searchString:String, isCase:Bool)
  12. @objc optional func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType)
  13. @objc optional func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  14. @objc optional func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem])
  15. @objc optional func controller(controller: KMLeftSideViewController, rotateType: KMRotateType)
  16. }
  17. class KMLeftSideViewController: KMSideViewController {
  18. var dataSource : [KMLeftMethodMode] = [KMLeftMethodMode]()
  19. var type : KMLeftMethodMode = KMLeftMethodMode()
  20. var isShowPanel : Bool = false
  21. var norImage : [String] = []
  22. var selectImage : [String] = []
  23. var mainVC: KMMainViewController?
  24. var selectPages: [Int]?
  25. open weak var delegate: KMLeftSideViewControllerDelegate?
  26. deinit {
  27. KMPrint("KMLeftSideViewController deinit.")
  28. NotificationCenter.default.removeObserver(self)
  29. }
  30. override var nibName: NSNib.Name? {
  31. return "LeftSideView"
  32. }
  33. convenience init(type : KMLeftMethodMode) {
  34. self.init()
  35. self.type = type
  36. }
  37. override func viewDidLoad() {
  38. super.viewDidLoad()
  39. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  40. self.isDisplayPageSize = UserDefaults.standard.bool(forKey: "kKMThumbnailDisplayPageSizeKey")
  41. }
  42. func showPanelView(show: Bool) {
  43. self.isShowPanel = show
  44. if show {
  45. self.leftView.segmentedControl.selectedSegment = 0
  46. } else {
  47. self.leftView.segmentedControl.selectedSegment = UInt8.max
  48. self.delegate?.controlStateChange?(self, show: false)
  49. }
  50. }
  51. func refreshMethodType(methodType: BotaType) {
  52. let newType = KMLeftMethodMode()
  53. var show = true
  54. if self.type.methodType != methodType {
  55. newType.methodType = methodType
  56. }
  57. if self.type.methodType == methodType {
  58. show = false
  59. } else if methodType == .None {
  60. show = false
  61. }
  62. self.type = newType;
  63. self.delegate?.controlStateChange?(self,show:show)
  64. }
  65. // MARK: - New
  66. /*
  67. NSArrayController *findArrayController;
  68. NSArrayController *groupedFindArrayController;
  69. }
  70. - (void)applySearchTableHeader:(NSString *)message;
  71. */
  72. @IBOutlet var segmentedControl: KMSegmentedControl!
  73. @IBOutlet var thumbnailTableView: KMThumbnailTableView!
  74. @IBOutlet var tocOutlineView: KMTocOutlineView!
  75. @IBOutlet var noteOutlineView: KMNoteOutlineView!
  76. @IBOutlet var findTableView: KMBotaTableView!
  77. @IBOutlet var groupedFindTableView: KMBotaTableView!
  78. @IBOutlet var snapshotTableView: KMBotaTableView!
  79. @IBOutlet weak var leftListView: NSView!
  80. @IBOutlet var searchViewController: KMBotaSearchViewController!
  81. @IBOutlet weak var toolButtonBox: NSBox!
  82. @IBOutlet weak var toolButtonBoxLayoutConstraint: NSLayoutConstraint!
  83. @IBOutlet weak var snapshotNormalView: NSView!
  84. @IBOutlet weak var snapshotLabel: NSTextField!
  85. @IBOutlet weak var snapshotNormalMoreButton: NSButton!
  86. @IBOutlet weak var snapshotNormalSearchButton: NSButton!
  87. @IBOutlet weak var snapshotNormalZoomOutButton: NSButton!
  88. @IBOutlet weak var snapshotNormalZoomInButton: NSButton!
  89. @IBOutlet weak var snapshotSearchZoomOutButton: NSButton!
  90. @IBOutlet weak var snapshotSearchZoomInButton: NSButton!
  91. @IBOutlet weak var snapshotSearchField: KMLeftSideViewSearchField!
  92. @IBOutlet weak var snapshotDoneButton: NSButton!
  93. @IBOutlet weak var outlineView: NSView!
  94. @IBOutlet weak var outlineMoreButton: NSButton!
  95. @IBOutlet weak var outlineAddButton: NSButton!
  96. @IBOutlet weak var outlineSearchButton: NSButton!
  97. @IBOutlet weak var outlineLabel: NSTextField!
  98. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  99. @IBOutlet weak var outlineDoneButton: NSButton!
  100. @IBOutlet weak var noteView: NSView!
  101. @IBOutlet weak var noteMoreButton: NSButton!
  102. @IBOutlet weak var noteFilterButton: NSButton!
  103. @IBOutlet weak var noteSearchButton: NSButton!
  104. @IBOutlet weak var noteSearchField: KMLeftSideViewSearchField!
  105. @IBOutlet weak var noteTitleLabel: NSTextField!
  106. @IBOutlet weak var noteHeaderView: NSView!
  107. @IBOutlet weak var sortTypeBox: KMBox!
  108. @IBOutlet weak var sortTypeLabel: NSTextField!
  109. @IBOutlet weak var noteSortButton: NSButton!
  110. @IBOutlet weak var noteDoneButton: NSButton!
  111. @IBOutlet weak var thumbnailView: NSView!
  112. @IBOutlet weak var thumbnailZoomOutButton: NSButton!
  113. @IBOutlet weak var thumbnailZoomInButton: NSButton!
  114. @IBOutlet weak var thumbnailTitleLabel: NSTextField!
  115. @IBOutlet weak var emptySearchBox: NSBox!
  116. @IBOutlet weak var emptySearchLabel: NSTextField!
  117. var filterButtonLayer: NSView?
  118. var moreButtonLayer: KMButtonLayer?
  119. var thumbnails: [KMThumbnail] = []
  120. var isDisplayPageSize = false
  121. var thumbnailCacheSize: CGFloat = 32 * 3
  122. private var _findState: KMFindState = .none
  123. var findState: KMFindState {
  124. get {
  125. return self._findState
  126. }
  127. set {
  128. if self._findState != newValue {
  129. self._findState = newValue
  130. self.displayFindState()
  131. if self._findState == .content {
  132. self.search(self.searchField)
  133. } else if self.findState == .note {
  134. self.searchNotes(self.searchField)
  135. } else if self.findState == .snapshot {
  136. self.searchNotes(self.searchField)
  137. }
  138. }
  139. }
  140. }
  141. var searchResults : [KMSearchMode] = [] {
  142. didSet {
  143. self.updataLeftSideFindView()
  144. }
  145. }
  146. var groupSearchResults: [KMSearchMode] = []
  147. var findPaneState: KMFindPaneState = .singular
  148. var isSearchOutlineMode = false
  149. var isSearchSnapshotMode = false
  150. var outlineIgnoreCaseFlag = false
  151. var noteTypeDict: [String : Any] = [:]
  152. private let MIN_SIDE_PANE_WIDTH: CGFloat = 270
  153. private let LABEL_COLUMNID = "label"
  154. var foldType: KMFoldAllAnnotationType = .none
  155. private let KMLeftSideViewNoteSortTypeKey = "KMLeftSideViewNoteSortTypeKey"
  156. private let KMLeftSideViewAscendSortBoolKey = "KMLeftSideViewAscendSortBoolKey"
  157. private let SKDisableTableToolTipsKey = "SKDisableTableToolTips"
  158. var tocType: KMFoldType = .none
  159. var snapshots: [KMSnapshotModel] = []
  160. var searchSnapshots: [KMSnapshotModel] = []
  161. private var _noteSortType: KMNoteSortType = .none
  162. var noteSortType: KMNoteSortType {
  163. get {
  164. return self._noteSortType
  165. }
  166. set {
  167. self._noteSortType = newValue
  168. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  169. }
  170. }
  171. var isAscendSort = false {
  172. didSet {
  173. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  174. }
  175. }
  176. lazy var leftSideEmptyVC: KMLeftSideEmptyFileViewController = {
  177. let vc = KMLeftSideEmptyFileViewController(nibName: "KMLeftSideEmptyFileViewController", bundle: nil)
  178. vc.view.wantsLayer = true
  179. return vc
  180. }()
  181. var preThumbnailRow: Int = 0
  182. var leftMargin: CGFloat = 0
  183. lazy var leftView: KMBotaLeftView = {
  184. let view = KMBotaLeftView()
  185. return view
  186. }()
  187. private var _copysPages: [CPDFPage] = []
  188. private var _annotations: [KMBOTAAnnotationSection] = []
  189. private var _allAnnotations: [CPDFAnnotation] = []
  190. private let kKMPDFViewOutlineDragDataType = "kKMPDFViewOutlineDragDataType"
  191. private let KPDFThumbnailDoucumentURLForDraggedTypes = "KPDFThumbnailDoucumentURLForDraggedTypes"
  192. var renamePDFOutline: CPDFOutline?
  193. var renamePDFOutlineTextField: NSTextField?
  194. var allFoldNotes: [CPDFAnnotation] = []
  195. var notes: [CPDFAnnotation] = []
  196. var canFoldNotes: [CPDFAnnotation] = []
  197. override func loadView() {
  198. super.loadView()
  199. self.view.wantsLayer = true
  200. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  201. self.view.addSubview(self.leftView)
  202. self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  203. self.leftView.autoresizingMask = [.height]
  204. self.leftView.wantsLayer = true
  205. self.leftView.layer?.backgroundColor = .white
  206. self.outlineView.wantsLayer = true
  207. self.outlineView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  208. self.noteView.wantsLayer = true
  209. self.noteView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  210. self.thumbnailView.wantsLayer = true
  211. self.thumbnailView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  212. self.snapshotNormalView.wantsLayer = true
  213. self.snapshotNormalView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  214. self.tocOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  215. self.noteOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  216. self.findTableView.backgroundColor = KMAppearance.Layout.l0Color()
  217. self.groupedFindTableView.backgroundColor = KMAppearance.Layout.l0Color()
  218. self.snapshotTableView.backgroundColor = KMAppearance.Layout.l0Color()
  219. self.thumbnailTableView.backgroundColor = KMAppearance.Layout.l0Color()
  220. self.leftListView.wantsLayer = true
  221. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  222. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  223. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  224. self.emptySearchBox.isHidden = true
  225. self.thumbnailTitleLabel.stringValue = KMLocalizedString("Thumbnails", nil)
  226. self.thumbnailTitleLabel.textColor = KMAppearance.Layout.h0Color()
  227. self.thumbnailZoomInButton.action = #selector(thumbnailSizeScaling)
  228. self.thumbnailZoomInButton.target = self
  229. self.thumbnailZoomInButton.tag = 1
  230. self.thumbnailZoomOutButton.action = #selector(thumbnailSizeScaling)
  231. self.thumbnailZoomOutButton.target = self
  232. self.thumbnailZoomOutButton.tag = 0
  233. self.snapshotTableView.delegate = self
  234. self.snapshotTableView.dataSource = self
  235. self.snapshotTableView.menu = NSMenu()
  236. self.snapshotTableView.menu?.delegate = self
  237. self.snapshotTableView.doubleAction = #selector(toggleSelectedSnapshots)
  238. self.snapshotTableView.target = self
  239. self.snapshotTableView.backgroundColor = .clear
  240. // [snapshotTableView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
  241. self.snapshotLabel.stringValue = KMLocalizedString("Snapshots", nil)
  242. self.snapshotLabel.textColor = KMAppearance.Layout.h0Color()
  243. self.snapshotNormalZoomInButton.action = #selector(thumbnailSizeScaling)
  244. self.snapshotNormalZoomInButton.target = self
  245. self.snapshotNormalZoomInButton.tag = 2
  246. self.snapshotNormalZoomOutButton.action = #selector(thumbnailSizeScaling)
  247. self.snapshotNormalZoomOutButton.target = self
  248. self.snapshotNormalZoomOutButton.tag = 3
  249. self.snapshotNormalSearchButton.toolTip = KMLocalizedString("Search", nil)
  250. self.snapshotNormalMoreButton.action = #selector(leftSideViewMoreButtonAction)
  251. self.snapshotNormalMoreButton.target = self
  252. self.snapshotNormalMoreButton.tag = 300
  253. self.snapshotSearchZoomInButton.action = #selector(thumbnailSizeScaling)
  254. self.snapshotSearchZoomInButton.target = self
  255. self.snapshotSearchZoomInButton.tag = 2
  256. self.snapshotSearchZoomOutButton.action = #selector(thumbnailSizeScaling)
  257. self.snapshotSearchZoomOutButton.target = self
  258. self.snapshotSearchZoomOutButton.tag = 3
  259. self.snapshotDoneButton.title = KMLocalizedString("Done", nil)
  260. self.snapshotDoneButton.toolTip = KMLocalizedString("Done", nil)
  261. self.snapshotDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  262. self.snapshotDoneButton.wantsLayer = true
  263. self.snapshotDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  264. self.snapshotDoneButton.layer?.cornerRadius = 4.0
  265. self.snapshotDoneButton.action = #selector(leftSideViewDoneButtonAction)
  266. self.snapshotDoneButton.target = self
  267. self.snapshotDoneButton.tag = 312
  268. self.snapshotDoneButton.isHidden = true
  269. self.noteOutlineView.autoresizesOutlineColumn = false
  270. self.noteOutlineView.delegate = self
  271. self.noteOutlineView.dataSource = self
  272. self.noteOutlineView.botaDelegate = self
  273. self.noteOutlineView.botaDataSource = self
  274. self.noteOutlineView.noteDelegate = self
  275. self.noteOutlineView.menu = NSMenu()
  276. self.noteOutlineView.menu?.delegate = self
  277. // [noteOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  278. self.noteOutlineView.indentationPerLevel = 0
  279. // [noteOutlineView registerForDraggedTypes:[NSColor readableTypesForPasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]]];
  280. self.noteOutlineView.target = self
  281. self.noteOutlineView.doubleAction = #selector(selectSelectedNote)
  282. self.tocOutlineView.menu = NSMenu()
  283. self.tocOutlineView.menu?.delegate = self
  284. self.outlineSearchField.delegate = self
  285. self.snapshotSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  286. self.outlineSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  287. self.noteSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  288. self.snapshotSearchField.wantsLayer = true
  289. self.outlineSearchField.wantsLayer = true
  290. self.noteSearchField.wantsLayer = true
  291. self.snapshotSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  292. self.outlineSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  293. self.noteSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  294. self.snapshotSearchField.layer?.borderWidth = 1.0
  295. self.outlineSearchField.layer?.borderWidth = 1.0
  296. self.noteSearchField.layer?.borderWidth = 1.0
  297. self.snapshotSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  298. self.outlineSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  299. self.noteSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  300. // __block typeof(self) blockSelf = self;
  301. // _snapshotSearchField.changeCallBack = ^(NSString *changeContent) {
  302. // NSString *editContent = @"";
  303. // if (changeContent) {
  304. // editContent = changeContent;
  305. // }
  306. // [blockSelf.mainController searchFieldChangeAction:editContent];
  307. // };
  308. self.snapshotSearchField.isHidden = true
  309. self.snapshotSearchZoomOutButton.isHidden = true
  310. self.snapshotSearchZoomInButton.isHidden = true
  311. // _snapshotSearchField.endEditCallBack = ^(BOOL isEndEdit) {
  312. // if (isEndEdit/* && searchViewController.segmentedControl.segmentCount == 3*/) {
  313. // _snapshotSearchField.hidden = YES;
  314. // _snapshotSearchZoomOutButton.hidden = YES;
  315. // _snapshotSearchZoomInButton.hidden = YES;
  316. // _snapshotLabel.hidden = NO;
  317. // _snapshotNormalZoomOutButton.hidden = NO;
  318. // _snapshotNormalZoomInButton.hidden = NO;
  319. // }
  320. // };
  321. self.thumbnailZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  322. self.snapshotNormalZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  323. self.snapshotSearchZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  324. self.thumbnailZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  325. self.snapshotNormalZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  326. self.snapshotSearchZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  327. self.outlineLabel.stringValue = KMLocalizedString("Outline", nil);
  328. self.outlineLabel.textColor = KMAppearance.Layout.h0Color()
  329. self.outlineAddButton.toolTip = KMLocalizedString("Add Item", nil)
  330. self.outlineAddButton.action = #selector(outlineContextMenuItemClicked_AddEntry)
  331. self.outlineAddButton.target = self
  332. self.outlineSearchButton.toolTip = KMLocalizedString("Search", nil)
  333. self.outlineMoreButton.action = #selector(leftSideViewMoreButtonAction)
  334. self.outlineMoreButton.target = self
  335. self.outlineMoreButton.tag = 302
  336. self.outlineDoneButton.title = KMLocalizedString("Done", nil);
  337. self.outlineDoneButton.toolTip = KMLocalizedString("Done", nil);
  338. self.outlineDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  339. self.outlineDoneButton.wantsLayer = true
  340. self.outlineDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  341. self.outlineDoneButton.layer?.cornerRadius = 4.0
  342. self.outlineDoneButton.action = #selector(leftSideViewDoneButtonAction)
  343. self.outlineDoneButton.target = self
  344. self.outlineDoneButton.tag = 310
  345. self.outlineDoneButton.isHidden = true
  346. self.outlineSearchField.isHidden = true
  347. // _outlineSearchField.endEditCallBack = ^(BOOL isEndEdit) {
  348. // if (isEndEdit) {
  349. // _outlineSearchField.hidden = YES;
  350. // _outlineLabel.hidden = NO;
  351. // _outlineSearchButton.hidden = NO;
  352. // }
  353. // };
  354. let menuOutline = NSMenu()
  355. menuOutline.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleOutlineCaseInsensitiveSearch), target: self)
  356. (self.outlineSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menuOutline
  357. (self.outlineSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Outline", nil)
  358. self.outlineSearchField.target = self
  359. let sud = UserDefaults.standard
  360. self.noteTitleLabel.stringValue = KMLocalizedString("Notes", nil);
  361. self.noteTitleLabel.textColor = KMAppearance.Layout.h0Color()
  362. self.noteMoreButton.action = #selector(leftSideViewMoreButtonAction)
  363. self.noteMoreButton.target = self
  364. self.noteMoreButton.tag = 304
  365. self.noteMoreButton.wantsLayer = true
  366. self.moreButtonLayer = KMButtonLayer()
  367. self.noteMoreButton.layer?.addSublayer(self.moreButtonLayer!)
  368. self.moreButtonLayer?.frame = CGRectMake(0, 0, CGRectGetWidth(self.noteMoreButton.bounds), CGRectGetHeight(self.noteMoreButton.bounds))
  369. self.moreButtonLayer?.layerType = .none
  370. self.moreButtonLayer?.isHidden = true
  371. self.noteFilterButton.action = #selector(noteFilterAction)
  372. self.noteFilterButton.target = self
  373. self.noteFilterButton.toolTip = KMLocalizedString("Sort", nil)
  374. self.noteFilterButton.wantsLayer = true
  375. self.filterButtonLayer = NSView()
  376. self.noteFilterButton.addSubview(self.filterButtonLayer!)
  377. self.filterButtonLayer?.frame = CGRectMake(14, 2, 8, 8)
  378. self.filterButtonLayer?.isHidden = true
  379. self.filterButtonLayer?.wantsLayer = true
  380. self.filterButtonLayer?.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  381. self.filterButtonLayer?.layer?.cornerRadius = 4.0
  382. self.noteDoneButton.title = KMLocalizedString("Done", nil)
  383. self.noteDoneButton.toolTip = KMLocalizedString("Done", nil)
  384. self.noteDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  385. self.noteDoneButton.wantsLayer = true
  386. self.noteDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  387. self.noteDoneButton.layer?.cornerRadius = 4.0
  388. self.noteDoneButton.action = #selector(leftSideViewDoneButtonAction)
  389. self.noteDoneButton.target = self
  390. self.noteDoneButton.tag = 311
  391. self.noteDoneButton.isHidden = true
  392. self.noteSearchButton.toolTip = KMLocalizedString("Search", nil)
  393. self.noteSearchField.delegate = self
  394. self.noteSearchField.isHidden = true
  395. self.noteSearchField.endEditCallBack = { [unowned self] isEndEdit in
  396. if (isEndEdit) {
  397. self.noteSearchField.isHidden = true
  398. self.noteSearchButton.isHidden = false
  399. self.noteTitleLabel.isHidden = false
  400. }
  401. };
  402. self.noteHeaderView.wantsLayer = true
  403. self.noteHeaderView.layer?.backgroundColor = KMAppearance.Else.textTagColor().cgColor
  404. self.noteHeaderView.layer?.cornerRadius = 1.0
  405. let sortType = sud.integer(forKey: KMLeftSideViewNoteSortTypeKey)
  406. if (sortType == 1) {
  407. self.noteSortType = KMNoteSortType(rawValue: sortType)!
  408. if (self.noteSortType == .time) {
  409. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  410. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  411. } else if (self._noteSortType == .page) {
  412. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  413. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  414. }
  415. } else {
  416. self.noteSortType = .time
  417. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  418. }
  419. self.sortTypeLabel.textColor = KMAppearance.Layout.h1Color()
  420. self.isAscendSort = sud.bool(forKey: KMLeftSideViewAscendSortBoolKey)
  421. if (self.isAscendSort) {
  422. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  423. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  424. } else {
  425. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  426. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  427. }
  428. self.sortTypeBox.downCallback = { [unowned self] downEntered, mouseBox, _ in
  429. if (downEntered) {
  430. let menu = NSMenu()
  431. let timeItem = menu.addItem(title: KMLocalizedString("Time", nil), action: #selector(sortTypeAction), target: self)
  432. timeItem?.representedObject = self
  433. timeItem?.tag = 0
  434. let pageItem = menu.addItem(title: KMLocalizedString("Page", nil), action: #selector(sortTypeAction), target: self)
  435. pageItem?.representedObject = self
  436. timeItem?.tag = 1
  437. if (self.noteSortType == .time) {
  438. timeItem?.state = .on
  439. pageItem?.state = .off
  440. } else if (self.noteSortType == .page) {
  441. timeItem?.state = .off
  442. pageItem?.state = .on
  443. }
  444. menu.popUp(positioning: nil, at: CGPointMake(-10, 0), in: self.sortTypeBox)
  445. }
  446. }
  447. self.searchViewController.loadView()
  448. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  449. self.searchField = self.searchViewController.searchField
  450. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  451. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  452. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  453. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  454. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  455. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  456. self.searchViewController.segmentedControl.selectedSegment = 0
  457. self.searchViewController.segmentedControl.block = { [unowned self] segIndex in
  458. if segIndex == 0 {
  459. self.findPaneState = .singular
  460. self.displayFindViewAnimating(false)
  461. } else {
  462. self.findPaneState = .grouped
  463. self.displayGroupedFindViewAnimating(false)
  464. }
  465. }
  466. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  467. self.toolButtonBox.isHidden = false
  468. self.toolButtonBoxLayoutConstraint.constant = 40.0
  469. if (segIndex == 0) {
  470. if self.type.methodType == .Thumbnail {
  471. self.leftView.segmentedControl.selectedSegment = UInt8.max
  472. self.refreshMethodType(methodType: .None)
  473. return
  474. }
  475. self.refreshMethodType(methodType: .Thumbnail)
  476. DispatchQueue.main.async {
  477. self.toolButtonBox.contentView = self.thumbnailView
  478. self.displayThumbnailViewAnimating(false)
  479. }
  480. } else if (segIndex == 1) {
  481. if self.type.methodType == .Outline {
  482. self.leftView.segmentedControl.selectedSegment = UInt8.max
  483. self.refreshMethodType(methodType: .None)
  484. return
  485. }
  486. self.refreshMethodType(methodType: .Outline)
  487. DispatchQueue.main.async {
  488. self.toolButtonBox.contentView = self.outlineView
  489. self.displayTocViewAnimating(false)
  490. }
  491. } else if (segIndex == 2) {
  492. if self.type.methodType == .Annotation {
  493. self.leftView.segmentedControl.selectedSegment = UInt8.max
  494. self.refreshMethodType(methodType: .None)
  495. return
  496. }
  497. self.refreshMethodType(methodType: .Annotation)
  498. DispatchQueue.main.async {
  499. self.toolButtonBox.contentView = self.noteView
  500. self.displayNoteViewAnimating(false)
  501. }
  502. } else if (segIndex == 3) {
  503. self.toolButtonBox.contentView = self.snapshotNormalView
  504. self.updateSnapshotFilterPredicate()
  505. self.displaySnapshotViewAnimating(false)
  506. self.updataLeftSideSnapView()
  507. } else if (segIndex == 4) {
  508. if self.type.methodType == .Search {
  509. self.leftView.segmentedControl.selectedSegment = UInt8.max
  510. self.refreshMethodType(methodType: .None)
  511. return
  512. }
  513. self.refreshMethodType(methodType: .Search)
  514. DispatchQueue.main.async {
  515. self.toolButtonBox.isHidden = true
  516. self.toolButtonBoxLayoutConstraint.constant = 0
  517. self.displayFindViewAnimating(false)
  518. }
  519. }
  520. }
  521. // self.button.setHelp(KMLocalizedString("View Thumbnails", "Tool tip message"), for: KMLeftSidePaneState.thumbnail.rawValue)
  522. // self.button.setHelp(KMLocalizedString("View Outline", "Tool tip message"), for: KMLeftSidePaneState.outline.rawValue)
  523. // self.alternateButton.setHelp(KMLocalizedString("Separate search results", "Tool tip message"), for: KMFindPaneState.singular.rawValue)
  524. // self.alternateButton.setHelp(KMLocalizedString("Group search results by page", "Tool tip message"), for: KMFindPaneState.grouped.rawValue)
  525. // NSMenu *menu = [NSMenu menu];
  526. // [menu addItemWithTitle:NSLocalizedString(@"Whole Words Only", @"Menu item title") action:@selector(toggleWholeWordSearch:) target:mainController];
  527. // [menu addItemWithTitle:NSLocalizedString(@"Ignore Case", @"Menu item title") action:@selector(toggleCaseInsensitiveSearch:) target:mainController];
  528. // [[searchField cell] setSearchMenuTemplate:menu];
  529. // [[searchField cell] setPlaceholderString:NSLocalizedString(@"Search PDF", @"placeholder")];
  530. self.searchField.action = #selector(search)
  531. self.searchField.target = self
  532. self.tocOutlineView.autoresizesOutlineColumn = false
  533. self.tocOutlineView.allowsMultipleSelection = true
  534. self.tocOutlineView.allowsEmptySelection = true
  535. self.tocOutlineView.delegate = self
  536. self.tocOutlineView.dataSource = self
  537. self.tocOutlineView.botaDelegate = self
  538. self.tocOutlineView.botaDataSource = self
  539. self.tocOutlineView.tocDelegate = self
  540. self.thumbnailTableView.delegate = self
  541. self.thumbnailTableView.dataSource = self
  542. self.thumbnailTableView.thumbDelegate = self
  543. self.thumbnailTableView.allowsMultipleSelection = true
  544. self.findTableView.delegate = self
  545. self.findTableView.dataSource = self
  546. self.findTableView.botaDelegate = self
  547. self.groupedFindTableView.delegate = self
  548. self.groupedFindTableView.dataSource = self
  549. self.groupedFindTableView.botaDelegate = self
  550. self.thumbnailTableView.menu?.delegate = self
  551. self.findTableView.menu?.delegate = self
  552. self.groupedFindTableView.menu?.delegate = self
  553. self.tocOutlineView.doubleAction = #selector(goToSelectedOutlineItem)
  554. self.tocOutlineView.target = self
  555. self.findTableView.doubleAction = #selector(goToSelectedFindResults)
  556. self.findTableView.target = self
  557. self.groupedFindTableView.doubleAction = #selector(goToSelectedFindResults)
  558. self.groupedFindTableView.target = self
  559. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  560. // //支持拖拽的文字类型
  561. // [thumbnailTableView registerForDraggedTypes:@[KPDFThumbnailLocalForDraggedTypes,NSFilenamesPboardType]];
  562. // self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL])
  563. self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL,.string,.pdf])
  564. // self.thumbnailTableView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
  565. // self.thumbnailTableView.setDraggingSourceOperationMask([.copy, .delete], forLocal: true)
  566. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  567. // [tocOutlineView registerForDraggedTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType]];
  568. // [[[findTableView tableColumnWithIdentifier:PAGE_COLUMNID] headerCell] setTitle:NSLocalizedString(@"Page", @"Table header title")];
  569. // [[[groupedFindTableView tableColumnWithIdentifier:PAGE_COLUMNID] headerCell] setTitle:NSLocalizedString(@"Page", @"Table header title")];
  570. // [[[groupedFindTableView tableColumnWithIdentifier:RELEVANCE_COLUMNID] dataCell] setEnabled:NO];
  571. self.thumbnailTableView.selectionHighlightStyle = .none
  572. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  573. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  574. //
  575. // self.thumbnailTableView.setDraggingSourceOperationMask(.every, forLocal: false)
  576. if UserDefaults.standard.bool(forKey: SKDisableTableToolTipsKey) == false {
  577. self.tocOutlineView.hasImageToolTips = true
  578. self.findTableView.hasImageToolTips = true
  579. self.groupedFindTableView.hasImageToolTips = true
  580. }
  581. self._updateViewColor()
  582. }
  583. func displayThumbnailViewAnimating(_ animate: Bool) {
  584. self.replaceSideView(self.thumbnailTableView.enclosingScrollView!, animate: animate)
  585. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  586. frame.origin.y = 0
  587. frame.origin.x = self.leftMargin
  588. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  589. self.thumbnailTableView.enclosingScrollView?.frame = frame
  590. self.resetThumbnails()
  591. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  592. frame.origin.y = 0
  593. frame.origin.x = self.leftMargin
  594. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  595. self.noteOutlineView.enclosingScrollView?.frame = frame
  596. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  597. frame.origin.y = 0
  598. frame.origin.x = self.leftMargin
  599. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  600. self.snapshotTableView.enclosingScrollView?.frame = frame
  601. // [self updateThumbnailSelection];
  602. }
  603. func displayFindViewAnimating(_ animate: Bool) {
  604. self.replaceSideView(self.searchViewController.view, animate: animate)
  605. if (self.findState != .content) {
  606. self.findState = .content
  607. } else {
  608. self.displayFindState()
  609. }
  610. var frame = self.searchViewController.view.frame
  611. frame.origin.y = 0
  612. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  613. self.searchViewController.view.frame = frame
  614. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  615. frame.origin.y = 0
  616. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  617. self.noteOutlineView.enclosingScrollView?.frame = frame
  618. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  619. frame.origin.y = 0
  620. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  621. self.snapshotTableView.enclosingScrollView?.frame = frame
  622. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  623. self.updataLeftSideSnapView()
  624. }
  625. func displayFindState() {
  626. if (self.findState == .content) {
  627. self.displayFind()
  628. } else if (self.findState == .note) {
  629. self.displayNoteFind()
  630. } else if (self.findState == .snapshot) {
  631. self.displaySnapshotFind()
  632. }
  633. }
  634. func updataLeftSideSnapView() {
  635. if (snapshots.count < 1) {
  636. self.snapshotNormalSearchButton.isEnabled = false
  637. // leftSideController.snapshotSearchZoomOutButton.enabled = NO;
  638. self.snapshotNormalZoomOutButton.isEnabled = false
  639. // leftSideController.snapshotSearchZoomInButton.enabled = NO;
  640. self.snapshotNormalZoomInButton.isEnabled = false
  641. self.snapshotNormalMoreButton.isEnabled = false
  642. self.leftSideEmptyVC.deleteSnapBtn.isEnabled = false
  643. self.leftSideEmptyVC.exportSnapBtn.isEnabled = false
  644. self.leftSideEmptyVC.printSnapBtn.isEnabled = false
  645. self.snapshotTableView.usesAlternatingRowBackgroundColors = false
  646. let view = self.snapshotTableView.enclosingScrollView!
  647. let emptyVcSize = self.leftSideEmptyVC.emptySnapView.frame.size
  648. self.leftSideEmptyVC.emptySnapView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  649. self.leftSideEmptyVC.emptySnapView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  650. self.snapshotTableView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptySnapView)
  651. } else {
  652. self.snapshotNormalSearchButton.isEnabled = true
  653. // leftSideController.snapshotSearchZoomOutButton.enabled = YES;
  654. self.snapshotNormalZoomOutButton.isEnabled = true
  655. // leftSideController.snapshotSearchZoomInButton.enabled = YES;
  656. self.snapshotNormalZoomInButton.isEnabled = true
  657. self.snapshotNormalMoreButton.isEnabled = true
  658. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  659. self.leftSideEmptyVC.deleteSnapBtn.isEnabled = true
  660. self.leftSideEmptyVC.exportSnapBtn.isEnabled = true
  661. self.leftSideEmptyVC.printSnapBtn.isEnabled = true
  662. }
  663. }
  664. func updataLeftSideFindView() {
  665. if (self.findState != .content) {
  666. return
  667. }
  668. if (self.searchResults.count > 0) {
  669. self.searchViewController.emptyBox.isHidden = true
  670. self.searchViewController.searchResultsView.isHidden = false
  671. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  672. } else {
  673. self.searchViewController.emptyBox.isHidden = false
  674. self.searchViewController.searchResultsView.isHidden = true
  675. }
  676. }
  677. func displayGroupedFindViewAnimating(_ animate: Bool) {
  678. self.replaceSideView(self.searchViewController.view , animate: animate)
  679. if (self.findState != .content) {
  680. self.findState = .content
  681. } else {
  682. self.displayFindState()
  683. }
  684. var frame = self.searchViewController.view.frame
  685. frame.origin.y = 0
  686. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  687. self.searchViewController.view.frame = frame
  688. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  689. frame.origin.y = 0
  690. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  691. self.noteOutlineView.enclosingScrollView?.frame = frame
  692. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  693. frame.origin.y = 0
  694. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  695. self.snapshotTableView.enclosingScrollView?.frame = frame
  696. self.updataLeftSideSnapView()
  697. }
  698. func displayNoteViewAnimating(_ animate: Bool) {
  699. self.reloadAnnotation()
  700. self.searchViewController.contentView = nil
  701. self.replaceSideView(self.noteOutlineView.enclosingScrollView!, animate: animate)
  702. if (self.findState != .note) {
  703. self.findState = .note
  704. } else {
  705. self.displayFindState()
  706. }
  707. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  708. frame.origin.y = 0
  709. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  710. self.noteOutlineView.enclosingScrollView?.frame = frame
  711. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  712. frame.origin.y = 0
  713. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  714. self.noteOutlineView.enclosingScrollView?.frame = frame
  715. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  716. frame.origin.y = 0
  717. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  718. self.snapshotTableView.enclosingScrollView?.frame = frame
  719. let view = self.noteOutlineView.enclosingScrollView!
  720. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  721. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  722. DispatchQueue.main.async {
  723. self.noteOutlineView.reloadData()
  724. }
  725. }
  726. func displaySnapshotViewAnimating(_ animate: Bool) {
  727. self.searchViewController.contentView = nil
  728. self.replaceSideView(self.snapshotTableView.enclosingScrollView!, animate: animate)
  729. if (self.findState != .snapshot) {
  730. self.findState = .snapshot
  731. } else {
  732. self.displayFindState()
  733. }
  734. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  735. frame.origin.y = 0
  736. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  737. self.snapshotTableView.enclosingScrollView?.frame = frame
  738. // frame = rightSideController.noteOutlineView.enclosingScrollView.frame;
  739. // frame.origin.y = 0;
  740. // frame.size.height = rightSideController.noteOutlineView.enclosingScrollView.superview.frame.size.height;
  741. // rightSideController.noteOutlineView.enclosingScrollView.frame = frame;
  742. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  743. frame.origin.y = 0
  744. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  745. self.tocOutlineView.enclosingScrollView?.frame = frame
  746. // [self updateSnapshotsIfNeeded];
  747. Task { @MainActor in
  748. self.snapshotTableView.reloadData()
  749. }
  750. }
  751. func displayFind() {
  752. self.searchField = self.searchViewController.searchField
  753. let menu = NSMenu()
  754. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  755. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  756. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  757. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  758. self.searchViewController.searchField.action = #selector(search)
  759. self.searchViewController.searchField.target = self
  760. if (self.findPaneState == .singular) {
  761. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  762. self.findTableView.wantsLayer = true
  763. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  764. DispatchQueue.main.async {
  765. self.findTableView.reloadData()
  766. }
  767. } else if (self.findPaneState == .grouped) {
  768. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  769. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  770. array.sort(){$0.datas.count > $1.datas.count}
  771. self.groupSearchResults = array
  772. self.groupedFindTableView.reloadData()
  773. }
  774. }
  775. func displayTocViewAnimating(_ animate: Bool) {
  776. self.replaceSideView(self.tocOutlineView.enclosingScrollView!, animate: animate)
  777. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  778. frame.origin.y = 0
  779. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  780. self.tocOutlineView.enclosingScrollView?.frame = frame
  781. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  782. frame.origin.y = 0
  783. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  784. self.noteOutlineView.enclosingScrollView?.frame = frame
  785. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  786. frame.origin.y = 0
  787. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  788. self.snapshotTableView.enclosingScrollView?.frame = frame
  789. let view = self.tocOutlineView.enclosingScrollView!
  790. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  791. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  792. DispatchQueue.main.async {
  793. self.tocOutlineView.reloadData()
  794. self.updateOutlineSelection()
  795. }
  796. }
  797. override func requiresAlternateButton(forView aview: NSView?) -> Bool {
  798. return false
  799. }
  800. func displayNoteFind() {
  801. self.searchField = self.noteSearchField
  802. let menu = NSMenu()
  803. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  804. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  805. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  806. self.noteSearchField.action = #selector(searchNotes)
  807. self.noteSearchField.target = self
  808. }
  809. func displaySnapshotFind() {
  810. self.searchField = self.snapshotSearchField;
  811. let menu = NSMenu()
  812. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  813. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  814. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  815. self.snapshotSearchField.action = #selector(searchNotes)
  816. self.snapshotSearchField.target = self
  817. self.snapshotSearchField.delegate = self
  818. }
  819. /*
  820. - (void)applySearchTableHeader:(NSString *)message {
  821. [[[findTableView tableColumnWithIdentifier:RESULTS_COLUMNID] headerCell] setStringValue:message];
  822. [[findTableView headerView] setNeedsDisplay:YES];
  823. [[[groupedFindTableView tableColumnWithIdentifier:RELEVANCE_COLUMNID] headerCell] setStringValue:message];
  824. [[groupedFindTableView headerView] setNeedsDisplay:YES];
  825. }
  826. */
  827. @IBAction func search(_ sender: NSSearchField) {
  828. self.delegate?.searchAction?(searchString: sender.stringValue, isCase: false)
  829. }
  830. @IBAction func snapshotNormalSearchButtonAction(_ sender: NSButton) {
  831. self.snapshotSearchField.isHidden = false
  832. // _snapshotSearchZoomOutButton.hidden = YES;
  833. self.snapshotSearchZoomInButton.isHidden = true
  834. self.snapshotNormalSearchButton.isHidden = true
  835. self.snapshotDoneButton.isHidden = false
  836. self.snapshotLabel.isHidden = true
  837. self.snapshotNormalZoomOutButton.isHidden = true
  838. self.snapshotNormalZoomInButton.isHidden = true
  839. self.snapshotSearchField.becomeFirstResponder()
  840. }
  841. func resetThumbnails() {
  842. // [self willChangeValueForKey:THUMBNAILS_KEY];
  843. // self.thumbnailCacheSize = 160
  844. self.thumbnails.removeAll()
  845. let pageLabels = self.listView.document.pageLabels()
  846. if (pageLabels.isEmpty == false) {
  847. let isLocked = self.listView.document.isLocked
  848. let firstPage = self.listView.document.page(at: 0)
  849. let emptyPage = CPDFPage()
  850. let firstFrame = firstPage?.bounds(for: .cropBox) ?? .zero
  851. let firstFrame2 = firstPage?.bounds(for: .mediaBox) ?? .zero
  852. emptyPage.setBounds(firstFrame, for: .cropBox)
  853. emptyPage.setBounds(firstFrame2, for: .mediaBox)
  854. emptyPage.rotation = firstPage?.rotation ?? 0
  855. let pageImage = firstPage!.thumbnail(of: NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize))
  856. // NSImage * = [emptyPage thumbnailWithSize:thumbnailCacheSize forBox:[pdfView displayBox]];
  857. var rect: NSRect = .zero
  858. rect.size = pageImage?.size ?? .zero
  859. let width = 1.2 * fmin(NSWidth(rect), NSHeight(rect))
  860. rect = NSInsetRect(rect, 0.5 * (NSWidth(rect) - width), 0.5 * (NSHeight(rect) - width));
  861. pageImage?.lockFocus()
  862. // NSImage(named: NSImage.applicationIconName)?.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  863. if (isLocked) {
  864. NSWorkspace.shared.icon(forFileType: NSFileTypeForHFSTypeCode(OSType(kLockedBadgeIcon))).draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  865. // [[[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kLockedBadgeIcon)] drawInRect:rect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:0.5];
  866. }
  867. pageImage?.unlockFocus()
  868. for (i, label) in pageLabels.enumerated() {
  869. let firstPage = self.listView.document.page(at: UInt(i))
  870. let size = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  871. // let pageImage = firstPage!.thumbnail(of: size)
  872. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  873. // thumbnail.delegate = self
  874. thumbnail.dirty = true
  875. self.thumbnails.append(thumbnail)
  876. }
  877. }
  878. // [self didChangeValueForKey:THUMBNAILS_KEY];
  879. // [self allThumbnailsNeedUpdate];
  880. DispatchQueue.main.async {
  881. self.thumbnailTableView.reloadData()
  882. }
  883. }
  884. @IBAction @objc func sortTypeAction(_ sender: NSMenuItem) {
  885. let item = sender
  886. let tag = item.tag
  887. if (item.state == .on) {
  888. item.state = .off
  889. } else {
  890. item.state = .on
  891. }
  892. if (tag == 0) {
  893. self.noteSortType = .page
  894. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  895. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  896. } else if (tag == 1) {
  897. self.noteSortType = .time
  898. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  899. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  900. }
  901. UserDefaults.standard.set(self.noteSortType.rawValue, forKey: KMLeftSideViewNoteSortTypeKey)
  902. UserDefaults.standard.synchronize()
  903. }
  904. @IBAction func noteSortAction(_ sender: AnyObject?) {
  905. if (self.isAscendSort) {
  906. self.isAscendSort = false
  907. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  908. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  909. } else {
  910. self.isAscendSort = true
  911. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  912. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  913. }
  914. UserDefaults.standard.setValue(self.isAscendSort, forKey: KMLeftSideViewAscendSortBoolKey)
  915. UserDefaults.standard.synchronize()
  916. }
  917. @IBAction func noteSearchAction(_ sender: NSButton) {
  918. self.noteSearchField.isHidden = false
  919. self.noteTitleLabel.isHidden = true
  920. self.noteSearchButton.isHidden = true
  921. self.noteDoneButton.isHidden = false
  922. self.noteFilterButton.isHidden = true
  923. self.noteMoreButton.isHidden = true
  924. self.noteSearchField.becomeFirstResponder()
  925. }
  926. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  927. let button = sender as? NSButton
  928. let tag = button?.tag ?? 0
  929. if (tag == 310) {
  930. self.outlineSearchField.isHidden = true
  931. self.outlineDoneButton.isHidden = true
  932. self.outlineLabel.isHidden = false
  933. self.outlineSearchButton.isHidden = false
  934. self.outlineMoreButton.isHidden = false
  935. self.outlineAddButton.isHidden = false
  936. } else if (tag == 311) {
  937. self.noteSearchField.isHidden = true
  938. self.noteTitleLabel.isHidden = false
  939. self.noteSearchButton.isHidden = false
  940. self.noteDoneButton.isHidden = true
  941. self.noteFilterButton.isHidden = false
  942. self.noteMoreButton.isHidden = false
  943. } else if (tag == 312) {
  944. self.snapshotSearchField.isHidden = true
  945. // leftSideController.snapshotSearchZoomOutButton.hidden = YES;
  946. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  947. self.snapshotNormalSearchButton.isHidden = false
  948. self.snapshotDoneButton.isHidden = true
  949. self.snapshotLabel.isHidden = false
  950. self.snapshotNormalZoomOutButton.isHidden = false
  951. self.snapshotNormalZoomInButton.isHidden = false
  952. }
  953. }
  954. @IBAction func leftSideViewMoreButtonAction(_ sender: AnyObject?) {
  955. let button = sender as? NSButton
  956. let tag = button?.tag ?? 0
  957. if (tag == 300) {
  958. var selectedRow = 0
  959. if (self.snapshotTableView.selectedRow >= 0) {
  960. selectedRow = self.snapshotTableView.selectedRow;
  961. } else {
  962. return
  963. }
  964. let model = self.snapshots[selectedRow]
  965. let controller = model.windowC
  966. let menu = NSMenu()
  967. let itemExport = menu.addItem(title: KMLocalizedString("Export", "Menu item title"), action: nil, target: self)
  968. let subMenu = NSMenu()
  969. var t = subMenu.addItem(title: KMLocalizedString("PNG", "Menu item title"), action: #selector(menuItemClick_ExportPNG), target: self)
  970. t?.representedObject = controller
  971. t = subMenu.addItem(title: KMLocalizedString("JPG", "Menu item title"), action: #selector(menuItemClick_ExportJPG), target: self)
  972. t?.representedObject = controller
  973. t = subMenu.addItem(title: KMLocalizedString("PDF", "Menu item title"), action: #selector(menuItemClick_ExportPDF), target: self)
  974. t?.representedObject = controller
  975. itemExport?.submenu = subMenu
  976. let itemPrint = menu.addItem(title: KMLocalizedString("Print", "Menu item title"), action: #selector(menuItemClick_Print), target: self)
  977. itemPrint?.representedObject = controller
  978. menu.addItem(.separator())
  979. let itemSelectAll = menu.addItem(title: KMLocalizedString("Select All", "Menu item title"), action: #selector(menuItemClick_SelectAll), target: self)
  980. itemSelectAll?.representedObject = controller
  981. menu.addItem(.separator())
  982. let itemDeleteAllSnapshot = menu.addItem(title: KMLocalizedString("Delete All Snapshots", "Menu item title"), action: #selector(deleteAllSnapshot), target: self)
  983. itemDeleteAllSnapshot?.representedObject = controller
  984. //
  985. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender as! NSButton)
  986. } else if (tag == 302) {
  987. let menu = NSMenu()
  988. let expandAllCommentsItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(toc_expandAllComments), target: self)
  989. expandAllCommentsItem?.representedObject = self.tocOutlineView
  990. let foldAllCommentsItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(toc_foldAllComments), target: self)
  991. expandAllCommentsItem?.representedObject = self.tocOutlineView
  992. let item = self.listView.document.outlineRoot()
  993. var num = 0
  994. for i in 0 ..< Int(item?.numberOfChildren ?? 0) {
  995. let outline = item?.child(at: UInt(i))
  996. if self.tocOutlineView.isItemExpanded(outline) {
  997. num += 1
  998. }
  999. }
  1000. if let cnt = item?.numberOfChildren, cnt > 0 && num == 0 {
  1001. self.tocType = .fold
  1002. } else if let cnt = item?.numberOfChildren, cnt > 0 && num == cnt {
  1003. self.tocType = .unfold
  1004. } else {
  1005. self.tocType = .none
  1006. }
  1007. if (self.tocType == .unfold) {
  1008. expandAllCommentsItem?.state = .on
  1009. foldAllCommentsItem?.state = .off
  1010. } else if (self.tocType == .fold) {
  1011. expandAllCommentsItem?.state = .off
  1012. foldAllCommentsItem?.state = .on
  1013. } else {
  1014. expandAllCommentsItem?.state = .off
  1015. foldAllCommentsItem?.state = .off
  1016. }
  1017. let removeEntryItem = menu.addItem(title: KMLocalizedString("Remove All Outlines", nil), action: #selector(leftSideEmptyAnnotationClick_DeleteOutline), target: self)
  1018. removeEntryItem?.representedObject = self.tocOutlineView
  1019. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender as! NSButton)
  1020. } else if (tag == 304) {
  1021. let menu = NSMenu()
  1022. let object = KMPopupMenuObject()
  1023. object.menuTag = 1001
  1024. menu.delegate = object
  1025. object.enterControllerCallback = { [weak self] isEnter in
  1026. if (isEnter) {
  1027. self?.moreButtonLayer?.isHidden = false
  1028. } else {
  1029. self?.moreButtonLayer?.isHidden = true
  1030. }
  1031. }
  1032. let expandAllCommentsItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(note_expandAllComments), target: self)
  1033. expandAllCommentsItem?.representedObject = self.noteOutlineView
  1034. let foldAllCommentsItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(note_foldAllComments), target: self)
  1035. foldAllCommentsItem?.representedObject = self.noteOutlineView
  1036. if (self.foldType == .unfold) {
  1037. expandAllCommentsItem?.state = .on
  1038. foldAllCommentsItem?.state = .off
  1039. } else if (self.foldType == .fold) {
  1040. expandAllCommentsItem?.state = .off
  1041. foldAllCommentsItem?.state = .on
  1042. } else {
  1043. expandAllCommentsItem?.state = .off
  1044. foldAllCommentsItem?.state = .off
  1045. }
  1046. let showAnnotationItem = menu.addItem(title: KMLocalizedString("Show Note", nil), action: nil, target: self)
  1047. let subMenu = NSMenu()
  1048. // NSMenuItem *t = [subMenu addItemWithTitle:NSLocalizedString(@"Type", nil) action:@selector(noteShowNoteAction:) target:self];
  1049. // if ([[self.noteTypeDict objectForKey:@"kKMNoteFilterAnnotationTypeKey"] boolValue]) {
  1050. // [t setState:NSControlStateValueOff];
  1051. // } else {
  1052. // [t setState:NSControlStateValueOn];
  1053. // }
  1054. // [t setRepresentedObject:self.rightSideController.noteOutlineView];
  1055. // t.tag = 100;
  1056. var t = subMenu.addItem(title: KMLocalizedString("Page", nil), action: #selector(noteShowNoteAction), target: self)
  1057. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool ?? false
  1058. if pageKey {
  1059. t?.state = .off
  1060. } else {
  1061. t?.state = .on
  1062. }
  1063. t?.representedObject = self.noteOutlineView
  1064. t?.tag = 101
  1065. t = subMenu.addItem(title: KMLocalizedString("Time", nil) , action: #selector(noteShowNoteAction), target: self)
  1066. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool ?? false
  1067. if timeKey {
  1068. t?.state = .off
  1069. } else {
  1070. t?.state = .on
  1071. }
  1072. t?.representedObject = self.noteOutlineView
  1073. t?.tag = 102
  1074. t = subMenu.addItem(title: KMLocalizedString("Author", nil) , action: #selector(noteShowNoteAction), target: self)
  1075. let authorKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool ?? false
  1076. if authorKey {
  1077. t?.state = .off
  1078. } else {
  1079. t?.state = .on
  1080. }
  1081. t?.representedObject = self.noteOutlineView
  1082. t?.tag = 103
  1083. showAnnotationItem?.submenu = subMenu
  1084. menu.addItem(.separator())
  1085. let exportAnnotationsItem = menu.addItem(title: NSLocalizedString("Export Annotations…", tableName: "MainMenu", comment: ""), action: nil, target: self)
  1086. let subMenu2 = NSMenu()
  1087. var t2 = subMenu2.addItem(title: NSLocalizedString("PDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1088. t2?.representedObject = self.noteOutlineView
  1089. t2?.tag = 0
  1090. t2 = subMenu2.addItem(title: NSLocalizedString("PDF Bundle", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1091. t2?.representedObject = self.noteOutlineView
  1092. t2?.tag = 1
  1093. t2 = subMenu2.addItem(title: NSLocalizedString("PDF Reader Pro Edition Notes", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1094. t2?.representedObject = self.noteOutlineView
  1095. t2?.tag = 2
  1096. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as Text", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1097. t2?.representedObject = self.noteOutlineView
  1098. t2?.tag = 3
  1099. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as RTF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1100. t2?.representedObject = self.noteOutlineView
  1101. t2?.tag = 4
  1102. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as RTFD", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1103. t2?.representedObject = self.noteOutlineView
  1104. t2?.tag = 5
  1105. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as FDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1106. t2?.representedObject = self.noteOutlineView
  1107. t2?.tag = 6
  1108. exportAnnotationsItem?.submenu = subMenu2
  1109. menu.addItem(.separator())
  1110. let removeAllAnnotationsItem = menu.addItem(title: NSLocalizedString("Remove All Annotations", tableName: "MainMenu", comment: ""), action: #selector(leftSideEmptyAnnotationClick_DeleteAnnotation), target: self)
  1111. removeAllAnnotationsItem?.representedObject = self.noteOutlineView
  1112. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: button!, with: nil)
  1113. }
  1114. }
  1115. @IBAction func note_expandAllComments(_ sender: AnyObject?) {
  1116. if (self.foldType == .unfold) {
  1117. return
  1118. }
  1119. self.foldType = .unfold
  1120. self.loadUnfoldDate(.none)
  1121. self.noteOutlineView.reloadData()
  1122. }
  1123. @IBAction func note_foldAllComments(_ sender: AnyObject?) {
  1124. if (self.foldType == .fold) {
  1125. return
  1126. }
  1127. self.foldType = .fold
  1128. self.loadUnfoldDate(.none)
  1129. self.noteOutlineView.reloadData()
  1130. }
  1131. @IBAction func noteShowNoteAction(_ sender: AnyObject?) {
  1132. let item = sender as? NSMenuItem
  1133. let tag = item?.tag ?? 0
  1134. if (tag == 100) {
  1135. // BOOL isType = [[self.noteTypeDict objectForKey:@"kKMNoteFilterAnnotationTypeKey"] boolValue];
  1136. // [self.noteTypeDict setObject:[NSNumber numberWithBool:!isType] forKey:@"kKMNoteFilterAnnotationTypeKey"];
  1137. } else if (tag == 101) {
  1138. let isPage = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool ?? false
  1139. self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] = isPage
  1140. } else if (tag == 102) {
  1141. let isTime = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool ?? false
  1142. self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] = isTime
  1143. } else if (tag == 103) {
  1144. let isAuther = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool ?? false
  1145. self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] = isAuther
  1146. }
  1147. UserDefaults.standard.set(self.noteTypeDict, forKey: "KMNoteOutlineViewTableColumnKey")
  1148. UserDefaults.standard.synchronize()
  1149. let selectRow = self.noteOutlineView.selectedRow
  1150. self.noteOutlineView.reloadData()
  1151. self.noteOutlineView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1152. }
  1153. @objc func exportAnnotationNotes(_ sender: AnyObject?) {
  1154. self.mainViewController.myDocument?.saveTo(sender)
  1155. }
  1156. @objc func leftSideEmptyAnnotationClick_DeleteAnnotation(_ sender: AnyObject?) {
  1157. // NSAlert* alert = [[NSAlert alloc] init];
  1158. // [alert setAlertStyle:NSAlertStyleCritical];
  1159. // [alert setMessageText:NSLocalizedString(@"This will permanently remove all annotations. Are you sure to continue?", nil)];
  1160. // [alert addButtonWithTitle:NSLocalizedString(@"Yes", nil)];
  1161. // [alert addButtonWithTitle:NSLocalizedString(@"No", nil)];
  1162. //
  1163. // NSModalResponse response = [alert runModal];
  1164. // if (response == NSAlertFirstButtonReturn) {
  1165. // NSMutableArray *annotations = [NSMutableArray array];
  1166. //
  1167. // for (NSUInteger i = 0; i < self.pdfView.document.pageCount; i++) {
  1168. // PDFPage *page = [[self.pdfView document] pageAtIndex:i];
  1169. // for (PDFAnnotation *annotation in [page annotations]) {
  1170. // if ([annotation isKindOfClass:[PDFAnnotationTextWidget class]] ||
  1171. // [annotation isKindOfClass:[PDFAnnotationButtonWidget class]] ||
  1172. // [annotation isKindOfClass:[PDFAnnotationChoiceWidget class]]) {
  1173. // continue;
  1174. // }
  1175. // if (@available(macOS 10.13, *)) {
  1176. // if ([annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature]) {
  1177. // continue;
  1178. // }
  1179. // }
  1180. // if ([annotation isKindOfClass:[PDFAnnotationLink class]]) {
  1181. // continue;
  1182. // }
  1183. // [annotations addObject:annotation];
  1184. // }
  1185. // }
  1186. //
  1187. // for (PDFAnnotation *annotation in annotations) {
  1188. // [self.pdfView removeAnnotation:annotation];
  1189. // }
  1190. // }
  1191. }
  1192. @IBAction func noteFilterAction(_ sender: AnyObject?) {
  1193. let button = sender as? NSButton
  1194. let menu = NSMenu()
  1195. let filterViewController = KMNoteOutlineFilterViewController()
  1196. filterViewController.view.layer?.backgroundColor = .clear
  1197. var notes = NSMutableArray()
  1198. for section in self._annotations {
  1199. if section.annotations?.count != 0 {
  1200. for item in section.annotations! {
  1201. notes.add(item.annotation!)
  1202. }
  1203. }
  1204. }
  1205. filterViewController.setNotesArray(notes)
  1206. filterViewController.applyFilterCallback = { [weak self] typeArr, colorArr, authorArr, isEmpty in
  1207. menu.cancelTracking()
  1208. if (isEmpty) {
  1209. self?.filterButtonLayer?.isHidden = true
  1210. } else {
  1211. self?.filterButtonLayer?.isHidden = false
  1212. }
  1213. //
  1214. // [blockSelf annotationSort:@[typeArr, colorArr, authorArr]];
  1215. }
  1216. filterViewController.cancelCallback = { isCancel in
  1217. if (isCancel) {
  1218. menu.cancelTracking()
  1219. }
  1220. }
  1221. let item = menu.addItem(withTitle: "", action: nil, keyEquivalent: "")
  1222. item.target = self
  1223. item.representedObject = filterViewController
  1224. item.view = filterViewController.view
  1225. menu.popUp(positioning: nil, at: CGPointMake(-130, 30), in: button)
  1226. }
  1227. @IBAction func outlineNormalSearchButtonAction(_ sender: NSButton) {
  1228. self.outlineSearchField.isHidden = false
  1229. self.outlineDoneButton.isHidden = false
  1230. self.outlineLabel.isHidden = true
  1231. self.outlineSearchButton.isHidden = true
  1232. self.outlineMoreButton.isHidden = true
  1233. self.outlineAddButton.isHidden = true
  1234. self.outlineSearchField.becomeFirstResponder()
  1235. }
  1236. @IBAction func toc_expandAllComments(_ sender: AnyObject?) {
  1237. if (self.tocType == .unfold) {
  1238. return
  1239. }
  1240. self.tocType = .unfold
  1241. self.tocOutlineView.reloadData()
  1242. self.tocOutlineView.expandItem(nil, expandChildren: true)
  1243. }
  1244. @IBAction func toc_foldAllComments(_ sender: AnyObject?) {
  1245. if (self.tocType == .fold) {
  1246. return
  1247. }
  1248. self.tocType = .fold
  1249. self.tocOutlineView.reloadData()
  1250. self.tocOutlineView.collapseItem(nil, collapseChildren: true)
  1251. }
  1252. @objc func leftSideEmptyAnnotationClick_DeleteOutline(_ sender: AnyObject?) {
  1253. let alert = NSAlert()
  1254. alert.alertStyle = .critical
  1255. alert.messageText = ""
  1256. alert.informativeText = KMLocalizedString("This will permanently remove all outlines. Are you sure to continue?", nil)
  1257. alert.addButton(withTitle: KMLocalizedString("Yes", nil))
  1258. alert.addButton(withTitle: KMLocalizedString("No", nil))
  1259. let response = alert.runModal()
  1260. if response == .alertFirstButtonReturn {
  1261. if let item = self.listView.document.outlineRoot() {
  1262. self.removeAllOutline(item)
  1263. }
  1264. }
  1265. }
  1266. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  1267. let sud = UserDefaults.standard
  1268. let tag = sender.tag
  1269. if (tag == 0 || tag == 1) {
  1270. var scaling = sud.float(forKey: "KMThumbnailSizeScalingKey")
  1271. if (scaling <= 0) {
  1272. scaling = 1
  1273. }
  1274. if (tag == 0) { // thumbnail Zoom In
  1275. scaling += 0.1
  1276. if scaling >= 2.2 {
  1277. return
  1278. }
  1279. } else if (tag == 1) { // thumbnail Zoom Out
  1280. scaling -= 0.1
  1281. if scaling <= 0.4 {
  1282. return
  1283. }
  1284. }
  1285. sud.setValue(scaling, forKey: "KMThumbnailSizeScalingKey")
  1286. let selectRow = self.thumbnailTableView.selectedRow
  1287. self.thumbnailTableView.reloadData()
  1288. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1289. } else if (tag == 2 || tag == 3) {
  1290. var scaling = sud.float(forKey: "KMSnapshotSizeScalingKey")
  1291. if (scaling <= 0) {
  1292. scaling = 1
  1293. }
  1294. if (tag == 2) { // snapshot Zoom In
  1295. scaling += 0.1
  1296. } else if (tag == 3) { // snapshot Zoom Out
  1297. scaling -= 0.1
  1298. }
  1299. sud.setValue(scaling, forKey: "KMSnapshotSizeScalingKey")
  1300. let selectRow = self.snapshotTableView.selectedRow
  1301. self.snapshotTableView.reloadData()
  1302. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1303. }
  1304. }
  1305. func reloadAnnotation() {
  1306. if self.listView != nil {
  1307. var dataArray: [KMBOTAAnnotationSection] = []
  1308. var annotationArray: [CPDFAnnotation] = []
  1309. for i in 0 ..< self.listView.document.pageCount {
  1310. var annotationItemArray: [KMBOTAAnnotationItem] = []
  1311. let page = self.listView.document.page(at: i)
  1312. let types = ["Highlight","Underline","Strikeout","Freehand","FreeText","Note","Square","Circle","Line","Stamp","Arrow","Image","Redact","Sign"]
  1313. var pageAnnotations: [CPDFAnnotation] = KMOCToolClass.filterAnnotation(annotations: page!.annotations,types: types) as! [CPDFAnnotation]
  1314. //添加签名注释
  1315. for annotation in page!.annotations {
  1316. if annotation.isKind(of: CPDFSignatureAnnotation.self) {
  1317. pageAnnotations.append(annotation)
  1318. }
  1319. }
  1320. for annotation in pageAnnotations {
  1321. if annotation.annotationShouldDisplay() == false {
  1322. pageAnnotations.removeObject(annotation)
  1323. }
  1324. }
  1325. //转换所有annotation类型
  1326. let section = KMBOTAAnnotationSection()
  1327. for annotation in pageAnnotations {
  1328. let item = KMBOTAAnnotationItem()
  1329. item.section = section
  1330. item.annotation = annotation
  1331. item.index = Int(annotation.page.pageIndex())
  1332. annotationItemArray.append(item)
  1333. }
  1334. if annotationItemArray.count != 0 {
  1335. section.annotations = annotationItemArray
  1336. section.page = page
  1337. section.isItemExpanded = true
  1338. dataArray.append(section)
  1339. }
  1340. //添加所有annotation 用于筛选
  1341. annotationArray += pageAnnotations
  1342. }
  1343. //转换对象,用于数据显示
  1344. self._annotations = dataArray
  1345. self._allAnnotations = annotationArray
  1346. // if self.annotations.count < 1 {
  1347. // self.filtrateButton.isEnabled = false
  1348. // } else {
  1349. // self.filtrateButton.isEnabled = true
  1350. // }
  1351. }
  1352. }
  1353. func annotationSort(sortArray:[[Any]]) {
  1354. if self.listView != nil {
  1355. var typeArr: [Any] = []
  1356. var colorArr: [Any] = []
  1357. var authorArr: [Any] = []
  1358. let sud = UserDefaults.standard
  1359. let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type" + self.listView.document.documentURL.path) as? Data
  1360. if typeData != nil {
  1361. typeArr = NSKeyedUnarchiver.unarchiveObject(with: typeData!) as! [Any]
  1362. }
  1363. let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color" + self.listView.document.documentURL.path) as? Data
  1364. if colorData != nil {
  1365. colorArr = NSKeyedUnarchiver.unarchiveObject(with: colorData!) as! [Any]
  1366. }
  1367. let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author" + self.listView.document.documentURL.path) as? Data
  1368. if authorData != nil {
  1369. authorArr = NSKeyedUnarchiver.unarchiveObject(with: authorData!) as! [Any]
  1370. }
  1371. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  1372. // self.filtrateButton.image = NSImage(named: "KMImageNameAnnotationsFiltrate")
  1373. self.reloadAnnotation()
  1374. } else {
  1375. // self.filtrateButton.image = NSImage(named: "icon_annotation_screening_select")
  1376. var dataArray: [KMBOTAAnnotationSection] = []
  1377. for i in 0 ..< self.listView.document.pageCount {
  1378. var annotationItemArray: [KMBOTAAnnotationItem] = []
  1379. let page = self.listView.document.page(at: i)
  1380. if page!.annotations.count > 0 {
  1381. var filterAnnotations: [CPDFAnnotation] = page!.annotations
  1382. if typeArr.count > 0 {
  1383. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations, types: typeArr) as! [CPDFAnnotation])
  1384. }
  1385. if (colorArr.count > 0) {
  1386. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,colors: colorArr) as! [CPDFAnnotation])
  1387. }
  1388. if (authorArr.count > 0) {
  1389. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,authors: authorArr) as! [CPDFAnnotation])
  1390. }
  1391. let section = KMBOTAAnnotationSection()
  1392. for annotation in filterAnnotations {
  1393. let item = KMBOTAAnnotationItem()
  1394. item.section = section
  1395. item.annotation = annotation
  1396. item.index = Int(page!.pageIndex())
  1397. annotationItemArray.append(item)
  1398. }
  1399. if annotationItemArray.count != 0 {
  1400. section.annotations = annotationItemArray
  1401. section.page = page
  1402. section.isItemExpanded = true
  1403. dataArray.append(section)
  1404. }
  1405. }
  1406. }
  1407. self._annotations = dataArray
  1408. }
  1409. }
  1410. }
  1411. func showSearchOutlineBlankState(_ toShowState: Bool) {
  1412. if (toShowState) {
  1413. self.leftSideEmptyVC.outlineSearchView.frame = CGRectMake((self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.width - self.leftSideEmptyVC.outlineSearchView.bounds.size.width)/2.0, (self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.height - self.leftSideEmptyVC.outlineSearchView.bounds.size.height)/2.0, self.leftSideEmptyVC.outlineSearchView.bounds.size.width, self.leftSideEmptyVC.outlineSearchView.bounds.size.height);
  1414. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  1415. self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1416. } else {
  1417. self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  1418. }
  1419. }
  1420. // func allRangeOfRoughString(_ roughString: String, searchString: String) -> [NSRange] {
  1421. //
  1422. // }
  1423. func removeAllOutline(_ outline: CPDFOutline) {
  1424. let ol = CPDFOutline()
  1425. self.listView.document.setOutlineRoot(ol)
  1426. for i in 0 ..< self.listView.document.pageCount {
  1427. self.listView.document.removeBookmark(forPageIndex: i)
  1428. }
  1429. self.listView.layoutDocumentView()
  1430. DispatchQueue.main.async {
  1431. self.tocOutlineView.reloadData()
  1432. }
  1433. }
  1434. func updateNoteFilterPredicate() {
  1435. //注释筛选
  1436. // [rightSideController.noteArrayController setFilterPredicate:[noteTypeSheetController filterPredicateForSearchString:[rightSideController.searchField stringValue] caseInsensitive:mwcFlags.caseInsensitiveNoteSearch]];
  1437. // NSPredicate *predicate = [noteTypeSheetController filterPredicateForSearchString:[rightSideController.searchField stringValue] caseInsensitive:mwcFlags.caseInsensitiveNoteSearch];
  1438. // [self loadAnnotationSortData:[NSArray arrayWithObjects:predicate, nil]];
  1439. // [rightSideController.noteOutlineView reloadData];
  1440. }
  1441. @objc func selectSelectedNote(_ sender: AnyObject?) {
  1442. if self.listView.hideNotes == false {
  1443. let selectedNotes = self.selectedNotes()
  1444. if selectedNotes.count == 1 {
  1445. let annotation = selectedNotes.last!
  1446. self.listView.go(to: annotation.bounds, on: annotation.page, animated: true)
  1447. // [pdfView scrollAnnotationToVisible:annotation];
  1448. // [pdfView setActiveAnnotation:annotation];
  1449. self.listView.updateActiveAnnotations([annotation])
  1450. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  1451. // }
  1452. }
  1453. // NSInteger column = [sender clickedColumn];
  1454. // if (column != -1) {
  1455. // NSString *colID = [[[sender tableColumns] objectAtIndex:column] identifier];
  1456. //
  1457. // if ([colID isEqualToString:@"color"]){
  1458. // for (PDFAnnotation *annotation in self.pdfView.activeAnnotations) {
  1459. // if (![annotation isKindOfClass:[PDFAnnotationChoiceWidget class]] &&
  1460. // ![annotation isKindOfClass:[PDFAnnotationButtonWidget class]] &&
  1461. // ![annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  1462. // [[NSColorPanel sharedColorPanel] orderFront:nil];
  1463. // break;
  1464. // }
  1465. //
  1466. // }
  1467. // }
  1468. // }
  1469. }
  1470. }
  1471. func selectedNotes() -> [CPDFAnnotation] {
  1472. var selectedNotes: [CPDFAnnotation] = []
  1473. let rowIndexes = self.noteOutlineView.selectedRowIndexes
  1474. for row in rowIndexes {
  1475. let item = self.noteOutlineView.item(atRow: row)
  1476. if item is KMBOTAAnnotationItem {
  1477. if let anno = (item as! KMBOTAAnnotationItem).annotation {
  1478. // if anno.type == nil {
  1479. // item = [(SKNoteText *)item note];
  1480. // }
  1481. if selectedNotes.contains(anno) == false {
  1482. selectedNotes.append(anno)
  1483. }
  1484. }
  1485. }
  1486. }
  1487. return selectedNotes
  1488. }
  1489. }
  1490. // MARK: - KMBotaTableViewDelegate
  1491. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  1492. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  1493. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1494. return rowIndexes.count > 0
  1495. }
  1496. return false
  1497. }
  1498. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  1499. if aTableView.isEqual(to: self.thumbnailTableView) {
  1500. if self._copysPages.count > 0 {
  1501. return true
  1502. }
  1503. }
  1504. return false
  1505. }
  1506. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  1507. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  1508. // return [rowIndexes count] > 0;
  1509. // } else
  1510. if aTableView.isEqual(to: self.thumbnailTableView) {
  1511. if self.listView.document.pageCount <= 1 {
  1512. return false
  1513. }
  1514. return true
  1515. }
  1516. return false
  1517. }
  1518. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  1519. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  1520. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1521. // return;
  1522. // }
  1523. if aTableView.isEqual(to: self.thumbnailTableView) {
  1524. if self._copysPages.count > 0 {
  1525. let index = self.listView.document.index(for: self.listView.currentPage()) + 1
  1526. if (index == NSNotFound) {
  1527. return
  1528. }
  1529. for page in self._copysPages.reversed() {
  1530. // if let newPage = page.copy() as? CPDFPage {
  1531. self.listView.document.insertPageObject(page, at: index)
  1532. // }
  1533. self.listView.layoutDocumentView()
  1534. // [pageLabels setArray:[[pdfView document] pageLabels]];
  1535. self.resetThumbnails()
  1536. let pageIndex = min(index, self.listView.document.pageCount-1)
  1537. self.listView.go(toPageIndex: Int(pageIndex), animated: true)
  1538. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  1539. }
  1540. }
  1541. }
  1542. }
  1543. func tableViewMoveLeft(_ aTableView: NSTableView) {
  1544. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1545. // [self updateFindResultHighlightsForDirection:NSSelectingPrevious];
  1546. }
  1547. }
  1548. func tableViewMoveRight(_ aTableView: NSTableView) {
  1549. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1550. // [self updateFindResultHighlightsForDirection:NSSelectingNext];
  1551. }
  1552. }
  1553. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  1554. if aTableView.isEqual(to: self.findTableView) {
  1555. if rowIndex >= self.searchResults.count {
  1556. return nil
  1557. }
  1558. let model = self.searchResults[rowIndex]
  1559. let selection = model.selection
  1560. let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  1561. return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  1562. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1563. if rowIndex >= self.groupSearchResults.count {
  1564. return nil
  1565. }
  1566. // let model = self.groupSearchResults[rowIndex]
  1567. // let selection = model.selection
  1568. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  1569. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  1570. }
  1571. return nil
  1572. }
  1573. /*
  1574. - (NSArray *)tableView:(NSTableView *)tv typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  1575. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1576. return pageLabels;
  1577. }
  1578. return nil;
  1579. }
  1580. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  1581. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1582. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  1583. }
  1584. }
  1585. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  1586. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1587. if (searchString.length > 0)
  1588. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  1589. else
  1590. [self updateLeftStatus];
  1591. }
  1592. }
  1593. */
  1594. }
  1595. // MARK: - KMThumbnailTableViewDelegate
  1596. extension KMLeftSideViewController: KMThumbnailTableViewDelegate {
  1597. func tableView(_ tableView: NSTableView, highlightLevelForRow row: Int) -> UInt {
  1598. if tableView.isEqual(to: self.thumbnailTableView) {
  1599. // NSUInteger i, iMax = [lastViewedPages count];
  1600. // for (i = 0; i < iMax; i++) {
  1601. // if (row == (NSInteger)[lastViewedPages pointerAtIndex:i])
  1602. // return i;
  1603. // }
  1604. }
  1605. return UInt.max
  1606. }
  1607. func tableView(_ tableView: NSTableView, commandSelectRow rowIndex: Int) -> Bool {
  1608. if tableView.isEqual(to: self.thumbnailTableView) {
  1609. // NSRect rect = [[[pdfView document] pageAtIndex:row] boundsForBox:kPDFDisplayBoxCropBox];
  1610. //
  1611. // rect.origin.y = NSMidY(rect) - 0.5 * SNAPSHOT_HEIGHT;
  1612. // rect.size.height = SNAPSHOT_HEIGHT;
  1613. // [self showSnapshotAtPageNumber:row forRect:rect scaleFactor:[pdfView scaleFactor] autoFits:NO];
  1614. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  1615. thumbailTabCell?.isSelectCell = true
  1616. var rowIndexSet = IndexSet()
  1617. for i in self.thumbnailTableView.selectedRowIndexes {
  1618. rowIndexSet.insert(i)
  1619. }
  1620. rowIndexSet.insert(rowIndex)
  1621. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1622. return true
  1623. }
  1624. return false
  1625. }
  1626. func tableView(_ tableView: NSTableView, shiftSelectRow rowIndex: Int) -> Bool {
  1627. if tableView.isEqual(to: self.thumbnailTableView) {
  1628. if (self.thumbnailTableView.selectedRowIndexes.count == 0) {
  1629. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  1630. thumbailTabCell?.isSelectCell = true
  1631. var rowIndexSet = IndexSet()
  1632. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1633. return true
  1634. } else if (self.thumbnailTableView.selectedRowIndexes.count == 1 && self.thumbnailTableView.selectedRowIndexes.first == rowIndex) {
  1635. return false
  1636. } else {
  1637. var fristIndex = self.thumbnailTableView.selectedRowIndexes.first ?? Int.min
  1638. var lastIndex = self.thumbnailTableView.selectedRowIndexes.last ?? Int.max
  1639. for idx in self.thumbnailTableView.selectedRowIndexes {
  1640. // [leftSideController.thumbnailTableView.selectedRowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  1641. if(idx < fristIndex) {
  1642. fristIndex = idx
  1643. }
  1644. if(idx > lastIndex) {
  1645. lastIndex = idx
  1646. }
  1647. }
  1648. if(rowIndex < fristIndex) {
  1649. fristIndex = rowIndex
  1650. } else if (rowIndex > lastIndex) {
  1651. lastIndex = rowIndex
  1652. }
  1653. var rowIndexSet = IndexSet()
  1654. for i in fristIndex ... lastIndex {
  1655. rowIndexSet.insert(i)
  1656. }
  1657. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1658. return true
  1659. }
  1660. }
  1661. return false
  1662. }
  1663. }
  1664. // MARK: - 扩展
  1665. extension KMLeftSideViewController {
  1666. public func selectType(_ type: BotaType) {
  1667. // 更新 type
  1668. var show = true
  1669. if (self.type.methodType == .None) {
  1670. show = true
  1671. } else {
  1672. if (self.type.methodType == type) {
  1673. show = false
  1674. } else {
  1675. show = true
  1676. }
  1677. }
  1678. var index: Int = NSNotFound
  1679. switch type {
  1680. case .None:
  1681. index = NSNotFound
  1682. break
  1683. case .Thumbnail:
  1684. index = 0
  1685. break
  1686. case .Outline:
  1687. index = 1
  1688. break
  1689. case .BookMark:
  1690. index = 2
  1691. break
  1692. case .Annotation:
  1693. index = 3
  1694. break
  1695. case .Search:
  1696. index = 4
  1697. break
  1698. case .From:
  1699. index = 5
  1700. break
  1701. case .Signature:
  1702. index = 6
  1703. break
  1704. case .snapshot:
  1705. index = 7
  1706. break
  1707. }
  1708. self.type = self.getMethodMode(show ? type : .None)
  1709. // 更新按钮状态
  1710. // self.updateViewButtonState()
  1711. // 将事件传递出去
  1712. self.delegate?.controlStateChange?(self,show:show)
  1713. if (index != NSNotFound) {
  1714. // 记录当前选中
  1715. UserDefaults.standard.set(index, forKey: "KMBOTASelectedIndexKey")
  1716. UserDefaults.standard.synchronize()
  1717. }
  1718. }
  1719. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  1720. let mode = KMLeftMethodMode()
  1721. mode.methodType = type
  1722. switch type {
  1723. case .None:
  1724. mode.methodName = ""
  1725. break
  1726. case .Thumbnail:
  1727. mode.methodName = thumbnailMethodKey
  1728. break
  1729. case .Outline:
  1730. mode.methodName = outlineMethodKey
  1731. break
  1732. case .BookMark:
  1733. mode.methodName = bookMarkMethodKey
  1734. break
  1735. case .Annotation:
  1736. mode.methodName = anntationMethodKey
  1737. break
  1738. case .Search:
  1739. mode.methodName = searchMethodKey
  1740. break
  1741. case .From:
  1742. mode.methodName = formMethodKey
  1743. break
  1744. case .Signature:
  1745. mode.methodName = signatureMethodKey
  1746. break
  1747. case .snapshot:
  1748. mode.methodName = snapshotMethodKey
  1749. }
  1750. return mode
  1751. }
  1752. }
  1753. //MARK: Cache
  1754. extension KMLeftSideViewController {
  1755. func clearAnnotationFilterData() {
  1756. if let _key = self.listView?.document?.documentURL?.path {
  1757. let userDefaults = UserDefaults.standard
  1758. let typeData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  1759. userDefaults.set(typeData, forKey: "KMNoteOutlineFilterSelectArray_Type" + _key)
  1760. let colorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  1761. userDefaults.set(colorData, forKey: "KMNoteOutlineFilterSelectArray_Color" + _key)
  1762. let authorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  1763. userDefaults.set(authorData, forKey: "KMNoteOutlineFilterSelectArray_Author" + _key)
  1764. userDefaults.synchronize()
  1765. }
  1766. }
  1767. func clearNotification() {
  1768. }
  1769. }
  1770. // MARK: - Analytics (埋点)
  1771. extension KMLeftSideViewController {
  1772. func trackEvent(type: BotaType) -> Void {
  1773. if (type == .Thumbnail) {
  1774. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Thumbnail", parameters: [
  1775. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1776. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1777. } else if (type == .Outline) {
  1778. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Outline", parameters: [
  1779. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1780. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1781. } else if (type == .BookMark) {
  1782. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_BookMark", parameters: [
  1783. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1784. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1785. } else if (type == .Annotation) {
  1786. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Annotation", parameters: [
  1787. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1788. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1789. } else if (type == .Search) {
  1790. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Search", parameters: [
  1791. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1792. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1793. }
  1794. }
  1795. }
  1796. // MARK: - Private Methods
  1797. extension KMLeftSideViewController {
  1798. @objc private func _themeChanged(_ notification: NSNotification) {
  1799. DispatchQueue.main.asyncAfter(deadline: .now()+0.3) {
  1800. self._updateViewColor()
  1801. }
  1802. }
  1803. private func _updateViewColor() {
  1804. if(KMAppearance.isDarkMode()){
  1805. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1806. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1807. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1808. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1809. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1810. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1811. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1812. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1813. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1814. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1815. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1816. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1817. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1818. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1819. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  1820. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  1821. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  1822. } else {
  1823. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1824. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1825. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1826. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1827. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1828. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1829. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1830. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1831. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1832. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1833. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1834. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1835. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1836. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1837. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  1838. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  1839. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  1840. }
  1841. }
  1842. private func _hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  1843. let label_low = outline.label.lowercased()
  1844. let searchString_low = searchString.lowercased()
  1845. if label_low.contains(searchString_low) {
  1846. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  1847. return true
  1848. } else {
  1849. var subHas = false
  1850. for i in 0 ..< outline.numberOfChildren {
  1851. if let subOutline = outline.child(at: i) {
  1852. subHas = self._hasContainString(searchString, rootOutline: subOutline)
  1853. } else {
  1854. continue
  1855. }
  1856. if (subHas) {
  1857. break
  1858. }
  1859. }
  1860. return subHas
  1861. }
  1862. return false
  1863. }
  1864. }
  1865. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  1866. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  1867. func numberOfRows(in tableView: NSTableView) -> Int {
  1868. if tableView.isEqual(to: self.thumbnailTableView) {
  1869. return self.thumbnails.count
  1870. } else if tableView.isEqual(to: self.findTableView) {
  1871. return self.searchResults.count
  1872. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1873. return self.groupSearchResults.count
  1874. } else if tableView.isEqual(to: self.snapshotTableView) {
  1875. if self.isSearchSnapshotMode {
  1876. return self.searchSnapshots.count
  1877. }
  1878. return self.snapshots.count
  1879. }
  1880. return 0
  1881. }
  1882. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  1883. if tableView.isEqual(to: self.thumbnailTableView) {
  1884. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMThumbnailTableviewCell"), owner: self) as! KMThumbnailTableviewCell
  1885. let thumbnail = self.thumbnails[row]
  1886. cell.pageNumLabel.stringValue = thumbnail.label
  1887. // cell.thumImage.image = thumbnail.image
  1888. cell.pageView.page = self.listView.document.page(at: UInt(row))
  1889. if let _image = thumbnail.image {
  1890. let multiplierHToW = _image.size.height / (_image.size.width == 0 ? 1 : _image.size.width)
  1891. let multiplierWToH = _image.size.width / (_image.size.height == 0 ? 1 : _image.size.height)
  1892. if (_image.size.height > _image.size.width) {
  1893. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  1894. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .height, relatedBy: .equal, toItem: cell.thumImage, attribute: .width, multiplier: multiplierHToW, constant: 0)
  1895. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  1896. } else {
  1897. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  1898. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .width, relatedBy: .equal, toItem: cell.thumImage, attribute: .height, multiplier: multiplierWToH, constant: 0)
  1899. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  1900. }
  1901. }
  1902. if (self.isDisplayPageSize) {
  1903. cell.sizeLabel.isHidden = false
  1904. //获取Page的真实尺寸
  1905. let page = self.listView.document.page(at: UInt(row))
  1906. let rect = page?.bounds(for: .cropBox) ?? .zero
  1907. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetWidth(rect)/595 * 210))
  1908. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetHeight(rect)/842 * 297))
  1909. if let data = page?.rotation, data == 90 || data == 270 {
  1910. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  1911. } else {
  1912. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  1913. }
  1914. } else {
  1915. cell.sizeLabel.isHidden = true
  1916. }
  1917. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  1918. if(self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  1919. cell.isSelectCell = true
  1920. } else {
  1921. cell.isSelectCell = false
  1922. }
  1923. return cell
  1924. } else if (tableView.isEqual(to: self.findTableView)) {
  1925. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMFindTableviewCell"), owner: self) as! KMFindTableviewCell
  1926. let selection = searchResults[row]
  1927. if let data = tableColumn?.identifier.rawValue, data == "results" {
  1928. cell.resultLabel.attributedStringValue = selection.attributedString
  1929. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  1930. } else if let data = tableColumn?.identifier.rawValue, data == "page" {
  1931. cell.resultLabel.stringValue = "\(Int(selection.selection.page?.pageIndex() ?? 0) + 1)"
  1932. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  1933. }
  1934. return cell
  1935. } else if tableView.isEqual(to: self.snapshotTableView) {
  1936. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMSnapshotTableViewCell"), owner: self) as! KMSnapshotTableViewCell
  1937. var snapshot: KMSnapshotModel?
  1938. if self.isSearchSnapshotMode {
  1939. snapshot = self.searchSnapshots[row]
  1940. } else {
  1941. snapshot = self.snapshots[row]
  1942. }
  1943. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  1944. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  1945. if let data = snapshot?.windowC?.hasWindow, data {
  1946. cell.snapshotImageView.isHidden = false
  1947. } else {
  1948. cell.snapshotImageView.isHidden = true
  1949. }
  1950. cell.isSelectCell = snapshot?.isSelected ?? false
  1951. if (row == tableView.selectedRow) {
  1952. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  1953. } else {
  1954. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  1955. }
  1956. return cell
  1957. }
  1958. return nil
  1959. }
  1960. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  1961. if tableView.isEqual(to: self.thumbnailTableView) {
  1962. let scaling = UserDefaults.standard.float(forKey: "KMThumbnailSizeScalingKey")
  1963. // let thumbnailSize = self.thumbnails[row].size
  1964. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  1965. let newScaling: CGFloat = scaling.cgFloat + 0.1
  1966. let newThumbnailHeight = thumbnailSize.width * newScaling
  1967. if (newThumbnailHeight > MIN_SIDE_PANE_WIDTH) {
  1968. self.thumbnailZoomOutButton.isEnabled = false
  1969. } else {
  1970. self.thumbnailZoomOutButton.isEnabled = true
  1971. }
  1972. if ((scaling - 0.1) < 0.3) {
  1973. self.thumbnailZoomInButton.isEnabled = false
  1974. } else {
  1975. self.thumbnailZoomInButton.isEnabled = true
  1976. }
  1977. var labelHeight = 0.0
  1978. if (self.isDisplayPageSize) {
  1979. labelHeight = 56.0
  1980. } else {
  1981. labelHeight = 41.5
  1982. }
  1983. let cellHeight = thumbnailSize.height + labelHeight
  1984. var thumbSize: NSSize = .zero
  1985. if (scaling != nil && scaling > 0) {
  1986. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1987. } else {
  1988. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  1989. }
  1990. return thumbSize.height
  1991. // NSSize cellSize = NSMakeSize([[tv tableColumnWithIdentifier:IMAGE_COLUMNID] width], fmin(thumbSize.height, roundedThumbnailSize));
  1992. // if (thumbSize.height < [tv rowHeight])
  1993. // return [tv rowHeight];
  1994. // else if (thumbSize.width / thumbSize.height < cellSize.width / cellSize.height)
  1995. // return cellSize.height;
  1996. // else
  1997. // return fmax([tv rowHeight], fmin(cellSize.width, thumbSize.width) * thumbSize.height / thumbSize.width);
  1998. } else if tableView.isEqual(to: self.snapshotTableView) {
  1999. let scaling = UserDefaults.standard.float(forKey: "KMSnapshotSizeScalingKey")
  2000. // NSSize snapshotSize = [[[[rightSideController.snapshotArrayController arrangedObjects] objectAtIndex:row] thumbnail] size];
  2001. let snapshotSize = CGSizeMake(120, 63)
  2002. var newScaling = scaling + 0.1
  2003. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat;
  2004. if (newSnapshotHeight > MIN_SIDE_PANE_WIDTH) {
  2005. self.snapshotNormalZoomInButton.isEnabled = false
  2006. } else {
  2007. self.snapshotNormalZoomInButton.isEnabled = true
  2008. }
  2009. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  2010. self.snapshotNormalZoomOutButton.isEnabled = false
  2011. } else {
  2012. self.snapshotNormalZoomOutButton.isEnabled = true
  2013. }
  2014. let cellHeight = snapshotSize.height + 24.0
  2015. var thumbSize: NSSize = .zero
  2016. if (scaling > 0) {
  2017. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  2018. } else {
  2019. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  2020. }
  2021. return thumbSize.height
  2022. } else if (tableView.isEqual(to: self.findTableView)) {
  2023. return 40.0
  2024. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2025. return 16
  2026. }
  2027. return tableView.rowHeight
  2028. }
  2029. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  2030. if (tableView.isEqual(to: self.findTableView)) {
  2031. let rowView = KMBotaTableRowView()
  2032. return rowView
  2033. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2034. let rowView = KMGroupFindTableRowView()
  2035. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  2036. let model = self.groupSearchResults[row]
  2037. rowView.number = model.datas.count
  2038. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  2039. return rowView
  2040. }
  2041. return nil
  2042. }
  2043. func tableViewSelectionIsChanging(_ notification: Notification) {
  2044. }
  2045. func tableViewSelectionDidChange(_ notification: Notification) {
  2046. // if ([[aNotification object] isEqual:leftSideController.findTableView] || [[aNotification object] isEqual:leftSideController.groupedFindTableView]) {
  2047. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  2048. //
  2049. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2050. // [self hideLeftSideWindow];
  2051. // } else
  2052. if self.findTableView.isEqual(to: notification.object) {
  2053. let row = self.findTableView.selectedRow
  2054. if row >= 0 {
  2055. let model = self.searchResults[row]
  2056. if model.selection != nil {
  2057. self.listView.go(to: model.selection, animated: true)
  2058. self.listView.setHighlightedSelection(model.selection, animated: true)
  2059. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2060. }
  2061. }
  2062. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  2063. // if (mwcFlags.updatingThumbnailSelection == 0) {
  2064. let row = self.thumbnailTableView.selectedRow
  2065. let curPage = self.listView.document.index(for: self.listView.currentPage())
  2066. if (row != -1 && row != curPage) {
  2067. // [pdfView goToPage:[[pdfView document] pageAtIndex:row]];
  2068. self.listView.go(toPageIndex: row, animated: true)
  2069. }
  2070. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2071. // [self hideLeftSideWindow];
  2072. // thumbnailSelectCount = row;
  2073. // var rowIndexSet = IndexSet()
  2074. // for i in 0 ..< self.thumbnailTableView.numberOfRows {
  2075. // rowIndexSet.insert(i)
  2076. // }
  2077. // self.thumbnailTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: IndexSet(integer: 0))
  2078. // }
  2079. let view = self.thumbnailTableView.view(atColumn: 0, row: self.preThumbnailRow, makeIfNecessary: false) as? KMThumbnailTableviewCell
  2080. view?.isSelectCell = false
  2081. let view2 = self.thumbnailTableView.view(atColumn: 0, row: row, makeIfNecessary: false) as? KMThumbnailTableviewCell
  2082. view2?.isSelectCell = true
  2083. self.preThumbnailRow = row
  2084. }
  2085. // else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2086. // NSInteger row = [rightSideController.snapshotTableView selectedRow];
  2087. // [selectCellList removeAllObjects];
  2088. // [selectCellList addObject:[NSString stringWithFormat:@"%ld",row]];
  2089. // if (row != -1) {
  2090. // SKSnapshotWindowController *controller = [[rightSideController.snapshotArrayController arrangedObjects] objectAtIndex:row];
  2091. // if ([[controller window] isVisible])
  2092. // [[controller window] orderFront:self];
  2093. // }
  2094. // NSMutableIndexSet *rowIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2095. // for (NSInteger i = 0; i < rightSideController.snapshotTableView.numberOfRows; i ++) {
  2096. // [rowIndexSet addIndex:i];
  2097. // }
  2098. // NSMutableIndexSet *columnIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2099. // [columnIndexSet addIndex:0];
  2100. // [rightSideController.snapshotTableView reloadDataForRowIndexes:rowIndexSet columnIndexes:columnIndexSet];
  2101. //
  2102. // }
  2103. }
  2104. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  2105. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  2106. return NSDragOperation(rawValue: 0)
  2107. }
  2108. let pboard = info.draggingPasteboard
  2109. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  2110. return .move
  2111. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  2112. guard let pbItems = pboard.pasteboardItems else {
  2113. return NSDragOperation(rawValue: 0)
  2114. }
  2115. // guard let _allowedFileTypes = self.kmAllowedFileTypes else {
  2116. // return .generic
  2117. // }
  2118. var hasValidFile = false
  2119. for item in pbItems {
  2120. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  2121. continue
  2122. }
  2123. let type = _url.pathExtension.lowercased()
  2124. // if (_allowedFileTypes.contains(type)) {
  2125. hasValidFile = true
  2126. // break
  2127. // }
  2128. }
  2129. if (!hasValidFile) {
  2130. return NSDragOperation(rawValue: 0)
  2131. }
  2132. }
  2133. return NSDragOperation(rawValue: 0)
  2134. }
  2135. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  2136. var result = false
  2137. if tableView.isEqual(to: self.thumbnailTableView) == false {
  2138. return result
  2139. }
  2140. // let pasteboard = info.draggingPasteboard
  2141. //
  2142. // if pasteboard.availableType(from: [.localDraggedTypes]) {
  2143. // result = true
  2144. // let rowData = pasteboard.data(forType: .localDraggedTypes)
  2145. // let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData!)
  2146. // NSData *urlData = [pasteboard dataForType:KPDFThumbnailDoucumentURLForDraggedTypes];
  2147. // NSString *url = [NSKeyedUnarchiver unarchiveObjectWithData:urlData];
  2148. // if(![url isEqualToString:[pdfView document].documentURL.absoluteString] && url) {
  2149. // if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]){
  2150. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2151. // if (fileNames.count == 1) {
  2152. // NSString *path = fileNames.firstObject;
  2153. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2154. // if ([pathExtension isEqualToString:@"pdf"]) {
  2155. // __block NSInteger index = row;
  2156. // __block NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2157. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]] autorelease];
  2158. // if ([pdf isEncrypted]) {
  2159. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2160. // vc.filePath = url;
  2161. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2162. // if (password) {
  2163. // [pdf unlockWithPassword:password];
  2164. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2165. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2166. // [self.pdfView.document insertPage:page atIndex:index];
  2167. // [insertIndexSet addIndex:index];
  2168. // index++;
  2169. // [page release];
  2170. // }
  2171. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2172. // }
  2173. // }];
  2174. // [vc release];
  2175. // } else {
  2176. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2177. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2178. // [self.pdfView.document insertPage:page atIndex:index];
  2179. // [insertIndexSet addIndex:index];
  2180. // index++;
  2181. // [page release];
  2182. // }
  2183. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2184. // }
  2185. // return YES;
  2186. // }
  2187. // }
  2188. // }
  2189. // }
  2190. // __block NSInteger pageIndex = 0;
  2191. // __block NSMutableArray *pages = [NSMutableArray array];
  2192. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2193. // PDFPage *page = [[[pdfView document] pageAtIndex:idx] copy];
  2194. // [pages addObject:page];
  2195. // [page release];
  2196. // }];
  2197. // PDFPage *toPage = nil;
  2198. // if (row < (NSInteger)pdfView.document.pageCount) {
  2199. // toPage = [pdfView.document pageAtIndex:row];
  2200. // }
  2201. // __block NSInteger toPageIndex = 0;
  2202. // if (toPage) {
  2203. // toPageIndex = [pdfView.document indexForPage:toPage];
  2204. // } else {
  2205. // toPageIndex = pdfView.document.pageCount;
  2206. // }
  2207. // for(NSUInteger i = 0;i<pages.count;i++) {
  2208. // PDFPage *page = pages[i];
  2209. // [pdfView.document insertPage:page atIndex:toPageIndex+i];
  2210. // pageIndex += 1;
  2211. // [self.pdfView goToPage:page];
  2212. // }
  2213. // [self.pdfView layoutDocumentView];
  2214. // __block NSMutableArray *deletepages = [NSMutableArray array];
  2215. // [rowIndexes enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2216. // if((NSInteger)idx < toPageIndex) {
  2217. // if((idx+pageIndex) < pdfView.document.pageCount) {
  2218. // PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2219. // [deletepages addObject:page];
  2220. // [pdfView.document removePageAtIndex:idx];
  2221. // }
  2222. // } else {
  2223. // if((idx+pageIndex) < pdfView.document.pageCount) {
  2224. // PDFPage *page = [[pdfView document] pageAtIndex:idx+pageIndex];
  2225. // [deletepages addObject:page];
  2226. // [pdfView.document removePageAtIndex:idx+pageIndex];
  2227. // }
  2228. // }
  2229. // }];
  2230. // [[[[self document] undoManager] prepareWithInvocationTarget:self] undoClick];
  2231. // [self.pageLabels setArray:[[self.pdfView document] pageLabels]];
  2232. // [self.pdfView layoutDocumentView];
  2233. // [self resetThumbnails];
  2234. //
  2235. // } else if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]] && [tableView isEqual:leftSideController.thumbnailTableView]) {
  2236. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2237. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2238. //
  2239. // return NO;
  2240. // }
  2241. //
  2242. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2243. // NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2244. // __block NSInteger index = row;
  2245. //
  2246. // if (fileNames.count == 1) {
  2247. // NSString *path = fileNames.firstObject;
  2248. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2249. // if ([pathExtension isEqualToString:@"pdf"]) {
  2250. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]]autorelease];
  2251. // if ([pdf isEncrypted]) {
  2252. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2253. // vc.filePath = path;
  2254. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2255. // if (password) {
  2256. // [pdf unlockWithPassword:password];
  2257. // for (NSUInteger i = 0; i< pdf.pageCount; i++) {
  2258. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2259. // [self.pdfView.document insertPage:page atIndex:index];
  2260. // [insertIndexSet addIndex:index];
  2261. // index++;
  2262. // [page release];
  2263. // }
  2264. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2265. // }
  2266. // }];
  2267. // [vc release];
  2268. // } else {
  2269. // for (NSUInteger i = 0; i < pdf.pageCount; i++) {
  2270. // PDFPage * page = [[pdf pageAtIndex:i] copy];
  2271. // [self.pdfView.document insertPage:page atIndex:index];
  2272. // [insertIndexSet addIndex:index];
  2273. // index++;
  2274. // [page release];
  2275. // }
  2276. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2277. //
  2278. // }
  2279. // } else if ([[KMImageToPDFMethod supportedImageTypes] containsObject:pathExtension]) {
  2280. // NSImage *image = [[[NSImage alloc] initWithContentsOfFile:path] autorelease];
  2281. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  2282. // [pdfView.document insertPage:page atIndex:index];
  2283. // [insertIndexSet addIndex:index];
  2284. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2285. // }
  2286. // result = YES;
  2287. // } else {
  2288. // result = NO;
  2289. // }
  2290. // }
  2291. return result == false
  2292. }
  2293. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  2294. if tableView.isEqual(to: self.thumbnailTableView) {
  2295. // let idx = rowIndexes.first
  2296. // if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2297. // PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2298. // NSString *fileExt = nil;
  2299. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2300. //
  2301. // if ([[pdfView document] allowsPrinting]) {
  2302. // NSData *pdfData = [page dataRepresentation];
  2303. // fileExt = @"pdf";
  2304. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypePDF, NSPasteboardTypeTIFF,NSFilenamesPboardType, NSFilesPromisePboardType, KPDFThumbnailLocalForDraggedTypes,KPDFThumbnailDoucumentURLForDraggedTypes,nil] owner:self];
  2305. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  2306. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  2307. // [pboard setData:zNSIndexSetData forType:KPDFThumbnailLocalForDraggedTypes];
  2308. // NSData *documentURL = [NSKeyedArchiver archivedDataWithRootObject:[[pdfView document].documentURL absoluteString]];
  2309. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  2310. // __block NSMutableString *pagesName = nil;
  2311. // if (rowIndexes.count > 1) {
  2312. // pagesName = [NSMutableString stringWithString:@" pages"];
  2313. //
  2314. // } else {
  2315. // pagesName = [NSMutableString stringWithString:@" page"];
  2316. //
  2317. // }
  2318. // NSString * tFileName = [NSString stringWithFormat:@"%@ %@",pagesName,[self fileNameWithSelectedPages:rowIndexes]];
  2319. // PDFDocument * pdf = [[[PDFDocument alloc] init] autorelease];
  2320. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2321. // PDFPage *copyPage = [[pdfView.document pageAtIndex:idx] copy];
  2322. // [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2323. // [copyPage release];
  2324. // }];
  2325. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2326. // NSString *cachesDir = [paths objectAtIndex:0];
  2327. // docmentName = [NSString stringWithFormat:@"%@%@",docmentName,tFileName];
  2328. // if (docmentName.length > 50) {
  2329. // [docmentName substringWithRange:NSMakeRange(0, 50)];
  2330. // }
  2331. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  2332. //
  2333. // BOOL success = [pdf writeToFile:cachesDir];
  2334. // if (success) {
  2335. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  2336. // }else{
  2337. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  2338. // }
  2339. // [pboard setData:documentURL forType:KPDFThumbnailDoucumentURLForDraggedTypes];
  2340. // } else {
  2341. // fileExt = @"tiff";
  2342. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2343. // }
  2344. // [pboard setData:tiffData forType:NSPasteboardTypeTIFF];
  2345. // [pboard setPropertyList:[NSArray arrayWithObject:fileExt] forType:NSFilesPromisePboardType];
  2346. let data: Data = try! NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  2347. pboard.declareTypes([.localDraggedTypes], owner: self)
  2348. pboard.setData(data, forType: .localDraggedTypes)
  2349. return true
  2350. // }
  2351. }
  2352. // else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2353. // NSUInteger idx = [rowIndexes firstIndex];
  2354. // if (idx != NSNotFound) {
  2355. // SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2356. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2357. // [pboard setData:[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] forType:NSPasteboardTypeTIFF];
  2358. // [pboard setPropertyList:[NSArray arrayWithObject:@"tiff"] forType:NSFilesPromisePboardType];
  2359. // return YES;
  2360. // }
  2361. // }
  2362. return false
  2363. }
  2364. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  2365. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2366. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2367. // return;
  2368. // }
  2369. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  2370. // NSArray *controllers = [[rightSideController.snapshotArrayController arrangedObjects] objectsAtIndexes:rowIndexes];
  2371. // [controllers makeObjectsPerformSelector:@selector(close)];
  2372. // } else
  2373. if aTableView.isEqual(to: self.thumbnailTableView) {
  2374. for idx in rowIndexes {
  2375. if idx >= self.listView.document.pageCount {
  2376. return
  2377. }
  2378. if let page = self.listView.document.page(at: UInt(idx)) {
  2379. for anno in page.annotations {
  2380. page.removeAnnotation(anno)
  2381. }
  2382. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  2383. self.listView.document.removePage(at: IndexSet(integer: idx))
  2384. }
  2385. }
  2386. self.listView.layoutDocumentView()
  2387. // [pageLabels setArray:[[pdfView document] pageLabels]];
  2388. self.resetThumbnails()
  2389. let idx = rowIndexes.first ?? -1
  2390. let index = min(idx, Int(self.listView.document.pageCount)-1)
  2391. self.listView.go(toPageIndex: index, animated: false)
  2392. }
  2393. }
  2394. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  2395. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  2396. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2397. // return;
  2398. // }
  2399. if aTableView.isEqual(to: self.thumbnailTableView) {
  2400. self._copysPages.removeAll()
  2401. if self.listView.document.isLocked == false {
  2402. for idx in rowIndexes {
  2403. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  2404. self._copysPages.append(page)
  2405. }
  2406. }
  2407. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2408. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2409. // NSPasteboardItem *pboardItem = [[[NSPasteboardItem alloc] init] autorelease];
  2410. // if ([[pdfView document] allowsPrinting])
  2411. // [pboardItem setData:[page dataRepresentation] forType:NSPasteboardTypePDF];
  2412. // [pboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
  2413. // [pboard clearContents];
  2414. // [pboard writeObjects:[NSArray arrayWithObjects:pboardItem, nil]];
  2415. }
  2416. }
  2417. // else if ([tv isEqual:leftSideController.findTableView]) {
  2418. // NSMutableString *string = [NSMutableString string];
  2419. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2420. // PDFSelection *match = [searchResults objectAtIndex:idx];
  2421. // [string appendString:@"* "];
  2422. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  2423. // [string appendFormat:@": %@\n", [[match contextString] string]];
  2424. // }];
  2425. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2426. // [pboard clearContents];
  2427. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2428. // } else if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2429. // NSMutableString *string = [NSMutableString string];
  2430. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2431. // SKGroupedSearchResult *result = [groupedSearchResults objectAtIndex:idx];
  2432. // NSArray *matches = [result matches];
  2433. // [string appendString:@"* "];
  2434. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [[result page] displayLabel]];
  2435. // [string appendString:@": "];
  2436. // [string appendFormat:NSLocalizedString(@"%ld Results", @""), (long)[matches count]];
  2437. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  2438. // }];
  2439. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2440. // [pboard clearContents];
  2441. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2442. // }
  2443. }
  2444. /*
  2445. #pragma mark dragging
  2446. - (NSArray *)tableView:(NSTableView *)tv namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2447. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2448. __block NSMutableArray *fileURLArray = [NSMutableArray array];
  2449. if (rowIndexes.count > 1) {
  2450. NSString *docmentName = @"";
  2451. NSString * tFileName = [NSString stringWithFormat:@"%@",[self fileNameWithSelectedPages:rowIndexes]];
  2452. PDFDocument *pdf = [[[PDFDocument alloc] init] autorelease];
  2453. [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2454. if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2455. PDFPage *copyPage = [[[pdfView document] pageAtIndex:idx] copy];
  2456. [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2457. [copyPage release];
  2458. }
  2459. }];
  2460. NSURL *fileURL = [[[dropDestination URLByAppendingPathComponent:tFileName] URLByAppendingPathExtension:@"pdf"] uniqueFileURL];
  2461. docmentName = fileURL.path;
  2462. BOOL success = [pdf writeToFile:docmentName];
  2463. if(success) {
  2464. [fileURLArray addObject:[fileURL lastPathComponent]];
  2465. }
  2466. } else {
  2467. PDFPage *page = [[pdfView document] pageAtIndex:rowIndexes.firstIndex];
  2468. NSURL *fileURL = [dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]];
  2469. NSString *pathExt = nil;
  2470. NSData *data = nil;
  2471. if ([[pdfView document] allowsPrinting]) {
  2472. pathExt = @"pdf";
  2473. data = [page dataRepresentation];
  2474. } else {
  2475. pathExt = @"tiff";
  2476. data = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2477. }
  2478. fileURL = [[fileURL URLByAppendingPathExtension:pathExt] uniqueFileURL];
  2479. if ([data writeToURL:fileURL atomically:YES]) {
  2480. [fileURLArray addObject:[fileURL lastPathComponent]];
  2481. }
  2482. }
  2483. return fileURLArray;
  2484. } else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2485. NSUInteger idx = [rowIndexes firstIndex];
  2486. if (idx != NSNotFound) {
  2487. SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2488. PDFPage *page = [[pdfView document] pageAtIndex:[snapshot pageIndex]];
  2489. NSURL *fileURL = [[dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]] URLByAppendingPathExtension:@"tiff"];
  2490. fileURL = [fileURL uniqueFileURL];
  2491. if ([[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] writeToURL:fileURL atomically:YES])
  2492. return [NSArray arrayWithObjects:[fileURL lastPathComponent], nil];
  2493. }
  2494. }
  2495. return [NSArray array];
  2496. }
  2497. - (void)tableView:(NSTableView *)tv sortDescriptorsDidChange:(NSArray *)oldDescriptors {
  2498. if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2499. [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  2500. }
  2501. }
  2502. #pragma mark NSTableView delegate protocol
  2503. - (void)tableViewColumnDidResize:(NSNotification *)aNotification {
  2504. if ([[[[aNotification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:IMAGE_COLUMNID]) {
  2505. if ([[aNotification object] isEqual:leftSideController.thumbnailTableView]) {
  2506. [leftSideController.thumbnailTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [leftSideController.thumbnailTableView numberOfRows])]];
  2507. } else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2508. [rightSideController.snapshotTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.snapshotTableView numberOfRows])]];
  2509. }
  2510. }
  2511. }
  2512. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2513. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2514. NSUInteger idx = [rowIndexes firstIndex];
  2515. if (idx != NSNotFound) {
  2516. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2517. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  2518. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  2519. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  2520. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  2521. [self fileWithPage:page atPath:filePath];
  2522. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  2523. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  2524. } else {
  2525. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  2526. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  2527. }
  2528. }
  2529. }
  2530. }
  2531. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  2532. NSData *data = [page dataRepresentation];
  2533. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  2534. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  2535. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  2536. if (success) {
  2537. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  2538. NSURL *url = [NSURL fileURLWithPath:filePath];
  2539. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  2540. }
  2541. [document release];
  2542. */
  2543. }
  2544. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  2545. /*
  2546. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  2547. if item is KMBOTAAnnotationSection {
  2548. let section = item as? KMBOTAAnnotationSection
  2549. return section!.annotations?[index] as Any
  2550. } else if item is KMBOTAAnnotationItem {
  2551. return item as Any
  2552. } else {
  2553. var tempArray: [KMBOTAAnnotationSection] = []
  2554. for temp in self.data {
  2555. if temp.annotations?.count != 0 {
  2556. tempArray.append(temp)
  2557. }
  2558. }
  2559. let section = tempArray[index]
  2560. return section as Any
  2561. }
  2562. }
  2563. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  2564. if item is KMBOTAAnnotationItem {
  2565. let cell : KMAnnotationOutlineCellView = KMAnnotationOutlineCellView.init()
  2566. cell.delegate = self
  2567. cell.model = item as? KMBOTAAnnotationItem
  2568. return cell
  2569. } else if item is KMBOTAAnnotationSection {
  2570. let section = item as? KMBOTAAnnotationSection
  2571. let cell : KMAnnotationOutlineSectionView = KMAnnotationOutlineSectionView.init()
  2572. cell.model = section
  2573. return cell
  2574. }
  2575. return NSTableCellView()
  2576. }
  2577. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2578. let rowView = KMAnnotationOutlineRowView()
  2579. if item is KMBOTAAnnotationItem {
  2580. rowView.model = (item as? KMBOTAAnnotationItem)
  2581. } else if item is KMBOTAAnnotationSection {
  2582. rowView.section = (item as? KMBOTAAnnotationSection)
  2583. }
  2584. rowView.mouseDownAction = { [unowned self] view, event in
  2585. if rowView.section != nil {
  2586. let expanded = outlineView.isItemExpanded(outlineView.item(atRow: outlineView.selectedRow))
  2587. if expanded {
  2588. outlineView.collapseItem(outlineView.item(atRow: outlineView.selectedRow), collapseChildren: true)
  2589. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2590. } else {
  2591. outlineView.expandItem(outlineView.item(atRow: outlineView.selectedRow), expandChildren: true)
  2592. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2593. }
  2594. } else if rowView.model != nil {
  2595. self.didSelectItem(view: rowView, event: event)
  2596. }
  2597. }
  2598. rowView.rightMouseDownAction = { [unowned self] view, event in
  2599. if rowView.section != nil {
  2600. } else if rowView.model != nil {
  2601. if !KMOCToolClass.arrayContains(array: self.selectItems, annotation: item) ||
  2602. self.selectItems.count == 1 {
  2603. self.selectItem(item: item as! KMBOTAAnnotationItem)
  2604. }
  2605. DispatchQueue.main.async {
  2606. self.delegate?.annotationOutlineView(self, rightMouseDownDidSelectView: view, evnet: event)
  2607. }
  2608. }
  2609. }
  2610. rowView.hoverCallback = { [unowned self] (mouseEntered, mouseBox) in
  2611. self.outlineView.enumerateAvailableRowViews { view, row in
  2612. if view is KMAnnotationOutlineRowView {
  2613. (view as? KMAnnotationOutlineRowView)?.model?.hover = false
  2614. (view as? KMAnnotationOutlineRowView)?.reloadData()
  2615. }
  2616. }
  2617. if mouseEntered {
  2618. rowView.model?.hover = true
  2619. } else {
  2620. rowView.model?.hover = false
  2621. }
  2622. }
  2623. return rowView
  2624. }
  2625. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2626. if item is KMBOTAAnnotationItem {
  2627. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: self.maxWidth - 16, height: 1000))
  2628. } else if item is KMBOTAAnnotationSection {
  2629. return 40
  2630. } else {
  2631. return 30
  2632. }
  2633. }
  2634. func outlineViewSelectionDidChange(_ notification: Notification) {
  2635. if self.outlineView.selectedRow == -1 {
  2636. self.cancelSelect()
  2637. }
  2638. }
  2639. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2640. if item is KMBOTAAnnotationItem {
  2641. return false
  2642. } else if item is KMBOTAAnnotationSection {
  2643. let section = item as? KMBOTAAnnotationSection
  2644. return section!.annotations?.count ?? 0 > 0
  2645. }
  2646. return false
  2647. }
  2648. func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
  2649. if let item = item as? KMBOTAAnnotationSection {
  2650. if !item.isItemExpanded {
  2651. item.isItemExpanded = true
  2652. outlineView.animator().expandItem(item, expandChildren: true)
  2653. return false
  2654. }
  2655. }
  2656. return true
  2657. }
  2658. func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
  2659. if let item = item as? KMBOTAAnnotationSection {
  2660. if item.isItemExpanded {
  2661. item.isItemExpanded = false
  2662. outlineView.animator().collapseItem(item, collapseChildren: true)
  2663. return false
  2664. }
  2665. }
  2666. return true
  2667. }
  2668. */
  2669. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  2670. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  2671. if outlineView.isEqual(to: self.tocOutlineView) {
  2672. let isLocked = self.listView.document?.isLocked ?? true
  2673. if isLocked { // 文档不存在 或 已加锁
  2674. return 0
  2675. }
  2676. if item == nil { // 第一层
  2677. // 获取根
  2678. guard let outline = self.listView.document.outlineRoot() else {
  2679. let view = self.tocOutlineView.enclosingScrollView!
  2680. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2681. //
  2682. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  2683. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2684. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2685. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  2686. return 0
  2687. }
  2688. if outline.numberOfChildren == 0 {
  2689. // return 0
  2690. }
  2691. if self.isSearchOutlineMode { // 是否为搜索模块
  2692. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: outline) {
  2693. self.showSearchOutlineBlankState(false)
  2694. } else {
  2695. self.showSearchOutlineBlankState(true)
  2696. return 0
  2697. }
  2698. } else {
  2699. if outline.numberOfChildren > 0 { // 有数据
  2700. self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  2701. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  2702. } else { // 没有数据
  2703. let view = self.tocOutlineView.enclosingScrollView!
  2704. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2705. //
  2706. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  2707. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2708. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2709. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  2710. return 0
  2711. }
  2712. }
  2713. // 搜索按钮
  2714. if outline.numberOfChildren > 0 {
  2715. self.outlineSearchButton.isEnabled = true
  2716. } else {
  2717. self.outlineSearchButton.isEnabled = false
  2718. }
  2719. if (self.isSearchOutlineMode) {
  2720. var num = 0
  2721. for i in 0 ..< outline.numberOfChildren {
  2722. if let child = outline.child(at: i) {
  2723. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  2724. num += 1
  2725. }
  2726. }
  2727. }
  2728. return num
  2729. } else {
  2730. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  2731. var bookmarkNum = 0
  2732. if array.isEmpty == false {
  2733. bookmarkNum = 1
  2734. }
  2735. return Int(outline.numberOfChildren) + bookmarkNum
  2736. }
  2737. } else { // 第二层 +
  2738. if self.isSearchOutlineMode {
  2739. if let data = item as? String, data == "Bookmarks" { // 书签group
  2740. return 0
  2741. } else if item is CPDFOutline { // 大纲
  2742. let child = item as! CPDFOutline
  2743. if child.numberOfChildren == 0 {
  2744. return 0
  2745. }
  2746. var num = 0
  2747. for i in 0 ..< child.numberOfChildren {
  2748. if let _child = child.child(at: i) {
  2749. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: _child) {
  2750. num += 1
  2751. }
  2752. }
  2753. }
  2754. return num
  2755. } else if item is CPDFBookmark { // 书签
  2756. return 0
  2757. }
  2758. } else {
  2759. if let data = item as? String, data == "Bookmarks" { // 书签group
  2760. return (self.listView.document?.bookmarks().count) ?? 0
  2761. } else if item is CPDFOutline { // 大纲
  2762. return Int((item as? CPDFOutline)?.numberOfChildren ?? 0)
  2763. } else if item is CPDFBookmark { // 书签
  2764. return 0
  2765. }
  2766. }
  2767. }
  2768. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2769. var count = 0
  2770. for section in self._annotations {
  2771. if section.annotations?.count != 0 {
  2772. count += section.annotations!.count
  2773. }
  2774. }
  2775. // if (item == nil){
  2776. // NSInteger count = [[rightSideController.noteArrayController arrangedObjects] count];
  2777. if (count < 1) {
  2778. // if (notes.count < 1) {
  2779. self.noteSearchButton.isEnabled = false
  2780. self.noteFilterButton.isEnabled = false
  2781. // }
  2782. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  2783. let view = self.noteOutlineView.enclosingScrollView!
  2784. var emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  2785. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  2786. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2787. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  2788. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  2789. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  2790. //
  2791. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  2792. self.noteHeaderView.isHidden = true
  2793. self.toolButtonBoxLayoutConstraint.constant = 40.0
  2794. }
  2795. } else {
  2796. self.noteSearchButton.isEnabled = true
  2797. self.noteFilterButton.isEnabled = true
  2798. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  2799. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  2800. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  2801. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  2802. //
  2803. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  2804. self.noteHeaderView.isHidden = false
  2805. self.toolButtonBoxLayoutConstraint.constant = 64.0
  2806. }
  2807. }
  2808. return count;
  2809. // } else {
  2810. // return [item hasNoteText];
  2811. // }
  2812. }
  2813. return 0
  2814. }
  2815. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  2816. if outlineView.isEqual(to: self.tocOutlineView) {
  2817. let isLocked = self.listView.document?.isLocked ?? true
  2818. if isLocked { // 文档不存在 或 已加锁
  2819. return ""
  2820. }
  2821. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  2822. var bookmarkNum = 0
  2823. if array.isEmpty == false {
  2824. bookmarkNum = 1
  2825. }
  2826. if item == nil {
  2827. if self.isSearchOutlineMode {
  2828. guard let outline = self.listView.document.outlineRoot() else {
  2829. return ""
  2830. }
  2831. if outline.numberOfChildren == 0 {
  2832. return ""
  2833. }
  2834. var array: [CPDFOutline] = []
  2835. for i in 0 ..< outline.numberOfChildren {
  2836. if let child = outline.child(at: i) {
  2837. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  2838. array.append(child)
  2839. }
  2840. }
  2841. }
  2842. if index < array.count {
  2843. return array[index]
  2844. }
  2845. return ""
  2846. } else {
  2847. if index == 0 && bookmarkNum == 1 {
  2848. return "Bookmarks"
  2849. } else {
  2850. var _index = bookmarkNum == 1 ? index-1 : index
  2851. let outline = self.listView.document.outlineRoot()
  2852. var obj = outline?.child(at: UInt(_index))
  2853. return obj as Any
  2854. }
  2855. }
  2856. } else {
  2857. if let data = item as? String, data == "Bookmarks" {
  2858. return array[index]
  2859. } else if item is CPDFOutline {
  2860. return (item as! CPDFOutline).child(at: UInt(index))
  2861. } else if item is CPDFBookmark {
  2862. return ""
  2863. }
  2864. }
  2865. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2866. // if (item == nil)
  2867. // {
  2868. // return [[rightSideController.noteArrayController arrangedObjects] objectAtIndex:anIndex];
  2869. // // return [self.notes objectAtIndex:anIndex];
  2870. // }
  2871. // else
  2872. // return [item noteText];
  2873. var tempArray: [KMBOTAAnnotationItem] = []
  2874. for secion in self._annotations {
  2875. if secion.annotations?.count != 0 {
  2876. for _item in secion.annotations! {
  2877. tempArray.append(_item)
  2878. }
  2879. }
  2880. }
  2881. return tempArray[index] as Any
  2882. }
  2883. return item
  2884. }
  2885. func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
  2886. if outlineView.isEqual(to: self.tocOutlineView) {
  2887. // let tcID = tableColumn?.identifier.rawValue ?? ""
  2888. // var ol = item as? CPDFOutline
  2889. // if(tcID == LABEL_COLUMNID) {
  2890. // if (self.isSearchOutlineMode) {
  2891. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  2892. //// NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  2893. //// NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  2894. //// for (NSUInteger i = 0; i <arr.count ; i++) {
  2895. //// NSValue * rangeValue = arr[i];
  2896. //// NSRange range = rangeValue.rangeValue;
  2897. //// range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  2898. //// [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  2899. //// }
  2900. //// [attributeString addAttribute:NSForegroundColorAttributeName value:[KMAppearance KMColor_Layout_H0] range:NSMakeRange(0, roughString.length)];
  2901. //// return attributeString;
  2902. // } else {
  2903. // var attributedString = NSMutableAttributedString()
  2904. //// attributedString
  2905. // attributedString.append(.init(string: ol?.label ?? "", attributes: [.foregroundColor : KMAppearance.Layout.h0Color()]))
  2906. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  2907. //// NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2908. //// NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  2909. //// [attributedString appendAttributedString:attr1];
  2910. //
  2911. // return attributedString
  2912. // }
  2913. //
  2914. // }
  2915. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  2916. // NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2917. // NSString *roughString = [ol pageLabel]? : @"";
  2918. // NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2919. // NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  2920. // [attributedString appendAttributedString:attr1];
  2921. //
  2922. // return attributedString;
  2923. // }
  2924. }
  2925. // else if ([ov isEqual:rightSideController.noteOutlineView]) {
  2926. // NSString *tcID = [tableColumn identifier];
  2927. // PDFAnnotation *note = item;
  2928. // if (tableColumn == nil || [tcID isEqualToString:NOTE_COLUMNID])
  2929. // return [note objectValue];
  2930. // else if([tcID isEqualToString:TYPE_COLUMNID]){
  2931. // NSString *noteType = [note type];
  2932. // if ([note isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  2933. // PDFAnnotationButtonWidget *buttonWidget = (PDFAnnotationButtonWidget *)note;
  2934. // if (buttonWidget.controlType == kPDFWidgetRadioButtonControl) {
  2935. // noteType = SKAnnotationFormRadioButtonKey;
  2936. // } else if (buttonWidget.controlType == kPDFWidgetCheckBoxControl){
  2937. // noteType = SKAnnotationFormCheckBoxKey;
  2938. // } else if (buttonWidget.controlType == kPDFWidgetPushButtonControl){
  2939. // noteType = SKAnnotationFormActionButtonKey;
  2940. // }
  2941. // } else if ([note isKindOfClass:[PDFAnnotationTextWidget class]]){
  2942. // noteType = SKAnnotationFormTextFieldKey;
  2943. // } else if ([note isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  2944. // PDFAnnotationChoiceWidget *choiceWidget = (PDFAnnotationChoiceWidget *)note;
  2945. // if (choiceWidget.isListChoice) {
  2946. // noteType = SKAnnotationFormListMenuKey;
  2947. // } else {
  2948. // noteType = SKAnnotationFormComboBoxKey;
  2949. // }
  2950. //
  2951. // }
  2952. // return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:note == [pdfView activeAnnotation]], SKAnnotationTypeImageCellActiveKey, noteType, SKAnnotationTypeImageCellTypeKey,[note color],SKAnnotationTypeImageCellColorKey, nil];
  2953. // }
  2954. // else if([tcID isEqualToString:COLOR_COLUMNID])
  2955. // return [note type] ? [note color] : nil;
  2956. // else if([tcID isEqualToString:PAGE_COLUMNID])
  2957. // return [[note page] displayLabel];
  2958. // else if([tcID isEqualToString:AUTHOR_COLUMNID])
  2959. // return [note type] ? [note userName] : nil;
  2960. // else if([tcID isEqualToString:DATE_COLUMNID])
  2961. // return [note type] ? [note modificationDate] : nil;
  2962. // }
  2963. return nil
  2964. }
  2965. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  2966. if outlineView.isEqual(to: self.tocOutlineView) {
  2967. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMTocTableCellView"), owner: self) as! KMTocTableCellView
  2968. let tcID = tableColumn?.identifier.rawValue
  2969. var title = ""
  2970. var pageLabel = ""
  2971. if let data = item as? String, data == "Bookmarks" {
  2972. title = NSLocalizedString("Bookmarks", comment: "")
  2973. } else if item is CPDFOutline {
  2974. title = (item as! CPDFOutline).label
  2975. pageLabel = "\(((item as! CPDFOutline).destination?.pageIndex ?? 0) + 1)"
  2976. } else if item is CPDFBookmark {
  2977. title = (item as! CPDFBookmark).label
  2978. pageLabel = "\((item as! CPDFBookmark).pageIndex + 1)"
  2979. }
  2980. if tcID == LABEL_COLUMNID {
  2981. if (self.isSearchOutlineMode) {
  2982. // NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines];
  2983. let roughString = title
  2984. // NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  2985. // NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  2986. //
  2987. // for (NSUInteger i = 0; i <arr.count ; i++) {
  2988. // NSValue * rangeValue = arr[i];
  2989. // NSRange range = rangeValue.rangeValue;
  2990. // range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  2991. // [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  2992. // }
  2993. // cell.tocLabel.attributedStringValue = attributeString;
  2994. cell.tocLabel.stringValue = title
  2995. } else {
  2996. cell.tocLabel.stringValue = title
  2997. }
  2998. cell.pageLabel.stringValue = pageLabel
  2999. }
  3000. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3001. // cell.pageLabel.stringValue = [ol pageLabel];
  3002. // }
  3003. return cell
  3004. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3005. let model = item as! KMBOTAAnnotationItem
  3006. let note = (item as! KMBOTAAnnotationItem).annotation!
  3007. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMNoteTableViewCell"), owner: self) as! KMNoteTableViewCell
  3008. cell.cellNote = note
  3009. let noteColor = note.color
  3010. var noteType = note.type ?? ""
  3011. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  3012. // NSString *pageString = [[note page] displayLabel] ? : @"";
  3013. var pageString = "\((note.page?.pageIndex() ?? 0) + 1)"
  3014. let formatter = DateFormatter()
  3015. formatter.dateFormat = "hh:mm"
  3016. var dateString = ""
  3017. if let date = note.modificationDate() {
  3018. dateString = formatter.string(from: date)
  3019. }
  3020. var authorString = note.userName() ?? ""
  3021. // NSString *noteTextString = [note noteText].string ? : @"";
  3022. var noteTextString = note.string() ?? ""
  3023. //
  3024. // if([noteType isEqualToString:@"Redact"]) {
  3025. // noteString = @"Redact";
  3026. // }
  3027. //
  3028. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool
  3029. if timeKey == nil || timeKey == false {
  3030. // if (date != nil) {
  3031. cell.timeLabel.stringValue = dateString
  3032. //
  3033. // } else {
  3034. // cell.timeLabel.stringValue = ""
  3035. // }
  3036. cell.timeLabel.isHidden = false
  3037. } else {
  3038. cell.timeLabel.isHidden = true
  3039. }
  3040. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool
  3041. if pageKey == nil || pageKey == false {
  3042. let labelsize = cell.pageLabel.stringValue.boundingRect(with: CGSizeMake(CGFloat(MAXFLOAT),CGRectGetHeight(cell.pageLabel.bounds)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font : NSFont.systemFont(ofSize: 12)])
  3043. cell.pageLabelWidthConstraint.constant = labelsize.size.width + 5
  3044. cell.pageLabel.stringValue = pageString
  3045. cell.pageLabel.isHidden = false
  3046. } else {
  3047. cell.pageLabel.isHidden = true
  3048. }
  3049. let autherKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool
  3050. if pageKey == nil || pageKey == false {
  3051. cell.autherLabel.stringValue = authorString
  3052. cell.autherLabel.isHidden = false
  3053. } else {
  3054. cell.autherLabel.isHidden = true
  3055. }
  3056. let imageView = KMNoteTypeImageView()
  3057. if note.isKind(of: CPDFStampAnnotation.self) {
  3058. let annotation_stamp = note as! CPDFStampAnnotation
  3059. if (annotation_stamp.stampImage() != nil) {
  3060. noteType = SKNStampString
  3061. }
  3062. } else if note.isKind(of: CPDFLineAnnotation.self) {
  3063. let annotation_line = note as! CPDFLineAnnotation
  3064. if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .none {
  3065. noteType = SKNLine_NoneString
  3066. } else if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .openArrow {
  3067. noteType = SKNLine_OpenArrowString
  3068. } else {
  3069. noteType = SKNLine_NoneString
  3070. }
  3071. } else if note.isKind(of: CPDFButtonWidgetAnnotation.self) {
  3072. let buttonWidget = note as! CPDFButtonWidgetAnnotation
  3073. if buttonWidget.controlType() == .radioButtonControl {
  3074. noteType = KMAnnotationFormRadioButtonKey
  3075. } else if buttonWidget.controlType() == .checkBoxControl {
  3076. noteType = KMAnnotationFormCheckBoxKey
  3077. } else if buttonWidget.controlType() == .pushButtonControl {
  3078. noteType = KMAnnotationFormActionButtonKey
  3079. }
  3080. } else if note.isKind(of: CPDFTextWidgetAnnotation.self) {
  3081. noteType = KMAnnotationFormTextFieldKey
  3082. } else if note.isKind(of: CPDFChoiceWidgetAnnotation.self) {
  3083. let choiceWidget = note as! CPDFChoiceWidgetAnnotation
  3084. if choiceWidget.isListChoice {
  3085. noteType = KMAnnotationFormListMenuKey
  3086. } else {
  3087. noteType = KMAnnotationFormComboBoxKey
  3088. }
  3089. } else if note.isKind(of: KMTableAnnotation.self) {
  3090. noteType = "Ink_Table"
  3091. } else if note.isKind(of: KMSelfSignAnnotation.self) {
  3092. let selfSignNote = note as! KMSelfSignAnnotation
  3093. if selfSignNote.annotationType == .signFalse {
  3094. noteType = "KMSelfSignTypeFalseActionButtonKey"
  3095. } else if (selfSignNote.annotationType == .signature) {
  3096. noteType = "KMSelfSignTypeTureActionButtonKey"
  3097. } else if (selfSignNote.annotationType == .signCircle) {
  3098. noteType = "KMSelfSignTypeCircleActionButtonKey"
  3099. } else if (selfSignNote.annotationType == .signLine) {
  3100. noteType = "KMSelfSignTypeLineActionButtonKey"
  3101. } else if (selfSignNote.annotationType == .signDot) {
  3102. noteType = "KMSelfSignTypeDotActionButtonKey"
  3103. } else if (selfSignNote.annotationType == .signText) {
  3104. noteType = "KMSelfSignTypeTextActionButtonKey"
  3105. }
  3106. } else if note.isKind(of: CPDFSquareAnnotation.self) {
  3107. noteType = SKNSquareString
  3108. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3109. noteType = SKNNoteString
  3110. } else if note.isKind(of: CPDFFreeTextAnnotation.self) {
  3111. noteType = SKNFreeTextString
  3112. } else if note.isKind(of: CPDFCircleAnnotation.self) {
  3113. noteType = SKNCircleString
  3114. } else if note.isKind(of: CPDFSignatureAnnotation.self) {
  3115. noteType = SKNSignatureString
  3116. } else if note.isKind(of: CPDFInkAnnotation.self) {
  3117. noteType = SKNInkString
  3118. } else if note.isKind(of: CPDFMarkupAnnotation.self) {
  3119. let anno = note as! CPDFMarkupAnnotation
  3120. if anno.markupType() == .highlight {
  3121. noteType = SKNHighlightString
  3122. } else if anno.markupType() == .underline {
  3123. noteType = SKNUnderlineString
  3124. } else if anno.markupType() == .strikeOut {
  3125. noteType = SKNStrikeOutString
  3126. }
  3127. }
  3128. cell.typeImageView.image = imageView.noteTypeImage(withType: noteType, color: noteColor ?? .red)
  3129. cell.typeImageView.isHidden = false
  3130. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3131. cell.isFold = true
  3132. }
  3133. cell.noteContentBox.isHidden = true
  3134. cell.noteImageView.isHidden = true
  3135. cell.foldButton.isHidden = true
  3136. cell.annotationContentLabel.isHidden = false
  3137. cell.noteContentLabel.stringValue = noteString
  3138. cell.contentView.isHidden = false
  3139. cell.contentViewHidden(false)
  3140. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3141. let markup = note as! CPDFMarkupAnnotation
  3142. var contentString = KMBOTAAnnotationTool.fetchText(text: markup.markupContent() ?? "")
  3143. contentString = contentString.replacingOccurrences(of: "\r", with: "")
  3144. contentString = contentString.replacingOccurrences(of: "\n", with: "")
  3145. // cell.noteContentLabel.stringValue = contentString
  3146. if(contentString.isEmpty == false) {
  3147. cell.foldButton.isHidden = false
  3148. }
  3149. var attributeStr = NSMutableAttributedString(string: contentString)
  3150. if (markup.markupType() == .highlight) {
  3151. attributeStr.addAttribute(.backgroundColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3152. } else if (markup.markupType() == .strikeOut) {
  3153. attributeStr.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3154. attributeStr.addAttribute(.strikethroughColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3155. } else if (markup.markupType() == .underline) {
  3156. attributeStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3157. attributeStr.addAttribute(.underlineColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3158. }
  3159. cell.annotationContentLabel.attributedStringValue = attributeStr
  3160. if (model.foldType == .unfold) {
  3161. cell.isFold = false
  3162. } else if (model.foldType == .fold) {
  3163. cell.isFold = true
  3164. } else {
  3165. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3166. cell.isFold = false
  3167. } else {
  3168. cell.isFold = true
  3169. }
  3170. }
  3171. // noteString.isEmpty == false &&
  3172. if (contentString.isEmpty == false) {
  3173. cell.contentViewHidden(false)
  3174. } else {
  3175. cell.contentViewHidden(true)
  3176. }
  3177. } else if note.isKind(of: CPDFLineAnnotation.self) || noteType == SKNSquareString || noteType == SKNCircleString || noteType == SKNInkString {
  3178. cell.annotationContentLabel.stringValue = noteString
  3179. if (noteString.isEmpty == false) {
  3180. cell.contentViewHidden(false)
  3181. } else {
  3182. cell.contentViewHidden(true)
  3183. }
  3184. } else if note.isKind(of: CPDFStampAnnotation.self) {
  3185. if note.isKind(of: KMSelfSignAnnotation.self) {
  3186. let newAnnotation = note as! KMSelfSignAnnotation
  3187. let type = newAnnotation.annotationType
  3188. var returnString = ""
  3189. if (type == .signFalse) {
  3190. returnString = KMLocalizedString("X", nil)
  3191. } else if (type == .signature) {
  3192. returnString = KMLocalizedString("Check mark", nil)
  3193. } else if (type == .signCircle) {
  3194. returnString = KMLocalizedString("Circle", nil)
  3195. } else if (type == .signLine) {
  3196. returnString = KMLocalizedString("Line", nil)
  3197. } else if (type == .signDot) {
  3198. returnString = KMLocalizedString("Dot", nil)
  3199. } else if (type == .signText) {
  3200. returnString = KMLocalizedString("Text", nil)
  3201. }
  3202. cell.annotationContentLabel.stringValue = returnString
  3203. } else {
  3204. cell.annotationContentLabel.isHidden = true
  3205. cell.noteImageView.isHidden = false
  3206. let anno = note as! CPDFStampAnnotation
  3207. cell.noteImageView.image = anno.stampImage()
  3208. }
  3209. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3210. cell.foldButton.isHidden = false
  3211. if noteString.isEmpty {
  3212. cell.annotationContentLabel.stringValue = noteTextString
  3213. }else{
  3214. cell.annotationContentLabel.stringValue = noteString
  3215. cell.noteContentLabel.stringValue = noteTextString
  3216. }
  3217. if (self.foldType == .unfold) {
  3218. cell.isFold = false
  3219. } else if (self.foldType == .fold) {
  3220. cell.isFold = true
  3221. } else {
  3222. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3223. cell.isFold = false
  3224. } else {
  3225. cell.isFold = true
  3226. }
  3227. }
  3228. if (noteString.isEmpty == false || noteTextString.isEmpty == false) {
  3229. cell.contentView.isHidden = false
  3230. } else {
  3231. cell.contentView.isHidden = true
  3232. cell.contentViewHidden(true)
  3233. }
  3234. // noteString.isEmpty == false &&
  3235. if (noteTextString.isEmpty == false) {
  3236. cell.foldButton.isHidden = false
  3237. }else{
  3238. cell.foldButton.isHidden = true
  3239. }
  3240. } else {
  3241. cell.annotationContentLabel.stringValue = noteString
  3242. cell.imageViewHeightConstraint.constant = cell.contentView.frame.size.height
  3243. if (noteString.isEmpty == false) {
  3244. cell.contentViewHidden(false)
  3245. } else {
  3246. cell.contentViewHidden(true)
  3247. }
  3248. }
  3249. cell.autherLayoutConstraint.constant = cell.autherLabel.isHidden ? -(cell.autherLabel.bounds.size.width) + 10.0 : 10.0
  3250. cell.typeImageViewLayoutConstraint.constant = cell.typeImageView.isHidden ? -(cell.typeImageView.bounds.size.width) : 0.0
  3251. cell.contentBoxLayoutConstraint.constant = cell.noteContentBox.isHidden ? -(cell.noteContentBox.bounds.size.height+8.0) : 8.0
  3252. if note.isKind(of: CPDFStampAnnotation.self) && note.isKind(of: KMSelfSignAnnotation.self) == false {
  3253. } else {
  3254. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3255. if (!cell.isFold) {
  3256. self.allFoldNotes.append(note)
  3257. } else {
  3258. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3259. }
  3260. } else {
  3261. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3262. }
  3263. }
  3264. cell.isUnFoldNote = { [unowned self] cellNote, isUnfold in
  3265. model.foldType = isUnfold ? .unfold : .fold
  3266. // let COLUMN_INDENTATION: CGFloat = 16
  3267. // if let _cell = tableColumn?.dataCell as? NSCell {
  3268. // _cell.objectValue = cell.annotationContentLabel.attributedStringValue
  3269. // let bound = NSMakeRect(0.0, 0.0, fmax(10.0, NSWidth(outlineView.frame) - COLUMN_INDENTATION - outlineView.indentationPerLevel-40), CGFLOAT_MAX)
  3270. // let height = _cell.cellSize(forBounds: bound).height
  3271. // KMPrint(height)
  3272. // }
  3273. if cellNote is CPDFMarkupAnnotation {
  3274. // let content = cell.annotationContentLabel.attributedStringValue
  3275. // let bound = content.string.boundingRect(with: NSMakeSize(150, CGFLOAT_MAX), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: nil)
  3276. // KMPrint(bound)
  3277. // 154 34 273
  3278. // 273 - 188 = 85 noteContentHeightConstraint maltlineLabelLayoutConstraint
  3279. model.foldH = isUnfold ? 30 : (cell.noteContentHeightConstraint.constant + cell.maltlineLabelLayoutConstraint.constant + 85)
  3280. }
  3281. if (isUnfold) {
  3282. if (self.allFoldNotes.contains(note)) {
  3283. self.allFoldNotes.removeObject(note)
  3284. }
  3285. if (self.allFoldNotes.count == 0) {
  3286. self.foldType = .fold
  3287. } else {
  3288. self.foldType = .none
  3289. }
  3290. } else {
  3291. if self.allFoldNotes.contains(note) == false {
  3292. self.allFoldNotes.append(note)
  3293. }
  3294. // if (rightSideController.allFoldNotes.count == rightSideController.canFoldNotes.count) {
  3295. self.foldType = .unfold
  3296. // } else {
  3297. // self.foldType = KMFoldAllAnnotationType_None;
  3298. // }
  3299. }
  3300. }
  3301. return cell
  3302. }
  3303. return nil
  3304. }
  3305. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  3306. if outlineView.isEqual(self.noteOutlineView) {
  3307. if item is KMBOTAAnnotationItem {
  3308. let model = item as! KMBOTAAnnotationItem
  3309. if model.foldType == .fold {
  3310. return model.foldH
  3311. }
  3312. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  3313. }
  3314. return 30
  3315. } else if outlineView.isEqual(self.tocOutlineView) {
  3316. if item is CPDFOutline {
  3317. let tempItem = item as! CPDFOutline
  3318. let string: NSString = tempItem.label as NSString
  3319. let paragraphStyle = NSMutableParagraphStyle()
  3320. paragraphStyle.lineHeightMultiple = 1.32
  3321. paragraphStyle.alignment = .left
  3322. let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
  3323. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  3324. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attributes)
  3325. return max(40, size.height + 16)
  3326. }
  3327. return 40
  3328. }
  3329. return outlineView.rowHeight
  3330. }
  3331. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  3332. if outlineView.isEqual(self.tocOutlineView) {
  3333. // var _item: CPDFOutline?
  3334. // if item == nil && self.listView.document.isLocked == false {
  3335. // _item = self.listView.document.outlineRoot()
  3336. // }
  3337. if let data = item as? String, data == "Bookmarks" {
  3338. return true
  3339. } else if item is CPDFOutline {
  3340. return ((item as! CPDFOutline).numberOfChildren ?? 0) != 0
  3341. } else if item is CPDFBookmark {
  3342. return false
  3343. }
  3344. if (self.isSearchOutlineMode) {
  3345. // return [self subOutLineContainString:self.leftSideController.outlineSearchField.stringValue rootOutline:(PDFOutline *)item];
  3346. } else {
  3347. // return ((_item?.numberOfChildren ?? 0) != 0)
  3348. }
  3349. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3350. // return [item hasNoteText];
  3351. return false
  3352. }
  3353. return false
  3354. }
  3355. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  3356. if outlineView.isEqual(self.tocOutlineView) {
  3357. let itemView = KMBotaTableRowView()
  3358. return itemView
  3359. } else if outlineView.isEqual(self.noteOutlineView) {
  3360. let itemView = KMBotaTableRowView()
  3361. return itemView;
  3362. }
  3363. return nil
  3364. }
  3365. func outlineViewSelectionDidChange(_ notification: Notification) {
  3366. if self.tocOutlineView.isEqual(to: notification.object) {
  3367. // if ([[notification object] isEqual:leftSideController.tocOutlineView] && (mwcFlags.updatingOutlineSelection == 0)){
  3368. // mwcFlags.updatingOutlineSelection = 1;
  3369. self.goToSelectedOutlineItem(nil)
  3370. // mwcFlags.updatingOutlineSelection = 0;
  3371. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  3372. // [self hideLeftSideWindow];
  3373. }
  3374. }
  3375. func outlineViewItemDidExpand(_ notification: Notification) {
  3376. if self.tocOutlineView.isEqual(to: notification.object) {
  3377. self.updateOutlineSelection()
  3378. }
  3379. }
  3380. func outlineViewItemDidCollapse(_ notification: Notification) {
  3381. if self.tocOutlineView.isEqual(to: notification.object) {
  3382. self.updateOutlineSelection()
  3383. }
  3384. }
  3385. /*
  3386. #pragma mark NSOutlineView datasource protocol
  3387. - (void)outlineView:(NSOutlineView *)ov setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item{
  3388. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3389. PDFAnnotation *note = item;
  3390. if ([note type]) {
  3391. if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  3392. if ([(object ?: @"") isEqualToString:([note string] ?: @"")] == NO)
  3393. [note setString:object];
  3394. } else if ([[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3395. if ([(object ?: @"") isEqualToString:([note userName] ?: @"")] == NO)
  3396. [note setUserName:object];
  3397. }
  3398. }
  3399. }
  3400. }
  3401. #pragma mark Drag
  3402. - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard{
  3403. if ([outlineView isEqual:leftSideController.tocOutlineView]) {
  3404. if (leftSideController.tocOutlineView.selectedRowIndexes.count > 1) {
  3405. return NO;
  3406. }
  3407. NSIndexSet *tIndex = [[[NSIndexSet alloc] initWithIndex:leftSideController.tocOutlineView.clickedRow] autorelease];
  3408. [leftSideController.tocOutlineView deselectRow:tIndex.firstIndex];
  3409. self.dragPDFOutline = items.firstObject;
  3410. NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
  3411. NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:set];
  3412. [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  3413. [pasteboard setData:zNSIndexSetData forType:kKMPDFViewOutlineDragDataType];
  3414. return YES;
  3415. }
  3416. return NO;
  3417. }
  3418. - (NSDragOperation)outlineView:(NSOutlineView *)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)anIndex {
  3419. NSDragOperation dragOp = NSDragOperationNone;
  3420. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3421. NSPasteboard *pboard = [info draggingPasteboard];
  3422. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]] &&
  3423. anIndex == NSOutlineViewDropOnItemIndex && [(PDFAnnotation *)item type] != nil)
  3424. dragOp = NSDragOperationEvery;
  3425. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3426. if (anIndex == -1) {
  3427. dragOp = NSDragOperationNone;
  3428. } else {
  3429. dragOp = NSDragOperationMove;
  3430. }
  3431. }
  3432. return dragOp;
  3433. }
  3434. - (BOOL)outlineView:(NSOutlineView *)ov acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)anIndex {
  3435. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3436. NSPasteboard *pboard = [info draggingPasteboard];
  3437. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]]) {
  3438. BOOL isShift = ([NSEvent standardModifierFlags] & NSEventModifierFlagShift) != 0;
  3439. BOOL isAlt = ([NSEvent standardModifierFlags] & NSEventModifierFlagOption) != 0;
  3440. [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  3441. return YES;
  3442. }
  3443. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3444. if (anIndex < 0) {
  3445. return NO;
  3446. }
  3447. PDFOutline *outline = item;
  3448. //root,drag item to root
  3449. if (!outline.parent) {
  3450. //fetch root
  3451. PDFOutline *root = self.dragPDFOutline;
  3452. while (root.parent) {
  3453. root = root.parent;
  3454. }
  3455. if ([self.dragPDFOutline.parent isEqual:root]) {
  3456. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3457. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3458. } else {
  3459. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:root];
  3460. }
  3461. } else {
  3462. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3463. }
  3464. } else {
  3465. //在同一个层级内移动
  3466. if ([self.dragPDFOutline.parent isEqual:item]) {
  3467. if (self.dragPDFOutline.index) {
  3468. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3469. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3470. }else{
  3471. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:outline];
  3472. }
  3473. } else {
  3474. return NO;
  3475. }
  3476. } else {
  3477. PDFOutline *tOutlline = outline;
  3478. BOOL isContains = NO;
  3479. while (tOutlline) {
  3480. if ([tOutlline isEqual:self.dragPDFOutline]) {
  3481. isContains = YES;
  3482. break;
  3483. }
  3484. tOutlline = tOutlline.parent;
  3485. }
  3486. if (!isContains) {
  3487. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3488. }
  3489. }
  3490. }
  3491. return YES;
  3492. }
  3493. return NO;
  3494. }
  3495. #pragma mark NSOutlineView delegate protocol
  3496. - (NSCell *)outlineView:(NSOutlineView *)ov dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3497. if ([ov isEqual:rightSideController.noteOutlineView] && tableColumn == nil && [(PDFAnnotation *)item type] == nil) {
  3498. return [[ov tableColumnWithIdentifier:NOTE_COLUMNID] dataCellForRow:[ov rowForItem:item]];
  3499. }
  3500. return [tableColumn dataCellForRow:[ov rowForItem:item]];
  3501. }
  3502. - (void)outlineView:(NSOutlineView *)ov willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3503. if ([ov isEqual:leftSideController.tocOutlineView] &&
  3504. [ov selectionHighlightStyle] == NSTableViewSelectionHighlightStyleRegular &&
  3505. [ov isRowSelected:[ov rowForItem:item]]) {
  3506. [cell setBackgroundStyle:NSBackgroundStyleLowered];
  3507. }
  3508. }
  3509. - (BOOL)outlineView:(NSOutlineView *)ov shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item{
  3510. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3511. if (tableColumn == nil) {
  3512. if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  3513. PDFAnnotation *annotation = [(SKNoteText *)item note];
  3514. [pdfView scrollAnnotationToVisible:annotation];
  3515. [pdfView setActiveAnnotation:annotation];
  3516. [self showNote:annotation];
  3517. SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  3518. [[noteController window] makeFirstResponder:[noteController textView]];
  3519. [[noteController textView] selectAll:nil];
  3520. }
  3521. return NO;
  3522. } else if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID] || [[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3523. return YES;
  3524. }
  3525. }
  3526. return NO;
  3527. }
  3528. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  3529. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3530. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  3531. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  3532. NSMutableArray *sortDescriptors = nil;
  3533. BOOL ascending = YES;
  3534. if ([oldTableColumn isEqual:newTableColumn]) {
  3535. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  3536. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  3537. ascending = [[sortDescriptors firstObject] ascending];
  3538. } else {
  3539. NSString *tcID = [newTableColumn identifier];
  3540. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  3541. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  3542. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  3543. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  3544. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  3545. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  3546. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  3547. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  3548. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3549. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  3550. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3551. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  3552. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  3553. }
  3554. if (oldTableColumn)
  3555. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  3556. [ov setHighlightedTableColumn:newTableColumn];
  3557. }
  3558. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  3559. if (newTableColumn)
  3560. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  3561. inTableColumn:newTableColumn];
  3562. [ov reloadData];
  3563. }
  3564. }
  3565. - (NSString *)outlineView:(NSOutlineView *)ov toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tableColumn item:(id)item mouseLocation:(NSPoint)mouseLocation {
  3566. if ([ov isEqual:rightSideController.noteOutlineView] &&
  3567. (tableColumn == nil || [[tableColumn identifier] isEqualToString:NOTE_COLUMNID])) {
  3568. return [item string];
  3569. }
  3570. return @"";
  3571. }
  3572. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  3573. if (mwcFlags.autoResizeNoteRows &&
  3574. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  3575. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  3576. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  3577. [rowHeights removeAllFloats];
  3578. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  3579. }
  3580. }
  3581. - (void)updateSelectRowHeight{
  3582. CGFloat rowHeight = 0;
  3583. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:leftSideController.tocOutlineView.selectedRow];
  3584. if (!outline){
  3585. return;
  3586. }
  3587. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3588. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3589. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3590. [attributedString appendAttributedString:attr1];
  3591. NSInteger *row = [leftSideController.tocOutlineView selectedRow];
  3592. NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:row makeIfNecessary:YES];
  3593. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3594. // id cell = [tableColumn dataCell];
  3595. id cell = [tableColumn dataCellForRow:row];
  3596. [cell setObjectValue:attributedString];
  3597. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3598. NSInteger num = [self getNum:outline];
  3599. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3600. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3601. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3602. [rowHeights setFloat:rowHeight forKey:outline];
  3603. if (@available(macOS 10.13, *)) {
  3604. } else {
  3605. rowHeight = 40.0;
  3606. }
  3607. CGRect fram = viewS.frame;
  3608. viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3609. [leftSideController.tocOutlineView reloadData];
  3610. }
  3611. - (NSInteger)getNum:(PDFOutline *)ol{
  3612. NSInteger num = 0;
  3613. PDFOutline *outLine = [ol parent];
  3614. do {
  3615. outLine = [outLine parent];
  3616. if (outLine){
  3617. num ++;
  3618. }
  3619. } while (outLine);
  3620. return num;
  3621. }
  3622. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  3623. {
  3624. NSInteger rowCount = [outlineView numberOfRows];
  3625. for (NSInteger i = 0; i < rowCount; i++){
  3626. CGFloat rowHeight = 0;
  3627. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  3628. if (!outline){
  3629. continue;
  3630. }
  3631. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3632. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3633. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3634. [attributedString appendAttributedString:attr1];
  3635. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  3636. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3637. // id cell = [tableColumn dataCell];
  3638. id cell = [tableColumn dataCellForRow:i];
  3639. [cell setObjectValue:attributedString];
  3640. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3641. NSInteger num = [self getNum:outline];
  3642. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3643. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3644. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3645. [rowHeights setFloat:rowHeight forKey:outline];
  3646. if (@available(macOS 10.13, *)) {
  3647. } else {
  3648. rowHeight = 40.0;
  3649. }
  3650. // CGRect fram = viewS.frame;
  3651. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3652. }
  3653. [leftSideController.tocOutlineView reloadData];
  3654. }
  3655. - (NSArray *)noteItems:(NSArray *)items {
  3656. NSMutableArray *noteItems = [NSMutableArray array];
  3657. for (PDFAnnotation *item in items) {
  3658. if ([item type] == nil) {
  3659. item = [(SKNoteText *)item note];
  3660. }
  3661. if ([noteItems containsObject:item] == NO)
  3662. [noteItems addObject:item];
  3663. }
  3664. return noteItems;
  3665. }
  3666. - (NSArray *)outlineView:(NSOutlineView *)ov typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  3667. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3668. NSInteger i, count = [rightSideController.noteOutlineView numberOfRows];
  3669. NSMutableArray *texts = [NSMutableArray arrayWithCapacity:count];
  3670. for (i = 0; i < count; i++) {
  3671. id item = [rightSideController.noteOutlineView itemAtRow:i];
  3672. NSString *string = [item string];
  3673. [texts addObject:string ?: @""];
  3674. }
  3675. return texts;
  3676. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3677. NSInteger i, count = [leftSideController.tocOutlineView numberOfRows];
  3678. NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
  3679. for (i = 0; i < count; i++)
  3680. [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  3681. return array;
  3682. }
  3683. return nil;
  3684. }
  3685. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  3686. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3687. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  3688. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3689. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  3690. }
  3691. }
  3692. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  3693. if ([typeSelectHelper isEqual:[leftSideController.thumbnailTableView typeSelectHelper]] || [typeSelectHelper isEqual:[pdfView typeSelectHelper]]) {
  3694. if (searchString)
  3695. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  3696. else
  3697. [self updateLeftStatus];
  3698. } else if ([typeSelectHelper isEqual:[rightSideController.noteOutlineView typeSelectHelper]]) {
  3699. if (searchString)
  3700. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding note: \"%@\"", @"Status message"), searchString]];
  3701. else
  3702. [self updateRightStatus];
  3703. } else if ([typeSelectHelper isEqual:[leftSideController.tocOutlineView typeSelectHelper]]) {
  3704. if (searchString)
  3705. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding: \"%@\"", @"Status message"), searchString]];
  3706. else
  3707. [self updateLeftStatus];
  3708. }
  3709. }
  3710. */
  3711. }
  3712. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  3713. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  3714. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  3715. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3716. return self.listView.hideNotes == false && items.count > 0
  3717. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  3718. return items.count > 0
  3719. }
  3720. return false
  3721. }
  3722. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  3723. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3724. if (items.isEmpty) {
  3725. return
  3726. }
  3727. // for (PDFAnnotation *item in [self noteItems:items])
  3728. // [pdfView removeAnnotation:item];
  3729. // [[[self document] undoManager] setActionName:NSLocalizedString(@"Remove Note", @"Undo action name")];
  3730. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  3731. // [self outlineContextMenuItemClicked_RemoveEntry:nil];
  3732. }
  3733. }
  3734. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  3735. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3736. if (items.count == 1) {
  3737. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  3738. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  3739. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  3740. // return NO;
  3741. // }
  3742. }
  3743. return items.count > 0
  3744. }
  3745. return false
  3746. }
  3747. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  3748. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  3749. let pboard = NSPasteboard.general
  3750. var copiedItems: [Any] = []
  3751. var attrString = NSMutableAttributedString()
  3752. var isAttributed = false
  3753. var item: AnyObject?
  3754. // for (item in [self noteItems:items]) {
  3755. // if ([item isMovable])
  3756. // [copiedItems addObject:item];
  3757. // }
  3758. // for (item in items) {
  3759. // if ([attrString length])
  3760. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  3761. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  3762. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  3763. // isAttributed = YES;
  3764. // } else {
  3765. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  3766. // }
  3767. // }
  3768. //
  3769. // [pboard clearContents];
  3770. // if (isAttributed)
  3771. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  3772. // else
  3773. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  3774. // if ([copiedItems count] > 0)
  3775. // [pboard writeObjects:copiedItems];
  3776. }
  3777. }
  3778. }
  3779. // MARK: - KMTocOutlineViewDelegate
  3780. extension KMLeftSideViewController: KMTocOutlineViewDelegate {
  3781. // func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  3782. // if ([ov isEqual:leftSideController.tocOutlineView]) {
  3783. // NSInteger numRows = [ov numberOfRows];
  3784. // NSUInteger firstPage = [[[ov itemAtRow:row] page] pageIndex];
  3785. // NSUInteger lastPage = row + 1 < numRows ? [[[ov itemAtRow:row + 1] page] pageIndex] : [[self pdfDocument] pageCount];
  3786. // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  3787. // NSUInteger i, iMax = [lastViewedPages count];
  3788. // for (i = 0; i < iMax; i++) {
  3789. // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  3790. // return i;
  3791. // }
  3792. // }
  3793. // return NSNotFound;
  3794. // }
  3795. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  3796. if anOutlineView.isEqual(to: self.tocOutlineView) {
  3797. if item == nil {
  3798. return true as AnyObject
  3799. }
  3800. if item is CPDFOutline {
  3801. return (item as! CPDFOutline).destination
  3802. }
  3803. }
  3804. return nil
  3805. }
  3806. }
  3807. extension KMLeftSideViewController: KMNoteOutlineViewDelegate {
  3808. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  3809. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3810. return true
  3811. }
  3812. return false
  3813. }
  3814. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  3815. // [rowHeights setFloat:newHeight forKey:item];
  3816. }
  3817. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  3818. // if (mwcFlags.autoResizeNoteRows &&
  3819. // [ov isEqual:rightSideController.noteOutlineView] &&
  3820. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  3821. // [rowHeights removeAllFloats];
  3822. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  3823. // }
  3824. }
  3825. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  3826. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  3827. // if (annotation) {
  3828. // [pdfView scrollAnnotationToVisible:annotation];
  3829. // [pdfView setActiveAnnotation:annotation];
  3830. // }
  3831. }
  3832. }
  3833. extension KMLeftSideViewController: NSSearchFieldDelegate {
  3834. func controlTextDidChange(_ obj: Notification) {
  3835. if self.outlineSearchField.isEqual(to: obj.object) {
  3836. if (self.outlineSearchField.stringValue.isEmpty == false) {
  3837. self.isSearchOutlineMode = true
  3838. self.tocOutlineView.reloadData()
  3839. self.tocOutlineView.expandItem(nil, expandChildren: true)
  3840. self.tocType = .unfold
  3841. } else {
  3842. self.isSearchOutlineMode = false
  3843. self.showSearchOutlineBlankState(false)
  3844. self.tocOutlineView.reloadData()
  3845. }
  3846. // self.leftSideEmptyVC.addOutlineBtn.enabled = !self.isSearchOutlineMode;
  3847. self.outlineAddButton.isEnabled = !self.isSearchOutlineMode
  3848. } else if self.snapshotSearchField.isEqual(to: obj.object) {
  3849. let searchString = self.snapshotSearchField.stringValue
  3850. // NSPredicate *filterPredicate = nil;
  3851. // if ([searchString length] > 0) {
  3852. // NSExpression *lhs = [NSExpression expressionForConstantValue:searchString];
  3853. // NSExpression *rhs = [NSExpression expressionForKeyPath:@"string"];
  3854. // NSUInteger options = NSDiacriticInsensitivePredicateOption;
  3855. // if (mwcFlags.caseInsensitiveNoteSearch)
  3856. // options |= NSCaseInsensitivePredicateOption;
  3857. // filterPredicate = [NSComparisonPredicate predicateWithLeftExpression:lhs rightExpression:rhs modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:options];
  3858. // }
  3859. // [rightSideController.snapshotArrayController setFilterPredicate:filterPredicate];
  3860. // NSArray * snapshots = [rightSideController.snapshotArrayController arrangedObjects];
  3861. self.searchSnapshots.removeAll()
  3862. if searchString.isEmpty {
  3863. self.isSearchSnapshotMode = false
  3864. self.searchSnapshots = self.snapshots.filter({ model in
  3865. let data = model.windowC?.string.contains(searchString) ?? false
  3866. return data
  3867. })
  3868. } else {
  3869. self.isSearchSnapshotMode = true
  3870. }
  3871. var snapshots = self.searchSnapshots
  3872. if self.isSearchSnapshotMode == false {
  3873. snapshots = self.snapshots
  3874. }
  3875. Task { @MainActor in
  3876. self.updataLeftSideSnapView()
  3877. self.snapshotTableView.reloadData()
  3878. }
  3879. if (snapshots.count > 0) {
  3880. self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  3881. } else {
  3882. let view = self.snapshotTableView.enclosingScrollView
  3883. let emptyVcSize = self.leftSideEmptyVC.outlineSearchView.frame.size
  3884. self.leftSideEmptyVC.outlineSearchView.frame = NSMakeRect((view!.frame.size.width-emptyVcSize.width)/2.0,(view!.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  3885. self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  3886. self.snapshotTableView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  3887. }
  3888. }
  3889. }
  3890. }
  3891. // MARK: - NSMenuDelegate
  3892. extension KMLeftSideViewController: NSMenuDelegate {
  3893. func menuNeedsUpdate(_ menu: NSMenu) {
  3894. if menu.isEqual(to: self.tocOutlineView.menu) {
  3895. menu.removeAllItems()
  3896. var item = menu.addItem(withTitle: NSLocalizedString("Add Item", comment: ""), action: #selector(outlineContextMenuItemClicked_AddEntry), target: self, tag: 1)
  3897. item = menu.addItem(withTitle: NSLocalizedString("Add Sub-Item", comment: ""), action: #selector(outlineContextMenuItemClicked_AddChildEntry), target: self, tag: 2)
  3898. item = menu.addItem(withTitle: NSLocalizedString("Add To A Higher Level", comment: ""), action: #selector(outlineContextMenuItemClicked_AddAuntEntry), target: self, tag: 3)
  3899. menu.addItem(.separator())
  3900. item = menu.addItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(outlineContextMenuItemClicked_RemoveEntry), target: self, tag: 4)
  3901. menu.addItem(.separator())
  3902. item = menu.addItem(withTitle: NSLocalizedString("Edit", comment: ""), action: #selector(outlineContextMenuItemClicked_Edit), target: self, tag: 5)
  3903. item = menu.addItem(withTitle: NSLocalizedString("Change Destination", comment: ""), action: #selector(outlineContextMenuItemClicked_SetDestination), target: self, tag: 6)
  3904. item = menu.addItem(withTitle: NSLocalizedString("Rename", comment: ""), action: #selector(outlineContextMenuItemClicked_Rename), target: self, tag: 7)
  3905. menu.addItem(.separator())
  3906. item = menu.addItem(withTitle: NSLocalizedString("Promote", comment: ""), action: #selector(outlineContextMenuItemClicked_Promote), target: self, tag: 8)
  3907. item = menu.addItem(withTitle: NSLocalizedString("Demote", comment: ""), action: #selector(outlineContextMenuItemClicked_Demote), target: self, tag: 9)
  3908. return
  3909. }
  3910. var item: NSMenuItem?
  3911. menu.removeAllItems()
  3912. if menu.isEqual(to: self.thumbnailTableView.menu) {
  3913. let row = self.thumbnailTableView.clickedRow
  3914. if self.listView.document.documentURL == nil || self.thumbnailTableView.selectedRowIndexes.contains(row) == false{
  3915. return
  3916. }
  3917. if (row != -1 && self.listView.document.isLocked == false) {
  3918. if(self.thumbnailTableView.selectedRowIndexes.count == self.listView.document.pageCount) {
  3919. item = menu.addItem(title: KMLocalizedString("Cut", "Menu item title"), action: nil, target: self)
  3920. } else {
  3921. item = menu.addItem(title: KMLocalizedString("Cut", "Menu item title"), action: #selector(cutPage), target: self)
  3922. }
  3923. item?.representedObject = IndexSet(integer: row)
  3924. item = menu.addItem(title: KMLocalizedString("Copy", "Menu item title"), action: #selector(copyPage), target: self)
  3925. item?.representedObject = IndexSet(integer: row)
  3926. if (self._copysPages.count > 0) {
  3927. item = menu.addItem(title: KMLocalizedString("Paste", "Menu item title"), action: #selector(pastePage), target: self)
  3928. }else{
  3929. item = menu.addItem(title: KMLocalizedString("Paste", "Menu item title"), action: nil, target: self)
  3930. }
  3931. item?.representedObject = IndexSet(integer: row)
  3932. menu.addItem(.separator())
  3933. if(self.thumbnailTableView.selectedRowIndexes.count == self.listView.document.pageCount) {
  3934. item = menu.addItem(title: KMLocalizedString("Delete", "Menu item title"), action: nil, target: self)
  3935. } else {
  3936. item = menu.addItem(title: KMLocalizedString("Delete", "Menu item title"), action: #selector(deletePage), target: self)
  3937. }
  3938. item?.representedObject = IndexSet(integer: row)
  3939. menu.addItem(.separator())
  3940. item = menu.addItem(title: KMLocalizedString("Rotate", "Menu item title"), action: #selector(rotatePageMenuAction), target: self)
  3941. item?.representedObject = IndexSet(integer: row)
  3942. item = menu.addItem(title: KMLocalizedString("Insert", "Menu item title"), action: nil, target: self)
  3943. let subMenu = NSMenu()
  3944. subMenu.addItem(title: KMLocalizedString("Blank Page", "Menu item title"), action: #selector(quickInsert), target: self)
  3945. subMenu.addItem(title: KMLocalizedString("Blank Page - Custom...", "Menu item title"), action: #selector(insert), target: self)
  3946. subMenu.addItem(title: KMLocalizedString("From PDF", "Menu item title"), action: #selector(insertPDF), target: self)
  3947. item?.submenu = subMenu
  3948. item?.representedObject = IndexSet(integer: row)
  3949. item = menu.addItem(title: KMLocalizedString("Extract", "Menu item title"), action: #selector(extractPage), target: self)
  3950. item?.representedObject = IndexSet(integer: row)
  3951. item = menu.addItem(title: KMLocalizedString("Page Edit", "Menu item title"), action: #selector(pageEdit), target: self)
  3952. menu.addItem(.separator())
  3953. var displayStr = ""
  3954. if (self.isDisplayPageSize) {
  3955. displayStr = KMLocalizedString("Hide Page Size", "Menu item title")
  3956. } else {
  3957. displayStr = KMLocalizedString("Display Page Size", "Menu item title")
  3958. }
  3959. item = menu.addItem(title: displayStr, action: #selector(displayPageSize), target: self)
  3960. item?.representedObject = IndexSet(integer: row)
  3961. item = menu.addItem(title: KMLocalizedString("Share", "Menu item title"), action: nil, target: self)
  3962. // NSString * tName = [self fileNameWithSelectedPages:leftSideController.thumbnailTableView.selectedRowIndexes];
  3963. // if (tName.length > 50) {
  3964. // tName = [tName substringWithRange:NSMakeRange(0, 50)];
  3965. // }
  3966. var tName = self.listView.document.documentURL.lastPathComponent
  3967. item?.submenu = NSSharingServicePicker.menu(forSharingItems: [self.listView.document.documentURL], subjectContext: tName, withTarget: self, selector: #selector(sharePage), serviceDelegate: nil)
  3968. }
  3969. } else if menu.isEqual(to: self.findTableView.menu) {
  3970. var rowIndexes = self.findTableView.selectedRowIndexes
  3971. var row = self.findTableView.clickedRow
  3972. if (row != -1) {
  3973. if rowIndexes.contains(row) == false {
  3974. rowIndexes = IndexSet(integer: row)
  3975. }
  3976. // NSArray *selections = [[leftSideController.findArrayController arrangedObjects] objectsAtIndexes:rowIndexes];
  3977. // if ([pdfView hideNotes] == NO && [[self pdfDocument] allowsNotes]) {
  3978. item = menu.addItem(withTitle: KMLocalizedString("Add New Circle", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 0)
  3979. //// [item setRepresentedObject:selections];
  3980. item = menu.addItem(withTitle: KMLocalizedString("Add New Rectangle", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 1)
  3981. //// [item setRepresentedObject:selections];
  3982. item = menu.addItem(withTitle: KMLocalizedString("Add New Highlight", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 2)
  3983. //// [item setRepresentedObject:selections];
  3984. item = menu.addItem(withTitle: KMLocalizedString("Add New Underline", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 3)
  3985. //// [item setRepresentedObject:selections];
  3986. item = menu.addItem(withTitle: KMLocalizedString("Add New Strikethrough", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 4)
  3987. // [item setRepresentedObject:selections];
  3988. // }
  3989. }
  3990. } else if menu.isEqual(to: self.groupedFindTableView.menu) {
  3991. var rowIndexes = self.groupedFindTableView.selectedRowIndexes
  3992. var row = self.groupedFindTableView.clickedRow
  3993. if (row != -1) {
  3994. if rowIndexes.contains(row) == false {
  3995. rowIndexes = IndexSet(integer: row)
  3996. }
  3997. // NSArray *selections = [[[leftSideController.groupedFindArrayController arrangedObjects] objectsAtIndexes:rowIndexes] valueForKeyPath:@"@unionOfArrays.matches"];
  3998. item = menu.addItem(title: KMLocalizedString("Select", "Menu item title"), action: #selector(selectSelections), target: self)
  3999. // [item setRepresentedObject:selections];
  4000. menu.addItem(.separator())
  4001. // if ([pdfView hideNotes] == NO && [[self pdfDocument] allowsNotes]) {
  4002. item = menu.addItem(withTitle: KMLocalizedString("Add New Circle", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 0)
  4003. // [item setRepresentedObject:selections];
  4004. item = menu.addItem(withTitle: KMLocalizedString("Add New Rectangle", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 1)
  4005. // [item setRepresentedObject:selections];
  4006. item = menu.addItem(withTitle: KMLocalizedString("Add New Highlight", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 2)
  4007. // [item setRepresentedObject:selections];
  4008. item = menu.addItem(withTitle: KMLocalizedString("Add New Underline", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 3)
  4009. // [item setRepresentedObject:selections];
  4010. item = menu.addItem(withTitle: KMLocalizedString("Add New Strikethrough", "Menu item title"), action: #selector(addAnnotationsForSelections), target: self, tag: 4)
  4011. // [item setRepresentedObject:selections];
  4012. // }
  4013. }
  4014. } else if menu.isEqual(to: self.snapshotTableView.menu) {
  4015. let row = self.snapshotTableView.clickedRow
  4016. if (row != -1) {
  4017. let model = self.snapshots[row]
  4018. let controller = model.windowC
  4019. if let data = controller?.window?.isVisible, data {
  4020. item = menu.addItem(title: KMLocalizedString("Hide", "Menu item title"), action: #selector(hideSnapshot), target: self)
  4021. item?.representedObject = controller
  4022. } else {
  4023. item = menu.addItem(title: KMLocalizedString("Show", "Menu item title"), action: #selector(showSnapshot), target: self)
  4024. item?.representedObject = controller
  4025. }
  4026. menu.addItem(.separator())
  4027. item = menu.addItem(title: KMLocalizedString("Export", "Menu item title"), action: nil, target: self)
  4028. let subMenu = NSMenu()
  4029. var t = subMenu.addItem(title: KMLocalizedString("PNG", "Menu item title"), action: #selector(menuItemClick_ExportPNG), target: self)
  4030. t?.representedObject = controller
  4031. t = subMenu.addItem(title: KMLocalizedString("JPG", "Menu item title"), action: #selector(menuItemClick_ExportJPG), target: self)
  4032. t?.representedObject = controller
  4033. t = subMenu.addItem(title: KMLocalizedString("PDF", "Menu item title"), action: #selector(menuItemClick_ExportPDF), target: self)
  4034. t?.representedObject = controller
  4035. item?.submenu = subMenu
  4036. item = menu.addItem(title: KMLocalizedString("Print", "Menu item title"), action: #selector(menuItemClick_Print), target: self)
  4037. item?.representedObject = controller
  4038. menu.addItem(.separator())
  4039. item = menu.addItem(title: KMLocalizedString("Copy", "Menu item title"), action: #selector(menuItemClick_Copy), target: self)
  4040. item?.representedObject = controller
  4041. menu.addItem(.separator())
  4042. item = menu.addItem(title: KMLocalizedString("Delete", "Menu item title"), action: #selector(deleteSnapshot), target: self)
  4043. item?.representedObject = controller
  4044. item = menu.addItem(title: KMLocalizedString("Delete All Snapshots", "Menu item title"), action: #selector(deleteAllSnapshot), target: self)
  4045. item?.representedObject = controller
  4046. }
  4047. } else if menu.isEqual(to: self.noteOutlineView.menu) {
  4048. // NSArray *items;
  4049. var rowIndexes = self.noteOutlineView.selectedRowIndexes
  4050. let row = self.noteOutlineView.clickedRow
  4051. if (row != -1) {
  4052. if rowIndexes.contains(row) == false {
  4053. rowIndexes = IndexSet(integer: row)
  4054. // items = [rightSideController.noteOutlineView itemsAtRowIndexes:rowIndexes];
  4055. // PDFAnnotation *foldNote = (PDFAnnotation *)notes[row];
  4056. var isFold = true
  4057. // if ([rightSideController.allFoldNotes containsObject:foldNote]) {
  4058. // isFold = NO;
  4059. // }
  4060. item = menu.addItem(title: KMLocalizedString("Expand", nil), action: #selector(unfoldNoteAction), target: self)
  4061. if (isFold) {
  4062. item?.state = .off
  4063. } else {
  4064. item?.state = .on
  4065. }
  4066. // [item setRepresentedObject:items];
  4067. item = menu.addItem(title: KMLocalizedString("Collapse", nil), action: #selector(foldNoteAction), target: self)
  4068. if (isFold) {
  4069. item?.state = .on
  4070. } else {
  4071. item?.state = .off
  4072. }
  4073. // [item setRepresentedObject:items];
  4074. //UX改版删除
  4075. // if ([self outlineView:rightSideController.noteOutlineView canCopyItems:items]) {
  4076. // item = [menu addItemWithTitle:NSLocalizedString(@"Copy", @"Menu item title") action:@selector(copyNotes:) target:self];
  4077. // [item setRepresentedObject:items];
  4078. // }
  4079. menu.addItem(.separator())
  4080. if self.listView.hideNotes == false {
  4081. // if ([pdfView hideNotes] == NO && [items count] == 1) {
  4082. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  4083. // if ([annotation isEditable]) {
  4084. // if ([(PDFAnnotation *)[items lastObject] type] == nil) {
  4085. // if ([[(SKNoteText *)[items lastObject] note] isNote]) {
  4086. // item = [menu addItemWithTitle:[NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis] action:@selector(editNoteTextFromTable:) target:self];
  4087. // [item setRepresentedObject:annotation];
  4088. // }
  4089. // } else if ([[rightSideController.noteOutlineView tableColumnWithIdentifier:NOTE_COLUMNID] isHidden]) {
  4090. // item = [menu addItemWithTitle:[NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis] action:@selector(editThisAnnotation:) target:pdfView];
  4091. // [item setRepresentedObject:annotation];
  4092. // } else {
  4093. // item = [menu addItemWithTitle:NSLocalizedString(@"Edit", @"Menu item title") action:@selector(editNoteFromTable:) target:self];
  4094. // [item setRepresentedObject:annotation];
  4095. // item = [menu addItemWithTitle:[NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis] action:@selector(editThisAnnotation:) target:pdfView];
  4096. // [item setRepresentedObject:annotation];
  4097. // [item setKeyEquivalentModifierMask:NSEventModifierFlagOption];
  4098. // [item setAlternate:YES];
  4099. // }
  4100. // }
  4101. // if ([pdfView hideNotes] == NO && [[self pdfDocument] allowsNotes]) {
  4102. // if ([pdfView activeAnnotation] == annotation) {
  4103. // item = [menu addItemWithTitle:NSLocalizedString(@"Deselect", @"Menu item title") action:@selector(deselectNote:) target:self];
  4104. // [item setRepresentedObject:annotation];
  4105. // } else {
  4106. // item = [menu addItemWithTitle:NSLocalizedString(@"Select", @"Menu item title") action:@selector(selectNote:) target:self];
  4107. // [item setRepresentedObject:annotation];
  4108. // }
  4109. // item = [menu addItemWithTitle:NSLocalizedString(@"Show", @"Menu item title") action:@selector(revealNote:) target:self];
  4110. // [item setRepresentedObject:annotation];
  4111. // }
  4112. // }
  4113. // if ([menu numberOfItems] > 0)
  4114. // [menu addItem:[NSMenuItem separatorItem]];
  4115. // item = [menu addItemWithTitle:[items count] == 1 ? NSLocalizedString(@"Auto Size Row", @"Menu item title") : NSLocalizedString(@"Auto Size Rows", @"Menu item title") action:@selector(autoSizeNoteRows:) target:self];
  4116. // [item setRepresentedObject:items];
  4117. // item = [menu addItemWithTitle:[items count] == 1 ? NSLocalizedString(@"Undo Auto Size Row", @"Menu item title") : NSLocalizedString(@"Undo Auto Size Rows", @"Menu item title") action:@selector(resetHeightOfNoteRows:) target:self];
  4118. // [item setRepresentedObject:items];
  4119. // [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
  4120. // [item setAlternate:YES];
  4121. // [menu addItemWithTitle:NSLocalizedString(@"Auto Size All", @"Menu item title") action:@selector(autoSizeNoteRows:) target:self];
  4122. // item = [menu addItemWithTitle:NSLocalizedString(@"Undo Auto Size All", @"Menu item title") action:@selector(resetHeightOfNoteRows:) target:self];
  4123. // [item setKeyEquivalentModifierMask:NSAlternateKeyMask];
  4124. // [item setAlternate:YES];
  4125. // [menu addItemWithTitle:NSLocalizedString(@"Automatically Resize", @"Menu item title") action:@selector(toggleAutoResizeNoteRows:) target:self];
  4126. if menu.numberOfItems > 0 {
  4127. item = menu.addItem(title: NSLocalizedString("Export Annotations…", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4128. let subMenu = NSMenu()
  4129. item?.submenu = subMenu
  4130. item = subMenu.addItem(title: NSLocalizedString("PDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4131. item?.tag = 0
  4132. item = subMenu.addItem(title: NSLocalizedString("PDF Bundle", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4133. item?.tag = 1
  4134. item = subMenu.addItem(title: NSLocalizedString("PDF Reader Pro Edition Notes", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4135. item?.tag = 2
  4136. item = subMenu.addItem(title: NSLocalizedString("Notes as Texts", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4137. item?.tag = 3
  4138. item = subMenu.addItem(title: NSLocalizedString("Notes as RTF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4139. item?.tag = 4
  4140. item = subMenu.addItem(title: NSLocalizedString("Notes as RTFD", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4141. item?.tag = 5
  4142. item = subMenu.addItem(title: NSLocalizedString("Notes as FDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  4143. item?.tag = 6
  4144. menu.addItem(.separator())
  4145. // if ([self outlineView:rightSideController.noteOutlineView canDeleteItems:items]) {
  4146. item = menu.addItem(title: KMLocalizedString("Delete", "Menu item title"), action: #selector(deleteNotes), target: self)
  4147. // [item setRepresentedObject:items];
  4148. // }
  4149. item = menu.addItem(title: NSLocalizedString("Remove All Annotations", tableName: "MainMenu", comment: "Menu item title"), action: #selector(removeAllAnnotations), target: self)
  4150. }
  4151. }
  4152. }
  4153. }
  4154. }
  4155. // else {
  4156. // item = [menu addItemWithTitle:NSLocalizedStringFromTable(@"Export Annotations…", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4157. //
  4158. // NSMenu *subMenu = [NSMenu menu];
  4159. // item.submenu = subMenu;
  4160. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"PDF", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4161. // item.tag = 0;
  4162. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"PDF Bundle", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4163. // item.tag = 1;
  4164. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"PDF Reader Pro Edition Notes", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4165. // item.tag = 2;
  4166. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"Notes as Text", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4167. // item.tag = 3;
  4168. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"Notes as RTF", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4169. // item.tag = 4;
  4170. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"Notes as RTFD", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4171. // item.tag = 5;
  4172. // item = [subMenu addItemWithTitle:NSLocalizedStringFromTable(@"Notes as FDF", @"MainMenu", @"Menu item title") action:@selector(exportAnnotationNotes:) target:self];
  4173. // item.tag = 6;
  4174. //
  4175. // item = [menu addItemWithTitle:NSLocalizedStringFromTable(@"Remove All Annotations", @"MainMenu", @"Menu item title") action:@selector(removeAllAnnotations:) target:self];
  4176. // }
  4177. // }
  4178. }
  4179. }
  4180. // MARK: - NSMenuItemValidation
  4181. extension KMLeftSideViewController: NSMenuItemValidation {
  4182. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  4183. if (self.listView.document == nil || self.listView.document!.isLocked) {
  4184. return false
  4185. }
  4186. let action = menuItem.action
  4187. // if (self.isRedactEdit) {
  4188. // if (action == @selector(redactAction:))
  4189. // return YES;
  4190. // return NO;
  4191. // }
  4192. //
  4193. // if (self.isShowPageEdit) {
  4194. // if (action == @selector(pageEdit:))
  4195. // return YES;
  4196. // return NO;
  4197. // }
  4198. // if (self.isShowTextEdit) {
  4199. // if (action == @selector(textEditAction:))
  4200. // return YES;
  4201. // return NO;
  4202. // }
  4203. // if (self.isCompareMode) {
  4204. // return NO;
  4205. // }
  4206. // if (action == @selector(createNewNote:)) {
  4207. // BOOL isMarkup = [menuItem tag] == SKHighlightNote || [menuItem tag] == SKUnderlineNote || [menuItem tag] == SKStrikeOutNote;
  4208. // isMarkup = NO;
  4209. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] allowsNotes] && ([pdfView toolMode] == SKTextToolMode || [pdfView toolMode] == SKNoteToolMode) && [pdfView hideNotes] == NO && (isMarkup == NO || [[pdfView currentSelection] hasCharacters]);
  4210. // } else if (action == @selector(editNote:)) {
  4211. // PDFAnnotation *annotation = [pdfView activeAnnotation];
  4212. // return [self interactionMode] != SKPresentationMode && [annotation isSkimNote] && ([annotation isEditable]);
  4213. // } else if (action == @selector(alignLeft:) || action == @selector(alignRight:) || action == @selector(alignCenter:)) {
  4214. // PDFAnnotation *annotation = [pdfView activeAnnotation];
  4215. // return [self interactionMode] != SKPresentationMode && [annotation isSkimNote] && ([annotation isEditable]) && [annotation respondsToSelector:@selector(setAlignment:)];
  4216. // } else if (action == @selector(toggleHideNotes:)) {
  4217. // if ([pdfView hideNotes])
  4218. // [menuItem setTitle:NSLocalizedString(@"Show Notes", @"Menu item title")];
  4219. // else
  4220. // [menuItem setTitle:NSLocalizedString(@"Hide Notes", @"Menu item title")];
  4221. // return YES;
  4222. // } else if (action == @selector(changeDisplaySinglePages:)) {
  4223. // [menuItem setState:([pdfView displayMode] & kPDFDisplayTwoUp) == (PDFDisplayMode)[menuItem tag] ? NSOnState : NSOffState];
  4224. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4225. // } else if (action == @selector(changeDisplayContinuous:)) {
  4226. // [menuItem setState:([pdfView displayMode] & kPDFDisplaySinglePageContinuous) == (PDFDisplayMode)[menuItem tag] ? NSOnState : NSOffState];
  4227. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4228. // } else if (action == @selector(changeDisplayMode:)) {
  4229. // [menuItem setState:[pdfView displayMode] == (PDFDisplayMode)[menuItem tag] ? NSOnState : NSOffState];
  4230. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4231. // } else if (action == @selector(toggleDisplayAsBook:)) {
  4232. // [menuItem setState:[pdfView displaysAsBook] ? NSOnState : NSOffState];
  4233. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO && ([pdfView displayMode] == kPDFDisplayTwoUp || [pdfView displayMode] == kPDFDisplayTwoUpContinuous);
  4234. // } else if (action == @selector(toggleDisplayPageBreaks:)) {
  4235. // [menuItem setState:[pdfView displaysPageBreaks] ? NSOnState : NSOffState];
  4236. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4237. // } else if (action == @selector(changeDisplayBox:)) {
  4238. // [menuItem setState:[pdfView displayBox] == (PDFDisplayBox)[menuItem tag] ? NSOnState : NSOffState];
  4239. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4240. // } else if (action == @selector(delete:) || action == @selector(copy:) || action == @selector(cut:) || action == @selector(paste:) || action == @selector(alternatePaste:) || action == @selector(pasteAsPlainText:) || action == @selector(deselectAll:) || action == @selector(changeAnnotationMode:) || action == @selector(changeToolMode:) || action == @selector(changeToolMode:)) {
  4241. // return [pdfView validateMenuItem:menuItem];
  4242. // } else
  4243. // if (action == @selector(doGoToNextPage:)) {
  4244. // return [pdfView canGoToNextPage];
  4245. // } else if (action == @selector(doGoToPreviousPage:) ) {
  4246. // return [pdfView canGoToPreviousPage];
  4247. // } else if (action == @selector(doGoToFirstPage:)) {
  4248. // return [pdfView canGoToFirstPage];
  4249. // } else if (action == @selector(doGoToLastPage:)) {
  4250. // return [pdfView canGoToLastPage];
  4251. // } else if (action == @selector(doGoToPage:)) {
  4252. // return [[self pdfDocument] isLocked] == NO;
  4253. // } else if (action == @selector(allGoToNextPage:)) {
  4254. // return [[allMainDocumentPDFViews() valueForKeyPath:@"@min.canGoToNextPage"] boolValue];
  4255. // } else if (action == @selector(allGoToPreviousPage:)) {
  4256. // return [[allMainDocumentPDFViews() valueForKeyPath:@"@min.canGoToPreviousPage"] boolValue];
  4257. // } else if (action == @selector(allGoToFirstPage:)) {
  4258. // return [[allMainDocumentPDFViews() valueForKeyPath:@"@min.canGoToFirstPage"] boolValue];
  4259. // } else if (action == @selector(allGoToLastPage:)) {
  4260. // return [[allMainDocumentPDFViews() valueForKeyPath:@"@min.canGoToLastPage"] boolValue];
  4261. // } else if (action == @selector(doGoBack:)) {
  4262. // return [pdfView canGoBack];
  4263. // } else if (action == @selector(doGoForward:)) {
  4264. // return [pdfView canGoForward];
  4265. // } else if (action == @selector(goToMarkedPage:)) {
  4266. // if (beforeMarkedPageIndex != NSNotFound) {
  4267. // [menuItem setTitle:NSLocalizedString(@"Jump Back From Marked Page", @"Menu item title")];
  4268. // return YES;
  4269. // } else {
  4270. // [menuItem setTitle:NSLocalizedString(@"Go To Marked Page", @"Menu item title")];
  4271. // return markedPageIndex != NSNotFound && markedPageIndex != [[pdfView currentPage] pageIndex];
  4272. // }
  4273. // } else if (action == @selector(markPage:)) {
  4274. // return [[self pdfDocument] isLocked] == NO;
  4275. // } else if (action == @selector(doZoomIn:)) {
  4276. // return [self interactionMode] != SKPresentationMode && [pdfView canZoomIn];
  4277. // } else if (action == @selector(doZoomOut:)) {
  4278. // return [self interactionMode] != SKPresentationMode && [pdfView canZoomOut];
  4279. // } else if (action == @selector(doZoomToActualSize:)) {
  4280. // return [[self pdfDocument] isLocked] == NO && ([pdfView autoScales] || fabs([pdfView scaleFactor] - 1.0 ) > 0.01);
  4281. // } else if (action == @selector(doZoomToPhysicalSize:)) {
  4282. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO && ([pdfView autoScales] || fabs([pdfView physicalScaleFactor] - 1.0 ) > 0.01);
  4283. // } else if (action == @selector(doMarqueeZoomTool:)) {
  4284. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4285. // } else if (action == @selector(doZoomToFit:)) {
  4286. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO && [pdfView autoScales] == NO;
  4287. // } else if (action == @selector(alternateZoomToFit:)) {
  4288. // PDFDisplayMode displayMode = [pdfView displayMode];
  4289. // if (displayMode == kPDFDisplaySinglePage || displayMode == kPDFDisplayTwoUp) {
  4290. // [menuItem setTitle:NSLocalizedString(@"Zoom To Width", @"Menu item title")];
  4291. // } else {
  4292. // [menuItem setTitle:NSLocalizedString(@"Zoom To Height", @"Menu item title")];
  4293. // }
  4294. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4295. // } else
  4296. // if (action == @selector(doAutoScale:)) {
  4297. // return [[self pdfDocument] isLocked] == NO && [pdfView autoScales] == NO;
  4298. // } else if (action == @selector(toggleAutoScale:)) {
  4299. // [menuItem setState:[pdfView autoScales] ? NSOnState : NSOffState];
  4300. // return [[self pdfDocument] isLocked] == NO;
  4301. // } else if (action == @selector(rotateRight:) || action == @selector(rotateLeft:) || action == @selector(rotateAllRight:) || action == @selector(rotateAllLeft:)) {
  4302. // return [[self pdfDocument] isLocked] == NO;
  4303. // } else if (action == @selector(cropAll:) || action == @selector(crop:) || action == @selector(autoCropAll:) || action == @selector(smartAutoCropAll:)) {
  4304. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4305. // } else if (action == @selector(autoSelectContent:)) {
  4306. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO && [pdfView toolMode] == SKSelectToolMode;
  4307. // } else if (action == @selector(takeSnapshot:)) {
  4308. // return [[self pdfDocument] isLocked] == NO;
  4309. // } else if (action == @selector(toggleLeftSidePane:)) {
  4310. // if ([self leftSidePaneIsOpen])
  4311. // [menuItem setTitle:NSLocalizedString(@"Hide Panel", @"Menu item title")];
  4312. // else
  4313. // [menuItem setTitle:NSLocalizedString(@"Show Panel", @"Menu item title")];
  4314. // return YES;
  4315. // } else if (action == @selector(toggleRightSidePane:)) {
  4316. // if ([self rightSidePaneIsOpen])
  4317. // [menuItem setTitle:NSLocalizedString(@"Hide Notes Pane", @"Menu item title")];
  4318. // else
  4319. // [menuItem setTitle:NSLocalizedString(@"Show Notes Pane", @"Menu item title")];
  4320. // return [self interactionMode] != SKPresentationMode;
  4321. // } else if (action == @selector(changeLeftSidePaneState:)) {
  4322. // [menuItem setState:mwcFlags.leftSidePaneState == (SKLeftSidePaneState)[menuItem tag] ? (([leftSideController.findTableView window] || [leftSideController.groupedFindTableView window]) ? NSMixedState : NSOnState) : NSOffState];
  4323. // return (SKLeftSidePaneState)[menuItem tag] == SKSidePaneStateThumbnail || [[pdfView document] outlineRoot];
  4324. // } else if (action == @selector(changeRightSidePaneState:)) {
  4325. // [menuItem setState:mwcFlags.rightSidePaneState == (SKRightSidePaneState)[menuItem tag] ? NSOnState : NSOffState];
  4326. // return [self interactionMode] != SKPresentationMode;
  4327. // }
  4328. // // else if (action == @selector(toggleSplitPDF:)) {
  4329. // // if ([(NSView *)secondaryPdfView window])
  4330. // // [menuItem setTitle:NSLocalizedString(@"Hide Split PDF", @"Menu item title")];
  4331. // // else
  4332. // // [menuItem setTitle:NSLocalizedString(@"Show Split PDF", @"Menu item title")];
  4333. // // return [self interactionMode] != SKPresentationMode;
  4334. // // }
  4335. // else
  4336. // if (action == @selector(toggleStatusBar:)) {
  4337. // if ([statusBar isVisible])
  4338. // [menuItem setTitle:NSLocalizedString(@"Hide Status Bar", @"Menu item title")];
  4339. // else
  4340. // [menuItem setTitle:NSLocalizedString(@"Show Status Bar", @"Menu item title")];
  4341. // return [self interactionMode] == SKNormalMode || [self interactionMode] == SKFullScreenMode;
  4342. // } else if (action == @selector(searchPDF:)) {
  4343. // return [self interactionMode] != SKPresentationMode;
  4344. // } else if (action == @selector(toggleFullscreen:)) {
  4345. // if ([self interactionMode] == SKFullScreenMode || [self interactionMode] == SKLegacyFullScreenMode)
  4346. // [menuItem setTitle:NSLocalizedString(@"Exit Full Screen", @"Menu item title")];
  4347. // else
  4348. // [menuItem setTitle:NSLocalizedString(@"Full Screen", @"Menu item title")];
  4349. // return [self canEnterFullscreen] || [self canExitFullscreen];
  4350. // } else if (action == @selector(togglePresentation:)) {
  4351. // if ([self interactionMode] == SKPresentationMode)
  4352. // [menuItem setTitle:NSLocalizedString(@"Exit Presentation", @"Menu item title")];
  4353. // else
  4354. // [menuItem setTitle:NSLocalizedString(@"Presentation", @"Menu item title")];
  4355. // return [self canEnterPresentation] || [self canExitPresentation];
  4356. // } else if (action == @selector(getInfo:)) {
  4357. // return [self interactionMode] != SKPresentationMode;
  4358. // } else if (action == @selector(performFit:)) {
  4359. // return [self interactionMode] == SKNormalMode && [[self pdfDocument] isLocked] == NO;
  4360. // } else if (action == @selector(password:)) {
  4361. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] permissionsStatus] != kPDFDocumentPermissionsOwner;
  4362. // } else if (action == @selector(toggleReadingBar:)) {
  4363. // if ([[self pdfView] hasReadingBar])
  4364. // [menuItem setTitle:NSLocalizedString(@"Hide Reading Bar", @"Menu item title")];
  4365. // else
  4366. // [menuItem setTitle:NSLocalizedString(@"Show Reading Bar", @"Menu item title")];
  4367. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4368. // } else
  4369. // if (action == @selector(savePDFSettingToDefaults:)) {
  4370. // if ([self interactionMode] == SKFullScreenMode || [self interactionMode] == SKLegacyFullScreenMode)
  4371. // [menuItem setTitle:NSLocalizedString(@"Use Current View Settings as Default for Full Screen", @"Menu item title")];
  4372. // else
  4373. // [menuItem setTitle:NSLocalizedString(@"Use Current View Settings as Default", @"Menu item title")];
  4374. // return [self interactionMode] != SKPresentationMode && [[self pdfDocument] isLocked] == NO;
  4375. // } else if (action == @selector(chooseTransition:)) {
  4376. // return [[self pdfDocument] pageCount] > 1;
  4377. // } else if (action == @selector(toggleCaseInsensitiveSearch:)) {
  4378. // [menuItem setState:mwcFlags.caseInsensitiveSearch ? NSOnState : NSOffState];
  4379. // return YES;
  4380. // } else if (action == @selector(toggleWholeWordSearch:)) {
  4381. // [menuItem setState:mwcFlags.wholeWordSearch ? NSOnState : NSOffState];
  4382. // return YES;
  4383. // } else if (action == @selector(toggleCaseInsensitiveNoteSearch:)) {
  4384. // [menuItem setState:mwcFlags.caseInsensitiveNoteSearch ? NSOnState : NSOffState];
  4385. // return YES;
  4386. // } else if (action == @selector(toggleAutoResizeNoteRows:)) {
  4387. // [menuItem setState:mwcFlags.autoResizeNoteRows ? NSOnState : NSOffState];
  4388. // return YES;
  4389. // } else if (action == @selector(performFindPanelAction:)) {
  4390. // if ([self interactionMode] == SKPresentationMode)
  4391. // return NO;
  4392. // switch ([menuItem tag]) {
  4393. // case NSFindPanelActionShowFindPanel:
  4394. // return YES;
  4395. // case NSFindPanelActionNext:
  4396. // case NSFindPanelActionPrevious:
  4397. // return YES;
  4398. // case NSFindPanelActionSetFindString:
  4399. // return [[[self pdfView] currentSelection] hasCharacters];
  4400. // default:
  4401. // return NO;
  4402. // }
  4403. // } else
  4404. // if (action == @selector(highlightFormFiled:)) {
  4405. // BOOL highlightFormFiled = [[NSUserDefaults standardUserDefaults] boolForKey:@"kPDFViewHighlightFormFiledKey"];
  4406. // [menuItem setState:highlightFormFiled ? NSOnState : NSOffState];
  4407. // return YES;
  4408. // } else if (action == @selector(highlightLinks:)) {
  4409. // BOOL highlightLinks = [[NSUserDefaults standardUserDefaults] boolForKey:@"kPDFViewHighlightLinksKey"];
  4410. // [menuItem setState:highlightLinks ? NSOnState : NSOffState];
  4411. // return YES;
  4412. // } else if (action == @selector(link:)) {
  4413. // return ([self.pdfView toolMode] == SKTextToolMode || [self.pdfView toolMode] == SKNoteToolMode) && [self.pdfView hideNotes] == NO && [self.pdfView.document isLocked] == NO;
  4414. // return ([self.pdfView toolMode] == SKTextToolMode || [self.pdfView toolMode] == SKNoteToolMode) && [self.pdfView hideNotes] == NO && [self.pdfView.document isLocked] == NO && [[self.pdfView currentSelection] hasCharacters];
  4415. // } else if (action == @selector(deletePage:)) {
  4416. // return self.pdfView.document.pageCount > 1 ? YES : NO;
  4417. // } else if (action == @selector(toggleAutoFlow:)) {
  4418. // [menuItem setState:[self.pdfView isAutoFlow] ? NSOnState : NSOffState];
  4419. // return YES;
  4420. // } else if (action == @selector(themesColor:)){
  4421. // if (KMPDFViewModeNormal== self.pdfView.viewMode) {
  4422. // [menuItem setState:(menuItem.tag == 0)?NSOnState:NSOffState];
  4423. // } else if (KMPDFViewModeSoft == self.pdfView.viewMode){
  4424. // [menuItem setState:(menuItem.tag == 1)?NSOnState:NSOffState];
  4425. // } else if (KMPDFViewModeNight == self.pdfView.viewMode){
  4426. // [menuItem setState:(menuItem.tag == 2)?NSOnState:NSOffState];
  4427. // } else if (KMPDFViewModeGreen == self.pdfView.viewMode){
  4428. // [menuItem setState:(menuItem.tag == 3)?NSOnState:NSOffState];
  4429. // } else if (KMPDFViewModeThemes1 == self.pdfView.viewMode){
  4430. // [menuItem setState:(menuItem.tag == 4)?NSOnState:NSOffState];
  4431. // } else if (KMPDFViewModeThemes2 == self.pdfView.viewMode){
  4432. // [menuItem setState:(menuItem.tag == 5)?NSOnState:NSOffState];
  4433. // } else if (KMPDFViewModeThemes3 == self.pdfView.viewMode){
  4434. // [menuItem setState:(menuItem.tag == 6)?NSOnState:NSOffState];
  4435. // } else if (KMPDFViewModeThemes4 == self.pdfView.viewMode){
  4436. // [menuItem setState:(menuItem.tag == 7)?NSOnState:NSOffState];
  4437. // }
  4438. // // else {
  4439. // // [menuItem setState:(menuItem.tag == 4)?NSOnState:NSOffState];
  4440. // // }
  4441. // NSData * data = [[NSUserDefaults standardUserDefaults] objectForKey:@"kKMPDFViewModeThemesArray"] ? : nil;
  4442. // NSInteger themesCount;
  4443. // if (data) {
  4444. // NSArray * appArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  4445. // NSMutableArray * mutableArray = [NSMutableArray arrayWithArray:appArray];
  4446. // themesCount = [menuItem tag] - mutableArray.count;
  4447. // } else {
  4448. // themesCount = [menuItem tag] - 4;
  4449. // }
  4450. // if (themesCount >= 0) {
  4451. // menuItem.hidden = YES;
  4452. // return NO;
  4453. // } else {
  4454. // menuItem.hidden = NO;
  4455. // return YES;
  4456. // }
  4457. // } else
  4458. // if (action == @selector(splitViewAction:)){
  4459. // if (KMPDFViewSplitModeHorizontal == self.pdfView.viewSplitMode) {
  4460. // [menuItem setState:(menuItem.tag == 0)?NSOnState:NSOffState];
  4461. // } else if (KMPDFViewSplitModeVertical == self.pdfView.viewSplitMode) {
  4462. // [menuItem setState:(menuItem.tag == 1)?NSOnState:NSOffState];
  4463. // } else if (KMPDFViewSplitModeDisable == self.pdfView.viewSplitMode) {
  4464. // [menuItem setState:(menuItem.tag == 2)?NSOnState:NSOffState];
  4465. // }
  4466. // } else if (action == @selector(outlineContextMenuItemClicked_AddEntry:) ||
  4467. // action == @selector(outlineContextMenuItemClicked_AddChildEntry:) ||
  4468. // action == @selector(outlineContextMenuItemClicked_AddAuntEntry:) ||
  4469. // action == @selector(outlineContextMenuItemClicked_RemoveEntry:) ||
  4470. // action == @selector(outlineContextMenuItemClicked_Edit:) ||
  4471. // action == @selector(outlineContextMenuItemClicked_SetDestination:) ||
  4472. // action == @selector(outlineContextMenuItemClicked_Rename:) ||
  4473. // action == @selector(outlineContextMenuItemClicked_Promote:) ||
  4474. // action == @selector(outlineContextMenuItemClicked_Demote:)) {
  4475. // if ([self.pdfView.document isLocked]) {
  4476. // return NO;
  4477. // }
  4478. // if (self.isSearchOutlineMode) {
  4479. // if (action == @selector(outlineContextMenuItemClicked_AddEntry:) ||
  4480. // action == @selector(outlineContextMenuItemClicked_AddChildEntry:) ||
  4481. // action == @selector(outlineContextMenuItemClicked_AddAuntEntry:) ||
  4482. // action == @selector(outlineContextMenuItemClicked_Edit:) ||
  4483. // action == @selector(outlineContextMenuItemClicked_Rename:)
  4484. // ) {
  4485. // return NO;
  4486. // }
  4487. // }
  4488. // if (self.leftSideController.tocOutlineView.selectedRowIndexes.count > 1) {
  4489. // if (menuItem.tag == KOutlineViewMenuItemTag_Remove) {
  4490. // return YES;
  4491. // }
  4492. // return NO;
  4493. // } else if (self.leftSideController.tocOutlineView.selectedRowIndexes.count > 0) {
  4494. // if (action == @selector(outlineContextMenuItemClicked_AddChildEntry:) ||
  4495. // action == @selector(outlineContextMenuItemClicked_SetDestination:)) {
  4496. // return YES;
  4497. // }
  4498. // }
  4499. // if (self.leftSideController.tocOutlineView.clickedRow == -1) {
  4500. // if (action == @selector(outlineContextMenuItemClicked_AddEntry:)) {
  4501. // return YES;
  4502. // } else {
  4503. // return NO;
  4504. // }
  4505. // } else {
  4506. // PDFOutline *clickedOutline = [self.leftSideController.tocOutlineView itemAtRow:self.leftSideController.tocOutlineView.clickedRow];
  4507. // if (clickedOutline.index > 0) {
  4508. // if (action == @selector(outlineContextMenuItemClicked_Demote:)) {
  4509. // return YES;
  4510. // }
  4511. // } else {
  4512. // if (action == @selector(outlineContextMenuItemClicked_Demote:)) {
  4513. // return NO;
  4514. // }
  4515. // }
  4516. // PDFOutline *parentOutLine = clickedOutline.parent;
  4517. // PDFOutline *grandparentOutLine = parentOutLine.parent;
  4518. // //if clicked PDFOutline's parent exist
  4519. // if (grandparentOutLine) {
  4520. // //and title is equla "add_AuntOutlineKey"
  4521. // if (action == @selector(outlineContextMenuItemClicked_AddAuntEntry:)) {
  4522. // return YES;
  4523. // } else if (action == @selector(outlineContextMenuItemClicked_Promote:)){
  4524. // return YES;
  4525. // }
  4526. // } else {
  4527. // if (action == @selector(outlineContextMenuItemClicked_AddAuntEntry:)) {
  4528. // return NO;
  4529. // }else if (action == @selector(outlineContextMenuItemClicked_Promote:)){
  4530. // return NO;
  4531. // }
  4532. // }
  4533. // }
  4534. // return YES;
  4535. // } else
  4536. // if ([menuItem action] == @selector(toggleEncryptFilePanel:)) {
  4537. // [menuItem setTitle:NSLocalizedString(@"Set Passwords", @"Menu item title")];
  4538. // NSURL *fileURL = [self.pdfView.document documentURL];
  4539. // if (!fileURL) {
  4540. // return YES;
  4541. // }
  4542. // PDFDocument *pdfDoc = [[[PDFDocument alloc] initWithURL:fileURL] autorelease];
  4543. //
  4544. // if ([pdfDoc isLocked]) {
  4545. // [menuItem setTitle:NSLocalizedString(@"Remove Security", @"Menu item title")];
  4546. // }
  4547. // } else if (action == @selector(toggleToolbarShow:)) {
  4548. // NSToolbar *toolbar = [self.window toolbar];
  4549. // if ([toolbar isVisible])
  4550. // [menuItem setTitle:NSLocalizedString(@"Hide Toolbar", @"Menu item title")];
  4551. // else
  4552. // [menuItem setTitle:NSLocalizedString(@"Show Toolbar", @"Menu item title")];
  4553. // return YES;
  4554. // } else if (action == @selector(readMode:)) {
  4555. // menuItem.state = self.isReadMode ? NSControlStateValueOn : NSControlStateValueOff;
  4556. // return YES;
  4557. // } else if (action == @selector(addForm:)) {
  4558. // return YES;
  4559. // } else if (action == @selector(toggleOutlineCaseInsensitiveSearch:)){
  4560. // [menuItem setState:self.outlineIgnoreCaseFlag?NSControlStateValueOn:NSControlStateValueOff];
  4561. // return YES;
  4562. // } else if (action == @selector(note_expandAllComments:) ||
  4563. // action == @selector(note_foldAllComments:) ||
  4564. // action == @selector(exportAnnotationNotes:) ||
  4565. // action == @selector(leftSideEmptyAnnotationClick_DeleteAnnotation:) ||
  4566. // action == @selector(removeAllAnnotations:)) {
  4567. // if (@available(macOS 10.13, *)) {
  4568. // if (notes.count == 0) {
  4569. // return NO;
  4570. // } else {
  4571. // return YES;
  4572. // }
  4573. // } else {
  4574. // if (action == @selector(note_expandAllComments:) ||
  4575. // action == @selector(note_foldAllComments:)) {
  4576. // return NO;
  4577. // }
  4578. // }
  4579. // } else
  4580. // if (action == @selector(unfoldNoteAction:) ||
  4581. // action == @selector(foldNoteAction:)) {
  4582. // NSInteger row = [rightSideController.noteOutlineView clickedRow];
  4583. // NSArray *noteArr = [rightSideController.noteArrayController arrangedObjects];
  4584. // PDFAnnotation *foldNote = (PDFAnnotation *)noteArr[row];
  4585. // if (@available(macOS 10.13, *)) {
  4586. // if ([foldNote isKindOfClass:[PDFAnnotationMarkup class]] ||
  4587. // [foldNote isKindOfClass:[SKNPDFAnnotationNote class]]) {
  4588. // return YES;
  4589. // } else {
  4590. // return NO;
  4591. // }
  4592. // } else {
  4593. // return NO;
  4594. // }
  4595. // } else
  4596. if (action == #selector(menuItemClick_ExportPNG) ||
  4597. action == #selector(menuItemClick_ExportJPG) ||
  4598. action == #selector(menuItemClick_ExportPDF)) {
  4599. if (self.snapshotTableView.selectedRow == -1 ) {
  4600. return false
  4601. } else {
  4602. return true
  4603. }
  4604. }
  4605. // else if (action == @selector(editNoteFromTable:)) {
  4606. // NSInteger row = [rightSideController.noteOutlineView clickedRow];
  4607. // NSArray * noteArr = [rightSideController.noteArrayController arrangedObjects];
  4608. // PDFAnnotation *foldNote = (PDFAnnotation *)noteArr[row];
  4609. // if (@available(macOS 10.13, *)) {
  4610. // if ([foldNote.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature]) {
  4611. // return NO;
  4612. // }
  4613. // }
  4614. // if ([foldNote isKindOfClass:[PDFAnnotationStamp class]] ||
  4615. // [foldNote isKindOfClass:[KMAnnotationStamp class]]) {
  4616. // return NO;
  4617. // } else {
  4618. // return YES;
  4619. // }
  4620. // }
  4621. else if (action == #selector(menuItemClick_SelectAll)) {
  4622. menuItem.state = self._snapshotListIsAllSelected() ? .on : .off
  4623. return true
  4624. }
  4625. // else if (action == @selector(leftSideEmptyAnnotationClick_DeleteOutline:)) {
  4626. // PDFOutline * item = [[pdfView document] outlineRoot];
  4627. // if (self.isSearchOutlineMode) {
  4628. // NSInteger num = 0;
  4629. // for (NSUInteger i = 0; i < [item numberOfChildren]; i++) {
  4630. // PDFOutline *outline = [item childAtIndex:i];
  4631. // if ([self hasContainString:self.leftSideController.outlineSearchField.stringValue rootOutline:outline]) {
  4632. // num ++;
  4633. // }
  4634. // }
  4635. // if (num > 0)
  4636. // return YES;
  4637. // else
  4638. // return NO;
  4639. // } else {
  4640. // if ([item numberOfChildren] > 0)
  4641. // return YES;
  4642. // else
  4643. // return NO;
  4644. // }
  4645. // }
  4646. return true
  4647. }
  4648. }
  4649. // MARK: - Menu Item Actions
  4650. extension KMLeftSideViewController {
  4651. @objc func cutPage(_ sender: AnyObject?) {
  4652. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4653. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4654. // return;
  4655. // }
  4656. self._tableView(self.thumbnailTableView, cutRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4657. }
  4658. @objc func copyPage(_ sender: AnyObject?) {
  4659. self.tableView(self.thumbnailTableView, copyRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4660. }
  4661. @objc func pastePage(_ sender: AnyObject?) {
  4662. self.tableView(self.thumbnailTableView, pasteFromPasteboard: nil)
  4663. }
  4664. @objc func deletePage(_ sender: AnyObject?) {
  4665. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4666. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4667. // return;
  4668. // }
  4669. self.tableView(self.thumbnailTableView, deleteRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4670. }
  4671. @objc func rotatePageMenuAction(_ sender: AnyObject?) {
  4672. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4673. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4674. // return;
  4675. // }
  4676. //
  4677. self.tableView(self.thumbnailTableView, rotateRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes as NSIndexSet)
  4678. }
  4679. @objc func quickInsert(_ sender: AnyObject?) {
  4680. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4681. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4682. // return;
  4683. // }
  4684. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4685. if idx == NSNotFound || idx >= self.listView.document.pageCount {
  4686. return
  4687. }
  4688. let result = self.listView.insertPage(KMNormalBlankSize, at: idx+1)
  4689. if result == false {
  4690. return
  4691. }
  4692. var selectedIndexSet = IndexSet()
  4693. selectedIndexSet.insert(idx+1)
  4694. self.insertPages(selectedIndexSet, pageAt: idx)
  4695. }
  4696. @objc func insert(_ sender: AnyObject?) {
  4697. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4698. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4699. // return;
  4700. // }
  4701. guard let document = self.listView.document else {
  4702. return
  4703. }
  4704. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4705. if idx == NSNotFound || idx >= document.pageCount {
  4706. return
  4707. }
  4708. if document.allowsCopying == false || document.allowsPrinting == false {
  4709. Task {
  4710. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4711. }
  4712. return
  4713. }
  4714. let insertVC = KMPDFEditInsertBlankPageWindow(document: document)
  4715. insertVC.insertLocation = 3
  4716. insertVC.currentPage = idx + 1
  4717. insertVC.callback = { [weak self] pdfDoc, _, pages, insertI in
  4718. if let _pages = pages {
  4719. // mm 单位的大小
  4720. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  4721. self?.km_endSheet()
  4722. return
  4723. }
  4724. var pageSize = _winC.pageSize
  4725. let direction = _winC.pageRotation == 0 ? 0 : 1
  4726. if (direction == 0) { // 纵向
  4727. if (pageSize.width > pageSize.height) { // 需要交换
  4728. let tmp = pageSize.width
  4729. pageSize.width = pageSize.height
  4730. pageSize.height = tmp
  4731. } else {
  4732. // no things.
  4733. }
  4734. } else { // 横向
  4735. if (pageSize.width > pageSize.height) {
  4736. // no things.
  4737. } else { // 需要交换
  4738. let tmp = pageSize.width
  4739. pageSize.width = pageSize.height
  4740. pageSize.height = tmp
  4741. }
  4742. }
  4743. /// 插入位置
  4744. let document = CPDFDocument()
  4745. document?.insertPage(pageSize, at: 0)
  4746. if let page: CPDFPage = (document?.page(at: 0)) {
  4747. self?.insertPage(page, pageAt: insertI)
  4748. }
  4749. }
  4750. self?.km_quick_endSheet()
  4751. }
  4752. self.km_beginSheet(windowC: insertVC)
  4753. }
  4754. @objc func insertPDF(_ sender: AnyObject?) {
  4755. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4756. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4757. // return;
  4758. // }
  4759. guard let document = self.listView.document else {
  4760. return
  4761. }
  4762. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4763. if idx == NSNotFound || idx >= document.pageCount {
  4764. return
  4765. }
  4766. if document.allowsCopying == false || document.allowsPrinting == false {
  4767. Task {
  4768. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4769. }
  4770. return
  4771. }
  4772. let panel = NSOpenPanel()
  4773. panel.allowedFileTypes = ["pdf"]
  4774. panel.beginSheetModal(for: self.view.window!) { response in
  4775. if response == .cancel {
  4776. return
  4777. }
  4778. for fileURL in panel.urls {
  4779. let pdfDoc = CPDFDocument(url: fileURL)
  4780. if let data = pdfDoc?.isLocked, data {
  4781. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4782. let com = PasswordWindowController(windowNibName: "PasswordWindowController")
  4783. com.fileURL = fileURL
  4784. self.km_beginSheet(windowC: com)
  4785. com.closeCallBack = { [unowned self] password in
  4786. self.km_quick_endSheet()
  4787. // }
  4788. if (password.isEmpty == false) {
  4789. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL, password: password)
  4790. insertVC.insertLocation = 3
  4791. insertVC.currentPage = idx + 1
  4792. self.km_beginSheet(windowC: insertVC)
  4793. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4794. var indexs = IndexSet()
  4795. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4796. self?.km_quick_endSheet()
  4797. return
  4798. }
  4799. let doc = _winC.insertDocument!
  4800. let fileAttribute = _winC.fileAttribute
  4801. var insertIndex = insertIdx
  4802. var insertPages: [CPDFPage] = []
  4803. for number in fileAttribute.fetchSelectPages() {
  4804. if let page = doc.page(at: UInt(number.intValue-1)) {
  4805. insertPages.append(page)
  4806. indexs.insert(insertIndex)
  4807. insertIndex += 1
  4808. }
  4809. }
  4810. for (i, page) in insertPages.enumerated() {
  4811. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4812. }
  4813. self?.insertPages(indexs, pageAt: insertIdx)
  4814. self?.km_quick_endSheet()
  4815. }
  4816. }
  4817. }
  4818. }
  4819. } else {
  4820. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL)
  4821. insertVC.insertLocation = 3
  4822. insertVC.currentPage = idx + 1
  4823. self.km_beginSheet(windowC: insertVC)
  4824. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4825. var indexs = IndexSet()
  4826. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4827. self?.km_quick_endSheet()
  4828. return
  4829. }
  4830. let doc = _winC.insertDocument!
  4831. let fileAttribute = _winC.fileAttribute
  4832. var insertIndex = insertIdx
  4833. var insertPages: [CPDFPage] = []
  4834. for number in fileAttribute.fetchSelectPages() {
  4835. if let page = doc.page(at: UInt(number.intValue-1)) {
  4836. insertPages.append(page)
  4837. indexs.insert(insertIndex)
  4838. insertIndex += 1
  4839. }
  4840. }
  4841. for (i, page) in insertPages.enumerated() {
  4842. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4843. }
  4844. self?.insertPages(indexs, pageAt: insertIdx)
  4845. self?.km_quick_endSheet()
  4846. }
  4847. }
  4848. }
  4849. }
  4850. }
  4851. @objc func extractPage(_ sender: AnyObject?) {
  4852. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4853. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4854. // return;
  4855. // }
  4856. self.tableView(self.thumbnailTableView, extractRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4857. }
  4858. @objc func pageEdit(_ sender: AnyObject?) {
  4859. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .pageEdit, params: nil)
  4860. }
  4861. @objc func displayPageSize(_ sender: AnyObject?) {
  4862. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4863. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4864. // return;
  4865. // }
  4866. self.isDisplayPageSize = !self.isDisplayPageSize;
  4867. UserDefaults.standard.setValue(self.isDisplayPageSize, forKey: "kKMThumbnailDisplayPageSizeKey")
  4868. UserDefaults.standard.synchronize()
  4869. Task { @MainActor in
  4870. self.thumbnailTableView.reloadData()
  4871. }
  4872. }
  4873. @objc func sharePage(_ sender: AnyObject?) {
  4874. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4875. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4876. // return;
  4877. // }
  4878. guard let document = self.listView.document else {
  4879. return
  4880. }
  4881. var pages = NSMutableArray()
  4882. for idx in self.thumbnailTableView.selectedRowIndexes {
  4883. if (idx < document.pageCount) {
  4884. if let page = self.listView.document.page(at: UInt(idx)) {
  4885. pages.add(page)
  4886. }
  4887. }
  4888. }
  4889. let pdf = CPDFDocument()
  4890. for page in pages {
  4891. // PDFPage *copyPage = [[page copy] autorelease];
  4892. if let _page = page as? CPDFPage {
  4893. pdf?.insertPageObject(_page, at: pdf?.pageCount ?? 0)
  4894. }
  4895. }
  4896. // NSString * = nil;
  4897. var fileName = ""
  4898. // NSString * = [self.pdfDocument.documentURL.lastPathComponent stringByDeletingPathExtension];
  4899. var documentFileName = document.documentURL?.deletingPathExtension().lastPathComponent ?? ""
  4900. var tName = self.fileNameWithSelectedPages(self.thumbnailTableView.selectedRowIndexes)
  4901. if (tName.count > 50) {
  4902. tName = tName.substring(to: 50)
  4903. }
  4904. if (pages.count > 1) {
  4905. fileName = String(format: "%@ pages %@", documentFileName, tName)
  4906. } else {
  4907. fileName = String(format: "%@ page %@", documentFileName, tName)
  4908. }
  4909. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  4910. var cachesDir = paths.first ?? ""
  4911. cachesDir = "\(cachesDir)/\(fileName).pdf"
  4912. var array = NSMutableArray()
  4913. let url = URL(fileURLWithPath: cachesDir)
  4914. array.add(url)
  4915. let vc = KMProgressWindowController()
  4916. // // [NSApp beginSheet:[vc window]
  4917. // // modalForWindow:self.window
  4918. // // modalDelegate:nil
  4919. // // didEndSelector:nil
  4920. // // contextInfo:NULL];
  4921. self.view.window?.beginSheet(vc.window!, completionHandler: { [unowned self] returnCode in
  4922. NSApp.endSheet(self.view.window!, returnCode: returnCode.rawValue)
  4923. })
  4924. DispatchQueue.global().async {
  4925. let sucess = pdf?.write(toFile: cachesDir) ?? false
  4926. if (sucess) {
  4927. DispatchQueue.main.async {
  4928. // [[sender representedObject] performWithItems:array];
  4929. let represent : NSSharingService = (sender as! NSMenuItem).representedObject as! NSSharingService
  4930. represent.perform(withItems: [url])
  4931. NSApp.endSheet(vc.window!)
  4932. vc.close()
  4933. }
  4934. } else {
  4935. NSApp.endSheet(vc.window!)
  4936. vc.close()
  4937. }
  4938. }
  4939. // [vc release];
  4940. }
  4941. @objc func unfoldNoteAction(_ sender: AnyObject?) {
  4942. KMPrint("KMLeftSideViewController-unfoldNoteAction...")
  4943. }
  4944. @objc func foldNoteAction(_ sender: AnyObject?) {
  4945. KMPrint("KMLeftSideViewController-foldNoteAction...")
  4946. }
  4947. @objc func deleteNotes(_ sender: AnyObject?) {
  4948. KMPrint("KMLeftSideViewController-deleteNotes...")
  4949. }
  4950. @objc func removeAllAnnotations(_ sender: AnyObject?) {
  4951. KMPrint("KMLeftSideViewController-removeAllAnnotations...")
  4952. }
  4953. @objc func addAnnotationsForSelections(_ sender: AnyObject?) {
  4954. KMPrint("KMLeftSideViewController-addAnnotationsForSelections...")
  4955. }
  4956. @objc func selectSelections(_ sender: AnyObject?) {
  4957. KMPrint("KMLeftSideViewController-selectSelections...")
  4958. }
  4959. @objc func toggleWholeWordSearch(_ sender: AnyObject?) {
  4960. KMPrint("KMLeftSideViewController-toggleWholeWordSearch...")
  4961. }
  4962. @objc func toggleCaseInsensitiveSearch(_ sender: AnyObject?) {
  4963. KMPrint("KMLeftSideViewController-toggleCaseInsensitiveSearch...")
  4964. }
  4965. @objc func toggleCaseInsensitiveNoteSearch(_ sender: AnyObject?) {
  4966. KMPrint("KMLeftSideViewController-toggleCaseInsensitiveNoteSearch...")
  4967. }
  4968. @objc func searchNotes(_ sender: AnyObject?) {
  4969. if self.findState == .note {
  4970. // if (mwcFlags.findState == SKFindStateNote)
  4971. // [self updateNoteFilterPredicate];
  4972. } else {
  4973. self.updateSnapshotFilterPredicate()
  4974. }
  4975. let textfield = sender as? NSSearchField
  4976. if let data = textfield?.stringValue.isEmpty, data == false {
  4977. let findPboard = NSPasteboard(name: .find)
  4978. findPboard.clearContents()
  4979. // findPboard.writeObjects([textfield!.stringValue])
  4980. }
  4981. }
  4982. @objc func toggleSelectedSnapshots(_ sender: AnyObject?) {
  4983. let indexs = self.snapshotTableView.selectedRowIndexes
  4984. if indexs.isEmpty {
  4985. return
  4986. }
  4987. let model = self.snapshots[indexs.last!]
  4988. let windowC = model.windowC
  4989. if let data = windowC?.window?.isVisible, data {
  4990. windowC?.miniaturize()
  4991. } else {
  4992. windowC?.deminiaturize()
  4993. }
  4994. var rowIndexSet = IndexSet()
  4995. let row = self.snapshotTableView.selectedRow
  4996. if row >= 0 && row < self.snapshots.count {
  4997. rowIndexSet.insert(row)
  4998. }
  4999. var columnIndexSet = IndexSet()
  5000. columnIndexSet.insert(0)
  5001. self.snapshotTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  5002. }
  5003. @objc func toggleOutlineCaseInsensitiveSearch(_ sender: AnyObject?) {
  5004. KMPrint("KMLeftSideViewController-toggleOutlineCaseInsensitiveSearch...")
  5005. }
  5006. @objc func outlineContextMenuItemClicked_AddEntry(_ sender: AnyObject?) {
  5007. var PDFOutlineArray = NSMutableArray()
  5008. let rowSet = self.selectedRowIndexes()
  5009. for idx in rowSet {
  5010. PDFOutlineArray.add(self.tocOutlineView.item(atRow: idx))
  5011. }
  5012. if (PDFOutlineArray.count == 0) {
  5013. var lastPDFLine = self.tocOutlineView.item(atRow: self.tocOutlineView.numberOfRows-1) as? CPDFOutline
  5014. var rootPDFOutline: CPDFOutline?
  5015. if (lastPDFLine != nil) {
  5016. while (lastPDFLine!.parent != nil) {
  5017. lastPDFLine = lastPDFLine?.parent
  5018. }
  5019. rootPDFOutline = lastPDFLine
  5020. } else {
  5021. rootPDFOutline = self.listView.document.outlineRoot()
  5022. if ((rootPDFOutline == nil)) {
  5023. rootPDFOutline = CPDFOutline()
  5024. self.listView.document.setOutlineRoot(rootPDFOutline)
  5025. }
  5026. }
  5027. let addOutLine = CPDFOutline()
  5028. addOutLine.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.listView.currentPageIndex+1)
  5029. addOutLine.destination = self.listView.currentDestination
  5030. self.addoutline(parent: rootPDFOutline, addOutline: addOutLine, index: Int(rootPDFOutline?.numberOfChildren ?? 0), needExpand: false)
  5031. } else {
  5032. let currentPDFline = PDFOutlineArray.lastObject as? CPDFOutline
  5033. let currentIndex = currentPDFline?.index ?? 0
  5034. var parent: CPDFOutline?
  5035. parent = currentPDFline?.parent
  5036. let addOutLine = CPDFOutline()
  5037. addOutLine.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.listView.currentPageIndex+1)
  5038. addOutLine.destination = self.listView.currentDestination
  5039. self.addoutline(parent: parent, addOutline: addOutLine, index: Int(currentIndex) + 1, needExpand: false)
  5040. self.tocOutlineView.scrollRowToVisible(Int(currentIndex) + 1)
  5041. self.tocOutlineView.deselectRow(Int(currentIndex)+1)
  5042. }
  5043. }
  5044. @objc func outlineContextMenuItemClicked_AddChildEntry(_ sender: AnyObject?) {
  5045. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_AddChildEntry...")
  5046. }
  5047. @objc func outlineContextMenuItemClicked_AddAuntEntry(_ sender: AnyObject?) {
  5048. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_AddAuntEntry...")
  5049. }
  5050. @objc func outlineContextMenuItemClicked_RemoveEntry(_ sender: AnyObject?) {
  5051. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_RemoveEntry...")
  5052. }
  5053. @objc func outlineContextMenuItemClicked_Edit(_ sender: AnyObject?) {
  5054. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_Edit...")
  5055. }
  5056. @objc func outlineContextMenuItemClicked_SetDestination(_ sender: AnyObject?) {
  5057. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_SetDestination...")
  5058. }
  5059. @objc func outlineContextMenuItemClicked_Rename(_ sender: AnyObject?) {
  5060. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_Rename...")
  5061. }
  5062. @objc func outlineContextMenuItemClicked_Promote(_ sender: AnyObject?) {
  5063. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_Promote...")
  5064. }
  5065. @objc func outlineContextMenuItemClicked_Demote(_ sender: AnyObject?) {
  5066. KMPrint("KMLeftSideViewController-outlineContextMenuItemClicked_Demote...")
  5067. }
  5068. private func _tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  5069. if tv.isEqual(to: self.thumbnailTableView) {
  5070. self._copysPages.removeAll()
  5071. for idx in rowIndexes {
  5072. if (idx != NSNotFound) {
  5073. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  5074. self._copysPages.append(page)
  5075. }
  5076. }
  5077. }
  5078. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  5079. }
  5080. }
  5081. // MARK: - Snapshot
  5082. @objc func menuItemClick_ExportPNG(_ sender: AnyObject?) {
  5083. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5084. return
  5085. }
  5086. let image = snapshot.thumbnailWithSize(0)
  5087. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.pngData(), allowedTypes: ["png"]) { url in
  5088. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  5089. }
  5090. }
  5091. @objc func menuItemClick_ExportJPG(_ sender: AnyObject?) {
  5092. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5093. return
  5094. }
  5095. let image = snapshot.thumbnailWithSize(0)
  5096. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.jpgData(), allowedTypes: ["jpg"]) { url in
  5097. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  5098. }
  5099. }
  5100. @objc func menuItemClick_ExportPDF(_ sender: AnyObject?) {
  5101. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5102. return
  5103. }
  5104. if let image = snapshot.thumbnailWithSize(0) {
  5105. let document = CPDFDocument()
  5106. _ = document?.km_insert(image: image, at: 0)
  5107. NSPanel.savePanel_pdf_success(self.view.window!, document: document) { url in
  5108. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  5109. }
  5110. }
  5111. }
  5112. @objc func menuItemClick_Print(_ sender: AnyObject?) {
  5113. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5114. return
  5115. }
  5116. if let image = snapshot.thumbnailWithSize(0) {
  5117. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .print, params: image)
  5118. }
  5119. }
  5120. @objc func menuItemClick_SelectAll(_ sender: AnyObject?) {
  5121. let selected = self._snapshotListIsAllSelected()
  5122. for model in self.snapshots {
  5123. model.isSelected = !selected
  5124. }
  5125. Task { @MainActor in
  5126. self.snapshotTableView.reloadData()
  5127. }
  5128. }
  5129. @objc func deleteAllSnapshot(_ sender: AnyObject?) {
  5130. for model in self.snapshots {
  5131. model.windowC?.close()
  5132. }
  5133. }
  5134. @objc func hideSnapshot(_ sender: AnyObject?) {
  5135. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5136. return
  5137. }
  5138. if let data = snapshot.window?.isVisible, data {
  5139. snapshot.miniaturize()
  5140. }
  5141. }
  5142. @objc func showSnapshot(_ sender: AnyObject?) {
  5143. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5144. return
  5145. }
  5146. if let data = snapshot.window?.isVisible, data {
  5147. snapshot.window?.orderFront(nil)
  5148. } else {
  5149. snapshot.deminiaturize()
  5150. }
  5151. }
  5152. @objc func deleteSnapshot(_ sender: AnyObject?) {
  5153. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5154. return
  5155. }
  5156. snapshot.close()
  5157. }
  5158. @objc func menuItemClick_Copy(_ sender: AnyObject?) {
  5159. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  5160. return
  5161. }
  5162. let image = snapshot.thumbnailWithSize(0)
  5163. if let tiffData = image?.tiffRepresentation {
  5164. let pasteboardItem = NSPasteboardItem()
  5165. pasteboardItem.setData(tiffData, forType: .tiff)
  5166. let pboard = NSPasteboard.general
  5167. pboard.clearContents()
  5168. pboard.writeObjects([pasteboardItem])
  5169. }
  5170. }
  5171. func updateSnapshotFilterPredicate() {
  5172. let searchString = self.snapshotSearchField.stringValue
  5173. self.searchSnapshots.removeAll()
  5174. if self.findState == .snapshot && searchString.isEmpty == false {
  5175. self.searchSnapshots = self.snapshots.filter({ model in
  5176. let data = model.windowC?.string.contains(searchString) ?? false
  5177. return data
  5178. })
  5179. }
  5180. Task { @MainActor in
  5181. self.updataLeftSideSnapView()
  5182. self.snapshotTableView.reloadData()
  5183. }
  5184. }
  5185. private func _snapshotListIsAllSelected() -> Bool {
  5186. if self.snapshots.isEmpty {
  5187. return false
  5188. }
  5189. for model in self.snapshots {
  5190. if model.isSelected == false {
  5191. return false
  5192. }
  5193. }
  5194. return true
  5195. }
  5196. }
  5197. // MARK: - Undo & Redo
  5198. extension KMLeftSideViewController {
  5199. @objc dynamic func tableView(_ tv: NSTableView, rotateRowsWithIndexes rowIndexes: NSIndexSet) {
  5200. if tv.isEqual(to: self.thumbnailTableView) {
  5201. for idx in rowIndexes {
  5202. if (idx != NSNotFound) {
  5203. let page = self.listView.document.page(at: UInt(idx))
  5204. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).rotatePage(page, pageAt: idx)
  5205. page?.rightRotate()
  5206. self.listView.layoutDocumentView()
  5207. self.resetThumbnails()
  5208. // NSInteger pageIndex = MIN(idx, [[pdfView document] pageCount]-1);
  5209. // [pdfView goToPage:[[pdfView document] pageAtIndex:pageIndex]];
  5210. }
  5211. self.thumbnailTableView.selectRowIndexes(rowIndexes as IndexSet, byExtendingSelection: true)
  5212. }
  5213. }
  5214. }
  5215. @objc dynamic func rotatePage(_ page: CPDFPage?, pageAt index: Int) {
  5216. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, rotateRowsWithIndexes: NSIndexSet(index: index))
  5217. page?.leftRotate()
  5218. self.listView.layoutDocumentView()
  5219. self.resetThumbnails()
  5220. }
  5221. @objc dynamic func insertPage(_ page: CPDFPage, pageAt index: Int) {
  5222. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: index))
  5223. self.listView.document.insertPageObject(page, at: UInt(index))
  5224. self.listView.layoutDocumentView()
  5225. // [pageLabels setArray:[[pdfView document] pageLabels]];
  5226. self.resetThumbnails()
  5227. let pageIndex = min(index, Int((self.listView.document?.pageCount ?? 0))-1)
  5228. self.listView.go(toPageIndex: pageIndex, animated: false)
  5229. }
  5230. @objc dynamic func insertPages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  5231. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).deletePages(selectedIndexSet, pageAt: index)
  5232. self.listView.layoutDocumentView()
  5233. // [pageLabels setArray:[[pdfView document] pageLabels]];
  5234. self.resetThumbnails()
  5235. if let pageIndex = selectedIndexSet.first {
  5236. self.listView.go(toPageIndex: pageIndex, animated: false)
  5237. }
  5238. }
  5239. @objc dynamic func deletePages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  5240. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPages(selectedIndexSet, pageAt: index)
  5241. for idx in selectedIndexSet {
  5242. if idx < self.listView.document.pageCount {
  5243. self.listView.document.removePage(at: UInt(idx))
  5244. }
  5245. }
  5246. self.listView.layoutDocumentView()
  5247. // [pageLabels setArray:[[pdfView document] pageLabels]];
  5248. self.resetThumbnails()
  5249. let pageIndex = min(index, Int(self.listView.document.pageCount)-1)
  5250. self.listView.go(toPageIndex: pageIndex, animated: false)
  5251. }
  5252. }
  5253. // MARK: - Other
  5254. extension KMLeftSideViewController {
  5255. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  5256. let outlineItem = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow)
  5257. let outline = self.tocOutlineView
  5258. if let cnt = outline?.selectedRowIndexes.count, cnt == 1 {
  5259. if outlineItem is CPDFOutline {
  5260. let outline = (outlineItem as! CPDFOutline)
  5261. if let des = outline.destination {
  5262. self.listView.go(to: des)
  5263. } else if let action = outline.action {
  5264. self.listView.perform(action)
  5265. }
  5266. } else if outlineItem is CPDFBookmark {
  5267. let bookmark = outlineItem as! CPDFBookmark
  5268. self.listView.go(toPageIndex: bookmark.pageIndex, animated: true)
  5269. }
  5270. }
  5271. }
  5272. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  5273. KMPrint("KMLeftSideViewController-goToSelectedFindResults...")
  5274. }
  5275. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  5276. if tv.isEqual(to: self.thumbnailTableView) {
  5277. guard let document = self.listView.document else {
  5278. return
  5279. }
  5280. var pages = NSMutableArray()
  5281. for idx in self.thumbnailTableView.selectedRowIndexes {
  5282. if (idx < document.pageCount) {
  5283. if let page = self.listView.document.page(at: UInt(idx)) {
  5284. pages.add(page)
  5285. }
  5286. }
  5287. }
  5288. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  5289. let saveAccessCtr = KMSavePanelAccessoryController()
  5290. let outputSavePanel = NSSavePanel()
  5291. outputSavePanel.allowedFileTypes = ["pdf"]
  5292. outputSavePanel.accessoryView = saveAccessCtr.view
  5293. outputSavePanel.nameFieldStringValue = fileName
  5294. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  5295. if (result == .OK) {
  5296. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  5297. let vc = KMProgressWindowController()
  5298. self.view.window?.beginSheet(vc.window!)
  5299. let saveFilePath = outputSavePanel.url?.path
  5300. DispatchQueue.global().async {
  5301. let pdf = CPDFDocument()
  5302. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  5303. DispatchQueue.main.async {
  5304. if (success) {
  5305. if (saveAccessCtr.openAutomaticButton.state == .on) {
  5306. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  5307. }
  5308. } else {
  5309. KMTools.viewFile(at: saveFilePath!)
  5310. }
  5311. }
  5312. NSApp.endSheet(vc.window!)
  5313. vc.close()
  5314. }
  5315. }
  5316. }
  5317. }
  5318. }
  5319. }
  5320. }
  5321. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  5322. var pagesName = ""
  5323. if (itemIndexes.count > 1) {
  5324. pagesName.append(" pages")
  5325. } else {
  5326. pagesName.append("page")
  5327. }
  5328. let docmentName = self.listView.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  5329. var fileName = ""
  5330. if (itemIndexes.count > 0) {
  5331. if (itemIndexes.count == 1) {
  5332. let idx = itemIndexes.first! + 1
  5333. let tFileName = String(format: "%@ %@", pagesName, "\(idx)")
  5334. return String(format: "%@%@", docmentName, tFileName)
  5335. }
  5336. var sortIndex = IndexSet()
  5337. for idx in itemIndexes {
  5338. let _idx = idx + 1
  5339. sortIndex.insert(_idx)
  5340. }
  5341. // NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
  5342. // NSArray *sortDesc = @[sort];
  5343. // NSArray *sortArray = [sortIndex sortedArrayUsingDescriptors:sortDesc];
  5344. let sortArray = sortIndex.sorted()
  5345. var a = 0
  5346. var b = 0
  5347. for num in sortArray {
  5348. // for (NSNumber *num in sortArray) {
  5349. if (fileName.isEmpty == false) {
  5350. if (num == b+1) {
  5351. b = num
  5352. if (num == sortArray.last) {
  5353. fileName = "\(fileName)\(a)-\(b)"
  5354. }
  5355. } else {
  5356. if (a == b) {
  5357. fileName = "\(fileName)\(a),"
  5358. } else {
  5359. fileName = "\(fileName)\(a)-\(b),"
  5360. }
  5361. b = num
  5362. a = b
  5363. if (num == sortArray.last) {
  5364. fileName = "\(fileName)\(a)"
  5365. }
  5366. }
  5367. } else {
  5368. fileName = ""
  5369. b = num
  5370. a = b
  5371. }
  5372. }
  5373. let tFileName = String(format: "%@ %@", pagesName,fileName)
  5374. return String(format: "%@%@", docmentName,tFileName)
  5375. }
  5376. return ""
  5377. }
  5378. // MARK: - Outline
  5379. func selectedRowIndexes() -> IndexSet {
  5380. var selectedIndexes = self.tocOutlineView.selectedRowIndexes
  5381. let clickedRow = self.tocOutlineView.clickedRow
  5382. if clickedRow != -1 && selectedIndexes.contains(clickedRow) == false {
  5383. var indexes = IndexSet(integer: clickedRow)
  5384. selectedIndexes = indexes
  5385. }
  5386. return selectedIndexes
  5387. }
  5388. func addoutline(parent parentOutline: CPDFOutline?, addOutline: CPDFOutline, index: Int, needExpand: Bool) {
  5389. var tempO = addOutline
  5390. if addOutline.label != nil {
  5391. parentOutline?.insertChild(addOutline, at: UInt(index))
  5392. } else {
  5393. let outline = parentOutline?.insertChild(at: UInt(index))
  5394. outline?.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.listView.currentPageIndex+1)
  5395. outline?.destination = self.listView.currentDestination
  5396. tempO = outline!
  5397. }
  5398. // [[[self.document undoManager] prepareWithInvocationTarget:self] removeOutlineWithParent:parentOutline removeOutline:addOutline index:index needExpand:needExpand];
  5399. self.view.window?.makeFirstResponder(nil)
  5400. Task { @MainActor in
  5401. self.tocOutlineView.reloadData()
  5402. if (needExpand) {
  5403. self.tocOutlineView.expandItem(parentOutline)
  5404. }
  5405. let idx = self.tocOutlineView.row(forItem: tempO)
  5406. self.tocOutlineView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
  5407. self.newAddOutlineEntryEditingMode(index)
  5408. }
  5409. // __block PDFOutline *taddOutline = [addOutline retain];
  5410. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  5411. // [self.leftSideController.tocOutlineView scrollRowToVisible:[leftSideController.tocOutlineView rowForItem:taddOutline]];
  5412. // [taddOutline release];
  5413. // });
  5414. }
  5415. }