KMLeftSideViewController.swift 252 KB

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