KMLeftSideViewController.swift 296 KB

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