KMLeftSideViewController.swift 254 KB

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