KMLeftSideViewController.swift 244 KB

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