KMLeftSideViewController.swift 255 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367
  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 = NSPasteboard.PasteboardType("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. var hasValidFile = false
  2422. for item in pbItems {
  2423. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  2424. continue
  2425. }
  2426. let type = _url.pathExtension.lowercased()
  2427. hasValidFile = true
  2428. }
  2429. if (!hasValidFile) {
  2430. return NSDragOperation(rawValue: 0)
  2431. }
  2432. }
  2433. return NSDragOperation(rawValue: 0)
  2434. }
  2435. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  2436. var result = false
  2437. if tableView.isEqual(to: self.thumbnailTableView) == false {
  2438. return result
  2439. }
  2440. let pasteboard = info.draggingPasteboard
  2441. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  2442. result = true
  2443. let rowData = pasteboard.data(forType: .localDraggedTypes)
  2444. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData!) as? IndexSet ?? IndexSet()
  2445. let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  2446. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData!) as? String
  2447. if url != nil && url != self.listView.document.documentURL.absoluteString {
  2448. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  2449. // if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]){
  2450. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2451. var fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  2452. if (fileNames.count == 1) {
  2453. let path = fileNames.first ?? ""
  2454. let pathExtension = path.pathExtension.lowercased()
  2455. if pathExtension == "pdf" {
  2456. var index = row
  2457. // __block NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2458. var insertIndexSet = IndexSet()
  2459. var pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  2460. if let data = pdf?.isEncrypted, data {
  2461. // if ([pdf isEncrypted]) {
  2462. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2463. // vc.filePath = url;
  2464. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2465. // if (password) {
  2466. // [pdf unlockWithPassword:password];
  2467. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2468. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2469. // [self.pdfView.document insertPage:page atIndex:index];
  2470. // [insertIndexSet addIndex:index];
  2471. // index++;
  2472. // [page release];
  2473. // }
  2474. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2475. // }
  2476. // }];
  2477. // [vc release];
  2478. } else {
  2479. for i in 0 ..< (pdf?.pageCount ?? 0) {
  2480. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2481. var page = pdf?.page(at: i)
  2482. self.listView.document.insertPageObject(page, at: UInt(index))
  2483. insertIndexSet.insert(index)
  2484. index += 1
  2485. }
  2486. self.insertPages(insertIndexSet, pageAt: index-1)
  2487. }
  2488. }
  2489. return true
  2490. }
  2491. }
  2492. }
  2493. var pageIndex = 0
  2494. var pages: [CPDFPage] = []
  2495. for idx in rowIndexes {
  2496. let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage
  2497. pages.append(page!)
  2498. }
  2499. var toPage: CPDFPage?
  2500. if row < self.listView.document.pageCount {
  2501. toPage = self.listView.document.page(at: UInt(row))
  2502. }
  2503. var toPageIndex = 0
  2504. if (toPage != nil) {
  2505. toPageIndex = Int(self.listView.document.index(for: toPage))
  2506. } else {
  2507. toPageIndex = Int(self.listView.document.pageCount)
  2508. }
  2509. for i in 0 ..< pages.count {
  2510. var page = pages[i]
  2511. self.listView.document.insertPageObject(page, at: UInt(toPageIndex+i))
  2512. pageIndex += 1
  2513. self.listView.go(toPageIndex: toPageIndex+i, animated: false)
  2514. }
  2515. self.listView.layoutDocumentView()
  2516. var deletepages: [CPDFPage] = []
  2517. for idx in rowIndexes {
  2518. if idx < toPageIndex {
  2519. if((idx+pageIndex) < self.listView.document.pageCount) {
  2520. var page = self.listView.document.page(at: UInt(idx))
  2521. deletepages.append(page!)
  2522. self.listView.document.removePage(at: IndexSet(integer: idx))
  2523. }
  2524. } else {
  2525. if((idx+pageIndex) < self.listView.document.pageCount) {
  2526. let page = self.listView.document.page(at: UInt(idx+pageIndex))
  2527. deletepages.append(page!)
  2528. self.listView.document.removePage(at: IndexSet(integer: idx+pageIndex))
  2529. }
  2530. }
  2531. }
  2532. // [[[[self document] undoManager] prepareWithInvocationTarget:self] undoClick];
  2533. // [self.pageLabels setArray:[[self.pdfView document] pageLabels]];
  2534. self.listView.layoutDocumentView()
  2535. self.resetThumbnails()
  2536. }
  2537. // else if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]] && [tableView isEqual:leftSideController.thumbnailTableView]) {
  2538. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2539. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2540. //
  2541. // return NO;
  2542. // }
  2543. //
  2544. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2545. // NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2546. // __block NSInteger index = row;
  2547. //
  2548. // if (fileNames.count == 1) {
  2549. // NSString *path = fileNames.firstObject;
  2550. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2551. // if ([pathExtension isEqualToString:@"pdf"]) {
  2552. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]]autorelease];
  2553. // if ([pdf isEncrypted]) {
  2554. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2555. // vc.filePath = path;
  2556. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2557. // if (password) {
  2558. // [pdf unlockWithPassword:password];
  2559. // for (NSUInteger i = 0; i< pdf.pageCount; i++) {
  2560. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2561. // [self.pdfView.document insertPage:page atIndex:index];
  2562. // [insertIndexSet addIndex:index];
  2563. // index++;
  2564. // [page release];
  2565. // }
  2566. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2567. // }
  2568. // }];
  2569. // [vc release];
  2570. // } else {
  2571. // for (NSUInteger i = 0; i < pdf.pageCount; i++) {
  2572. // PDFPage * page = [[pdf pageAtIndex:i] copy];
  2573. // [self.pdfView.document insertPage:page atIndex:index];
  2574. // [insertIndexSet addIndex:index];
  2575. // index++;
  2576. // [page release];
  2577. // }
  2578. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2579. //
  2580. // }
  2581. // } else if ([[KMImageToPDFMethod supportedImageTypes] containsObject:pathExtension]) {
  2582. // NSImage *image = [[[NSImage alloc] initWithContentsOfFile:path] autorelease];
  2583. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  2584. // [pdfView.document insertPage:page atIndex:index];
  2585. // [insertIndexSet addIndex:index];
  2586. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2587. // }
  2588. // result = YES;
  2589. // } else {
  2590. // result = NO;
  2591. // }
  2592. // }
  2593. return result == false
  2594. }
  2595. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  2596. if tableView.isEqual(to: self.thumbnailTableView) {
  2597. let idx = rowIndexes.first ?? NSNotFound
  2598. if (idx != NSNotFound && self.listView.document.isLocked == false) {
  2599. let page = self.listView.document.page(at: UInt(idx))
  2600. var fileExt: String?
  2601. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.listView.displayBox) ?? .zero)
  2602. if self.listView.document.allowsPrinting {
  2603. // NSData *pdfData = [page dataRepresentation];
  2604. fileExt = "pdf"
  2605. // filenames
  2606. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  2607. // let newDoc = CPDFDocument()
  2608. // newDoc?.insertPageObject(page, at: 0)
  2609. // let data = newDoc?.dataRepresentation()
  2610. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  2611. pboard.setData(tiffData, forType: .pdf)
  2612. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  2613. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  2614. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  2615. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.listView.document.documentURL?.absoluteString)
  2616. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  2617. var docmentName = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  2618. // __block NSMutableString *pagesName = nil;
  2619. var pagesName = ""
  2620. if (rowIndexes.count > 1) {
  2621. pagesName = " pages"
  2622. } else {
  2623. pagesName = " page"
  2624. }
  2625. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  2626. let pdf = CPDFDocument()
  2627. for idx in rowIndexes {
  2628. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  2629. var copyPage = self.listView.document.page(at: UInt(idx))
  2630. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  2631. }
  2632. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  2633. var cachesDir = paths.first ?? ""
  2634. // docmentName = [NSString stringWithFormat:@"%@%@",docmentName,tFileName];
  2635. docmentName = String(format: "%@%@", docmentName, tFileName)
  2636. if (docmentName.count > 50) {
  2637. docmentName = docmentName.substring(to: 50)
  2638. }
  2639. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  2640. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  2641. let success = pdf?.write(toFile: cachesDir) ?? false
  2642. if (success) {
  2643. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  2644. pboard.setPropertyList([cachesDir], forType: .fileURL)
  2645. } else{
  2646. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  2647. pboard.setPropertyList([], forType: .fileURL)
  2648. }
  2649. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  2650. } else {
  2651. fileExt = "tiff"
  2652. pboard.declareTypes([.tiff, .filePromise], owner: self)
  2653. }
  2654. pboard.setData(tiffData, forType: .tiff)
  2655. pboard.setPropertyList([fileExt], forType: .filePromise)
  2656. // let data: Data = try! NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  2657. // pboard.declareTypes([.localDraggedTypes], owner: self)
  2658. // pboard.setData(data, forType: .localDraggedTypes)
  2659. return true
  2660. }
  2661. }
  2662. // else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2663. // NSUInteger idx = [rowIndexes firstIndex];
  2664. // if (idx != NSNotFound) {
  2665. // SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2666. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2667. // [pboard setData:[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] forType:NSPasteboardTypeTIFF];
  2668. // [pboard setPropertyList:[NSArray arrayWithObject:@"tiff"] forType:NSFilesPromisePboardType];
  2669. // return YES;
  2670. // }
  2671. // }
  2672. return false
  2673. }
  2674. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  2675. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2676. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2677. // return;
  2678. // }
  2679. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  2680. // NSArray *controllers = [[rightSideController.snapshotArrayController arrangedObjects] objectsAtIndexes:rowIndexes];
  2681. // [controllers makeObjectsPerformSelector:@selector(close)];
  2682. // } else
  2683. if aTableView.isEqual(to: self.thumbnailTableView) {
  2684. for idx in rowIndexes {
  2685. if idx >= self.listView.document.pageCount {
  2686. return
  2687. }
  2688. if let page = self.listView.document.page(at: UInt(idx)) {
  2689. for anno in page.annotations {
  2690. page.removeAnnotation(anno)
  2691. }
  2692. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  2693. self.listView.document.removePage(at: IndexSet(integer: idx))
  2694. }
  2695. }
  2696. self.listView.layoutDocumentView()
  2697. // [pageLabels setArray:[[pdfView document] pageLabels]];
  2698. self.resetThumbnails()
  2699. let idx = rowIndexes.first ?? -1
  2700. let index = min(idx, Int(self.listView.document.pageCount)-1)
  2701. self.listView.go(toPageIndex: index, animated: false)
  2702. }
  2703. }
  2704. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  2705. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  2706. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2707. // return;
  2708. // }
  2709. if aTableView.isEqual(to: self.thumbnailTableView) {
  2710. self._copysPages.removeAll()
  2711. if self.listView.document.isLocked == false {
  2712. for idx in rowIndexes {
  2713. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  2714. self._copysPages.append(page)
  2715. }
  2716. }
  2717. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2718. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2719. // NSPasteboardItem *pboardItem = [[[NSPasteboardItem alloc] init] autorelease];
  2720. // if ([[pdfView document] allowsPrinting])
  2721. // [pboardItem setData:[page dataRepresentation] forType:NSPasteboardTypePDF];
  2722. // [pboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
  2723. // [pboard clearContents];
  2724. // [pboard writeObjects:[NSArray arrayWithObjects:pboardItem, nil]];
  2725. }
  2726. }
  2727. // else if ([tv isEqual:leftSideController.findTableView]) {
  2728. // NSMutableString *string = [NSMutableString string];
  2729. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2730. // PDFSelection *match = [searchResults objectAtIndex:idx];
  2731. // [string appendString:@"* "];
  2732. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  2733. // [string appendFormat:@": %@\n", [[match contextString] string]];
  2734. // }];
  2735. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2736. // [pboard clearContents];
  2737. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2738. // } else if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2739. // NSMutableString *string = [NSMutableString string];
  2740. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2741. // SKGroupedSearchResult *result = [groupedSearchResults objectAtIndex:idx];
  2742. // NSArray *matches = [result matches];
  2743. // [string appendString:@"* "];
  2744. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [[result page] displayLabel]];
  2745. // [string appendString:@": "];
  2746. // [string appendFormat:NSLocalizedString(@"%ld Results", @""), (long)[matches count]];
  2747. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  2748. // }];
  2749. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2750. // [pboard clearContents];
  2751. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2752. // }
  2753. }
  2754. /*
  2755. #pragma mark dragging
  2756. - (NSArray *)tableView:(NSTableView *)tv namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2757. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2758. __block NSMutableArray *fileURLArray = [NSMutableArray array];
  2759. if (rowIndexes.count > 1) {
  2760. NSString *docmentName = @"";
  2761. NSString * tFileName = [NSString stringWithFormat:@"%@",[self fileNameWithSelectedPages:rowIndexes]];
  2762. PDFDocument *pdf = [[[PDFDocument alloc] init] autorelease];
  2763. [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2764. if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2765. PDFPage *copyPage = [[[pdfView document] pageAtIndex:idx] copy];
  2766. [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2767. [copyPage release];
  2768. }
  2769. }];
  2770. NSURL *fileURL = [[[dropDestination URLByAppendingPathComponent:tFileName] URLByAppendingPathExtension:@"pdf"] uniqueFileURL];
  2771. docmentName = fileURL.path;
  2772. BOOL success = [pdf writeToFile:docmentName];
  2773. if(success) {
  2774. [fileURLArray addObject:[fileURL lastPathComponent]];
  2775. }
  2776. } else {
  2777. PDFPage *page = [[pdfView document] pageAtIndex:rowIndexes.firstIndex];
  2778. NSURL *fileURL = [dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]];
  2779. NSString *pathExt = nil;
  2780. NSData *data = nil;
  2781. if ([[pdfView document] allowsPrinting]) {
  2782. pathExt = @"pdf";
  2783. data = [page dataRepresentation];
  2784. } else {
  2785. pathExt = @"tiff";
  2786. data = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2787. }
  2788. fileURL = [[fileURL URLByAppendingPathExtension:pathExt] uniqueFileURL];
  2789. if ([data writeToURL:fileURL atomically:YES]) {
  2790. [fileURLArray addObject:[fileURL lastPathComponent]];
  2791. }
  2792. }
  2793. return fileURLArray;
  2794. } else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2795. NSUInteger idx = [rowIndexes firstIndex];
  2796. if (idx != NSNotFound) {
  2797. SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2798. PDFPage *page = [[pdfView document] pageAtIndex:[snapshot pageIndex]];
  2799. NSURL *fileURL = [[dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]] URLByAppendingPathExtension:@"tiff"];
  2800. fileURL = [fileURL uniqueFileURL];
  2801. if ([[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] writeToURL:fileURL atomically:YES])
  2802. return [NSArray arrayWithObjects:[fileURL lastPathComponent], nil];
  2803. }
  2804. }
  2805. return [NSArray array];
  2806. }
  2807. - (void)tableView:(NSTableView *)tv sortDescriptorsDidChange:(NSArray *)oldDescriptors {
  2808. if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2809. [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  2810. }
  2811. }
  2812. #pragma mark NSTableView delegate protocol
  2813. - (void)tableViewColumnDidResize:(NSNotification *)aNotification {
  2814. if ([[[[aNotification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:IMAGE_COLUMNID]) {
  2815. if ([[aNotification object] isEqual:leftSideController.thumbnailTableView]) {
  2816. [leftSideController.thumbnailTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [leftSideController.thumbnailTableView numberOfRows])]];
  2817. } else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2818. [rightSideController.snapshotTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.snapshotTableView numberOfRows])]];
  2819. }
  2820. }
  2821. }
  2822. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2823. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2824. NSUInteger idx = [rowIndexes firstIndex];
  2825. if (idx != NSNotFound) {
  2826. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2827. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  2828. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  2829. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  2830. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  2831. [self fileWithPage:page atPath:filePath];
  2832. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  2833. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  2834. } else {
  2835. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  2836. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  2837. }
  2838. }
  2839. }
  2840. }
  2841. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  2842. NSData *data = [page dataRepresentation];
  2843. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  2844. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  2845. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  2846. if (success) {
  2847. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  2848. NSURL *url = [NSURL fileURLWithPath:filePath];
  2849. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  2850. }
  2851. [document release];
  2852. */
  2853. }
  2854. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  2855. /*
  2856. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  2857. if item is KMBOTAAnnotationSection {
  2858. let section = item as? KMBOTAAnnotationSection
  2859. return section!.annotations?[index] as Any
  2860. } else if item is KMBOTAAnnotationItem {
  2861. return item as Any
  2862. } else {
  2863. var tempArray: [KMBOTAAnnotationSection] = []
  2864. for temp in self.data {
  2865. if temp.annotations?.count != 0 {
  2866. tempArray.append(temp)
  2867. }
  2868. }
  2869. let section = tempArray[index]
  2870. return section as Any
  2871. }
  2872. }
  2873. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  2874. if item is KMBOTAAnnotationItem {
  2875. let cell : KMAnnotationOutlineCellView = KMAnnotationOutlineCellView.init()
  2876. cell.delegate = self
  2877. cell.model = item as? KMBOTAAnnotationItem
  2878. return cell
  2879. } else if item is KMBOTAAnnotationSection {
  2880. let section = item as? KMBOTAAnnotationSection
  2881. let cell : KMAnnotationOutlineSectionView = KMAnnotationOutlineSectionView.init()
  2882. cell.model = section
  2883. return cell
  2884. }
  2885. return NSTableCellView()
  2886. }
  2887. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2888. let rowView = KMAnnotationOutlineRowView()
  2889. if item is KMBOTAAnnotationItem {
  2890. rowView.model = (item as? KMBOTAAnnotationItem)
  2891. } else if item is KMBOTAAnnotationSection {
  2892. rowView.section = (item as? KMBOTAAnnotationSection)
  2893. }
  2894. rowView.mouseDownAction = { [unowned self] view, event in
  2895. if rowView.section != nil {
  2896. let expanded = outlineView.isItemExpanded(outlineView.item(atRow: outlineView.selectedRow))
  2897. if expanded {
  2898. outlineView.collapseItem(outlineView.item(atRow: outlineView.selectedRow), collapseChildren: true)
  2899. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2900. } else {
  2901. outlineView.expandItem(outlineView.item(atRow: outlineView.selectedRow), expandChildren: true)
  2902. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2903. }
  2904. } else if rowView.model != nil {
  2905. self.didSelectItem(view: rowView, event: event)
  2906. }
  2907. }
  2908. rowView.rightMouseDownAction = { [unowned self] view, event in
  2909. if rowView.section != nil {
  2910. } else if rowView.model != nil {
  2911. if !KMOCToolClass.arrayContains(array: self.selectItems, annotation: item) ||
  2912. self.selectItems.count == 1 {
  2913. self.selectItem(item: item as! KMBOTAAnnotationItem)
  2914. }
  2915. DispatchQueue.main.async {
  2916. self.delegate?.annotationOutlineView(self, rightMouseDownDidSelectView: view, evnet: event)
  2917. }
  2918. }
  2919. }
  2920. rowView.hoverCallback = { [unowned self] (mouseEntered, mouseBox) in
  2921. self.outlineView.enumerateAvailableRowViews { view, row in
  2922. if view is KMAnnotationOutlineRowView {
  2923. (view as? KMAnnotationOutlineRowView)?.model?.hover = false
  2924. (view as? KMAnnotationOutlineRowView)?.reloadData()
  2925. }
  2926. }
  2927. if mouseEntered {
  2928. rowView.model?.hover = true
  2929. } else {
  2930. rowView.model?.hover = false
  2931. }
  2932. }
  2933. return rowView
  2934. }
  2935. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2936. if item is KMBOTAAnnotationItem {
  2937. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: self.maxWidth - 16, height: 1000))
  2938. } else if item is KMBOTAAnnotationSection {
  2939. return 40
  2940. } else {
  2941. return 30
  2942. }
  2943. }
  2944. func outlineViewSelectionDidChange(_ notification: Notification) {
  2945. if self.outlineView.selectedRow == -1 {
  2946. self.cancelSelect()
  2947. }
  2948. }
  2949. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2950. if item is KMBOTAAnnotationItem {
  2951. return false
  2952. } else if item is KMBOTAAnnotationSection {
  2953. let section = item as? KMBOTAAnnotationSection
  2954. return section!.annotations?.count ?? 0 > 0
  2955. }
  2956. return false
  2957. }
  2958. func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
  2959. if let item = item as? KMBOTAAnnotationSection {
  2960. if !item.isItemExpanded {
  2961. item.isItemExpanded = true
  2962. outlineView.animator().expandItem(item, expandChildren: true)
  2963. return false
  2964. }
  2965. }
  2966. return true
  2967. }
  2968. func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
  2969. if let item = item as? KMBOTAAnnotationSection {
  2970. if item.isItemExpanded {
  2971. item.isItemExpanded = false
  2972. outlineView.animator().collapseItem(item, collapseChildren: true)
  2973. return false
  2974. }
  2975. }
  2976. return true
  2977. }
  2978. */
  2979. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  2980. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  2981. if outlineView.isEqual(to: self.tocOutlineView) {
  2982. let isLocked = self.listView.document?.isLocked ?? true
  2983. if isLocked { // 文档不存在 或 已加锁
  2984. return 0
  2985. }
  2986. if item == nil { // 第一层
  2987. // 获取根
  2988. guard let outline = self.listView.document.outlineRoot() else {
  2989. let view = self.tocOutlineView.enclosingScrollView!
  2990. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2991. //
  2992. 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)
  2993. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2994. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2995. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  2996. return 0
  2997. }
  2998. if outline.numberOfChildren == 0 {
  2999. // return 0
  3000. }
  3001. if self.isSearchOutlineMode { // 是否为搜索模块
  3002. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: outline) {
  3003. self.showSearchOutlineBlankState(false)
  3004. } else {
  3005. self.showSearchOutlineBlankState(true)
  3006. return 0
  3007. }
  3008. } else {
  3009. if outline.numberOfChildren > 0 { // 有数据
  3010. self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  3011. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  3012. } else { // 没有数据
  3013. let view = self.tocOutlineView.enclosingScrollView!
  3014. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  3015. //
  3016. 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)
  3017. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  3018. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  3019. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  3020. return 0
  3021. }
  3022. }
  3023. // 搜索按钮
  3024. if outline.numberOfChildren > 0 {
  3025. self.outlineSearchButton.isEnabled = true
  3026. } else {
  3027. self.outlineSearchButton.isEnabled = false
  3028. }
  3029. if (self.isSearchOutlineMode) {
  3030. var num = 0
  3031. for i in 0 ..< outline.numberOfChildren {
  3032. if let child = outline.child(at: i) {
  3033. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  3034. num += 1
  3035. }
  3036. }
  3037. }
  3038. return num
  3039. } else {
  3040. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  3041. var bookmarkNum = 0
  3042. if array.isEmpty == false {
  3043. bookmarkNum = 1
  3044. }
  3045. return Int(outline.numberOfChildren) + bookmarkNum
  3046. }
  3047. } else { // 第二层 +
  3048. if self.isSearchOutlineMode {
  3049. if let data = item as? String, data == "Bookmarks" { // 书签group
  3050. return 0
  3051. } else if item is CPDFOutline { // 大纲
  3052. let child = item as! CPDFOutline
  3053. if child.numberOfChildren == 0 {
  3054. return 0
  3055. }
  3056. var num = 0
  3057. for i in 0 ..< child.numberOfChildren {
  3058. if let _child = child.child(at: i) {
  3059. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: _child) {
  3060. num += 1
  3061. }
  3062. }
  3063. }
  3064. return num
  3065. } else if item is CPDFBookmark { // 书签
  3066. return 0
  3067. }
  3068. } else {
  3069. if let data = item as? String, data == "Bookmarks" { // 书签group
  3070. return (self.listView.document?.bookmarks().count) ?? 0
  3071. } else if item is CPDFOutline { // 大纲
  3072. return Int((item as? CPDFOutline)?.numberOfChildren ?? 0)
  3073. } else if item is CPDFBookmark { // 书签
  3074. return 0
  3075. }
  3076. }
  3077. }
  3078. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3079. if self.noteSearchMode {
  3080. return self.noteSearchArray.count
  3081. }
  3082. var count = 0
  3083. for section in self._annotations {
  3084. if section.annotations?.count != 0 {
  3085. count += section.annotations!.count
  3086. }
  3087. }
  3088. // if (item == nil){
  3089. // NSInteger count = [[rightSideController.noteArrayController arrangedObjects] count];
  3090. if (count < 1) {
  3091. // if (notes.count < 1) {
  3092. self.noteSearchButton.isEnabled = false
  3093. self.noteFilterButton.isEnabled = false
  3094. // }
  3095. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  3096. let view = self.noteOutlineView.enclosingScrollView!
  3097. var emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  3098. 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)
  3099. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  3100. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  3101. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  3102. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  3103. //
  3104. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  3105. self.noteHeaderView.isHidden = true
  3106. self.toolButtonBoxLayoutConstraint.constant = 40.0
  3107. }
  3108. } else {
  3109. self.noteSearchButton.isEnabled = true
  3110. self.noteFilterButton.isEnabled = true
  3111. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  3112. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  3113. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  3114. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  3115. //
  3116. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  3117. self.noteHeaderView.isHidden = false
  3118. self.toolButtonBoxLayoutConstraint.constant = 64.0
  3119. }
  3120. }
  3121. return count
  3122. // } else {
  3123. // return [item hasNoteText];
  3124. // }
  3125. }
  3126. return 0
  3127. }
  3128. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  3129. if outlineView.isEqual(to: self.tocOutlineView) {
  3130. let isLocked = self.listView.document?.isLocked ?? true
  3131. if isLocked { // 文档不存在 或 已加锁
  3132. return ""
  3133. }
  3134. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  3135. var bookmarkNum = 0
  3136. if array.isEmpty == false {
  3137. bookmarkNum = 1
  3138. }
  3139. if item == nil {
  3140. if self.isSearchOutlineMode {
  3141. guard let outline = self.listView.document.outlineRoot() else {
  3142. return ""
  3143. }
  3144. if outline.numberOfChildren == 0 {
  3145. return ""
  3146. }
  3147. var array: [CPDFOutline] = []
  3148. for i in 0 ..< outline.numberOfChildren {
  3149. if let child = outline.child(at: i) {
  3150. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  3151. array.append(child)
  3152. }
  3153. }
  3154. }
  3155. if index < array.count {
  3156. return array[index]
  3157. }
  3158. return ""
  3159. } else {
  3160. if index == 0 && bookmarkNum == 1 {
  3161. return "Bookmarks"
  3162. } else {
  3163. var _index = bookmarkNum == 1 ? index-1 : index
  3164. let outline = self.listView.document.outlineRoot()
  3165. var obj = outline?.child(at: UInt(_index))
  3166. return obj as Any
  3167. }
  3168. }
  3169. } else {
  3170. if let data = item as? String, data == "Bookmarks" {
  3171. return array[index]
  3172. } else if item is CPDFOutline {
  3173. return (item as! CPDFOutline).child(at: UInt(index))
  3174. } else if item is CPDFBookmark {
  3175. return ""
  3176. }
  3177. }
  3178. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3179. // if (item == nil)
  3180. // {
  3181. // return [[rightSideController.noteArrayController arrangedObjects] objectAtIndex:anIndex];
  3182. // // return [self.notes objectAtIndex:anIndex];
  3183. // }
  3184. // else
  3185. // return [item noteText];
  3186. if self.noteSearchMode {
  3187. return self.noteSearchArray[index]
  3188. }
  3189. var tempArray: [KMBOTAAnnotationItem] = []
  3190. for secion in self._annotations {
  3191. if secion.annotations?.count != 0 {
  3192. for _item in secion.annotations! {
  3193. tempArray.append(_item)
  3194. }
  3195. }
  3196. }
  3197. return tempArray[index] as Any
  3198. }
  3199. return item
  3200. }
  3201. func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
  3202. if outlineView.isEqual(to: self.tocOutlineView) {
  3203. // let tcID = tableColumn?.identifier.rawValue ?? ""
  3204. // var ol = item as? CPDFOutline
  3205. // if(tcID == LABEL_COLUMNID) {
  3206. // if (self.isSearchOutlineMode) {
  3207. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  3208. //// NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  3209. //// NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  3210. //// for (NSUInteger i = 0; i <arr.count ; i++) {
  3211. //// NSValue * rangeValue = arr[i];
  3212. //// NSRange range = rangeValue.rangeValue;
  3213. //// range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  3214. //// [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  3215. //// }
  3216. //// [attributeString addAttribute:NSForegroundColorAttributeName value:[KMAppearance KMColor_Layout_H0] range:NSMakeRange(0, roughString.length)];
  3217. //// return attributeString;
  3218. // } else {
  3219. // var attributedString = NSMutableAttributedString()
  3220. //// attributedString
  3221. // attributedString.append(.init(string: ol?.label ?? "", attributes: [.foregroundColor : KMAppearance.Layout.h0Color()]))
  3222. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  3223. //// NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3224. //// NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  3225. //// [attributedString appendAttributedString:attr1];
  3226. //
  3227. // return attributedString
  3228. // }
  3229. //
  3230. // }
  3231. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3232. // NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3233. // NSString *roughString = [ol pageLabel]? : @"";
  3234. // NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3235. // NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  3236. // [attributedString appendAttributedString:attr1];
  3237. //
  3238. // return attributedString;
  3239. // }
  3240. }
  3241. // else if ([ov isEqual:rightSideController.noteOutlineView]) {
  3242. // NSString *tcID = [tableColumn identifier];
  3243. // PDFAnnotation *note = item;
  3244. // if (tableColumn == nil || [tcID isEqualToString:NOTE_COLUMNID])
  3245. // return [note objectValue];
  3246. // else if([tcID isEqualToString:TYPE_COLUMNID]){
  3247. // NSString *noteType = [note type];
  3248. // if ([note isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  3249. // PDFAnnotationButtonWidget *buttonWidget = (PDFAnnotationButtonWidget *)note;
  3250. // if (buttonWidget.controlType == kPDFWidgetRadioButtonControl) {
  3251. // noteType = SKAnnotationFormRadioButtonKey;
  3252. // } else if (buttonWidget.controlType == kPDFWidgetCheckBoxControl){
  3253. // noteType = SKAnnotationFormCheckBoxKey;
  3254. // } else if (buttonWidget.controlType == kPDFWidgetPushButtonControl){
  3255. // noteType = SKAnnotationFormActionButtonKey;
  3256. // }
  3257. // } else if ([note isKindOfClass:[PDFAnnotationTextWidget class]]){
  3258. // noteType = SKAnnotationFormTextFieldKey;
  3259. // } else if ([note isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  3260. // PDFAnnotationChoiceWidget *choiceWidget = (PDFAnnotationChoiceWidget *)note;
  3261. // if (choiceWidget.isListChoice) {
  3262. // noteType = SKAnnotationFormListMenuKey;
  3263. // } else {
  3264. // noteType = SKAnnotationFormComboBoxKey;
  3265. // }
  3266. //
  3267. // }
  3268. // return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:note == [pdfView activeAnnotation]], SKAnnotationTypeImageCellActiveKey, noteType, SKAnnotationTypeImageCellTypeKey,[note color],SKAnnotationTypeImageCellColorKey, nil];
  3269. // }
  3270. // else if([tcID isEqualToString:COLOR_COLUMNID])
  3271. // return [note type] ? [note color] : nil;
  3272. // else if([tcID isEqualToString:PAGE_COLUMNID])
  3273. // return [[note page] displayLabel];
  3274. // else if([tcID isEqualToString:AUTHOR_COLUMNID])
  3275. // return [note type] ? [note userName] : nil;
  3276. // else if([tcID isEqualToString:DATE_COLUMNID])
  3277. // return [note type] ? [note modificationDate] : nil;
  3278. // }
  3279. return nil
  3280. }
  3281. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  3282. if outlineView.isEqual(to: self.tocOutlineView) {
  3283. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMTocTableCellView"), owner: self) as! KMTocTableCellView
  3284. let tcID = tableColumn?.identifier.rawValue
  3285. var title = ""
  3286. var pageLabel = ""
  3287. if let data = item as? String, data == "Bookmarks" {
  3288. title = NSLocalizedString("Bookmarks", comment: "")
  3289. } else if item is CPDFOutline {
  3290. title = (item as! CPDFOutline).label
  3291. pageLabel = "\(((item as! CPDFOutline).destination?.pageIndex ?? 0) + 1)"
  3292. } else if item is CPDFBookmark {
  3293. title = (item as! CPDFBookmark).label
  3294. pageLabel = "\((item as! CPDFBookmark).pageIndex + 1)"
  3295. }
  3296. if tcID == LABEL_COLUMNID {
  3297. if (self.isSearchOutlineMode) {
  3298. // NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines];
  3299. let roughString = title
  3300. // NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  3301. // NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  3302. //
  3303. // for (NSUInteger i = 0; i <arr.count ; i++) {
  3304. // NSValue * rangeValue = arr[i];
  3305. // NSRange range = rangeValue.rangeValue;
  3306. // range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  3307. // [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  3308. // }
  3309. // cell.tocLabel.attributedStringValue = attributeString;
  3310. cell.tocLabel.stringValue = title
  3311. } else {
  3312. cell.tocLabel.stringValue = title
  3313. }
  3314. cell.pageLabel.stringValue = pageLabel
  3315. }
  3316. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3317. // cell.pageLabel.stringValue = [ol pageLabel];
  3318. // }
  3319. return cell
  3320. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3321. let model = item as? KMBOTAAnnotationItem
  3322. var note: CPDFAnnotation!
  3323. if self.noteSearchMode {
  3324. note = item as! CPDFAnnotation
  3325. } else {
  3326. note = (item as! KMBOTAAnnotationItem).annotation!
  3327. }
  3328. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMNoteTableViewCell"), owner: self) as! KMNoteTableViewCell
  3329. cell.cellNote = note
  3330. let noteColor = note.color
  3331. var noteType = note.type ?? ""
  3332. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  3333. // NSString *pageString = [[note page] displayLabel] ? : @"";
  3334. var pageString = "\((note.page?.pageIndex() ?? 0) + 1)"
  3335. let formatter = DateFormatter()
  3336. formatter.dateFormat = "hh:mm"
  3337. var dateString = ""
  3338. if let date = note.modificationDate() {
  3339. dateString = formatter.string(from: date)
  3340. }
  3341. var authorString = note.userName() ?? ""
  3342. // NSString *noteTextString = [note noteText].string ? : @"";
  3343. var noteTextString = note.string() ?? ""
  3344. //
  3345. // if([noteType isEqualToString:@"Redact"]) {
  3346. // noteString = @"Redact";
  3347. // }
  3348. //
  3349. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool
  3350. if timeKey == nil || timeKey == false {
  3351. // if (date != nil) {
  3352. cell.timeLabel.stringValue = dateString
  3353. //
  3354. // } else {
  3355. // cell.timeLabel.stringValue = ""
  3356. // }
  3357. cell.timeLabel.isHidden = false
  3358. } else {
  3359. cell.timeLabel.isHidden = true
  3360. }
  3361. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool
  3362. if pageKey == nil || pageKey == false {
  3363. let labelsize = cell.pageLabel.stringValue.boundingRect(with: CGSizeMake(CGFloat(MAXFLOAT),CGRectGetHeight(cell.pageLabel.bounds)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font : NSFont.systemFont(ofSize: 12)])
  3364. cell.pageLabelWidthConstraint.constant = labelsize.size.width + 5
  3365. cell.pageLabel.stringValue = pageString
  3366. cell.pageLabel.isHidden = false
  3367. } else {
  3368. cell.pageLabel.isHidden = true
  3369. }
  3370. let autherKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool
  3371. if pageKey == nil || pageKey == false {
  3372. cell.autherLabel.stringValue = authorString
  3373. cell.autherLabel.isHidden = false
  3374. } else {
  3375. cell.autherLabel.isHidden = true
  3376. }
  3377. let imageView = KMNoteTypeImageView()
  3378. if note.isKind(of: CPDFStampAnnotation.self) {
  3379. let annotation_stamp = note as! CPDFStampAnnotation
  3380. if (annotation_stamp.stampImage() != nil) {
  3381. noteType = SKNStampString
  3382. }
  3383. } else if note.isKind(of: CPDFLineAnnotation.self) {
  3384. let annotation_line = note as! CPDFLineAnnotation
  3385. if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .none {
  3386. noteType = SKNLine_NoneString
  3387. } else if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .openArrow {
  3388. noteType = SKNLine_OpenArrowString
  3389. } else {
  3390. noteType = SKNLine_NoneString
  3391. }
  3392. } else if note.isKind(of: CPDFButtonWidgetAnnotation.self) {
  3393. let buttonWidget = note as! CPDFButtonWidgetAnnotation
  3394. if buttonWidget.controlType() == .radioButtonControl {
  3395. noteType = KMAnnotationFormRadioButtonKey
  3396. } else if buttonWidget.controlType() == .checkBoxControl {
  3397. noteType = KMAnnotationFormCheckBoxKey
  3398. } else if buttonWidget.controlType() == .pushButtonControl {
  3399. noteType = KMAnnotationFormActionButtonKey
  3400. }
  3401. } else if note.isKind(of: CPDFTextWidgetAnnotation.self) {
  3402. noteType = KMAnnotationFormTextFieldKey
  3403. } else if note.isKind(of: CPDFChoiceWidgetAnnotation.self) {
  3404. let choiceWidget = note as! CPDFChoiceWidgetAnnotation
  3405. if choiceWidget.isListChoice {
  3406. noteType = KMAnnotationFormListMenuKey
  3407. } else {
  3408. noteType = KMAnnotationFormComboBoxKey
  3409. }
  3410. } else if note.isKind(of: KMTableAnnotation.self) {
  3411. noteType = "Ink_Table"
  3412. } else if note.isKind(of: KMSelfSignAnnotation.self) {
  3413. let selfSignNote = note as! KMSelfSignAnnotation
  3414. if selfSignNote.annotationType == .signFalse {
  3415. noteType = "KMSelfSignTypeFalseActionButtonKey"
  3416. } else if (selfSignNote.annotationType == .signature) {
  3417. noteType = "KMSelfSignTypeTureActionButtonKey"
  3418. } else if (selfSignNote.annotationType == .signCircle) {
  3419. noteType = "KMSelfSignTypeCircleActionButtonKey"
  3420. } else if (selfSignNote.annotationType == .signLine) {
  3421. noteType = "KMSelfSignTypeLineActionButtonKey"
  3422. } else if (selfSignNote.annotationType == .signDot) {
  3423. noteType = "KMSelfSignTypeDotActionButtonKey"
  3424. } else if (selfSignNote.annotationType == .signText) {
  3425. noteType = "KMSelfSignTypeTextActionButtonKey"
  3426. }
  3427. } else if note.isKind(of: CPDFSquareAnnotation.self) {
  3428. noteType = SKNSquareString
  3429. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3430. noteType = SKNNoteString
  3431. } else if note.isKind(of: CPDFFreeTextAnnotation.self) {
  3432. noteType = SKNFreeTextString
  3433. } else if note.isKind(of: CPDFCircleAnnotation.self) {
  3434. noteType = SKNCircleString
  3435. } else if note.isKind(of: CPDFSignatureAnnotation.self) {
  3436. noteType = SKNSignatureString
  3437. } else if note.isKind(of: CPDFInkAnnotation.self) {
  3438. noteType = SKNInkString
  3439. } else if note.isKind(of: CPDFMarkupAnnotation.self) {
  3440. let anno = note as! CPDFMarkupAnnotation
  3441. if anno.markupType() == .highlight {
  3442. noteType = SKNHighlightString
  3443. } else if anno.markupType() == .underline {
  3444. noteType = SKNUnderlineString
  3445. } else if anno.markupType() == .strikeOut {
  3446. noteType = SKNStrikeOutString
  3447. }
  3448. }
  3449. cell.typeImageView.image = imageView.noteTypeImage(withType: noteType, color: noteColor ?? .red)
  3450. cell.typeImageView.isHidden = false
  3451. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3452. cell.isFold = true
  3453. }
  3454. cell.noteContentBox.isHidden = true
  3455. cell.noteImageView.isHidden = true
  3456. cell.foldButton.isHidden = true
  3457. cell.annotationContentLabel.isHidden = false
  3458. cell.noteContentLabel.stringValue = noteString
  3459. cell.contentView.isHidden = false
  3460. cell.contentViewHidden(false)
  3461. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3462. let markup = note as! CPDFMarkupAnnotation
  3463. var contentString = KMBOTAAnnotationTool.fetchText(text: markup.markupContent() ?? "")
  3464. contentString = contentString.replacingOccurrences(of: "\r", with: "")
  3465. contentString = contentString.replacingOccurrences(of: "\n", with: "")
  3466. cell.noteContentLabel.stringValue = contentString
  3467. if(contentString.isEmpty == false) {
  3468. cell.foldButton.isHidden = false
  3469. }
  3470. var attributeStr = NSMutableAttributedString(string: contentString)
  3471. if (markup.markupType() == .highlight) {
  3472. attributeStr.addAttribute(.backgroundColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3473. } else if (markup.markupType() == .strikeOut) {
  3474. attributeStr.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3475. attributeStr.addAttribute(.strikethroughColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3476. } else if (markup.markupType() == .underline) {
  3477. attributeStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3478. attributeStr.addAttribute(.underlineColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3479. }
  3480. cell.annotationContentLabel.attributedStringValue = attributeStr
  3481. if let data = model?.foldType, data == .unfold {
  3482. cell.isFold = false
  3483. } else if let data = model?.foldType, data == .fold {
  3484. cell.isFold = true
  3485. } else {
  3486. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3487. cell.isFold = false
  3488. } else {
  3489. cell.isFold = true
  3490. }
  3491. }
  3492. // noteString.isEmpty == false &&
  3493. if (contentString.isEmpty == false) {
  3494. cell.contentViewHidden(false)
  3495. } else {
  3496. cell.contentViewHidden(true)
  3497. }
  3498. } else if note.isKind(of: CPDFLineAnnotation.self) || noteType == SKNSquareString || noteType == SKNCircleString || noteType == SKNInkString {
  3499. cell.annotationContentLabel.stringValue = noteString
  3500. if (noteString.isEmpty == false) {
  3501. cell.contentViewHidden(false)
  3502. } else {
  3503. cell.contentViewHidden(true)
  3504. }
  3505. } else if note.isKind(of: CPDFStampAnnotation.self) {
  3506. if note.isKind(of: KMSelfSignAnnotation.self) {
  3507. let newAnnotation = note as! KMSelfSignAnnotation
  3508. let type = newAnnotation.annotationType
  3509. var returnString = ""
  3510. if (type == .signFalse) {
  3511. returnString = KMLocalizedString("X", nil)
  3512. } else if (type == .signature) {
  3513. returnString = KMLocalizedString("Check mark", nil)
  3514. } else if (type == .signCircle) {
  3515. returnString = KMLocalizedString("Circle", nil)
  3516. } else if (type == .signLine) {
  3517. returnString = KMLocalizedString("Line", nil)
  3518. } else if (type == .signDot) {
  3519. returnString = KMLocalizedString("Dot", nil)
  3520. } else if (type == .signText) {
  3521. returnString = KMLocalizedString("Text", nil)
  3522. }
  3523. cell.annotationContentLabel.stringValue = returnString
  3524. } else {
  3525. cell.annotationContentLabel.isHidden = true
  3526. cell.noteImageView.isHidden = false
  3527. let anno = note as! CPDFStampAnnotation
  3528. cell.noteImageView.image = anno.stampImage()
  3529. }
  3530. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3531. cell.foldButton.isHidden = false
  3532. if noteString.isEmpty {
  3533. cell.annotationContentLabel.stringValue = noteTextString
  3534. }else{
  3535. cell.annotationContentLabel.stringValue = noteString
  3536. cell.noteContentLabel.stringValue = noteTextString
  3537. }
  3538. if (self.foldType == .unfold) {
  3539. cell.isFold = false
  3540. } else if (self.foldType == .fold) {
  3541. cell.isFold = true
  3542. } else {
  3543. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3544. cell.isFold = false
  3545. } else {
  3546. cell.isFold = true
  3547. }
  3548. }
  3549. if (noteString.isEmpty == false || noteTextString.isEmpty == false) {
  3550. cell.contentView.isHidden = false
  3551. } else {
  3552. cell.contentView.isHidden = true
  3553. cell.contentViewHidden(true)
  3554. }
  3555. // noteString.isEmpty == false &&
  3556. if (noteTextString.isEmpty == false) {
  3557. cell.foldButton.isHidden = false
  3558. }else{
  3559. cell.foldButton.isHidden = true
  3560. }
  3561. } else {
  3562. cell.annotationContentLabel.stringValue = noteString
  3563. cell.imageViewHeightConstraint.constant = cell.contentView.frame.size.height
  3564. if (noteString.isEmpty == false) {
  3565. cell.contentViewHidden(false)
  3566. } else {
  3567. cell.contentViewHidden(true)
  3568. }
  3569. }
  3570. cell.autherLayoutConstraint.constant = cell.autherLabel.isHidden ? -(cell.autherLabel.bounds.size.width) + 10.0 : 10.0
  3571. cell.typeImageViewLayoutConstraint.constant = cell.typeImageView.isHidden ? -(cell.typeImageView.bounds.size.width) : 0.0
  3572. cell.contentBoxLayoutConstraint.constant = cell.noteContentBox.isHidden ? -(cell.noteContentBox.bounds.size.height+8.0) : 8.0
  3573. if note.isKind(of: CPDFStampAnnotation.self) && note.isKind(of: KMSelfSignAnnotation.self) == false {
  3574. } else {
  3575. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3576. if (!cell.isFold) {
  3577. self.allFoldNotes.append(note)
  3578. } else {
  3579. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3580. }
  3581. } else {
  3582. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3583. }
  3584. }
  3585. cell.isUnFoldNote = { [unowned self] cellNote, isUnfold in
  3586. model?.foldType = isUnfold ? .unfold : .fold
  3587. // let COLUMN_INDENTATION: CGFloat = 16
  3588. // if let _cell = tableColumn?.dataCell as? NSCell {
  3589. // _cell.objectValue = cell.annotationContentLabel.attributedStringValue
  3590. // let bound = NSMakeRect(0.0, 0.0, fmax(10.0, NSWidth(outlineView.frame) - COLUMN_INDENTATION - outlineView.indentationPerLevel-40), CGFLOAT_MAX)
  3591. // let height = _cell.cellSize(forBounds: bound).height
  3592. // KMPrint(height)
  3593. // }
  3594. if cellNote is CPDFMarkupAnnotation {
  3595. // let content = cell.annotationContentLabel.attributedStringValue
  3596. // let bound = content.string.boundingRect(with: NSMakeSize(150, CGFLOAT_MAX), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: nil)
  3597. // KMPrint(bound)
  3598. // 154 34 273
  3599. // 273 - 188 = 85 noteContentHeightConstraint maltlineLabelLayoutConstraint
  3600. model?.foldH = isUnfold ? 30 : (cell.noteContentHeightConstraint.constant + cell.maltlineLabelLayoutConstraint.constant + 85)
  3601. }
  3602. if (isUnfold) {
  3603. if (self.allFoldNotes.contains(note)) {
  3604. self.allFoldNotes.removeObject(note)
  3605. }
  3606. if (self.allFoldNotes.count == 0) {
  3607. self.foldType = .fold
  3608. } else {
  3609. self.foldType = .none
  3610. }
  3611. } else {
  3612. if self.allFoldNotes.contains(note) == false {
  3613. self.allFoldNotes.append(note)
  3614. }
  3615. // if (rightSideController.allFoldNotes.count == rightSideController.canFoldNotes.count) {
  3616. self.foldType = .unfold
  3617. // } else {
  3618. // self.foldType = KMFoldAllAnnotationType_None;
  3619. // }
  3620. }
  3621. }
  3622. return cell
  3623. }
  3624. return nil
  3625. }
  3626. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  3627. if outlineView.isEqual(self.noteOutlineView) {
  3628. if item is KMBOTAAnnotationItem {
  3629. let model = item as! KMBOTAAnnotationItem
  3630. if model.foldType == .fold {
  3631. return model.foldH
  3632. }
  3633. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  3634. }
  3635. return 30
  3636. } else if outlineView.isEqual(self.tocOutlineView) {
  3637. if item is CPDFOutline {
  3638. let tempItem = item as! CPDFOutline
  3639. let string: NSString = tempItem.label as NSString
  3640. let paragraphStyle = NSMutableParagraphStyle()
  3641. paragraphStyle.lineHeightMultiple = 1.32
  3642. paragraphStyle.alignment = .left
  3643. let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
  3644. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  3645. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attributes)
  3646. return max(40, size.height + 16)
  3647. }
  3648. return 40
  3649. }
  3650. return outlineView.rowHeight
  3651. }
  3652. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  3653. if outlineView.isEqual(self.tocOutlineView) {
  3654. // var _item: CPDFOutline?
  3655. // if item == nil && self.listView.document.isLocked == false {
  3656. // _item = self.listView.document.outlineRoot()
  3657. // }
  3658. if let data = item as? String, data == "Bookmarks" {
  3659. return true
  3660. } else if item is CPDFOutline {
  3661. return ((item as! CPDFOutline).numberOfChildren ?? 0) != 0
  3662. } else if item is CPDFBookmark {
  3663. return false
  3664. }
  3665. if (self.isSearchOutlineMode) {
  3666. // return [self subOutLineContainString:self.leftSideController.outlineSearchField.stringValue rootOutline:(PDFOutline *)item];
  3667. } else {
  3668. // return ((_item?.numberOfChildren ?? 0) != 0)
  3669. }
  3670. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3671. // return [item hasNoteText];
  3672. return false
  3673. }
  3674. return false
  3675. }
  3676. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  3677. if outlineView.isEqual(self.tocOutlineView) {
  3678. let itemView = KMBotaTableRowView()
  3679. return itemView
  3680. } else if outlineView.isEqual(self.noteOutlineView) {
  3681. let itemView = KMBotaTableRowView()
  3682. return itemView;
  3683. }
  3684. return nil
  3685. }
  3686. func outlineViewSelectionDidChange(_ notification: Notification) {
  3687. if self.tocOutlineView.isEqual(to: notification.object) {
  3688. // if ([[notification object] isEqual:leftSideController.tocOutlineView] && (mwcFlags.updatingOutlineSelection == 0)){
  3689. // mwcFlags.updatingOutlineSelection = 1;
  3690. self.goToSelectedOutlineItem(nil)
  3691. // mwcFlags.updatingOutlineSelection = 0;
  3692. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  3693. // [self hideLeftSideWindow];
  3694. }
  3695. }
  3696. func outlineViewItemDidExpand(_ notification: Notification) {
  3697. if self.tocOutlineView.isEqual(to: notification.object) {
  3698. self.updateOutlineSelection()
  3699. }
  3700. }
  3701. func outlineViewItemDidCollapse(_ notification: Notification) {
  3702. if self.tocOutlineView.isEqual(to: notification.object) {
  3703. self.updateOutlineSelection()
  3704. }
  3705. }
  3706. /*
  3707. #pragma mark NSOutlineView datasource protocol
  3708. - (void)outlineView:(NSOutlineView *)ov setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item{
  3709. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3710. PDFAnnotation *note = item;
  3711. if ([note type]) {
  3712. if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  3713. if ([(object ?: @"") isEqualToString:([note string] ?: @"")] == NO)
  3714. [note setString:object];
  3715. } else if ([[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3716. if ([(object ?: @"") isEqualToString:([note userName] ?: @"")] == NO)
  3717. [note setUserName:object];
  3718. }
  3719. }
  3720. }
  3721. }
  3722. #pragma mark Drag
  3723. - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard{
  3724. if ([outlineView isEqual:leftSideController.tocOutlineView]) {
  3725. if (leftSideController.tocOutlineView.selectedRowIndexes.count > 1) {
  3726. return NO;
  3727. }
  3728. NSIndexSet *tIndex = [[[NSIndexSet alloc] initWithIndex:leftSideController.tocOutlineView.clickedRow] autorelease];
  3729. [leftSideController.tocOutlineView deselectRow:tIndex.firstIndex];
  3730. self.dragPDFOutline = items.firstObject;
  3731. NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
  3732. NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:set];
  3733. [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  3734. [pasteboard setData:zNSIndexSetData forType:kKMPDFViewOutlineDragDataType];
  3735. return YES;
  3736. }
  3737. return NO;
  3738. }
  3739. - (NSDragOperation)outlineView:(NSOutlineView *)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)anIndex {
  3740. NSDragOperation dragOp = NSDragOperationNone;
  3741. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3742. NSPasteboard *pboard = [info draggingPasteboard];
  3743. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]] &&
  3744. anIndex == NSOutlineViewDropOnItemIndex && [(PDFAnnotation *)item type] != nil)
  3745. dragOp = NSDragOperationEvery;
  3746. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3747. if (anIndex == -1) {
  3748. dragOp = NSDragOperationNone;
  3749. } else {
  3750. dragOp = NSDragOperationMove;
  3751. }
  3752. }
  3753. return dragOp;
  3754. }
  3755. - (BOOL)outlineView:(NSOutlineView *)ov acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)anIndex {
  3756. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3757. NSPasteboard *pboard = [info draggingPasteboard];
  3758. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]]) {
  3759. BOOL isShift = ([NSEvent standardModifierFlags] & NSEventModifierFlagShift) != 0;
  3760. BOOL isAlt = ([NSEvent standardModifierFlags] & NSEventModifierFlagOption) != 0;
  3761. [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  3762. return YES;
  3763. }
  3764. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3765. if (anIndex < 0) {
  3766. return NO;
  3767. }
  3768. PDFOutline *outline = item;
  3769. //root,drag item to root
  3770. if (!outline.parent) {
  3771. //fetch root
  3772. PDFOutline *root = self.dragPDFOutline;
  3773. while (root.parent) {
  3774. root = root.parent;
  3775. }
  3776. if ([self.dragPDFOutline.parent isEqual:root]) {
  3777. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3778. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3779. } else {
  3780. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:root];
  3781. }
  3782. } else {
  3783. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3784. }
  3785. } else {
  3786. //在同一个层级内移动
  3787. if ([self.dragPDFOutline.parent isEqual:item]) {
  3788. if (self.dragPDFOutline.index) {
  3789. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3790. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3791. }else{
  3792. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:outline];
  3793. }
  3794. } else {
  3795. return NO;
  3796. }
  3797. } else {
  3798. PDFOutline *tOutlline = outline;
  3799. BOOL isContains = NO;
  3800. while (tOutlline) {
  3801. if ([tOutlline isEqual:self.dragPDFOutline]) {
  3802. isContains = YES;
  3803. break;
  3804. }
  3805. tOutlline = tOutlline.parent;
  3806. }
  3807. if (!isContains) {
  3808. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3809. }
  3810. }
  3811. }
  3812. return YES;
  3813. }
  3814. return NO;
  3815. }
  3816. #pragma mark NSOutlineView delegate protocol
  3817. - (NSCell *)outlineView:(NSOutlineView *)ov dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3818. if ([ov isEqual:rightSideController.noteOutlineView] && tableColumn == nil && [(PDFAnnotation *)item type] == nil) {
  3819. return [[ov tableColumnWithIdentifier:NOTE_COLUMNID] dataCellForRow:[ov rowForItem:item]];
  3820. }
  3821. return [tableColumn dataCellForRow:[ov rowForItem:item]];
  3822. }
  3823. - (void)outlineView:(NSOutlineView *)ov willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3824. if ([ov isEqual:leftSideController.tocOutlineView] &&
  3825. [ov selectionHighlightStyle] == NSTableViewSelectionHighlightStyleRegular &&
  3826. [ov isRowSelected:[ov rowForItem:item]]) {
  3827. [cell setBackgroundStyle:NSBackgroundStyleLowered];
  3828. }
  3829. }
  3830. - (BOOL)outlineView:(NSOutlineView *)ov shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item{
  3831. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3832. if (tableColumn == nil) {
  3833. if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  3834. PDFAnnotation *annotation = [(SKNoteText *)item note];
  3835. [pdfView scrollAnnotationToVisible:annotation];
  3836. [pdfView setActiveAnnotation:annotation];
  3837. [self showNote:annotation];
  3838. SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  3839. [[noteController window] makeFirstResponder:[noteController textView]];
  3840. [[noteController textView] selectAll:nil];
  3841. }
  3842. return NO;
  3843. } else if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID] || [[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3844. return YES;
  3845. }
  3846. }
  3847. return NO;
  3848. }
  3849. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  3850. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3851. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  3852. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  3853. NSMutableArray *sortDescriptors = nil;
  3854. BOOL ascending = YES;
  3855. if ([oldTableColumn isEqual:newTableColumn]) {
  3856. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  3857. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  3858. ascending = [[sortDescriptors firstObject] ascending];
  3859. } else {
  3860. NSString *tcID = [newTableColumn identifier];
  3861. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  3862. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  3863. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  3864. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  3865. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  3866. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  3867. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  3868. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  3869. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3870. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  3871. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3872. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  3873. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  3874. }
  3875. if (oldTableColumn)
  3876. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  3877. [ov setHighlightedTableColumn:newTableColumn];
  3878. }
  3879. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  3880. if (newTableColumn)
  3881. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  3882. inTableColumn:newTableColumn];
  3883. [ov reloadData];
  3884. }
  3885. }
  3886. - (NSString *)outlineView:(NSOutlineView *)ov toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tableColumn item:(id)item mouseLocation:(NSPoint)mouseLocation {
  3887. if ([ov isEqual:rightSideController.noteOutlineView] &&
  3888. (tableColumn == nil || [[tableColumn identifier] isEqualToString:NOTE_COLUMNID])) {
  3889. return [item string];
  3890. }
  3891. return @"";
  3892. }
  3893. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  3894. if (mwcFlags.autoResizeNoteRows &&
  3895. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  3896. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  3897. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  3898. [rowHeights removeAllFloats];
  3899. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  3900. }
  3901. }
  3902. - (void)updateSelectRowHeight{
  3903. CGFloat rowHeight = 0;
  3904. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:leftSideController.tocOutlineView.selectedRow];
  3905. if (!outline){
  3906. return;
  3907. }
  3908. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3909. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3910. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3911. [attributedString appendAttributedString:attr1];
  3912. NSInteger *row = [leftSideController.tocOutlineView selectedRow];
  3913. NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:row makeIfNecessary:YES];
  3914. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3915. // id cell = [tableColumn dataCell];
  3916. id cell = [tableColumn dataCellForRow:row];
  3917. [cell setObjectValue:attributedString];
  3918. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3919. NSInteger num = [self getNum:outline];
  3920. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3921. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3922. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3923. [rowHeights setFloat:rowHeight forKey:outline];
  3924. if (@available(macOS 10.13, *)) {
  3925. } else {
  3926. rowHeight = 40.0;
  3927. }
  3928. CGRect fram = viewS.frame;
  3929. viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3930. [leftSideController.tocOutlineView reloadData];
  3931. }
  3932. - (NSInteger)getNum:(PDFOutline *)ol{
  3933. NSInteger num = 0;
  3934. PDFOutline *outLine = [ol parent];
  3935. do {
  3936. outLine = [outLine parent];
  3937. if (outLine){
  3938. num ++;
  3939. }
  3940. } while (outLine);
  3941. return num;
  3942. }
  3943. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  3944. {
  3945. NSInteger rowCount = [outlineView numberOfRows];
  3946. for (NSInteger i = 0; i < rowCount; i++){
  3947. CGFloat rowHeight = 0;
  3948. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  3949. if (!outline){
  3950. continue;
  3951. }
  3952. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3953. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3954. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3955. [attributedString appendAttributedString:attr1];
  3956. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  3957. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3958. // id cell = [tableColumn dataCell];
  3959. id cell = [tableColumn dataCellForRow:i];
  3960. [cell setObjectValue:attributedString];
  3961. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3962. NSInteger num = [self getNum:outline];
  3963. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3964. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3965. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3966. [rowHeights setFloat:rowHeight forKey:outline];
  3967. if (@available(macOS 10.13, *)) {
  3968. } else {
  3969. rowHeight = 40.0;
  3970. }
  3971. // CGRect fram = viewS.frame;
  3972. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3973. }
  3974. [leftSideController.tocOutlineView reloadData];
  3975. }
  3976. */
  3977. func noteItems(_ items: NSArray) -> NSArray {
  3978. var noteItems = NSMutableArray()
  3979. for item in items {
  3980. guard let anno = (item as? KMBOTAAnnotationItem)?.annotation else {
  3981. continue
  3982. }
  3983. if anno.type == nil {
  3984. // item = [(SKNoteText *)item note];
  3985. }
  3986. if noteItems.contains(anno) == false {
  3987. noteItems.add(anno)
  3988. }
  3989. }
  3990. return noteItems
  3991. }
  3992. /*
  3993. - (NSArray *)outlineView:(NSOutlineView *)ov typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  3994. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3995. NSInteger i, count = [rightSideController.noteOutlineView numberOfRows];
  3996. NSMutableArray *texts = [NSMutableArray arrayWithCapacity:count];
  3997. for (i = 0; i < count; i++) {
  3998. id item = [rightSideController.noteOutlineView itemAtRow:i];
  3999. NSString *string = [item string];
  4000. [texts addObject:string ?: @""];
  4001. }
  4002. return texts;
  4003. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  4004. NSInteger i, count = [leftSideController.tocOutlineView numberOfRows];
  4005. NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
  4006. for (i = 0; i < count; i++)
  4007. [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  4008. return array;
  4009. }
  4010. return nil;
  4011. }
  4012. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  4013. if ([ov isEqual:rightSideController.noteOutlineView]) {
  4014. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  4015. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  4016. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  4017. }
  4018. }
  4019. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  4020. if ([typeSelectHelper isEqual:[leftSideController.thumbnailTableView typeSelectHelper]] || [typeSelectHelper isEqual:[pdfView typeSelectHelper]]) {
  4021. if (searchString)
  4022. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  4023. else
  4024. [self updateLeftStatus];
  4025. } else if ([typeSelectHelper isEqual:[rightSideController.noteOutlineView typeSelectHelper]]) {
  4026. if (searchString)
  4027. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding note: \"%@\"", @"Status message"), searchString]];
  4028. else
  4029. [self updateRightStatus];
  4030. } else if ([typeSelectHelper isEqual:[leftSideController.tocOutlineView typeSelectHelper]]) {
  4031. if (searchString)
  4032. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding: \"%@\"", @"Status message"), searchString]];
  4033. else
  4034. [self updateLeftStatus];
  4035. }
  4036. }
  4037. */
  4038. }
  4039. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  4040. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  4041. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  4042. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4043. return self.listView.hideNotes == false && items.count > 0
  4044. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  4045. return items.count > 0
  4046. }
  4047. return false
  4048. }
  4049. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  4050. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4051. if (items.isEmpty) {
  4052. return
  4053. }
  4054. for item in self.noteItems(items as NSArray) {
  4055. guard let anno = item as? CPDFAnnotation else {
  4056. continue
  4057. }
  4058. self.listView.remove(anno)
  4059. }
  4060. self.listView.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  4061. self.reloadAnnotation()
  4062. self.annotationSort(sortArray: [])
  4063. self.noteOutlineView.reloadData()
  4064. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  4065. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  4066. }
  4067. }
  4068. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  4069. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4070. if (items.count == 1) {
  4071. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  4072. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  4073. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  4074. // return NO;
  4075. // }
  4076. }
  4077. return items.count > 0
  4078. }
  4079. return false
  4080. }
  4081. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  4082. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  4083. let pboard = NSPasteboard.general
  4084. var copiedItems: [Any] = []
  4085. var attrString = NSMutableAttributedString()
  4086. var isAttributed = false
  4087. var item: AnyObject?
  4088. // for (item in [self noteItems:items]) {
  4089. // if ([item isMovable])
  4090. // [copiedItems addObject:item];
  4091. // }
  4092. // for (item in items) {
  4093. // if ([attrString length])
  4094. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  4095. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  4096. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  4097. // isAttributed = YES;
  4098. // } else {
  4099. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  4100. // }
  4101. // }
  4102. //
  4103. // [pboard clearContents];
  4104. // if (isAttributed)
  4105. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  4106. // else
  4107. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  4108. // if ([copiedItems count] > 0)
  4109. // [pboard writeObjects:copiedItems];
  4110. }
  4111. }
  4112. }
  4113. // MARK: - KMTocOutlineViewDelegate
  4114. extension KMLeftSideViewController: KMTocOutlineViewDelegate {
  4115. // func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  4116. // if ([ov isEqual:leftSideController.tocOutlineView]) {
  4117. // NSInteger numRows = [ov numberOfRows];
  4118. // NSUInteger firstPage = [[[ov itemAtRow:row] page] pageIndex];
  4119. // NSUInteger lastPage = row + 1 < numRows ? [[[ov itemAtRow:row + 1] page] pageIndex] : [[self pdfDocument] pageCount];
  4120. // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  4121. // NSUInteger i, iMax = [lastViewedPages count];
  4122. // for (i = 0; i < iMax; i++) {
  4123. // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  4124. // return i;
  4125. // }
  4126. // }
  4127. // return NSNotFound;
  4128. // }
  4129. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  4130. if anOutlineView.isEqual(to: self.tocOutlineView) {
  4131. if item == nil {
  4132. return true as AnyObject
  4133. }
  4134. if item is CPDFOutline {
  4135. return (item as! CPDFOutline).destination
  4136. }
  4137. }
  4138. return nil
  4139. }
  4140. }
  4141. extension KMLeftSideViewController: KMNoteOutlineViewDelegate {
  4142. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  4143. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4144. return true
  4145. }
  4146. return false
  4147. }
  4148. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  4149. // [rowHeights setFloat:newHeight forKey:item];
  4150. }
  4151. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  4152. // if (mwcFlags.autoResizeNoteRows &&
  4153. // [ov isEqual:rightSideController.noteOutlineView] &&
  4154. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  4155. // [rowHeights removeAllFloats];
  4156. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  4157. // }
  4158. }
  4159. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  4160. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  4161. // if (annotation) {
  4162. // [pdfView scrollAnnotationToVisible:annotation];
  4163. // [pdfView setActiveAnnotation:annotation];
  4164. // }
  4165. }
  4166. }
  4167. // MARK: - Menu Item Actions
  4168. extension KMLeftSideViewController {
  4169. @objc func cutPage(_ sender: AnyObject?) {
  4170. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4171. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4172. // return;
  4173. // }
  4174. self._tableView(self.thumbnailTableView, cutRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4175. }
  4176. @objc func copyPage(_ sender: AnyObject?) {
  4177. self.tableView(self.thumbnailTableView, copyRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4178. }
  4179. @objc func pastePage(_ sender: AnyObject?) {
  4180. self.tableView(self.thumbnailTableView, pasteFromPasteboard: nil)
  4181. }
  4182. @objc func deletePage(_ sender: AnyObject?) {
  4183. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4184. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4185. // return;
  4186. // }
  4187. self.tableView(self.thumbnailTableView, deleteRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4188. }
  4189. @objc func rotatePageMenuAction(_ sender: AnyObject?) {
  4190. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4191. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4192. // return;
  4193. // }
  4194. //
  4195. self.tableView(self.thumbnailTableView, rotateRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes as NSIndexSet)
  4196. }
  4197. @objc func quickInsert(_ sender: AnyObject?) {
  4198. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4199. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4200. // return;
  4201. // }
  4202. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4203. if idx == NSNotFound || idx >= self.listView.document.pageCount {
  4204. return
  4205. }
  4206. let result = self.listView.insertPage(KMNormalBlankSize, at: idx+1)
  4207. if result == false {
  4208. return
  4209. }
  4210. var selectedIndexSet = IndexSet()
  4211. selectedIndexSet.insert(idx+1)
  4212. self.insertPages(selectedIndexSet, pageAt: idx)
  4213. }
  4214. @objc func insert(_ sender: AnyObject?) {
  4215. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4216. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4217. // return;
  4218. // }
  4219. guard let document = self.listView.document else {
  4220. return
  4221. }
  4222. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4223. if idx == NSNotFound || idx >= document.pageCount {
  4224. return
  4225. }
  4226. if document.allowsCopying == false || document.allowsPrinting == false {
  4227. Task {
  4228. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4229. }
  4230. return
  4231. }
  4232. let insertVC = KMPDFEditInsertBlankPageWindow(document: document)
  4233. insertVC.insertLocation = 3
  4234. insertVC.currentPage = idx + 1
  4235. insertVC.callback = { [weak self] pdfDoc, _, pages, insertI in
  4236. if let _pages = pages {
  4237. // mm 单位的大小
  4238. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  4239. self?.km_endSheet()
  4240. return
  4241. }
  4242. var pageSize = _winC.pageSize
  4243. let direction = _winC.pageRotation == 0 ? 0 : 1
  4244. if (direction == 0) { // 纵向
  4245. if (pageSize.width > pageSize.height) { // 需要交换
  4246. let tmp = pageSize.width
  4247. pageSize.width = pageSize.height
  4248. pageSize.height = tmp
  4249. } else {
  4250. // no things.
  4251. }
  4252. } else { // 横向
  4253. if (pageSize.width > pageSize.height) {
  4254. // no things.
  4255. } else { // 需要交换
  4256. let tmp = pageSize.width
  4257. pageSize.width = pageSize.height
  4258. pageSize.height = tmp
  4259. }
  4260. }
  4261. /// 插入位置
  4262. let document = CPDFDocument()
  4263. document?.insertPage(pageSize, at: 0)
  4264. if let page: CPDFPage = (document?.page(at: 0)) {
  4265. self?.insertPage(page, pageAt: insertI)
  4266. }
  4267. }
  4268. self?.km_quick_endSheet()
  4269. }
  4270. self.km_beginSheet(windowC: insertVC)
  4271. }
  4272. @objc func insertPDF(_ sender: AnyObject?) {
  4273. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4274. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4275. // return;
  4276. // }
  4277. guard let document = self.listView.document else {
  4278. return
  4279. }
  4280. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4281. if idx == NSNotFound || idx >= document.pageCount {
  4282. return
  4283. }
  4284. if document.allowsCopying == false || document.allowsPrinting == false {
  4285. Task {
  4286. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4287. }
  4288. return
  4289. }
  4290. let panel = NSOpenPanel()
  4291. panel.allowedFileTypes = ["pdf"]
  4292. panel.beginSheetModal(for: self.view.window!) { response in
  4293. if response == .cancel {
  4294. return
  4295. }
  4296. for fileURL in panel.urls {
  4297. let pdfDoc = CPDFDocument(url: fileURL)
  4298. if let data = pdfDoc?.isLocked, data {
  4299. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4300. let com = PasswordWindowController(windowNibName: "PasswordWindowController")
  4301. com.fileURL = fileURL
  4302. self.km_beginSheet(windowC: com)
  4303. com.closeCallBack = { [unowned self] password in
  4304. self.km_quick_endSheet()
  4305. // }
  4306. if (password.isEmpty == false) {
  4307. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL, password: password)
  4308. insertVC.insertLocation = 3
  4309. insertVC.currentPage = idx + 1
  4310. self.km_beginSheet(windowC: insertVC)
  4311. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4312. var indexs = IndexSet()
  4313. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4314. self?.km_quick_endSheet()
  4315. return
  4316. }
  4317. let doc = _winC.insertDocument!
  4318. let fileAttribute = _winC.fileAttribute
  4319. var insertIndex = insertIdx
  4320. var insertPages: [CPDFPage] = []
  4321. for number in fileAttribute.fetchSelectPages() {
  4322. if let page = doc.page(at: UInt(number-1)) {
  4323. insertPages.append(page)
  4324. indexs.insert(insertIndex)
  4325. insertIndex += 1
  4326. }
  4327. }
  4328. for (i, page) in insertPages.enumerated() {
  4329. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4330. }
  4331. self?.insertPages(indexs, pageAt: insertIdx)
  4332. self?.km_quick_endSheet()
  4333. }
  4334. }
  4335. }
  4336. }
  4337. } else {
  4338. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL)
  4339. insertVC.insertLocation = 3
  4340. insertVC.currentPage = idx + 1
  4341. self.km_beginSheet(windowC: insertVC)
  4342. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4343. var indexs = IndexSet()
  4344. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4345. self?.km_quick_endSheet()
  4346. return
  4347. }
  4348. let doc = _winC.insertDocument!
  4349. let fileAttribute = _winC.fileAttribute
  4350. var insertIndex = insertIdx
  4351. var insertPages: [CPDFPage] = []
  4352. for number in fileAttribute.fetchSelectPages() {
  4353. if let page = doc.page(at: UInt(number-1)) {
  4354. insertPages.append(page)
  4355. indexs.insert(insertIndex)
  4356. insertIndex += 1
  4357. }
  4358. }
  4359. for (i, page) in insertPages.enumerated() {
  4360. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4361. }
  4362. self?.insertPages(indexs, pageAt: insertIdx)
  4363. self?.km_quick_endSheet()
  4364. }
  4365. }
  4366. }
  4367. }
  4368. }
  4369. @objc func extractPage(_ sender: AnyObject?) {
  4370. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4371. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4372. // return;
  4373. // }
  4374. self.tableView(self.thumbnailTableView, extractRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4375. }
  4376. @objc func pageEdit(_ sender: AnyObject?) {
  4377. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .pageEdit, params: nil)
  4378. }
  4379. @objc func displayPageSize(_ sender: AnyObject?) {
  4380. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4381. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4382. // return;
  4383. // }
  4384. self.isDisplayPageSize = !self.isDisplayPageSize;
  4385. UserDefaults.standard.setValue(self.isDisplayPageSize, forKey: "kKMThumbnailDisplayPageSizeKey")
  4386. UserDefaults.standard.synchronize()
  4387. Task { @MainActor in
  4388. self.thumbnailTableView.reloadData()
  4389. }
  4390. }
  4391. @objc func sharePage(_ sender: AnyObject?) {
  4392. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4393. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4394. // return;
  4395. // }
  4396. guard let document = self.listView.document else {
  4397. return
  4398. }
  4399. var pages = NSMutableArray()
  4400. for idx in self.thumbnailTableView.selectedRowIndexes {
  4401. if (idx < document.pageCount) {
  4402. if let page = self.listView.document.page(at: UInt(idx)) {
  4403. pages.add(page)
  4404. }
  4405. }
  4406. }
  4407. let pdf = CPDFDocument()
  4408. for page in pages {
  4409. // PDFPage *copyPage = [[page copy] autorelease];
  4410. if let _page = page as? CPDFPage {
  4411. pdf?.insertPageObject(_page, at: pdf?.pageCount ?? 0)
  4412. }
  4413. }
  4414. // NSString * = nil;
  4415. var fileName = ""
  4416. // NSString * = [self.pdfDocument.documentURL.lastPathComponent stringByDeletingPathExtension];
  4417. var documentFileName = document.documentURL?.deletingPathExtension().lastPathComponent ?? ""
  4418. var tName = self.fileNameWithSelectedPages(self.thumbnailTableView.selectedRowIndexes)
  4419. if (tName.count > 50) {
  4420. tName = tName.substring(to: 50)
  4421. }
  4422. if (pages.count > 1) {
  4423. fileName = String(format: "%@ pages %@", documentFileName, tName)
  4424. } else {
  4425. fileName = String(format: "%@ page %@", documentFileName, tName)
  4426. }
  4427. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  4428. var cachesDir = paths.first ?? ""
  4429. cachesDir = "\(cachesDir)/\(fileName).pdf"
  4430. var array = NSMutableArray()
  4431. let url = URL(fileURLWithPath: cachesDir)
  4432. array.add(url)
  4433. let vc = KMProgressWindowController()
  4434. // // [NSApp beginSheet:[vc window]
  4435. // // modalForWindow:self.window
  4436. // // modalDelegate:nil
  4437. // // didEndSelector:nil
  4438. // // contextInfo:NULL];
  4439. self.view.window?.beginSheet(vc.window!, completionHandler: { [unowned self] returnCode in
  4440. NSApp.endSheet(self.view.window!, returnCode: returnCode.rawValue)
  4441. })
  4442. DispatchQueue.global().async {
  4443. let sucess = pdf?.write(toFile: cachesDir) ?? false
  4444. if (sucess) {
  4445. DispatchQueue.main.async {
  4446. // [[sender representedObject] performWithItems:array];
  4447. let represent : NSSharingService = (sender as! NSMenuItem).representedObject as! NSSharingService
  4448. represent.perform(withItems: [url])
  4449. NSApp.endSheet(vc.window!)
  4450. vc.close()
  4451. }
  4452. } else {
  4453. NSApp.endSheet(vc.window!)
  4454. vc.close()
  4455. }
  4456. }
  4457. // [vc release];
  4458. }
  4459. @objc func toggleCaseInsensitiveNoteSearch(_ sender: AnyObject?) {
  4460. KMPrint("KMLeftSideViewController-toggleCaseInsensitiveNoteSearch...")
  4461. }
  4462. @objc func searchNotes(_ sender: AnyObject?) {
  4463. self.noteSearchMode = false
  4464. if self.findState == .note {
  4465. if self.noteSearchField.isEqual(to: sender) {
  4466. self.noteSearchMode = true
  4467. }
  4468. self.updateNoteFilterPredicate()
  4469. } else {
  4470. self.updateSnapshotFilterPredicate()
  4471. }
  4472. let textfield = sender as? NSSearchField
  4473. if let data = textfield?.stringValue.isEmpty, data == false {
  4474. let findPboard = NSPasteboard(name: .find)
  4475. findPboard.clearContents()
  4476. // findPboard.writeObjects([textfield!.stringValue])
  4477. }
  4478. }
  4479. @objc func toggleSelectedSnapshots(_ sender: AnyObject?) {
  4480. let indexs = self.snapshotTableView.selectedRowIndexes
  4481. if indexs.isEmpty {
  4482. return
  4483. }
  4484. let model = self.snapshots[indexs.last!]
  4485. let windowC = model.windowC
  4486. if let data = windowC?.window?.isVisible, data {
  4487. windowC?.miniaturize()
  4488. } else {
  4489. windowC?.deminiaturize()
  4490. }
  4491. var rowIndexSet = IndexSet()
  4492. let row = self.snapshotTableView.selectedRow
  4493. if row >= 0 && row < self.snapshots.count {
  4494. rowIndexSet.insert(row)
  4495. }
  4496. var columnIndexSet = IndexSet()
  4497. columnIndexSet.insert(0)
  4498. self.snapshotTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  4499. }
  4500. private func _tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  4501. if tv.isEqual(to: self.thumbnailTableView) {
  4502. self._copysPages.removeAll()
  4503. for idx in rowIndexes {
  4504. if (idx != NSNotFound) {
  4505. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  4506. self._copysPages.append(page)
  4507. }
  4508. }
  4509. }
  4510. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  4511. }
  4512. }
  4513. // MARK: - Snapshot
  4514. @objc func menuItemClick_ExportPNG(_ sender: AnyObject?) {
  4515. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4516. return
  4517. }
  4518. let image = snapshot.thumbnailWithSize(0)
  4519. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.pngData(), allowedTypes: ["png"]) { url in
  4520. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4521. }
  4522. }
  4523. @objc func menuItemClick_ExportJPG(_ sender: AnyObject?) {
  4524. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4525. return
  4526. }
  4527. let image = snapshot.thumbnailWithSize(0)
  4528. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.jpgData(), allowedTypes: ["jpg"]) { url in
  4529. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4530. }
  4531. }
  4532. @objc func menuItemClick_ExportPDF(_ sender: AnyObject?) {
  4533. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4534. return
  4535. }
  4536. if let image = snapshot.thumbnailWithSize(0) {
  4537. let document = CPDFDocument()
  4538. _ = document?.km_insert(image: image, at: 0)
  4539. NSPanel.savePanel_pdf_success(self.view.window!, document: document) { url in
  4540. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4541. }
  4542. }
  4543. }
  4544. @objc func menuItemClick_Print(_ sender: AnyObject?) {
  4545. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4546. return
  4547. }
  4548. if let image = snapshot.thumbnailWithSize(0) {
  4549. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .print, params: image)
  4550. }
  4551. }
  4552. @objc func menuItemClick_SelectAll(_ sender: AnyObject?) {
  4553. let selected = self.snapshotListIsAllSelected()
  4554. for model in self.snapshots {
  4555. model.isSelected = !selected
  4556. }
  4557. Task { @MainActor in
  4558. self.snapshotTableView.reloadData()
  4559. }
  4560. }
  4561. @objc func deleteAllSnapshot(_ sender: AnyObject?) {
  4562. for model in self.snapshots {
  4563. model.windowC?.close()
  4564. }
  4565. }
  4566. @objc func hideSnapshot(_ sender: AnyObject?) {
  4567. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4568. return
  4569. }
  4570. if let data = snapshot.window?.isVisible, data {
  4571. snapshot.miniaturize()
  4572. }
  4573. }
  4574. @objc func showSnapshot(_ sender: AnyObject?) {
  4575. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4576. return
  4577. }
  4578. if let data = snapshot.window?.isVisible, data {
  4579. snapshot.window?.orderFront(nil)
  4580. } else {
  4581. snapshot.deminiaturize()
  4582. }
  4583. }
  4584. @objc func deleteSnapshot(_ sender: AnyObject?) {
  4585. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4586. return
  4587. }
  4588. snapshot.close()
  4589. }
  4590. @objc func menuItemClick_Copy(_ sender: AnyObject?) {
  4591. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4592. return
  4593. }
  4594. let image = snapshot.thumbnailWithSize(0)
  4595. if let tiffData = image?.tiffRepresentation {
  4596. let pasteboardItem = NSPasteboardItem()
  4597. pasteboardItem.setData(tiffData, forType: .tiff)
  4598. let pboard = NSPasteboard.general
  4599. pboard.clearContents()
  4600. pboard.writeObjects([pasteboardItem])
  4601. }
  4602. }
  4603. func updateSnapshotFilterPredicate() {
  4604. let searchString = self.snapshotSearchField.stringValue
  4605. self.searchSnapshots.removeAll()
  4606. if self.findState == .snapshot && searchString.isEmpty == false {
  4607. self.searchSnapshots = self.snapshots.filter({ model in
  4608. let data = model.windowC?.string.contains(searchString) ?? false
  4609. return data
  4610. })
  4611. }
  4612. Task { @MainActor in
  4613. self.updataLeftSideSnapView()
  4614. self.snapshotTableView.reloadData()
  4615. }
  4616. }
  4617. func snapshotListIsAllSelected() -> Bool {
  4618. if self.snapshots.isEmpty {
  4619. return false
  4620. }
  4621. for model in self.snapshots {
  4622. if model.isSelected == false {
  4623. return false
  4624. }
  4625. }
  4626. return true
  4627. }
  4628. }
  4629. // MARK: - Undo & Redo
  4630. extension KMLeftSideViewController {
  4631. @objc dynamic func tableView(_ tv: NSTableView, rotateRowsWithIndexes rowIndexes: NSIndexSet) {
  4632. if tv.isEqual(to: self.thumbnailTableView) {
  4633. for idx in rowIndexes {
  4634. if (idx != NSNotFound) {
  4635. let page = self.listView.document.page(at: UInt(idx))
  4636. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).rotatePage(page, pageAt: idx)
  4637. page?.rightRotate()
  4638. self.listView.layoutDocumentView()
  4639. self.resetThumbnails()
  4640. // NSInteger pageIndex = MIN(idx, [[pdfView document] pageCount]-1);
  4641. // [pdfView goToPage:[[pdfView document] pageAtIndex:pageIndex]];
  4642. }
  4643. self.thumbnailTableView.selectRowIndexes(rowIndexes as IndexSet, byExtendingSelection: true)
  4644. }
  4645. }
  4646. }
  4647. @objc dynamic func rotatePage(_ page: CPDFPage?, pageAt index: Int) {
  4648. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, rotateRowsWithIndexes: NSIndexSet(index: index))
  4649. page?.leftRotate()
  4650. self.listView.layoutDocumentView()
  4651. self.resetThumbnails()
  4652. }
  4653. @objc dynamic func insertPage(_ page: CPDFPage, pageAt index: Int) {
  4654. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: index))
  4655. self.listView.document.insertPageObject(page, at: UInt(index))
  4656. self.listView.layoutDocumentView()
  4657. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4658. self.resetThumbnails()
  4659. let pageIndex = min(index, Int((self.listView.document?.pageCount ?? 0))-1)
  4660. self.listView.go(toPageIndex: pageIndex, animated: false)
  4661. }
  4662. @objc dynamic func insertPages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  4663. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).deletePages(selectedIndexSet, pageAt: index)
  4664. self.listView.layoutDocumentView()
  4665. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4666. self.resetThumbnails()
  4667. if let pageIndex = selectedIndexSet.first {
  4668. self.listView.go(toPageIndex: pageIndex, animated: false)
  4669. }
  4670. }
  4671. @objc dynamic func deletePages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  4672. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPages(selectedIndexSet, pageAt: index)
  4673. for idx in selectedIndexSet {
  4674. if idx < self.listView.document.pageCount {
  4675. self.listView.document.removePage(at: UInt(idx))
  4676. }
  4677. }
  4678. self.listView.layoutDocumentView()
  4679. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4680. self.resetThumbnails()
  4681. let pageIndex = min(index, Int(self.listView.document.pageCount)-1)
  4682. self.listView.go(toPageIndex: pageIndex, animated: false)
  4683. }
  4684. }
  4685. // MARK: - Other
  4686. extension KMLeftSideViewController {
  4687. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  4688. let outlineItem = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow)
  4689. let outline = self.tocOutlineView
  4690. if let cnt = outline?.selectedRowIndexes.count, cnt == 1 {
  4691. if outlineItem is CPDFOutline {
  4692. let outline = (outlineItem as! CPDFOutline)
  4693. if let des = outline.destination {
  4694. self.listView.go(to: des)
  4695. } else if let action = outline.action {
  4696. self.listView.perform(action)
  4697. }
  4698. } else if outlineItem is CPDFBookmark {
  4699. let bookmark = outlineItem as! CPDFBookmark
  4700. self.listView.go(toPageIndex: bookmark.pageIndex, animated: true)
  4701. }
  4702. }
  4703. }
  4704. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  4705. KMPrint("KMLeftSideViewController-goToSelectedFindResults...")
  4706. }
  4707. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  4708. if tv.isEqual(to: self.thumbnailTableView) {
  4709. guard let document = self.listView.document else {
  4710. return
  4711. }
  4712. var pages = NSMutableArray()
  4713. for idx in self.thumbnailTableView.selectedRowIndexes {
  4714. if (idx < document.pageCount) {
  4715. if let page = self.listView.document.page(at: UInt(idx)) {
  4716. pages.add(page)
  4717. }
  4718. }
  4719. }
  4720. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  4721. let saveAccessCtr = KMSavePanelAccessoryController()
  4722. let outputSavePanel = NSSavePanel()
  4723. outputSavePanel.allowedFileTypes = ["pdf"]
  4724. outputSavePanel.accessoryView = saveAccessCtr.view
  4725. outputSavePanel.nameFieldStringValue = fileName
  4726. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  4727. if (result == .OK) {
  4728. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  4729. let vc = KMProgressWindowController()
  4730. self.view.window?.beginSheet(vc.window!)
  4731. let saveFilePath = outputSavePanel.url?.path
  4732. DispatchQueue.global().async {
  4733. let pdf = CPDFDocument()
  4734. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  4735. DispatchQueue.main.async {
  4736. if (success) {
  4737. if (saveAccessCtr.openAutomaticButton.state == .on) {
  4738. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  4739. }
  4740. } else {
  4741. KMTools.viewFile(at: saveFilePath!)
  4742. }
  4743. }
  4744. NSApp.endSheet(vc.window!)
  4745. vc.close()
  4746. }
  4747. }
  4748. }
  4749. }
  4750. }
  4751. }
  4752. }
  4753. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  4754. var pagesName = ""
  4755. if (itemIndexes.count > 1) {
  4756. pagesName.append(" pages")
  4757. } else {
  4758. pagesName.append("page")
  4759. }
  4760. let docmentName = self.listView.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  4761. var fileName = ""
  4762. if (itemIndexes.count > 0) {
  4763. if (itemIndexes.count == 1) {
  4764. let idx = itemIndexes.first! + 1
  4765. let tFileName = String(format: "%@ %@", pagesName, "\(idx)")
  4766. return String(format: "%@%@", docmentName, tFileName)
  4767. }
  4768. var sortIndex = IndexSet()
  4769. for idx in itemIndexes {
  4770. let _idx = idx + 1
  4771. sortIndex.insert(_idx)
  4772. }
  4773. // NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
  4774. // NSArray *sortDesc = @[sort];
  4775. // NSArray *sortArray = [sortIndex sortedArrayUsingDescriptors:sortDesc];
  4776. let sortArray = sortIndex.sorted()
  4777. var a = 0
  4778. var b = 0
  4779. for num in sortArray {
  4780. // for (NSNumber *num in sortArray) {
  4781. if (fileName.isEmpty == false) {
  4782. if (num == b+1) {
  4783. b = num
  4784. if (num == sortArray.last) {
  4785. fileName = "\(fileName)\(a)-\(b)"
  4786. }
  4787. } else {
  4788. if (a == b) {
  4789. fileName = "\(fileName)\(a),"
  4790. } else {
  4791. fileName = "\(fileName)\(a)-\(b),"
  4792. }
  4793. b = num
  4794. a = b
  4795. if (num == sortArray.last) {
  4796. fileName = "\(fileName)\(a)"
  4797. }
  4798. }
  4799. } else {
  4800. fileName = ""
  4801. b = num
  4802. a = b
  4803. }
  4804. }
  4805. let tFileName = String(format: "%@ %@", pagesName,fileName)
  4806. return String(format: "%@%@", docmentName,tFileName)
  4807. }
  4808. return ""
  4809. }
  4810. func switchType(_ type: BotaType) {
  4811. if type == .Thumbnail {
  4812. self.leftView.segmentedControl.selectedSegment = 0
  4813. } else if type == .Outline {
  4814. self.leftView.segmentedControl.selectedSegment = 1
  4815. } else if type == .Annotation {
  4816. self.leftView.segmentedControl.selectedSegment = 2
  4817. } else if type == .snapshot {
  4818. self.leftView.segmentedControl.selectedSegment = 3
  4819. } else if type == .Search {
  4820. self.leftView.segmentedControl.selectedSegment = 4
  4821. }
  4822. }
  4823. var TINY_SIZE: Float {
  4824. get {
  4825. return 32.0
  4826. }
  4827. }
  4828. var SMALL_SIZE: Float {
  4829. get {
  4830. return 64.0
  4831. }
  4832. }
  4833. var LARGE_SIZE: Float {
  4834. get {
  4835. return 128.0
  4836. }
  4837. }
  4838. var HUGE_SIZE: Float {
  4839. get {
  4840. return 256.0
  4841. }
  4842. }
  4843. var FUDGE_SIZE: Float {
  4844. get {
  4845. return 0.1
  4846. }
  4847. }
  4848. func updateTableFont() {
  4849. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  4850. self.tocOutlineView.font = font
  4851. self.noteOutlineView.font = font
  4852. self.findTableView.font = font
  4853. self.groupedFindTableView.font = font
  4854. }
  4855. }