KMLeftSideViewController.swift 246 KB

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