KMLeftSideViewController.swift 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456
  1. //
  2. // KMLeftSideViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. private let KMLeftSideViewNoteSortTypeKey = "KMLeftSideViewNoteSortTypeKey"
  9. private let KMLeftSideViewAscendSortBoolKey = "KMLeftSideViewAscendSortBoolKey"
  10. @objc protocol KMLeftSideViewControllerDelegate {
  11. @objc optional func controlStateChange(_ obj: KMLeftSideViewController,show:Bool)
  12. @objc optional func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int])
  13. @objc optional func searchAction(searchString:String, isCase:Bool)
  14. @objc optional func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType)
  15. @objc optional func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  16. @objc optional func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem])
  17. @objc optional func controller(controller: KMLeftSideViewController, rotateType: KMRotateType)
  18. }
  19. class KMLeftSideViewController: KMSideViewController {
  20. var dataSource : [KMLeftMethodMode] = [KMLeftMethodMode]()
  21. var type : KMLeftMethodMode = KMLeftMethodMode()
  22. var isShowPanel : Bool = false
  23. var norImage : [String] = []
  24. var selectImage : [String] = []
  25. var mainVC: KMMainViewController?
  26. var selectPages: [Int]?
  27. open weak var delegate: KMLeftSideViewControllerDelegate?
  28. let noteColumnId = NSUserInterfaceItemIdentifier(rawValue: "note")
  29. let authorColumnId = NSUserInterfaceItemIdentifier(rawValue: "author")
  30. deinit {
  31. KMPrint("KMLeftSideViewController deinit.")
  32. NotificationCenter.default.removeObserver(self)
  33. DistributedNotificationCenter.default().removeObserver(self)
  34. }
  35. override var nibName: NSNib.Name? {
  36. return "LeftSideView"
  37. }
  38. convenience init(type : KMLeftMethodMode) {
  39. self.init()
  40. self.type = type
  41. }
  42. override func viewDidLoad() {
  43. super.viewDidLoad()
  44. self.reloadThumbnailSize()
  45. self.reloadSnapshotSize()
  46. // DistributedNotificationCenter.default().addObserver(self, selector: #selector(interfaceThemeDidChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  47. self.isDisplayPageSize = UserDefaults.standard.bool(forKey: "kKMThumbnailDisplayPageSizeKey")
  48. }
  49. func showPanelView(show: Bool) {
  50. self.isShowPanel = show
  51. if show {
  52. self.leftView.segmentedControl.selectedSegment = 0
  53. } else {
  54. self.leftView.segmentedControl.selectedSegment = UInt8.max
  55. self.type.methodType = .None
  56. self.delegate?.controlStateChange?(self, show: false)
  57. }
  58. }
  59. func refreshMethodType(methodType: BotaType) {
  60. let newType = KMLeftMethodMode()
  61. var show = true
  62. if self.type.methodType != methodType {
  63. newType.methodType = methodType
  64. }
  65. if self.type.methodType == methodType {
  66. show = false
  67. } else if methodType == .None {
  68. show = false
  69. }
  70. self.type = newType;
  71. self.delegate?.controlStateChange?(self,show:show)
  72. }
  73. // MARK: - New
  74. /*
  75. NSArrayController *findArrayController;
  76. NSArrayController *groupedFindArrayController;
  77. }
  78. */
  79. @IBOutlet var segmentedControl: KMSegmentedControl!
  80. @IBOutlet var thumbnailTableView: KMThumbnailTableView!
  81. @IBOutlet var tocOutlineView: KMTocOutlineView!
  82. @IBOutlet var noteOutlineView: KMNoteOutlineView!
  83. @IBOutlet var findTableView: KMBotaTableView!
  84. @IBOutlet var groupedFindTableView: KMBotaTableView!
  85. @IBOutlet var snapshotTableView: KMBotaTableView!
  86. @IBOutlet weak var leftListView: NSView!
  87. @IBOutlet var searchViewController: KMBotaSearchViewController!
  88. @IBOutlet weak var toolButtonBox: NSBox!
  89. @IBOutlet weak var toolButtonBoxLayoutConstraint: NSLayoutConstraint!
  90. @IBOutlet weak var snapshotNormalView: NSView!
  91. @IBOutlet weak var snapshotLabel: NSTextField!
  92. @IBOutlet weak var snapshotNormalMoreButton: NSButton!
  93. @IBOutlet weak var snapshotNormalSearchButton: NSButton!
  94. @IBOutlet weak var snapshotNormalZoomOutButton: NSButton!
  95. @IBOutlet weak var snapshotNormalZoomInButton: NSButton!
  96. @IBOutlet weak var snapshotSearchZoomOutButton: NSButton!
  97. @IBOutlet weak var snapshotSearchZoomInButton: NSButton!
  98. @IBOutlet weak var snapshotSearchField: KMLeftSideViewSearchField!
  99. @IBOutlet weak var snapshotDoneButton: NSButton!
  100. @IBOutlet weak var outlineView: NSView!
  101. @IBOutlet weak var outlineMoreButton: NSButton!
  102. @IBOutlet weak var outlineAddButton: NSButton!
  103. @IBOutlet weak var outlineSearchButton: NSButton!
  104. @IBOutlet weak var outlineLabel: NSTextField!
  105. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  106. @IBOutlet weak var outlineDoneButton: NSButton!
  107. @IBOutlet weak var noteView: NSView!
  108. @IBOutlet weak var noteMoreButton: NSButton!
  109. @IBOutlet weak var noteFilterButton: NSButton!
  110. @IBOutlet weak var noteSearchButton: NSButton!
  111. @IBOutlet weak var noteSearchField: KMLeftSideViewSearchField!
  112. @IBOutlet weak var noteTitleLabel: NSTextField!
  113. @IBOutlet weak var noteHeaderView: NSView!
  114. @IBOutlet weak var sortTypeBox: KMBox!
  115. @IBOutlet weak var sortTypeLabel: NSTextField!
  116. @IBOutlet weak var noteSortButton: NSButton!
  117. @IBOutlet weak var noteDoneButton: NSButton!
  118. @IBOutlet weak var thumbnailView: NSView!
  119. @IBOutlet weak var thumbnailZoomOutButton: NSButton!
  120. @IBOutlet weak var thumbnailZoomInButton: NSButton!
  121. @IBOutlet weak var thumbnailTitleLabel: NSTextField!
  122. @IBOutlet weak var emptySearchBox: NSBox!
  123. @IBOutlet weak var emptySearchLabel: NSTextField!
  124. var filterButtonLayer: NSView?
  125. var moreButtonLayer: KMButtonLayer?
  126. var thumbnails: [KMThumbnail] = []
  127. var isDisplayPageSize = false
  128. var thumbnailCacheSize: CGFloat = 32 * 3
  129. var snapshotCacheSize: CGFloat = 32 * 3
  130. private var _findState: KMFindState = .none
  131. var findState: KMFindState {
  132. get {
  133. return self._findState
  134. }
  135. set {
  136. if self._findState != newValue {
  137. self._findState = newValue
  138. self.displayFindState()
  139. if self._findState == .content {
  140. self.search(self.searchField)
  141. } else if self.findState == .note {
  142. // self.searchNotes(self.searchField)
  143. self.searchNotes(nil)
  144. } else if self.findState == .snapshot {
  145. self.searchNotes(self.searchField)
  146. }
  147. }
  148. }
  149. }
  150. var searchResults : [KMSearchMode] = [] {
  151. didSet {
  152. self.updataLeftSideFindView()
  153. }
  154. }
  155. var groupSearchResults: [KMSearchMode] = []
  156. var findPaneState: KMFindPaneState = .singular
  157. var isSearchOutlineMode = false
  158. var isSearchSnapshotMode = false
  159. var outlineIgnoreCaseFlag = false
  160. var noteTypeDict: [String : Any] = [:]
  161. private let MIN_SIDE_PANE_WIDTH: CGFloat = 270
  162. private let LABEL_COLUMNID = "label"
  163. var foldType: KMFoldAllAnnotationType = .none
  164. static let noteSortTypeKey = KMLeftSideViewNoteSortTypeKey
  165. static let ascendSorKey = KMLeftSideViewAscendSortBoolKey
  166. private let SKDisableTableToolTipsKey = "SKDisableTableToolTips"
  167. var tocType: KMFoldType = .none
  168. var snapshots: [KMSnapshotModel] = []
  169. var dirtySnapshots: [KMSnapshotWindowController] = []
  170. var searchSnapshots: [KMSnapshotModel] = []
  171. private var _noteSortType: KMNoteSortType = .none
  172. var noteSortType: KMNoteSortType {
  173. get {
  174. return self._noteSortType
  175. }
  176. set {
  177. self._noteSortType = newValue
  178. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  179. }
  180. }
  181. var isAscendSort = false {
  182. didSet {
  183. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  184. }
  185. }
  186. lazy var leftSideEmptyVC: KMLeftSideEmptyFileViewController = {
  187. let vc = KMLeftSideEmptyFileViewController(nibName: "KMLeftSideEmptyFileViewController", bundle: nil)
  188. vc.view.wantsLayer = true
  189. return vc
  190. }()
  191. var preThumbnailRow: Int = 0
  192. var leftMargin: CGFloat = 0
  193. lazy var leftView: KMBotaLeftView = {
  194. let view = KMBotaLeftView()
  195. return view
  196. }()
  197. private var _copysPages: [CPDFPage] = []
  198. var copyPages: [CPDFPage] {
  199. get {
  200. return self._copysPages
  201. }
  202. }
  203. var annotations: [KMBOTAAnnotationSection] = []
  204. var allAnnotations: [CPDFAnnotation] = []
  205. private let kKMPDFViewOutlineDragDataType = NSPasteboard.PasteboardType("kKMPDFViewOutlineDragDataType")
  206. private let KPDFThumbnailDoucumentURLForDraggedTypes = NSPasteboard.PasteboardType("KPDFThumbnailDoucumentURLForDraggedTypes")
  207. var renamePDFOutline: CPDFOutline?
  208. var renamePDFOutlineTextField: NSTextField?
  209. var allFoldNotes: [CPDFAnnotation] = []
  210. var notes: [CPDFAnnotation] = []
  211. var canFoldNotes: [CPDFAnnotation] = []
  212. var isRenameNoteOutline = false
  213. var caseInsensitiveNoteSearch = false
  214. var noteSearchArray: [CPDFAnnotation] = []
  215. var noteSearchMode = false
  216. var mwcFlags: MwcFlags = MwcFlags()
  217. private var _dragPDFOutline: CPDFOutline?
  218. var updatingOutlineSelection = false
  219. override func loadView() {
  220. super.loadView()
  221. self.initSubView()
  222. self.initDefalutValue()
  223. self.searchViewController.loadView()
  224. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  225. self.searchField = self.searchViewController.searchField
  226. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  227. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  228. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  229. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  230. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  231. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  232. self.searchViewController.segmentedControl.selectedSegment = 0
  233. self.searchViewController.segmentedControl.block = { [unowned self] segIndex in
  234. if segIndex == 0 {
  235. self.findPaneState = .singular
  236. self.displayFindViewAnimating(false)
  237. } else {
  238. self.findPaneState = .grouped
  239. self.displayGroupedFindViewAnimating(false)
  240. }
  241. }
  242. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  243. self.toolButtonBox.isHidden = false
  244. self.toolButtonBoxLayoutConstraint.constant = 40.0
  245. if (segIndex == 0) {
  246. if self.type.methodType == .Thumbnail {
  247. self.leftView.segmentedControl.selectedSegment = UInt8.max
  248. self.refreshMethodType(methodType: .None)
  249. return
  250. }
  251. self.refreshMethodType(methodType: .Thumbnail)
  252. DispatchQueue.main.async {
  253. self.toolButtonBox.contentView = self.thumbnailView
  254. self.displayThumbnailViewAnimating(false)
  255. }
  256. } else if (segIndex == 1) {
  257. if self.type.methodType == .Outline {
  258. self.leftView.segmentedControl.selectedSegment = UInt8.max
  259. self.refreshMethodType(methodType: .None)
  260. return
  261. }
  262. self.refreshMethodType(methodType: .Outline)
  263. DispatchQueue.main.async {
  264. self.toolButtonBox.contentView = self.outlineView
  265. self.displayTocViewAnimating(false)
  266. }
  267. } else if (segIndex == 2) {
  268. if self.type.methodType == .Annotation {
  269. self.leftView.segmentedControl.selectedSegment = UInt8.max
  270. self.refreshMethodType(methodType: .None)
  271. return
  272. }
  273. self.refreshMethodType(methodType: .Annotation)
  274. DispatchQueue.main.async {
  275. self.toolButtonBox.contentView = self.noteView
  276. self.displayNoteViewAnimating(false)
  277. }
  278. } else if (segIndex == 3) {
  279. if self.type.methodType == .snapshot {
  280. self.leftView.segmentedControl.selectedSegment = UInt8.max
  281. self.refreshMethodType(methodType: .None)
  282. return
  283. }
  284. self.refreshMethodType(methodType: .snapshot)
  285. self.toolButtonBox.contentView = self.snapshotNormalView
  286. self.updateSnapshotFilterPredicate()
  287. self.displaySnapshotViewAnimating(false)
  288. self.updataLeftSideSnapView()
  289. } else if (segIndex == 4) {
  290. if self.type.methodType == .Search {
  291. self.leftView.segmentedControl.selectedSegment = UInt8.max
  292. self.refreshMethodType(methodType: .None)
  293. return
  294. }
  295. self.refreshMethodType(methodType: .Search)
  296. DispatchQueue.main.async {
  297. self.toolButtonBox.isHidden = true
  298. self.toolButtonBoxLayoutConstraint.constant = 0
  299. self.displayFindViewAnimating(false)
  300. }
  301. }
  302. }
  303. // self.button.setHelp(KMLocalizedString("View Thumbnails", "Tool tip message"), for: KMLeftSidePaneState.thumbnail.rawValue)
  304. // self.button.setHelp(KMLocalizedString("View Outline", "Tool tip message"), for: KMLeftSidePaneState.outline.rawValue)
  305. // self.alternateButton.setHelp(KMLocalizedString("Separate search results", "Tool tip message"), for: KMFindPaneState.singular.rawValue)
  306. // self.alternateButton.setHelp(KMLocalizedString("Group search results by page", "Tool tip message"), for: KMFindPaneState.grouped.rawValue)
  307. let menu = NSMenu()
  308. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  309. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  310. (self.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  311. (self.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  312. self.searchField.action = #selector(search)
  313. self.searchField.target = self
  314. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  315. // //支持拖拽的文字类型
  316. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  317. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  318. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  319. if UserDefaults.standard.bool(forKey: SKDisableTableToolTipsKey) == false {
  320. self.tocOutlineView.hasImageToolTips = true
  321. self.findTableView.hasImageToolTips = true
  322. self.groupedFindTableView.hasImageToolTips = true
  323. }
  324. self._updateViewColor()
  325. }
  326. func initSubView() {
  327. self.view.addSubview(self.leftView)
  328. self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  329. self.leftView.autoresizingMask = [.height]
  330. self.thumb_initSubViews()
  331. self.outline_initSubViews()
  332. self.note_initSubViews()
  333. self.snapshot_initSubViews()
  334. self.search_initSubViews()
  335. }
  336. func initDefalutValue() {
  337. self.view.wantsLayer = true
  338. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  339. let sud = UserDefaults.standard
  340. self.isAscendSort = sud.bool(forKey: KMLeftSideViewAscendSortBoolKey)
  341. self.mwcFlags.wholeWordSearch = UserDefaults.standard.integer(forKey: SKWholeWordSearchKey)
  342. self.mwcFlags.caseInsensitiveSearch = UserDefaults.standard.integer(forKey: SKCaseInsensitiveSearchKey)
  343. self.leftView.wantsLayer = true
  344. self.leftView.layer?.backgroundColor = .white
  345. self.leftListView.wantsLayer = true
  346. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  347. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  348. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  349. self.emptySearchBox.isHidden = true
  350. self.thumb_initDefalutValue()
  351. self.outline_initDefalutValue()
  352. self.note_initDefalutValue()
  353. self.snapshot_initDefalutValue()
  354. self.search_initDefalutValue()
  355. }
  356. func displayThumbnailViewAnimating(_ animate: Bool) {
  357. self.replaceSideView(self.thumbnailTableView.enclosingScrollView!, animate: animate)
  358. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  359. frame.origin.y = 0
  360. frame.origin.x = self.leftMargin
  361. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  362. self.thumbnailTableView.enclosingScrollView?.frame = frame
  363. self.resetThumbnails()
  364. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  365. frame.origin.y = 0
  366. frame.origin.x = self.leftMargin
  367. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  368. self.noteOutlineView.enclosingScrollView?.frame = frame
  369. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  370. frame.origin.y = 0
  371. frame.origin.x = self.leftMargin
  372. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  373. self.snapshotTableView.enclosingScrollView?.frame = frame
  374. // [self updateThumbnailSelection];
  375. }
  376. func displayFindViewAnimating(_ animate: Bool) {
  377. self.replaceSideView(self.searchViewController.view, animate: animate)
  378. if (self.findState != .content) {
  379. self.findState = .content
  380. } else {
  381. self.displayFindState()
  382. }
  383. var frame = self.searchViewController.view.frame
  384. frame.origin.y = 0
  385. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  386. self.searchViewController.view.frame = frame
  387. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  388. frame.origin.y = 0
  389. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  390. self.noteOutlineView.enclosingScrollView?.frame = frame
  391. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  392. frame.origin.y = 0
  393. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  394. self.snapshotTableView.enclosingScrollView?.frame = frame
  395. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  396. self.updataLeftSideSnapView()
  397. }
  398. func displayFindState() {
  399. if (self.findState == .content) {
  400. self.displayFind()
  401. } else if (self.findState == .note) {
  402. self.displayNoteFind()
  403. } else if (self.findState == .snapshot) {
  404. self.displaySnapshotFind()
  405. }
  406. }
  407. func updataLeftSideFindView() {
  408. if (self.findState != .content) {
  409. return
  410. }
  411. if (self.searchResults.count > 0) {
  412. self.searchViewController.emptyBox.isHidden = true
  413. self.searchViewController.searchResultsView.isHidden = false
  414. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  415. } else {
  416. self.searchViewController.emptyBox.isHidden = false
  417. self.searchViewController.searchResultsView.isHidden = true
  418. }
  419. }
  420. func displayGroupedFindViewAnimating(_ animate: Bool) {
  421. self.replaceSideView(self.searchViewController.view , animate: animate)
  422. if (self.findState != .content) {
  423. self.findState = .content
  424. } else {
  425. self.displayFindState()
  426. }
  427. var frame = self.searchViewController.view.frame
  428. frame.origin.y = 0
  429. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  430. self.searchViewController.view.frame = frame
  431. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  432. frame.origin.y = 0
  433. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  434. self.noteOutlineView.enclosingScrollView?.frame = frame
  435. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  436. frame.origin.y = 0
  437. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  438. self.snapshotTableView.enclosingScrollView?.frame = frame
  439. self.updataLeftSideSnapView()
  440. }
  441. func displayNoteViewAnimating(_ animate: Bool) {
  442. self.reloadAnnotation()
  443. self.annotationSort(sortArray: [])
  444. self.searchViewController.contentView = nil
  445. self.replaceSideView(self.noteOutlineView.enclosingScrollView!, animate: animate)
  446. if (self.findState != .note) {
  447. self.findState = .note
  448. } else {
  449. self.displayFindState()
  450. }
  451. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  452. frame.origin.y = 0
  453. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  454. self.noteOutlineView.enclosingScrollView?.frame = frame
  455. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  456. frame.origin.y = 0
  457. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  458. self.noteOutlineView.enclosingScrollView?.frame = frame
  459. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  460. frame.origin.y = 0
  461. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  462. self.snapshotTableView.enclosingScrollView?.frame = frame
  463. let view = self.noteOutlineView.enclosingScrollView!
  464. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  465. 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)
  466. DispatchQueue.main.async {
  467. self.noteOutlineView.reloadData()
  468. }
  469. }
  470. func displaySnapshotViewAnimating(_ animate: Bool) {
  471. self.searchViewController.contentView = nil
  472. self.replaceSideView(self.snapshotTableView.enclosingScrollView!, animate: animate)
  473. if (self.findState != .snapshot) {
  474. self.findState = .snapshot
  475. } else {
  476. self.displayFindState()
  477. }
  478. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  479. frame.origin.y = 0
  480. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  481. self.snapshotTableView.enclosingScrollView?.frame = frame
  482. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  483. frame.origin.y = 0
  484. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  485. self.noteOutlineView.enclosingScrollView?.frame = frame
  486. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  487. frame.origin.y = 0
  488. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  489. self.tocOutlineView.enclosingScrollView?.frame = frame
  490. // [self updateSnapshotsIfNeeded];
  491. Task { @MainActor in
  492. self.snapshotTableView.reloadData()
  493. }
  494. }
  495. func displayFind() {
  496. self.searchField = self.searchViewController.searchField
  497. let menu = NSMenu()
  498. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  499. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  500. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  501. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  502. self.searchViewController.searchField.action = #selector(search)
  503. self.searchViewController.searchField.target = self
  504. if (self.findPaneState == .singular) {
  505. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  506. self.findTableView.wantsLayer = true
  507. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  508. DispatchQueue.main.async {
  509. self.findTableView.reloadData()
  510. }
  511. } else if (self.findPaneState == .grouped) {
  512. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  513. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  514. array.sort(){$0.datas.count > $1.datas.count}
  515. self.groupSearchResults = array
  516. self.groupedFindTableView.reloadData()
  517. }
  518. }
  519. func displayTocViewAnimating(_ animate: Bool) {
  520. self.replaceSideView(self.tocOutlineView.enclosingScrollView!, animate: animate)
  521. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  522. frame.origin.y = 0
  523. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  524. self.tocOutlineView.enclosingScrollView?.frame = frame
  525. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  526. frame.origin.y = 0
  527. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  528. self.noteOutlineView.enclosingScrollView?.frame = frame
  529. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  530. frame.origin.y = 0
  531. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  532. self.snapshotTableView.enclosingScrollView?.frame = frame
  533. let view = self.tocOutlineView.enclosingScrollView!
  534. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  535. 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);
  536. DispatchQueue.main.async {
  537. self.tocOutlineView.reloadData()
  538. self.updateOutlineSelection()
  539. }
  540. }
  541. override func requiresAlternateButton(forView aview: NSView?) -> Bool {
  542. return false
  543. }
  544. func displayNoteFind() {
  545. self.searchField = self.noteSearchField
  546. let menu = NSMenu()
  547. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  548. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  549. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  550. self.noteSearchField.action = #selector(searchNotes)
  551. self.noteSearchField.target = self
  552. }
  553. func displaySnapshotFind() {
  554. self.searchField = self.snapshotSearchField;
  555. let menu = NSMenu()
  556. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  557. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  558. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  559. self.snapshotSearchField.action = #selector(searchNotes)
  560. self.snapshotSearchField.target = self
  561. self.snapshotSearchField.delegate = self
  562. }
  563. func resetThumbnails() {
  564. // [self willChangeValueForKey:THUMBNAILS_KEY];
  565. // self.thumbnailCacheSize = 160
  566. self.thumbnails.removeAll()
  567. let pageLabels = self.listView.document.pageLabels()
  568. if (pageLabels.isEmpty == false) {
  569. let isLocked = self.listView.document.isLocked
  570. let firstPage = self.listView.document.page(at: 0)
  571. let emptyPage = CPDFPage()
  572. let firstFrame = firstPage?.bounds(for: .cropBox) ?? .zero
  573. let firstFrame2 = firstPage?.bounds(for: .mediaBox) ?? .zero
  574. emptyPage.setBounds(firstFrame, for: .cropBox)
  575. emptyPage.setBounds(firstFrame2, for: .mediaBox)
  576. emptyPage.rotation = firstPage?.rotation ?? 0
  577. let pageImage = firstPage!.thumbnail(of: NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize))
  578. // NSImage * = [emptyPage thumbnailWithSize:thumbnailCacheSize forBox:[pdfView displayBox]];
  579. var rect: NSRect = .zero
  580. rect.size = pageImage?.size ?? .zero
  581. let width = 1.2 * fmin(NSWidth(rect), NSHeight(rect))
  582. rect = NSInsetRect(rect, 0.5 * (NSWidth(rect) - width), 0.5 * (NSHeight(rect) - width));
  583. pageImage?.lockFocus()
  584. // NSImage(named: NSImage.applicationIconName)?.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  585. if (isLocked) {
  586. NSWorkspace.shared.icon(forFileType: NSFileTypeForHFSTypeCode(OSType(kLockedBadgeIcon))).draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  587. // [[[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kLockedBadgeIcon)] drawInRect:rect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:0.5];
  588. }
  589. pageImage?.unlockFocus()
  590. for (i, label) in pageLabels.enumerated() {
  591. let firstPage = self.listView.document.page(at: UInt(i))
  592. let size = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  593. // let pageImage = firstPage!.thumbnail(of: size)
  594. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  595. // thumbnail.delegate = self
  596. thumbnail.dirty = true
  597. self.thumbnails.append(thumbnail)
  598. }
  599. }
  600. // [self didChangeValueForKey:THUMBNAILS_KEY];
  601. // [self allThumbnailsNeedUpdate];
  602. DispatchQueue.main.async {
  603. self.thumbnailTableView.reloadData()
  604. }
  605. }
  606. @IBAction @objc func sortTypeAction(_ sender: NSMenuItem) {
  607. let item = sender
  608. let tag = item.tag
  609. if (item.state == .on) {
  610. item.state = .off
  611. } else {
  612. item.state = .on
  613. }
  614. if (tag == 0) {
  615. self.noteSortType = .page
  616. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  617. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  618. } else if (tag == 1) {
  619. self.noteSortType = .time
  620. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  621. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  622. }
  623. UserDefaults.standard.set(self.noteSortType.rawValue, forKey: KMLeftSideViewNoteSortTypeKey)
  624. UserDefaults.standard.synchronize()
  625. self.annotationSort(sortArray: [])
  626. }
  627. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  628. let button = sender as? NSButton
  629. let tag = button?.tag ?? 0
  630. if (tag == 310) {
  631. self.outlineSearchField.isHidden = true
  632. self.outlineDoneButton.isHidden = true
  633. self.outlineLabel.isHidden = false
  634. self.outlineSearchButton.isHidden = false
  635. self.outlineMoreButton.isHidden = false
  636. self.outlineAddButton.isHidden = false
  637. } else if (tag == 311) {
  638. self.noteSearchField.isHidden = true
  639. self.noteTitleLabel.isHidden = false
  640. self.noteSearchButton.isHidden = false
  641. self.noteDoneButton.isHidden = true
  642. self.noteFilterButton.isHidden = false
  643. self.noteMoreButton.isHidden = false
  644. } else if (tag == 312) {
  645. self.snapshotSearchField.isHidden = true
  646. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  647. self.snapshotNormalSearchButton.isHidden = false
  648. self.snapshotDoneButton.isHidden = true
  649. self.snapshotLabel.isHidden = false
  650. self.snapshotNormalZoomOutButton.isHidden = false
  651. self.snapshotNormalZoomInButton.isHidden = false
  652. }
  653. }
  654. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  655. let sud = UserDefaults.standard
  656. let tag = sender.tag
  657. if (tag == 0 || tag == 1) {
  658. var scaling = sud.float(forKey: "KMThumbnailSizeScalingKey")
  659. if (scaling <= 0) {
  660. scaling = 1
  661. }
  662. if (tag == 0) { // thumbnail Zoom In
  663. scaling += 0.1
  664. if scaling >= 2.2 {
  665. return
  666. }
  667. } else if (tag == 1) { // thumbnail Zoom Out
  668. scaling -= 0.1
  669. if scaling <= 0.4 {
  670. return
  671. }
  672. }
  673. sud.setValue(scaling, forKey: "KMThumbnailSizeScalingKey")
  674. let selectRow = self.thumbnailTableView.selectedRow
  675. self.thumbnailTableView.reloadData()
  676. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  677. } else if (tag == 2 || tag == 3) {
  678. var scaling = sud.float(forKey: "KMSnapshotSizeScalingKey")
  679. if (scaling <= 0) {
  680. scaling = 1
  681. }
  682. if (tag == 2) { // snapshot Zoom In
  683. scaling += 0.1
  684. } else if (tag == 3) { // snapshot Zoom Out
  685. scaling -= 0.1
  686. }
  687. sud.setValue(scaling, forKey: "KMSnapshotSizeScalingKey")
  688. let selectRow = self.snapshotTableView.selectedRow
  689. self.snapshotTableView.reloadData()
  690. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  691. }
  692. }
  693. func tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  694. if tv.isEqual(to: self.thumbnailTableView) {
  695. self._copysPages.removeAll()
  696. for idx in rowIndexes {
  697. if (idx != NSNotFound) {
  698. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  699. self._copysPages.append(page)
  700. }
  701. }
  702. }
  703. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  704. }
  705. }
  706. }
  707. // MARK: - KMBotaTableViewDelegate
  708. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  709. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  710. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  711. return rowIndexes.count > 0
  712. }
  713. return false
  714. }
  715. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  716. if aTableView.isEqual(to: self.thumbnailTableView) {
  717. if self._copysPages.count > 0 {
  718. return true
  719. }
  720. }
  721. return false
  722. }
  723. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  724. if aTableView.isEqual(to: self.snapshotTableView) {
  725. return rowIndexes.count > 0
  726. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  727. if self.listView.document.pageCount <= 1 {
  728. return false
  729. }
  730. return true
  731. }
  732. return false
  733. }
  734. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  735. if IAPProductsManager.default().isAvailableAllFunction() == false {
  736. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  737. return
  738. }
  739. if aTableView.isEqual(to: self.thumbnailTableView) {
  740. if self._copysPages.count > 0 {
  741. let index = self.listView.document.index(for: self.listView.currentPage()) + 1
  742. if (index == NSNotFound) {
  743. return
  744. }
  745. for page in self._copysPages.reversed() {
  746. // if let newPage = page.copy() as? CPDFPage {
  747. self.listView.document.insertPageObject(page, at: index)
  748. // }
  749. self.listView.layoutDocumentView()
  750. // [pageLabels setArray:[[pdfView document] pageLabels]];
  751. self.resetThumbnails()
  752. let pageIndex = min(index, self.listView.document.pageCount-1)
  753. self.listView.go(toPageIndex: Int(pageIndex), animated: true)
  754. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  755. }
  756. }
  757. }
  758. }
  759. func tableViewMoveLeft(_ aTableView: NSTableView) {
  760. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  761. // [self updateFindResultHighlightsForDirection:NSSelectingPrevious];
  762. }
  763. }
  764. func tableViewMoveRight(_ aTableView: NSTableView) {
  765. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  766. // [self updateFindResultHighlightsForDirection:NSSelectingNext];
  767. }
  768. }
  769. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  770. if aTableView.isEqual(to: self.findTableView) {
  771. if rowIndex >= self.searchResults.count {
  772. return nil
  773. }
  774. let model = self.searchResults[rowIndex]
  775. let selection = model.selection
  776. let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  777. return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  778. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  779. if rowIndex >= self.groupSearchResults.count {
  780. return nil
  781. }
  782. // let model = self.groupSearchResults[rowIndex]
  783. // let selection = model.selection
  784. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  785. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  786. }
  787. return nil
  788. }
  789. /*
  790. - (NSArray *)tableView:(NSTableView *)tv typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  791. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  792. return pageLabels;
  793. }
  794. return nil;
  795. }
  796. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  797. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  798. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  799. }
  800. }
  801. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  802. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  803. if (searchString.length > 0)
  804. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  805. else
  806. [self updateLeftStatus];
  807. }
  808. }
  809. */
  810. }
  811. // MARK: - 扩展
  812. extension KMLeftSideViewController {
  813. public func selectType(_ type: BotaType) {
  814. // 更新 type
  815. var show = true
  816. if (self.type.methodType == .None) {
  817. show = true
  818. } else {
  819. if (self.type.methodType == type) {
  820. show = false
  821. } else {
  822. show = true
  823. }
  824. }
  825. var index: Int = NSNotFound
  826. switch type {
  827. case .None:
  828. index = NSNotFound
  829. break
  830. case .Thumbnail:
  831. index = 0
  832. break
  833. case .Outline:
  834. index = 1
  835. break
  836. case .BookMark:
  837. index = 2
  838. break
  839. case .Annotation:
  840. index = 3
  841. break
  842. case .Search:
  843. index = 4
  844. break
  845. case .From:
  846. index = 5
  847. break
  848. case .Signature:
  849. index = 6
  850. break
  851. case .snapshot:
  852. index = 7
  853. break
  854. }
  855. self.type = self.getMethodMode(show ? type : .None)
  856. // 更新按钮状态
  857. // self.updateViewButtonState()
  858. // 将事件传递出去
  859. self.delegate?.controlStateChange?(self,show:show)
  860. if (index != NSNotFound) {
  861. // 记录当前选中
  862. UserDefaults.standard.set(index, forKey: "KMBOTASelectedIndexKey")
  863. UserDefaults.standard.synchronize()
  864. }
  865. }
  866. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  867. let mode = KMLeftMethodMode()
  868. mode.methodType = type
  869. switch type {
  870. case .None:
  871. mode.methodName = ""
  872. break
  873. case .Thumbnail:
  874. mode.methodName = thumbnailMethodKey
  875. break
  876. case .Outline:
  877. mode.methodName = outlineMethodKey
  878. break
  879. case .BookMark:
  880. mode.methodName = bookMarkMethodKey
  881. break
  882. case .Annotation:
  883. mode.methodName = anntationMethodKey
  884. break
  885. case .Search:
  886. mode.methodName = searchMethodKey
  887. break
  888. case .From:
  889. mode.methodName = formMethodKey
  890. break
  891. case .Signature:
  892. mode.methodName = signatureMethodKey
  893. break
  894. case .snapshot:
  895. mode.methodName = snapshotMethodKey
  896. }
  897. return mode
  898. }
  899. }
  900. //MARK: Cache
  901. extension KMLeftSideViewController {
  902. func clearAnnotationFilterData() {
  903. if let _key = self.listView?.document?.documentURL?.path {
  904. let userDefaults = UserDefaults.standard
  905. let typeData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  906. userDefaults.set(typeData, forKey: "KMNoteOutlineFilterSelectArray_Type" + _key)
  907. let colorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  908. userDefaults.set(colorData, forKey: "KMNoteOutlineFilterSelectArray_Color" + _key)
  909. let authorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  910. userDefaults.set(authorData, forKey: "KMNoteOutlineFilterSelectArray_Author" + _key)
  911. userDefaults.synchronize()
  912. }
  913. }
  914. func clearNotification() {
  915. }
  916. }
  917. // MARK: - Analytics (埋点)
  918. extension KMLeftSideViewController {
  919. func trackEvent(type: BotaType) -> Void {
  920. if (type == .Thumbnail) {
  921. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Thumbnail", parameters: [
  922. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  923. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  924. } else if (type == .Outline) {
  925. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Outline", parameters: [
  926. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  927. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  928. } else if (type == .BookMark) {
  929. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_BookMark", parameters: [
  930. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  931. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  932. } else if (type == .Annotation) {
  933. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Annotation", parameters: [
  934. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  935. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  936. } else if (type == .Search) {
  937. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Search", parameters: [
  938. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  939. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  940. }
  941. }
  942. }
  943. // MARK: - Private Methods
  944. extension KMLeftSideViewController {
  945. func updateViewColor() {
  946. self._updateViewColor()
  947. }
  948. private func _updateViewColor() {
  949. if(KMAppearance.isDarkMode()){
  950. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  951. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  952. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  953. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  954. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  955. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  956. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  957. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  958. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  959. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  960. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  961. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  962. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  963. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  964. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  965. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  966. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  967. } else {
  968. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  969. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  970. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  971. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  972. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  973. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  974. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  975. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  976. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  977. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  978. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  979. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  980. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  981. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  982. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  983. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  984. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  985. }
  986. }
  987. private func _hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  988. var label = outline.label ?? ""
  989. var searchLabel = searchString
  990. if self.outlineIgnoreCaseFlag {
  991. label = label.lowercased()
  992. searchLabel = searchLabel.lowercased()
  993. }
  994. if label.contains(searchLabel) {
  995. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  996. return true
  997. } else {
  998. var subHas = false
  999. for i in 0 ..< outline.numberOfChildren {
  1000. if let subOutline = outline.child(at: i) {
  1001. subHas = self._hasContainString(searchString, rootOutline: subOutline)
  1002. } else {
  1003. continue
  1004. }
  1005. if (subHas) {
  1006. break
  1007. }
  1008. }
  1009. return subHas
  1010. }
  1011. return false
  1012. }
  1013. }
  1014. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  1015. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  1016. func numberOfRows(in tableView: NSTableView) -> Int {
  1017. if tableView.isEqual(to: self.thumbnailTableView) {
  1018. return self.thumbnails.count
  1019. } else if tableView.isEqual(to: self.findTableView) {
  1020. return self.searchResults.count
  1021. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1022. return self.groupSearchResults.count
  1023. } else if tableView.isEqual(to: self.snapshotTableView) {
  1024. if self.isSearchSnapshotMode {
  1025. return self.searchSnapshots.count
  1026. }
  1027. return self.snapshots.count
  1028. }
  1029. return 0
  1030. }
  1031. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  1032. if tableView.isEqual(to: self.thumbnailTableView) {
  1033. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMThumbnailTableviewCell"), owner: self) as! KMThumbnailTableviewCell
  1034. let thumbnail = self.thumbnails[row]
  1035. cell.pageNumLabel.stringValue = thumbnail.label
  1036. // cell.thumImage.image = thumbnail.image
  1037. cell.pageView.page = self.listView.document.page(at: UInt(row))
  1038. if let _image = thumbnail.image {
  1039. let multiplierHToW = _image.size.height / (_image.size.width == 0 ? 1 : _image.size.width)
  1040. let multiplierWToH = _image.size.width / (_image.size.height == 0 ? 1 : _image.size.height)
  1041. if (_image.size.height > _image.size.width) {
  1042. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  1043. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .height, relatedBy: .equal, toItem: cell.thumImage, attribute: .width, multiplier: multiplierHToW, constant: 0)
  1044. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  1045. } else {
  1046. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  1047. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .width, relatedBy: .equal, toItem: cell.thumImage, attribute: .height, multiplier: multiplierWToH, constant: 0)
  1048. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  1049. }
  1050. }
  1051. if (self.isDisplayPageSize) {
  1052. cell.sizeLabel.isHidden = false
  1053. //获取Page的真实尺寸
  1054. let page = self.listView.document.page(at: UInt(row))
  1055. let rect = page?.bounds(for: .cropBox) ?? .zero
  1056. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetWidth(rect)/595 * 210))
  1057. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetHeight(rect)/842 * 297))
  1058. if let data = page?.rotation, data == 90 || data == 270 {
  1059. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  1060. } else {
  1061. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  1062. }
  1063. } else {
  1064. cell.sizeLabel.isHidden = true
  1065. }
  1066. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  1067. if(self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  1068. cell.isSelectCell = true
  1069. } else {
  1070. cell.isSelectCell = false
  1071. }
  1072. return cell
  1073. } else if (tableView.isEqual(to: self.findTableView)) {
  1074. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMFindTableviewCell"), owner: self) as! KMFindTableviewCell
  1075. let selection = searchResults[row]
  1076. if let data = tableColumn?.identifier.rawValue, data == kResultsColumnId.rawValue {
  1077. cell.resultLabel.attributedStringValue = selection.attributedString
  1078. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  1079. } else if let data = tableColumn?.identifier.rawValue, data == kPageColumnId.rawValue {
  1080. cell.resultLabel.stringValue = "\(Int(selection.selection.page?.pageIndex() ?? 0) + 1)"
  1081. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  1082. }
  1083. return cell
  1084. } else if tableView.isEqual(to: self.snapshotTableView) {
  1085. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMSnapshotTableViewCell"), owner: self) as! KMSnapshotTableViewCell
  1086. var snapshot: KMSnapshotModel?
  1087. if self.isSearchSnapshotMode {
  1088. snapshot = self.searchSnapshots[row]
  1089. } else {
  1090. snapshot = self.snapshots[row]
  1091. }
  1092. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  1093. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  1094. if let data = snapshot?.windowC?.hasWindow, data {
  1095. cell.snapshotImageView.isHidden = false
  1096. } else {
  1097. cell.snapshotImageView.isHidden = true
  1098. }
  1099. cell.isSelectCell = snapshot?.isSelected ?? false
  1100. if (row == tableView.selectedRow) {
  1101. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  1102. } else {
  1103. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  1104. }
  1105. return cell
  1106. }
  1107. return nil
  1108. }
  1109. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  1110. if tableView.isEqual(to: self.thumbnailTableView) {
  1111. let scaling = UserDefaults.standard.float(forKey: "KMThumbnailSizeScalingKey")
  1112. // let thumbnailSize = self.thumbnails[row].size
  1113. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  1114. let newScaling: CGFloat = scaling.cgFloat + 0.1
  1115. let newThumbnailHeight = thumbnailSize.width * newScaling
  1116. if (newThumbnailHeight > MIN_SIDE_PANE_WIDTH) {
  1117. self.thumbnailZoomOutButton.isEnabled = false
  1118. } else {
  1119. self.thumbnailZoomOutButton.isEnabled = true
  1120. }
  1121. if ((scaling - 0.1) < 0.3) {
  1122. self.thumbnailZoomInButton.isEnabled = false
  1123. } else {
  1124. self.thumbnailZoomInButton.isEnabled = true
  1125. }
  1126. var labelHeight = 0.0
  1127. if (self.isDisplayPageSize) {
  1128. labelHeight = 56.0
  1129. } else {
  1130. labelHeight = 41.5
  1131. }
  1132. let cellHeight = thumbnailSize.height + labelHeight
  1133. var thumbSize: NSSize = .zero
  1134. if (scaling != nil && scaling > 0) {
  1135. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1136. } else {
  1137. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  1138. }
  1139. return thumbSize.height
  1140. // NSSize cellSize = NSMakeSize([[tv tableColumnWithIdentifier:IMAGE_COLUMNID] width], fmin(thumbSize.height, roundedThumbnailSize));
  1141. // if (thumbSize.height < [tv rowHeight])
  1142. // return [tv rowHeight];
  1143. // else if (thumbSize.width / thumbSize.height < cellSize.width / cellSize.height)
  1144. // return cellSize.height;
  1145. // else
  1146. // return fmax([tv rowHeight], fmin(cellSize.width, thumbSize.width) * thumbSize.height / thumbSize.width);
  1147. } else if tableView.isEqual(to: self.snapshotTableView) {
  1148. let scaling = UserDefaults.standard.float(forKey: "KMSnapshotSizeScalingKey")
  1149. let snapshotSize = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC?.thumbnail?.size ?? CGSizeMake(120, 63)
  1150. var newScaling = scaling + 0.1
  1151. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat;
  1152. if (newSnapshotHeight > MIN_SIDE_PANE_WIDTH) {
  1153. self.snapshotNormalZoomInButton.isEnabled = false
  1154. } else {
  1155. self.snapshotNormalZoomInButton.isEnabled = true
  1156. }
  1157. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  1158. self.snapshotNormalZoomOutButton.isEnabled = false
  1159. } else {
  1160. self.snapshotNormalZoomOutButton.isEnabled = true
  1161. }
  1162. let cellHeight = snapshotSize.height + 24.0
  1163. var thumbSize: NSSize = .zero
  1164. if (scaling > 0) {
  1165. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1166. } else {
  1167. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  1168. }
  1169. return thumbSize.height
  1170. } else if (tableView.isEqual(to: self.findTableView)) {
  1171. return 40.0
  1172. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1173. return 16
  1174. }
  1175. return tableView.rowHeight
  1176. }
  1177. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  1178. if (tableView.isEqual(to: self.findTableView)) {
  1179. let rowView = KMBotaTableRowView()
  1180. return rowView
  1181. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1182. let rowView = KMGroupFindTableRowView()
  1183. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  1184. let model = self.groupSearchResults[row]
  1185. rowView.number = model.datas.count
  1186. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  1187. return rowView
  1188. }
  1189. return nil
  1190. }
  1191. func tableViewSelectionIsChanging(_ notification: Notification) {
  1192. }
  1193. func tableViewSelectionDidChange(_ notification: Notification) {
  1194. if self.findTableView.isEqual(to: notification.object) {
  1195. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1196. //
  1197. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  1198. // [self hideLeftSideWindow];
  1199. let row = self.findTableView.selectedRow
  1200. if row >= 0 {
  1201. let model = self.searchResults[row]
  1202. if model.selection != nil {
  1203. self.listView.go(to: model.selection, animated: true)
  1204. self.listView.setHighlightedSelection(model.selection, animated: true)
  1205. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  1206. }
  1207. }
  1208. } else if self.groupedFindTableView.isEqual(to: notification.object) {
  1209. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1210. //
  1211. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  1212. // [self hideLeftSideWindow];
  1213. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  1214. // if (mwcFlags.updatingThumbnailSelection == 0) {
  1215. let row = self.thumbnailTableView.selectedRow
  1216. let curPage = self.listView.document.index(for: self.listView.currentPage())
  1217. if (row != -1 && row != curPage) {
  1218. // [pdfView goToPage:[[pdfView document] pageAtIndex:row]];
  1219. self.listView.go(toPageIndex: row, animated: true)
  1220. }
  1221. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  1222. // [self hideLeftSideWindow];
  1223. // thumbnailSelectCount = row;
  1224. // var rowIndexSet = IndexSet()
  1225. // for i in 0 ..< self.thumbnailTableView.numberOfRows {
  1226. // rowIndexSet.insert(i)
  1227. // }
  1228. // self.thumbnailTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: IndexSet(integer: 0))
  1229. // }
  1230. let view = self.thumbnailTableView.view(atColumn: 0, row: self.preThumbnailRow, makeIfNecessary: false) as? KMThumbnailTableviewCell
  1231. view?.isSelectCell = false
  1232. let view2 = self.thumbnailTableView.view(atColumn: 0, row: row, makeIfNecessary: false) as? KMThumbnailTableviewCell
  1233. view2?.isSelectCell = true
  1234. self.preThumbnailRow = row
  1235. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1236. let row = self.snapshotTableView.selectedRow
  1237. // 更新选中数据
  1238. for (i, model) in self.snapshots.enumerated() {
  1239. model.isSelected = i == row
  1240. }
  1241. if (row != -1) {
  1242. let controller = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC
  1243. if let data = controller?.window?.isVisible, data {
  1244. controller?.window?.orderFront(self)
  1245. }
  1246. }
  1247. // self.snapshotTableView.reloadData()
  1248. self.snapshotTableView.ks_reloadData()
  1249. }
  1250. }
  1251. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  1252. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  1253. return NSDragOperation(rawValue: 0)
  1254. }
  1255. let pboard = info.draggingPasteboard
  1256. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  1257. return .move
  1258. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  1259. guard let pbItems = pboard.pasteboardItems else {
  1260. return NSDragOperation(rawValue: 0)
  1261. }
  1262. var hasValidFile = false
  1263. for item in pbItems {
  1264. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  1265. continue
  1266. }
  1267. let type = _url.pathExtension.lowercased()
  1268. if type == "pdf" || KMImageToPDFMethod.supportedImageTypes().contains(type) {
  1269. hasValidFile = true
  1270. }
  1271. }
  1272. if (!hasValidFile) {
  1273. return NSDragOperation(rawValue: 0)
  1274. } else {
  1275. return .move
  1276. }
  1277. }
  1278. return NSDragOperation(rawValue: 0)
  1279. }
  1280. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1281. var result = false
  1282. if tableView.isEqual(to: self.thumbnailTableView) == false {
  1283. return result
  1284. }
  1285. let pasteboard = info.draggingPasteboard
  1286. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  1287. result = true
  1288. let rowData = pasteboard.data(forType: .localDraggedTypes)
  1289. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData!) as? IndexSet ?? IndexSet()
  1290. let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1291. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData!) as? String
  1292. if url != nil && url != self.listView.document.documentURL.absoluteString {
  1293. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  1294. // if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]){
  1295. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  1296. var fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  1297. if (fileNames.count == 1) {
  1298. let path = fileNames.first ?? ""
  1299. let pathExtension = path.pathExtension.lowercased()
  1300. if pathExtension == "pdf" {
  1301. var index = row
  1302. var insertIndexSet = IndexSet()
  1303. var pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  1304. if let data = pdf?.isEncrypted, data {
  1305. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: path)) { success, resultPassword in
  1306. if success && resultPassword.isEmpty == false {
  1307. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1308. let page = pdf?.page(at: i).copy() as? CPDFPage
  1309. self.listView.document.insertPageObject(page!, at: UInt(index))
  1310. insertIndexSet.insert(index)
  1311. index += 1
  1312. }
  1313. self.insertPages(insertIndexSet, pageAt: index-1)
  1314. }
  1315. }
  1316. } else {
  1317. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1318. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  1319. var page = pdf?.page(at: i)
  1320. self.listView.document.insertPageObject(page, at: UInt(index))
  1321. insertIndexSet.insert(index)
  1322. index += 1
  1323. }
  1324. self.insertPages(insertIndexSet, pageAt: index-1)
  1325. }
  1326. }
  1327. return true
  1328. }
  1329. }
  1330. }
  1331. var pageIndex = 0
  1332. var pages: [CPDFPage] = []
  1333. for idx in rowIndexes {
  1334. let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage
  1335. pages.append(page!)
  1336. }
  1337. var toPage: CPDFPage?
  1338. if row < self.listView.document.pageCount {
  1339. toPage = self.listView.document.page(at: UInt(row))
  1340. }
  1341. var toPageIndex = 0
  1342. if (toPage != nil) {
  1343. toPageIndex = Int(self.listView.document.index(for: toPage))
  1344. } else {
  1345. toPageIndex = Int(self.listView.document.pageCount)
  1346. }
  1347. for i in 0 ..< pages.count {
  1348. var page = pages[i]
  1349. self.listView.document.insertPageObject(page, at: UInt(toPageIndex+i))
  1350. pageIndex += 1
  1351. self.listView.go(toPageIndex: toPageIndex+i, animated: false)
  1352. }
  1353. self.listView.layoutDocumentView()
  1354. var deletepages: [CPDFPage] = []
  1355. for idx in rowIndexes {
  1356. if idx < toPageIndex {
  1357. if((idx+pageIndex) < self.listView.document.pageCount) {
  1358. var page = self.listView.document.page(at: UInt(idx))
  1359. deletepages.append(page!)
  1360. self.listView.document.removePage(at: IndexSet(integer: idx))
  1361. }
  1362. } else {
  1363. if((idx+pageIndex) < self.listView.document.pageCount) {
  1364. let page = self.listView.document.page(at: UInt(idx+pageIndex))
  1365. deletepages.append(page!)
  1366. self.listView.document.removePage(at: IndexSet(integer: idx+pageIndex))
  1367. }
  1368. }
  1369. }
  1370. // [[[[self document] undoManager] prepareWithInvocationTarget:self] undoClick];
  1371. // [self.pageLabels setArray:[[self.pdfView document] pageLabels]];
  1372. self.listView.layoutDocumentView()
  1373. self.resetThumbnails()
  1374. } else if pasteboard.availableType(from: [.fileURL]) != nil && tableView.isEqual(to: self.thumbnailTableView) {
  1375. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1376. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1377. return false
  1378. }
  1379. var fileNames = pasteboard.propertyList(forType: .fileURL)
  1380. var insertIndexSet = IndexSet()
  1381. var index = row
  1382. // if (fileNames.count == 1) {
  1383. if fileNames != nil {
  1384. // var path = fileNames.first as? String ?? ""
  1385. var path = fileNames as? String ?? ""
  1386. let url = URL(string: path)
  1387. let pathExtension = url?.pathExtension.lowercased() ?? ""
  1388. if pathExtension == "pdf" {
  1389. let pdf = CPDFDocument(url: url!)
  1390. if let data = pdf?.isEncrypted, data {
  1391. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  1392. KMBaseWindowController.checkPassword(url: url!) { success, resultPassword in
  1393. if success && resultPassword.isEmpty == false {
  1394. pdf?.unlock(withPassword: resultPassword)
  1395. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1396. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1397. let page = pdf?.page(at: i)
  1398. self.listView.document.insertPageObject(page!, at: UInt(index))
  1399. insertIndexSet.insert(index)
  1400. index += 1
  1401. }
  1402. self.insertPages(insertIndexSet, pageAt: index-1)
  1403. }
  1404. }
  1405. } else {
  1406. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1407. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1408. let page = pdf?.page(at: i)
  1409. self.listView.document.insertPageObject(page!, at: UInt(index))
  1410. insertIndexSet.insert(index)
  1411. index += 1
  1412. }
  1413. self.insertPages(insertIndexSet, pageAt: index-1)
  1414. }
  1415. } else if KMImageToPDFMethod.supportedImageTypes().contains(pathExtension) {
  1416. let image = NSImage(contentsOfFile: url?.path ?? "")
  1417. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  1418. // [pdfView.document insertPage:page atIndex:index];
  1419. _ = self.listView.document.km_insert(image: image!, at: UInt(index))
  1420. insertIndexSet.insert(index)
  1421. self.insertPages(insertIndexSet, pageAt: index-1)
  1422. }
  1423. result = true
  1424. } else {
  1425. result = false
  1426. }
  1427. }
  1428. return result == false
  1429. }
  1430. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  1431. if tableView.isEqual(to: self.thumbnailTableView) {
  1432. let idx = rowIndexes.first ?? NSNotFound
  1433. if (idx != NSNotFound && self.listView.document.isLocked == false) {
  1434. let page = self.listView.document.page(at: UInt(idx))
  1435. var fileExt: String?
  1436. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.listView.displayBox) ?? .zero)
  1437. if self.listView.document.allowsPrinting {
  1438. // NSData *pdfData = [page dataRepresentation];
  1439. fileExt = "pdf"
  1440. // filenames
  1441. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  1442. // let newDoc = CPDFDocument()
  1443. // newDoc?.insertPageObject(page, at: 0)
  1444. // let data = newDoc?.dataRepresentation()
  1445. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  1446. pboard.setData(tiffData, forType: .pdf)
  1447. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  1448. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  1449. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1450. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.listView.document.documentURL?.absoluteString)
  1451. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  1452. var docmentName = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  1453. // __block NSMutableString *pagesName = nil;
  1454. var pagesName = ""
  1455. if (rowIndexes.count > 1) {
  1456. pagesName = " pages"
  1457. } else {
  1458. pagesName = " page"
  1459. }
  1460. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  1461. let pdf = CPDFDocument()
  1462. for idx in rowIndexes {
  1463. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1464. var copyPage = self.listView.document.page(at: UInt(idx))
  1465. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1466. }
  1467. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  1468. var cachesDir = paths.first ?? ""
  1469. docmentName = String(format: "%@%@", docmentName, tFileName)
  1470. if (docmentName.count > 50) {
  1471. docmentName = docmentName.substring(to: 50)
  1472. }
  1473. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  1474. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  1475. let success = pdf?.write(toFile: cachesDir) ?? false
  1476. if (success) {
  1477. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  1478. pboard.setPropertyList([cachesDir], forType: .fileURL)
  1479. } else{
  1480. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  1481. pboard.setPropertyList([], forType: .fileURL)
  1482. }
  1483. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1484. } else {
  1485. fileExt = "tiff"
  1486. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1487. }
  1488. pboard.setData(tiffData, forType: .tiff)
  1489. pboard.setPropertyList([fileExt], forType: .filePromise)
  1490. return true
  1491. }
  1492. } else if self.snapshotTableView.isEqual(to: tableView) {
  1493. let idx = rowIndexes.first ?? NSNotFound
  1494. if (idx != NSNotFound) {
  1495. let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC
  1496. if let data = snapshot?.thumbnailWithSize(0)?.tiffRepresentation {
  1497. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1498. pboard.setData(data, forType: .tiff)
  1499. pboard.setPropertyList(["tiff"], forType: .filePromise)
  1500. return true
  1501. }
  1502. }
  1503. }
  1504. return false
  1505. }
  1506. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  1507. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1508. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1509. return
  1510. }
  1511. if aTableView.isEqual(to: self.snapshotTableView) {
  1512. var controllers: [KMSnapshotWindowController] = []
  1513. for i in rowIndexes {
  1514. let model: KMSnapshotModel? = self.snapshots.safe_element(for: i) as? KMSnapshotModel
  1515. if let winC = model?.windowC {
  1516. controllers.append(winC)
  1517. }
  1518. }
  1519. for c in controllers {
  1520. c.close()
  1521. }
  1522. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  1523. for idx in rowIndexes {
  1524. if idx >= self.listView.document.pageCount {
  1525. return
  1526. }
  1527. if let page = self.listView.document.page(at: UInt(idx)) {
  1528. for anno in page.annotations {
  1529. page.removeAnnotation(anno)
  1530. }
  1531. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  1532. self.listView.document.removePage(at: IndexSet(integer: idx))
  1533. }
  1534. }
  1535. self.listView.layoutDocumentView()
  1536. // [pageLabels setArray:[[pdfView document] pageLabels]];
  1537. self.resetThumbnails()
  1538. let idx = rowIndexes.first ?? -1
  1539. let index = min(idx, Int(self.listView.document.pageCount)-1)
  1540. self.listView.go(toPageIndex: index, animated: false)
  1541. }
  1542. }
  1543. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  1544. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1545. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1546. return
  1547. }
  1548. if aTableView.isEqual(to: self.thumbnailTableView) {
  1549. self._copysPages.removeAll()
  1550. if self.listView.document.isLocked == false {
  1551. for idx in rowIndexes {
  1552. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  1553. self._copysPages.append(page)
  1554. }
  1555. }
  1556. }
  1557. } else if aTableView.isEqual(to: self.findTableView) {
  1558. var string = ""
  1559. for idx in rowIndexes {
  1560. let match = self.searchResults[idx].selection
  1561. string.append("* ")
  1562. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  1563. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  1564. // [string appendFormat:@"", [[match contextString] string]];
  1565. string = string.appendingFormat(": %@\n", match.string() ?? "")
  1566. }
  1567. let pboard = NSPasteboard.general
  1568. pboard.clearContents()
  1569. pboard.writeObjects([string as NSPasteboardWriting])
  1570. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1571. var string = ""
  1572. for idx in rowIndexes {
  1573. let result = self.groupSearchResults[idx]
  1574. let matches = result.datas
  1575. string.append("* ")
  1576. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(result.selectionPageIndex)")
  1577. string.append(": ")
  1578. string = string.appendingFormat(KMLocalizedString("%ld Results", ""), matches.count)
  1579. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  1580. var tmpString = ""
  1581. for model in matches {
  1582. tmpString.append("\(model.selection.string() ?? "")")
  1583. }
  1584. string = string.appendingFormat(":\n\t%@\n", tmpString)
  1585. }
  1586. let pboard = NSPasteboard.general
  1587. pboard.clearContents()
  1588. pboard.writeObjects([string as NSPasteboardWriting])
  1589. }
  1590. }
  1591. func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
  1592. if self.thumbnailTableView.isEqual(to: tableView) {
  1593. var fileURLArray: [String] = []
  1594. if indexSet.count > 1 {
  1595. var docmentName = ""
  1596. var tFileName = String(format: "%@", self.fileNameWithSelectedPages(indexSet))
  1597. var pdf = CPDFDocument()
  1598. for idx in indexSet {
  1599. if idx != NSNotFound && self.listView.document.isLocked == false {
  1600. let copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1601. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1602. }
  1603. }
  1604. var fileURL = dropDestination.appendingPathComponent(tFileName).appendingPathExtension("pdf").uniqueFileURL()
  1605. docmentName = fileURL.path
  1606. let success = pdf?.write(toFile: docmentName) ?? false
  1607. if(success) {
  1608. fileURLArray.append(fileURL.lastPathComponent)
  1609. }
  1610. } else {
  1611. if let page = self.listView.document.page(at: UInt(indexSet.first ?? 0)) {
  1612. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page))
  1613. var pathExt = ""
  1614. var fileData: Data?
  1615. if let data = self.listView?.document?.allowsPrinting, data {
  1616. pathExt = "pdf"
  1617. // data = [page dataRepresentation];
  1618. } else {
  1619. pathExt = "tiff"
  1620. fileData = page.PDFListViewTIFFData(for: page.bounds(for: self.listView?.displayBox ?? .cropBox))
  1621. }
  1622. fileURL = fileURL.appendingPathExtension(pathExt).uniqueFileURL()
  1623. let success = try?fileData?.write(to: fileURL)
  1624. if success != nil {
  1625. fileURLArray.append(fileURL.lastPathComponent)
  1626. }
  1627. }
  1628. }
  1629. return fileURLArray
  1630. } else if self.snapshotTableView.isEqual(to: tableView) {
  1631. let idx = indexSet.first ?? NSNotFound
  1632. if (idx != NSNotFound) {
  1633. if let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC {
  1634. if let page = self.listView?.document?.page(at: snapshot.pageIndex()) {
  1635. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page)).appendingPathExtension("tiff")
  1636. fileURL = fileURL.uniqueFileURL()
  1637. if ((try?snapshot.thumbnailWithSize(0)?.tiffRepresentation?.write(to: fileURL)) != nil) {
  1638. return [fileURL.lastPathComponent]
  1639. }
  1640. }
  1641. }
  1642. }
  1643. }
  1644. return[]
  1645. }
  1646. func tableViewColumnDidResize(_ notification: Notification) {
  1647. guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else {
  1648. return
  1649. }
  1650. if column.identifier.rawValue == IMAGE_COLUMNID {
  1651. if self.thumbnailTableView.isEqual(to: notification.object) {
  1652. self.thumbnailTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.thumbnailTableView.numberOfRows)) as IndexSet)
  1653. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1654. self.snapshotTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.snapshotTableView.numberOfRows)) as IndexSet)
  1655. }
  1656. }
  1657. }
  1658. func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
  1659. if tableView.isEqual(to: self.groupedFindTableView) {
  1660. // [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  1661. }
  1662. }
  1663. /*
  1664. #pragma mark NSTableView delegate protocol
  1665. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  1666. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1667. NSUInteger idx = [rowIndexes firstIndex];
  1668. if (idx != NSNotFound) {
  1669. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  1670. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  1671. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1672. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  1673. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  1674. [self fileWithPage:page atPath:filePath];
  1675. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  1676. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  1677. } else {
  1678. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  1679. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  1680. }
  1681. }
  1682. }
  1683. }
  1684. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  1685. NSData *data = [page dataRepresentation];
  1686. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  1687. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1688. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  1689. if (success) {
  1690. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  1691. NSURL *url = [NSURL fileURLWithPath:filePath];
  1692. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  1693. }
  1694. [document release];
  1695. */
  1696. }
  1697. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  1698. /*
  1699. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1700. if item is KMBOTAAnnotationSection {
  1701. let section = item as? KMBOTAAnnotationSection
  1702. return section!.annotations?[index] as Any
  1703. } else if item is KMBOTAAnnotationItem {
  1704. return item as Any
  1705. } else {
  1706. var tempArray: [KMBOTAAnnotationSection] = []
  1707. for temp in self.data {
  1708. if temp.annotations?.count != 0 {
  1709. tempArray.append(temp)
  1710. }
  1711. }
  1712. let section = tempArray[index]
  1713. return section as Any
  1714. }
  1715. }
  1716. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  1717. if item is KMBOTAAnnotationItem {
  1718. let cell : KMAnnotationOutlineCellView = KMAnnotationOutlineCellView.init()
  1719. cell.delegate = self
  1720. cell.model = item as? KMBOTAAnnotationItem
  1721. return cell
  1722. } else if item is KMBOTAAnnotationSection {
  1723. let section = item as? KMBOTAAnnotationSection
  1724. let cell : KMAnnotationOutlineSectionView = KMAnnotationOutlineSectionView.init()
  1725. cell.model = section
  1726. return cell
  1727. }
  1728. return NSTableCellView()
  1729. }
  1730. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  1731. let rowView = KMAnnotationOutlineRowView()
  1732. if item is KMBOTAAnnotationItem {
  1733. rowView.model = (item as? KMBOTAAnnotationItem)
  1734. } else if item is KMBOTAAnnotationSection {
  1735. rowView.section = (item as? KMBOTAAnnotationSection)
  1736. }
  1737. rowView.mouseDownAction = { [unowned self] view, event in
  1738. if rowView.section != nil {
  1739. let expanded = outlineView.isItemExpanded(outlineView.item(atRow: outlineView.selectedRow))
  1740. if expanded {
  1741. outlineView.collapseItem(outlineView.item(atRow: outlineView.selectedRow), collapseChildren: true)
  1742. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  1743. } else {
  1744. outlineView.expandItem(outlineView.item(atRow: outlineView.selectedRow), expandChildren: true)
  1745. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  1746. }
  1747. } else if rowView.model != nil {
  1748. self.didSelectItem(view: rowView, event: event)
  1749. }
  1750. }
  1751. rowView.rightMouseDownAction = { [unowned self] view, event in
  1752. if rowView.section != nil {
  1753. } else if rowView.model != nil {
  1754. if !KMOCToolClass.arrayContains(array: self.selectItems, annotation: item) ||
  1755. self.selectItems.count == 1 {
  1756. self.selectItem(item: item as! KMBOTAAnnotationItem)
  1757. }
  1758. DispatchQueue.main.async {
  1759. self.delegate?.annotationOutlineView(self, rightMouseDownDidSelectView: view, evnet: event)
  1760. }
  1761. }
  1762. }
  1763. rowView.hoverCallback = { [unowned self] (mouseEntered, mouseBox) in
  1764. self.outlineView.enumerateAvailableRowViews { view, row in
  1765. if view is KMAnnotationOutlineRowView {
  1766. (view as? KMAnnotationOutlineRowView)?.model?.hover = false
  1767. (view as? KMAnnotationOutlineRowView)?.reloadData()
  1768. }
  1769. }
  1770. if mouseEntered {
  1771. rowView.model?.hover = true
  1772. } else {
  1773. rowView.model?.hover = false
  1774. }
  1775. }
  1776. return rowView
  1777. }
  1778. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  1779. if item is KMBOTAAnnotationItem {
  1780. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: self.maxWidth - 16, height: 1000))
  1781. } else if item is KMBOTAAnnotationSection {
  1782. return 40
  1783. } else {
  1784. return 30
  1785. }
  1786. }
  1787. func outlineViewSelectionDidChange(_ notification: Notification) {
  1788. if self.outlineView.selectedRow == -1 {
  1789. self.cancelSelect()
  1790. }
  1791. }
  1792. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  1793. if item is KMBOTAAnnotationItem {
  1794. return false
  1795. } else if item is KMBOTAAnnotationSection {
  1796. let section = item as? KMBOTAAnnotationSection
  1797. return section!.annotations?.count ?? 0 > 0
  1798. }
  1799. return false
  1800. }
  1801. func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
  1802. if let item = item as? KMBOTAAnnotationSection {
  1803. if !item.isItemExpanded {
  1804. item.isItemExpanded = true
  1805. outlineView.animator().expandItem(item, expandChildren: true)
  1806. return false
  1807. }
  1808. }
  1809. return true
  1810. }
  1811. func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
  1812. if let item = item as? KMBOTAAnnotationSection {
  1813. if item.isItemExpanded {
  1814. item.isItemExpanded = false
  1815. outlineView.animator().collapseItem(item, collapseChildren: true)
  1816. return false
  1817. }
  1818. }
  1819. return true
  1820. }
  1821. */
  1822. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  1823. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  1824. if outlineView.isEqual(to: self.tocOutlineView) {
  1825. let isLocked = self.listView.document?.isLocked ?? true
  1826. if isLocked { // 文档不存在 或 已加锁
  1827. return 0
  1828. }
  1829. if item == nil { // 第一层
  1830. // 获取根
  1831. guard let outline = self.listView.document.outlineRoot() else {
  1832. let view = self.tocOutlineView.enclosingScrollView!
  1833. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  1834. //
  1835. 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)
  1836. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1837. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  1838. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  1839. return 0
  1840. }
  1841. if outline.numberOfChildren == 0 {
  1842. // return 0
  1843. }
  1844. if self.isSearchOutlineMode { // 是否为搜索模块
  1845. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: outline) {
  1846. self.showSearchOutlineBlankState(false)
  1847. } else {
  1848. self.showSearchOutlineBlankState(true)
  1849. return 0
  1850. }
  1851. } else {
  1852. if outline.numberOfChildren > 0 { // 有数据
  1853. self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  1854. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  1855. } else { // 没有数据
  1856. let view = self.tocOutlineView.enclosingScrollView!
  1857. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  1858. //
  1859. 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)
  1860. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1861. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  1862. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  1863. return 0
  1864. }
  1865. }
  1866. // 搜索按钮
  1867. if outline.numberOfChildren > 0 {
  1868. self.outlineSearchButton.isEnabled = true
  1869. } else {
  1870. self.outlineSearchButton.isEnabled = false
  1871. }
  1872. if (self.isSearchOutlineMode) {
  1873. var num = 0
  1874. for i in 0 ..< outline.numberOfChildren {
  1875. if let child = outline.child(at: i) {
  1876. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  1877. num += 1
  1878. }
  1879. }
  1880. }
  1881. return num
  1882. } else {
  1883. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  1884. var bookmarkNum = 0
  1885. if array.isEmpty == false {
  1886. bookmarkNum = 1
  1887. }
  1888. return Int(outline.numberOfChildren) + bookmarkNum
  1889. }
  1890. } else { // 第二层 +
  1891. if self.isSearchOutlineMode {
  1892. if let data = item as? String, data == "Bookmarks" { // 书签group
  1893. return 0
  1894. } else if item is CPDFOutline { // 大纲
  1895. let child = item as! CPDFOutline
  1896. if child.numberOfChildren == 0 {
  1897. return 0
  1898. }
  1899. var num = 0
  1900. for i in 0 ..< child.numberOfChildren {
  1901. if let _child = child.child(at: i) {
  1902. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: _child) {
  1903. num += 1
  1904. }
  1905. }
  1906. }
  1907. return num
  1908. } else if item is CPDFBookmark { // 书签
  1909. return 0
  1910. }
  1911. } else {
  1912. if let data = item as? String, data == "Bookmarks" { // 书签group
  1913. return (self.listView.document?.bookmarks().count) ?? 0
  1914. } else if item is CPDFOutline { // 大纲
  1915. return Int((item as? CPDFOutline)?.numberOfChildren ?? 0)
  1916. } else if item is CPDFBookmark { // 书签
  1917. return 0
  1918. }
  1919. }
  1920. }
  1921. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1922. if self.noteSearchMode {
  1923. return self.noteSearchArray.count
  1924. }
  1925. var count = 0
  1926. for section in self.annotations {
  1927. if section.annotations?.count != 0 {
  1928. count += section.annotations!.count
  1929. }
  1930. }
  1931. // if (item == nil){
  1932. // NSInteger count = [[rightSideController.noteArrayController arrangedObjects] count];
  1933. if (count < 1) {
  1934. // if (notes.count < 1) {
  1935. self.noteSearchButton.isEnabled = false
  1936. self.noteFilterButton.isEnabled = false
  1937. // }
  1938. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1939. let view = self.noteOutlineView.enclosingScrollView!
  1940. var emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  1941. 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)
  1942. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1943. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  1944. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  1945. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  1946. //
  1947. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  1948. self.noteHeaderView.isHidden = true
  1949. self.toolButtonBoxLayoutConstraint.constant = 40.0
  1950. }
  1951. } else {
  1952. self.noteSearchButton.isEnabled = true
  1953. self.noteFilterButton.isEnabled = true
  1954. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1955. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  1956. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  1957. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  1958. //
  1959. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  1960. self.noteHeaderView.isHidden = false
  1961. self.toolButtonBoxLayoutConstraint.constant = 64.0
  1962. }
  1963. }
  1964. return count
  1965. // } else {
  1966. // return [item hasNoteText];
  1967. // }
  1968. }
  1969. return 0
  1970. }
  1971. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1972. if outlineView.isEqual(to: self.tocOutlineView) {
  1973. let isLocked = self.listView.document?.isLocked ?? true
  1974. if isLocked { // 文档不存在 或 已加锁
  1975. return ""
  1976. }
  1977. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  1978. var bookmarkNum = 0
  1979. if array.isEmpty == false {
  1980. bookmarkNum = 1
  1981. }
  1982. if item == nil {
  1983. if self.isSearchOutlineMode {
  1984. guard let outline = self.listView.document.outlineRoot() else {
  1985. return ""
  1986. }
  1987. if outline.numberOfChildren == 0 {
  1988. return ""
  1989. }
  1990. var array: [CPDFOutline] = []
  1991. for i in 0 ..< outline.numberOfChildren {
  1992. if let child = outline.child(at: i) {
  1993. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  1994. array.append(child)
  1995. }
  1996. }
  1997. }
  1998. if index < array.count {
  1999. return array[index]
  2000. }
  2001. return ""
  2002. } else {
  2003. if index == 0 && bookmarkNum == 1 {
  2004. return "Bookmarks"
  2005. } else {
  2006. var _index = bookmarkNum == 1 ? index-1 : index
  2007. let outline = self.listView.document.outlineRoot()
  2008. var obj = outline?.child(at: UInt(_index))
  2009. return obj as Any
  2010. }
  2011. }
  2012. } else {
  2013. if let data = item as? String, data == "Bookmarks" {
  2014. return array[index]
  2015. } else if item is CPDFOutline {
  2016. return (item as! CPDFOutline).child(at: UInt(index))
  2017. } else if item is CPDFBookmark {
  2018. return ""
  2019. }
  2020. }
  2021. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2022. // if (item == nil)
  2023. // {
  2024. // return [[rightSideController.noteArrayController arrangedObjects] objectAtIndex:anIndex];
  2025. // // return [self.notes objectAtIndex:anIndex];
  2026. // }
  2027. // else
  2028. // return [item noteText];
  2029. if self.noteSearchMode {
  2030. return self.noteSearchArray[index]
  2031. }
  2032. var tempArray: [KMBOTAAnnotationItem] = []
  2033. for secion in self.annotations {
  2034. if secion.annotations?.count != 0 {
  2035. for _item in secion.annotations! {
  2036. tempArray.append(_item)
  2037. }
  2038. }
  2039. }
  2040. return tempArray[index] as Any
  2041. }
  2042. return item
  2043. }
  2044. func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
  2045. if outlineView.isEqual(to: self.tocOutlineView) {
  2046. // let tcID = tableColumn?.identifier.rawValue ?? ""
  2047. // var ol = item as? CPDFOutline
  2048. // if(tcID == LABEL_COLUMNID) {
  2049. // if (self.isSearchOutlineMode) {
  2050. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  2051. //// NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  2052. //// NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  2053. //// for (NSUInteger i = 0; i <arr.count ; i++) {
  2054. //// NSValue * rangeValue = arr[i];
  2055. //// NSRange range = rangeValue.rangeValue;
  2056. //// range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  2057. //// [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  2058. //// }
  2059. //// [attributeString addAttribute:NSForegroundColorAttributeName value:[KMAppearance KMColor_Layout_H0] range:NSMakeRange(0, roughString.length)];
  2060. //// return attributeString;
  2061. // } else {
  2062. // var attributedString = NSMutableAttributedString()
  2063. //// attributedString
  2064. // attributedString.append(.init(string: ol?.label ?? "", attributes: [.foregroundColor : KMAppearance.Layout.h0Color()]))
  2065. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  2066. //// NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2067. //// NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  2068. //// [attributedString appendAttributedString:attr1];
  2069. //
  2070. // return attributedString
  2071. // }
  2072. //
  2073. // }
  2074. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  2075. // NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2076. // NSString *roughString = [ol pageLabel]? : @"";
  2077. // NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2078. // NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  2079. // [attributedString appendAttributedString:attr1];
  2080. //
  2081. // return attributedString;
  2082. // }
  2083. }
  2084. // else if ([ov isEqual:rightSideController.noteOutlineView]) {
  2085. // NSString *tcID = [tableColumn identifier];
  2086. // PDFAnnotation *note = item;
  2087. // if (tableColumn == nil || [tcID isEqualToString:NOTE_COLUMNID])
  2088. // return [note objectValue];
  2089. // else if([tcID isEqualToString:TYPE_COLUMNID]){
  2090. // NSString *noteType = [note type];
  2091. // if ([note isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  2092. // PDFAnnotationButtonWidget *buttonWidget = (PDFAnnotationButtonWidget *)note;
  2093. // if (buttonWidget.controlType == kPDFWidgetRadioButtonControl) {
  2094. // noteType = SKAnnotationFormRadioButtonKey;
  2095. // } else if (buttonWidget.controlType == kPDFWidgetCheckBoxControl){
  2096. // noteType = SKAnnotationFormCheckBoxKey;
  2097. // } else if (buttonWidget.controlType == kPDFWidgetPushButtonControl){
  2098. // noteType = SKAnnotationFormActionButtonKey;
  2099. // }
  2100. // } else if ([note isKindOfClass:[PDFAnnotationTextWidget class]]){
  2101. // noteType = SKAnnotationFormTextFieldKey;
  2102. // } else if ([note isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  2103. // PDFAnnotationChoiceWidget *choiceWidget = (PDFAnnotationChoiceWidget *)note;
  2104. // if (choiceWidget.isListChoice) {
  2105. // noteType = SKAnnotationFormListMenuKey;
  2106. // } else {
  2107. // noteType = SKAnnotationFormComboBoxKey;
  2108. // }
  2109. //
  2110. // }
  2111. // return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:note == [pdfView activeAnnotation]], SKAnnotationTypeImageCellActiveKey, noteType, SKAnnotationTypeImageCellTypeKey,[note color],SKAnnotationTypeImageCellColorKey, nil];
  2112. // }
  2113. // else if([tcID isEqualToString:COLOR_COLUMNID])
  2114. // return [note type] ? [note color] : nil;
  2115. // else if([tcID isEqualToString:PAGE_COLUMNID])
  2116. // return [[note page] displayLabel];
  2117. // else if([tcID isEqualToString:AUTHOR_COLUMNID])
  2118. // return [note type] ? [note userName] : nil;
  2119. // else if([tcID isEqualToString:DATE_COLUMNID])
  2120. // return [note type] ? [note modificationDate] : nil;
  2121. // }
  2122. return nil
  2123. }
  2124. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  2125. if outlineView.isEqual(to: self.tocOutlineView) {
  2126. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMTocTableCellView"), owner: self) as! KMTocTableCellView
  2127. let tcID = tableColumn?.identifier.rawValue
  2128. var title = ""
  2129. var pageLabel = ""
  2130. if let data = item as? String, data == "Bookmarks" {
  2131. title = NSLocalizedString("Bookmarks", comment: "")
  2132. } else if item is CPDFOutline {
  2133. title = (item as! CPDFOutline).label
  2134. pageLabel = "\(((item as! CPDFOutline).destination?.pageIndex ?? 0) + 1)"
  2135. } else if item is CPDFBookmark {
  2136. title = (item as! CPDFBookmark).label
  2137. pageLabel = "\((item as! CPDFBookmark).pageIndex + 1)"
  2138. }
  2139. if tcID == LABEL_COLUMNID {
  2140. if (self.isSearchOutlineMode) {
  2141. // NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines];
  2142. let roughString = title
  2143. // NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  2144. // NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  2145. //
  2146. // for (NSUInteger i = 0; i <arr.count ; i++) {
  2147. // NSValue * rangeValue = arr[i];
  2148. // NSRange range = rangeValue.rangeValue;
  2149. // range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  2150. // [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  2151. // }
  2152. // cell.tocLabel.attributedStringValue = attributeString;
  2153. cell.tocLabel.stringValue = title
  2154. } else {
  2155. cell.tocLabel.stringValue = title
  2156. }
  2157. cell.pageLabel.stringValue = pageLabel
  2158. }
  2159. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  2160. // cell.pageLabel.stringValue = [ol pageLabel];
  2161. // }
  2162. return cell
  2163. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2164. let model = item as? KMBOTAAnnotationItem
  2165. var note: CPDFAnnotation!
  2166. if self.noteSearchMode {
  2167. note = item as! CPDFAnnotation
  2168. } else {
  2169. note = (item as! KMBOTAAnnotationItem).annotation!
  2170. }
  2171. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMNoteTableViewCell"), owner: self) as! KMNoteTableViewCell
  2172. cell.cellNote = note
  2173. let noteColor = note.color
  2174. var noteType = note.type ?? ""
  2175. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  2176. // NSString *pageString = [[note page] displayLabel] ? : @"";
  2177. var pageString = "\((note.page?.pageIndex() ?? 0) + 1)"
  2178. let formatter = DateFormatter()
  2179. formatter.dateFormat = "hh:mm"
  2180. var dateString = ""
  2181. if let date = note.modificationDate() {
  2182. dateString = formatter.string(from: date)
  2183. }
  2184. var authorString = note.userName() ?? ""
  2185. // NSString *noteTextString = [note noteText].string ? : @"";
  2186. var noteTextString = note.string() ?? ""
  2187. //
  2188. // if([noteType isEqualToString:@"Redact"]) {
  2189. // noteString = @"Redact";
  2190. // }
  2191. //
  2192. let timeKey = self.noteTypeDict[Self.noteFilterTimeKey] as? Bool
  2193. if timeKey == nil || timeKey == false {
  2194. // if (date != nil) {
  2195. cell.timeLabel.stringValue = dateString
  2196. //
  2197. // } else {
  2198. // cell.timeLabel.stringValue = ""
  2199. // }
  2200. cell.timeLabel.isHidden = false
  2201. } else {
  2202. cell.timeLabel.isHidden = true
  2203. }
  2204. let pageKey = self.noteTypeDict[Self.noteFilterPageKey] as? Bool
  2205. if pageKey == nil || pageKey == false {
  2206. let labelsize = cell.pageLabel.stringValue.boundingRect(with: CGSizeMake(CGFloat(MAXFLOAT),CGRectGetHeight(cell.pageLabel.bounds)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font : NSFont.systemFont(ofSize: 12)])
  2207. cell.pageLabelWidthConstraint.constant = labelsize.size.width + 5
  2208. cell.pageLabel.stringValue = pageString
  2209. cell.pageLabel.isHidden = false
  2210. } else {
  2211. cell.pageLabel.isHidden = true
  2212. }
  2213. let autherKey = self.noteTypeDict[Self.noteFilterAutherKey] as? Bool
  2214. if autherKey == nil || autherKey == false {
  2215. cell.autherLabel.stringValue = authorString
  2216. cell.autherLabel.isHidden = false
  2217. } else {
  2218. cell.autherLabel.isHidden = true
  2219. }
  2220. let imageView = KMNoteTypeImageView()
  2221. if note.isKind(of: CPDFStampAnnotation.self) {
  2222. let annotation_stamp = note as! CPDFStampAnnotation
  2223. if (annotation_stamp.stampImage() != nil) {
  2224. noteType = SKNStampString
  2225. }
  2226. } else if note.isKind(of: CPDFLineAnnotation.self) {
  2227. let annotation_line = note as! CPDFLineAnnotation
  2228. if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .none {
  2229. noteType = SKNLine_NoneString
  2230. } else if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .openArrow {
  2231. noteType = SKNLine_OpenArrowString
  2232. } else {
  2233. noteType = SKNLine_NoneString
  2234. }
  2235. } else if note.isKind(of: CPDFButtonWidgetAnnotation.self) {
  2236. let buttonWidget = note as! CPDFButtonWidgetAnnotation
  2237. if buttonWidget.controlType() == .radioButtonControl {
  2238. noteType = KMAnnotationFormRadioButtonKey
  2239. } else if buttonWidget.controlType() == .checkBoxControl {
  2240. noteType = KMAnnotationFormCheckBoxKey
  2241. } else if buttonWidget.controlType() == .pushButtonControl {
  2242. noteType = KMAnnotationFormActionButtonKey
  2243. }
  2244. } else if note.isKind(of: CPDFTextWidgetAnnotation.self) {
  2245. noteType = KMAnnotationFormTextFieldKey
  2246. } else if note.isKind(of: CPDFChoiceWidgetAnnotation.self) {
  2247. let choiceWidget = note as! CPDFChoiceWidgetAnnotation
  2248. if choiceWidget.isListChoice {
  2249. noteType = KMAnnotationFormListMenuKey
  2250. } else {
  2251. noteType = KMAnnotationFormComboBoxKey
  2252. }
  2253. } else if note.isKind(of: KMTableAnnotation.self) {
  2254. noteType = "Ink_Table"
  2255. } else if note.isKind(of: KMSelfSignAnnotation.self) {
  2256. let selfSignNote = note as! KMSelfSignAnnotation
  2257. if selfSignNote.annotationType == .signFalse {
  2258. noteType = "KMSelfSignTypeFalseActionButtonKey"
  2259. } else if (selfSignNote.annotationType == .signature) {
  2260. noteType = "KMSelfSignTypeTureActionButtonKey"
  2261. } else if (selfSignNote.annotationType == .signCircle) {
  2262. noteType = "KMSelfSignTypeCircleActionButtonKey"
  2263. } else if (selfSignNote.annotationType == .signLine) {
  2264. noteType = "KMSelfSignTypeLineActionButtonKey"
  2265. } else if (selfSignNote.annotationType == .signDot) {
  2266. noteType = "KMSelfSignTypeDotActionButtonKey"
  2267. } else if (selfSignNote.annotationType == .signText) {
  2268. noteType = "KMSelfSignTypeTextActionButtonKey"
  2269. }
  2270. } else if note.isKind(of: CPDFSquareAnnotation.self) {
  2271. noteType = SKNSquareString
  2272. } else if note.isKind(of: CPDFTextAnnotation.self) {
  2273. noteType = SKNNoteString
  2274. } else if note.isKind(of: CPDFFreeTextAnnotation.self) {
  2275. noteType = SKNFreeTextString
  2276. } else if note.isKind(of: CPDFCircleAnnotation.self) {
  2277. noteType = SKNCircleString
  2278. } else if note.isKind(of: CPDFSignatureAnnotation.self) {
  2279. noteType = SKNSignatureString
  2280. } else if note.isKind(of: CPDFInkAnnotation.self) {
  2281. noteType = SKNInkString
  2282. } else if note.isKind(of: CPDFMarkupAnnotation.self) {
  2283. let anno = note as! CPDFMarkupAnnotation
  2284. if anno.markupType() == .highlight {
  2285. noteType = SKNHighlightString
  2286. } else if anno.markupType() == .underline {
  2287. noteType = SKNUnderlineString
  2288. } else if anno.markupType() == .strikeOut {
  2289. noteType = SKNStrikeOutString
  2290. }
  2291. }
  2292. cell.typeImageView.image = imageView.noteTypeImage(withType: noteType, color: noteColor ?? .red)
  2293. cell.typeImageView.isHidden = false
  2294. if note.isKind(of: CPDFMarkupAnnotation.self) {
  2295. cell.isFold = true
  2296. }
  2297. cell.noteContentBox.isHidden = true
  2298. cell.noteImageView.isHidden = true
  2299. cell.foldButton.isHidden = true
  2300. cell.annotationContentLabel.isHidden = false
  2301. cell.noteContentLabel.stringValue = noteString
  2302. cell.contentView.isHidden = false
  2303. cell.contentViewHidden(false)
  2304. if note.isKind(of: CPDFMarkupAnnotation.self) {
  2305. let markup = note as! CPDFMarkupAnnotation
  2306. var contentString = KMBOTAAnnotationTool.fetchText(text: markup.markupContent() ?? "")
  2307. contentString = contentString.replacingOccurrences(of: "\r", with: "")
  2308. contentString = contentString.replacingOccurrences(of: "\n", with: "")
  2309. cell.noteContentLabel.stringValue = contentString
  2310. if(contentString.isEmpty == false) {
  2311. cell.foldButton.isHidden = false
  2312. }
  2313. var attributeStr = NSMutableAttributedString(string: contentString)
  2314. if (markup.markupType() == .highlight) {
  2315. attributeStr.addAttribute(.backgroundColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  2316. } else if (markup.markupType() == .strikeOut) {
  2317. attributeStr.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  2318. attributeStr.addAttribute(.strikethroughColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  2319. } else if (markup.markupType() == .underline) {
  2320. attributeStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  2321. attributeStr.addAttribute(.underlineColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  2322. }
  2323. cell.annotationContentLabel.attributedStringValue = attributeStr
  2324. if self.foldType == .unfold {
  2325. // if let data = model?.foldType, data == .unfold { // 全部展开
  2326. cell.isFold = false
  2327. } else if self.foldType == .fold {
  2328. // else if let data = model?.foldType, data == .fold { // 全部折叠
  2329. cell.isFold = true
  2330. } else { // 混合
  2331. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  2332. cell.isFold = false
  2333. } else {
  2334. cell.isFold = true
  2335. }
  2336. }
  2337. // noteString.isEmpty == false &&
  2338. if (contentString.isEmpty == false) {
  2339. cell.contentViewHidden(false)
  2340. } else {
  2341. cell.contentViewHidden(true)
  2342. }
  2343. } else if note.isKind(of: CPDFLineAnnotation.self) || noteType == SKNSquareString || noteType == SKNCircleString || noteType == SKNInkString {
  2344. cell.annotationContentLabel.stringValue = noteString
  2345. if (noteString.isEmpty == false) {
  2346. cell.contentViewHidden(false)
  2347. } else {
  2348. cell.contentViewHidden(true)
  2349. }
  2350. } else if note.isKind(of: CPDFStampAnnotation.self) {
  2351. if note.isKind(of: KMSelfSignAnnotation.self) {
  2352. let newAnnotation = note as! KMSelfSignAnnotation
  2353. let type = newAnnotation.annotationType
  2354. var returnString = ""
  2355. if (type == .signFalse) {
  2356. returnString = KMLocalizedString("X", nil)
  2357. } else if (type == .signature) {
  2358. returnString = KMLocalizedString("Check mark", nil)
  2359. } else if (type == .signCircle) {
  2360. returnString = KMLocalizedString("Circle", nil)
  2361. } else if (type == .signLine) {
  2362. returnString = KMLocalizedString("Line", nil)
  2363. } else if (type == .signDot) {
  2364. returnString = KMLocalizedString("Dot", nil)
  2365. } else if (type == .signText) {
  2366. returnString = KMLocalizedString("Text", nil)
  2367. }
  2368. cell.annotationContentLabel.stringValue = returnString
  2369. } else {
  2370. cell.annotationContentLabel.isHidden = true
  2371. cell.noteImageView.isHidden = false
  2372. let anno = note as! CPDFStampAnnotation
  2373. cell.noteImageView.image = anno.stampImage()
  2374. }
  2375. } else if note.isKind(of: CPDFTextAnnotation.self) {
  2376. cell.foldButton.isHidden = false
  2377. if noteString.isEmpty {
  2378. cell.annotationContentLabel.stringValue = noteTextString
  2379. }else{
  2380. cell.annotationContentLabel.stringValue = noteString
  2381. cell.noteContentLabel.stringValue = noteTextString
  2382. }
  2383. if (self.foldType == .unfold) {
  2384. cell.isFold = false
  2385. } else if (self.foldType == .fold) {
  2386. cell.isFold = true
  2387. } else {
  2388. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  2389. cell.isFold = false
  2390. } else {
  2391. cell.isFold = true
  2392. }
  2393. }
  2394. if (noteString.isEmpty == false || noteTextString.isEmpty == false) {
  2395. cell.contentView.isHidden = false
  2396. } else {
  2397. cell.contentView.isHidden = true
  2398. cell.contentViewHidden(true)
  2399. }
  2400. // noteString.isEmpty == false &&
  2401. if (noteTextString.isEmpty == false) {
  2402. cell.foldButton.isHidden = false
  2403. }else{
  2404. cell.foldButton.isHidden = true
  2405. }
  2406. } else {
  2407. cell.annotationContentLabel.stringValue = noteString
  2408. cell.imageViewHeightConstraint.constant = cell.contentView.frame.size.height
  2409. if (noteString.isEmpty == false) {
  2410. cell.contentViewHidden(false)
  2411. } else {
  2412. cell.contentViewHidden(true)
  2413. }
  2414. }
  2415. cell.autherLayoutConstraint.constant = cell.autherLabel.isHidden ? -(cell.autherLabel.bounds.size.width) + 10.0 : 10.0
  2416. cell.typeImageViewLayoutConstraint.constant = cell.typeImageView.isHidden ? -(cell.typeImageView.bounds.size.width) : 0.0
  2417. cell.contentBoxLayoutConstraint.constant = cell.noteContentBox.isHidden ? -(cell.noteContentBox.bounds.size.height+8.0) : 8.0
  2418. if note.isKind(of: CPDFStampAnnotation.self) && note.isKind(of: KMSelfSignAnnotation.self) == false {
  2419. } else {
  2420. if note.isKind(of: CPDFMarkupAnnotation.self) {
  2421. if (!cell.isFold) {
  2422. self.allFoldNotes.append(note)
  2423. } else {
  2424. cell.imageViewHeightConstraint.constant = 18.0 + 8
  2425. }
  2426. } else {
  2427. cell.imageViewHeightConstraint.constant = 18.0 + 8
  2428. }
  2429. }
  2430. cell.isUnFoldNote = { [unowned self] cellNote, isUnfold in
  2431. model?.foldType = isUnfold ? .unfold : .fold
  2432. // let COLUMN_INDENTATION: CGFloat = 16
  2433. // if let _cell = tableColumn?.dataCell as? NSCell {
  2434. // _cell.objectValue = cell.annotationContentLabel.attributedStringValue
  2435. // let bound = NSMakeRect(0.0, 0.0, fmax(10.0, NSWidth(outlineView.frame) - COLUMN_INDENTATION - outlineView.indentationPerLevel-40), CGFLOAT_MAX)
  2436. // let height = _cell.cellSize(forBounds: bound).height
  2437. // KMPrint(height)
  2438. // }
  2439. if cellNote is CPDFMarkupAnnotation {
  2440. // let content = cell.annotationContentLabel.attributedStringValue
  2441. // let bound = content.string.boundingRect(with: NSMakeSize(150, CGFLOAT_MAX), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: nil)
  2442. // KMPrint(bound)
  2443. // 154 34 273
  2444. // 273 - 188 = 85 noteContentHeightConstraint maltlineLabelLayoutConstraint
  2445. model?.foldH = isUnfold ? 30 : (cell.noteContentHeightConstraint.constant + cell.maltlineLabelLayoutConstraint.constant + 85)
  2446. }
  2447. if (isUnfold) {
  2448. if (self.allFoldNotes.contains(note)) {
  2449. self.allFoldNotes.removeObject(note)
  2450. }
  2451. if (self.allFoldNotes.count == 0) {
  2452. self.foldType = .fold
  2453. } else {
  2454. self.foldType = .none
  2455. }
  2456. } else {
  2457. if self.allFoldNotes.contains(note) == false {
  2458. self.allFoldNotes.append(note)
  2459. }
  2460. // if (rightSideController.allFoldNotes.count == rightSideController.canFoldNotes.count) {
  2461. self.foldType = .unfold
  2462. // } else {
  2463. // self.foldType = KMFoldAllAnnotationType_None;
  2464. // }
  2465. }
  2466. }
  2467. return cell
  2468. }
  2469. return nil
  2470. }
  2471. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2472. if outlineView.isEqual(self.noteOutlineView) {
  2473. if item is KMBOTAAnnotationItem {
  2474. let model = item as! KMBOTAAnnotationItem
  2475. if model.foldType == .fold {
  2476. return model.foldH
  2477. }
  2478. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  2479. }
  2480. return 30
  2481. } else if outlineView.isEqual(self.tocOutlineView) {
  2482. if item is CPDFOutline {
  2483. let tempItem = item as! CPDFOutline
  2484. let string: NSString = tempItem.label as NSString
  2485. let paragraphStyle = NSMutableParagraphStyle()
  2486. paragraphStyle.lineHeightMultiple = 1.32
  2487. paragraphStyle.alignment = .left
  2488. let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
  2489. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  2490. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attributes)
  2491. return max(40, size.height + 16)
  2492. }
  2493. return 40
  2494. }
  2495. return outlineView.rowHeight
  2496. }
  2497. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2498. if outlineView.isEqual(self.tocOutlineView) {
  2499. // var _item: CPDFOutline?
  2500. // if item == nil && self.listView.document.isLocked == false {
  2501. // _item = self.listView.document.outlineRoot()
  2502. // }
  2503. if let data = item as? String, data == "Bookmarks" {
  2504. return true
  2505. } else if item is CPDFOutline {
  2506. return ((item as! CPDFOutline).numberOfChildren ?? 0) != 0
  2507. } else if item is CPDFBookmark {
  2508. return false
  2509. }
  2510. if (self.isSearchOutlineMode) {
  2511. // return [self subOutLineContainString:self.leftSideController.outlineSearchField.stringValue rootOutline:(PDFOutline *)item];
  2512. } else {
  2513. // return ((_item?.numberOfChildren ?? 0) != 0)
  2514. }
  2515. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2516. // return [item hasNoteText];
  2517. return false
  2518. }
  2519. return false
  2520. }
  2521. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2522. if outlineView.isEqual(self.tocOutlineView) {
  2523. let itemView = KMBotaTableRowView()
  2524. return itemView
  2525. } else if outlineView.isEqual(self.noteOutlineView) {
  2526. let itemView = KMBotaTableRowView()
  2527. return itemView;
  2528. }
  2529. return nil
  2530. }
  2531. func outlineViewSelectionDidChange(_ notification: Notification) {
  2532. if self.tocOutlineView.isEqual(to: notification.object) {
  2533. if self.updatingOutlineSelection == false {
  2534. self.updatingOutlineSelection = true
  2535. self.goToSelectedOutlineItem(nil)
  2536. self.updatingOutlineSelection = false
  2537. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2538. // [self hideLeftSideWindow];
  2539. }
  2540. }
  2541. }
  2542. func outlineViewItemDidExpand(_ notification: Notification) {
  2543. if self.tocOutlineView.isEqual(to: notification.object) {
  2544. self.updateOutlineSelection()
  2545. }
  2546. }
  2547. func outlineViewItemDidCollapse(_ notification: Notification) {
  2548. if self.tocOutlineView.isEqual(to: notification.object) {
  2549. self.updateOutlineSelection()
  2550. }
  2551. }
  2552. func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
  2553. var dragOp = NSDragOperation(rawValue: 0)
  2554. if outlineView.isEqual(to: self.noteOutlineView) {
  2555. let pboard = info.draggingPasteboard
  2556. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) && index == NSOutlineViewDropOnItemIndex {
  2557. if let note = item as? CPDFAnnotation, note.type != nil {
  2558. dragOp = .every
  2559. }
  2560. }
  2561. } else if outlineView.isEqual(to: self.tocOutlineView) {
  2562. if (index == -1) {
  2563. dragOp = NSDragOperation(rawValue: 0)
  2564. } else {
  2565. dragOp = .move
  2566. }
  2567. }
  2568. return dragOp
  2569. }
  2570. func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
  2571. if outlineView.isEqual(to: self.tocOutlineView) {
  2572. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  2573. return false
  2574. }
  2575. let tIndex = IndexSet(integer: self.tocOutlineView.clickedRow)
  2576. self.tocOutlineView.deselectRow(tIndex.first ?? 0)
  2577. self._dragPDFOutline = items.first as? CPDFOutline
  2578. let set = IndexSet(integer: 0)
  2579. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: set)
  2580. // [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  2581. pasteboard.declareTypes([.localDraggedTypes], owner: self)
  2582. pasteboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  2583. return true
  2584. }
  2585. return false
  2586. }
  2587. func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
  2588. if outlineView.isEqual(to: self.noteOutlineView) {
  2589. let pboard = info.draggingPasteboard
  2590. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) {
  2591. // [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  2592. let isShift = NSEvent.modifierFlags.contains(.shift)
  2593. let isAlt = NSEvent.modifierFlags.contains(.option)
  2594. guard let note = item as? CPDFAnnotation else {
  2595. NSSound.beep()
  2596. return false
  2597. }
  2598. if let color = NSColor(from: pboard) {
  2599. note.setColor(color, alternate: isAlt, updateDefaults: isShift)
  2600. return true
  2601. }
  2602. return false
  2603. }
  2604. } else if outlineView.isEqual(to: self.tocOutlineView) {
  2605. if (index < 0) {
  2606. return false
  2607. }
  2608. // guard let outline = item as? CPDFOutline else {
  2609. // return false
  2610. // }
  2611. let outline = item as? CPDFOutline
  2612. guard let dragPDFOL = self._dragPDFOutline else {
  2613. return false
  2614. }
  2615. //root,drag item to root
  2616. if ((outline?.parent == nil)) {
  2617. //fetch root
  2618. var root = dragPDFOL
  2619. while (root.parent != nil) {
  2620. root = root.parent
  2621. }
  2622. if dragPDFOL.parent.isEqual(to: root) {
  2623. if dragPDFOL.index > index {
  2624. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  2625. } else {
  2626. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: root)
  2627. }
  2628. } else {
  2629. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  2630. }
  2631. } else {
  2632. //在同一个层级内移动
  2633. if dragPDFOL.parent.isEqual(to: item) {
  2634. if (dragPDFOL.index > 0) {
  2635. if dragPDFOL.index > index {
  2636. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  2637. }else{
  2638. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: outline)
  2639. }
  2640. } else {
  2641. return false
  2642. }
  2643. } else {
  2644. var tOutlline: CPDFOutline? = outline
  2645. var isContains = false
  2646. while (tOutlline != nil) {
  2647. if tOutlline!.isEqual(to: self._dragPDFOutline) {
  2648. isContains = true
  2649. break
  2650. }
  2651. tOutlline = tOutlline?.parent
  2652. }
  2653. if (!isContains) {
  2654. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  2655. }
  2656. }
  2657. }
  2658. return true
  2659. }
  2660. return false
  2661. }
  2662. func outlineView(_ outlineView: NSOutlineView, willDisplayOutlineCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
  2663. if outlineView.isEqual(to: self.tocOutlineView) {
  2664. if outlineView.selectionHighlightStyle == .regular && outlineView.isRowSelected(outlineView.row(forItem: item)) {
  2665. (cell as? NSCell)?.backgroundStyle = .lowered
  2666. }
  2667. }
  2668. }
  2669. func outlineView(_ outlineView: NSOutlineView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, byItem item: Any?) {
  2670. if outlineView.isEqual(to: self.noteOutlineView) {
  2671. // PDFAnnotation *note = item;
  2672. var note = item as? CPDFAnnotation
  2673. if note == nil && note is KMBOTAAnnotationItem {
  2674. note = (note as? KMBOTAAnnotationItem)?.annotation
  2675. }
  2676. if let data = note?.type, data.isEmpty == false {
  2677. if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2678. let string1 = (object as? String) ?? ""
  2679. let string2 = note?.string() ?? ""
  2680. if string1 != string2 {
  2681. note?.setString(string1)
  2682. }
  2683. } else if tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  2684. let string1 = (object as? String) ?? ""
  2685. let string2 = note?.userName() ?? ""
  2686. if string1 != string2 {
  2687. note?.setUserName(string1)
  2688. }
  2689. }
  2690. }
  2691. }
  2692. }
  2693. func outlineView(_ outlineView: NSOutlineView, dataCellFor tableColumn: NSTableColumn?, item: Any) -> NSCell? {
  2694. if self.noteOutlineView.isEqual(to: outlineView) {
  2695. if tableColumn == nil {
  2696. if let anno = item as? CPDFAnnotation, anno.type == nil {
  2697. return outlineView.tableColumn(withIdentifier: self.noteColumnId)?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  2698. }
  2699. }
  2700. }
  2701. return tableColumn?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  2702. }
  2703. func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool {
  2704. if outlineView.isEqual(to: self.noteOutlineView) {
  2705. if (tableColumn == nil) {
  2706. if self.listView.hideNotes == false {
  2707. if let anno = item as? CPDFAnnotation, anno.isNote() {
  2708. // if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  2709. // PDFAnnotation *annotation = [(SKNoteText *)item note];
  2710. self.listView.scrollAnnotationToVisible(anno)
  2711. self.listView.updateActiveAnnotations([anno])
  2712. // [self showNote:annotation];
  2713. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  2714. // [[noteController window] makeFirstResponder:[noteController textView]];
  2715. // [[noteController textView] selectAll:nil];
  2716. }
  2717. }
  2718. return false
  2719. } else if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue || tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  2720. return true
  2721. }
  2722. }
  2723. return false
  2724. }
  2725. func outlineView(_ outlineView: NSOutlineView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, item: Any, mouseLocation: NSPoint) -> String {
  2726. if outlineView.isEqual(to: self.noteOutlineView) {
  2727. if tableColumn == nil || tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2728. return (item as? CPDFAnnotation)?.string() ?? ""
  2729. }
  2730. }
  2731. return ""
  2732. }
  2733. /*
  2734. #pragma mark NSOutlineView delegate protocol
  2735. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  2736. if ([ov isEqual:rightSideController.noteOutlineView]) {
  2737. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  2738. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  2739. NSMutableArray *sortDescriptors = nil;
  2740. BOOL ascending = YES;
  2741. if ([oldTableColumn isEqual:newTableColumn]) {
  2742. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  2743. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  2744. ascending = [[sortDescriptors firstObject] ascending];
  2745. } else {
  2746. NSString *tcID = [newTableColumn identifier];
  2747. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  2748. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  2749. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  2750. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  2751. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  2752. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  2753. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  2754. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  2755. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2756. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  2757. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2758. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  2759. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  2760. }
  2761. if (oldTableColumn)
  2762. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  2763. [ov setHighlightedTableColumn:newTableColumn];
  2764. }
  2765. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  2766. if (newTableColumn)
  2767. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  2768. inTableColumn:newTableColumn];
  2769. [ov reloadData];
  2770. }
  2771. }
  2772. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  2773. if (mwcFlags.autoResizeNoteRows &&
  2774. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  2775. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  2776. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  2777. [rowHeights removeAllFloats];
  2778. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  2779. }
  2780. }
  2781. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  2782. {
  2783. NSInteger rowCount = [outlineView numberOfRows];
  2784. for (NSInteger i = 0; i < rowCount; i++){
  2785. CGFloat rowHeight = 0;
  2786. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  2787. if (!outline){
  2788. continue;
  2789. }
  2790. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2791. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2792. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  2793. [attributedString appendAttributedString:attr1];
  2794. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  2795. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  2796. // id cell = [tableColumn dataCell];
  2797. id cell = [tableColumn dataCellForRow:i];
  2798. [cell setObjectValue:attributedString];
  2799. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  2800. NSInteger num = [self getNum:outline];
  2801. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  2802. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  2803. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  2804. [rowHeights setFloat:rowHeight forKey:outline];
  2805. if (@available(macOS 10.13, *)) {
  2806. } else {
  2807. rowHeight = 40.0;
  2808. }
  2809. // CGRect fram = viewS.frame;
  2810. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  2811. }
  2812. [leftSideController.tocOutlineView reloadData];
  2813. }
  2814. */
  2815. func noteItems(_ items: NSArray) -> NSArray {
  2816. var noteItems = NSMutableArray()
  2817. for item in items {
  2818. guard let anno = (item as? KMBOTAAnnotationItem)?.annotation else {
  2819. continue
  2820. }
  2821. if anno.type == nil {
  2822. // item = [(SKNoteText *)item note];
  2823. }
  2824. if noteItems.contains(anno) == false {
  2825. noteItems.add(anno)
  2826. }
  2827. }
  2828. return noteItems
  2829. }
  2830. }
  2831. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  2832. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  2833. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  2834. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2835. return self.listView.hideNotes == false && items.count > 0
  2836. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2837. return items.count > 0
  2838. }
  2839. return false
  2840. }
  2841. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  2842. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2843. if (items.isEmpty) {
  2844. return
  2845. }
  2846. for item in self.noteItems(items as NSArray) {
  2847. guard let anno = item as? CPDFAnnotation else {
  2848. continue
  2849. }
  2850. self.listView.remove(anno)
  2851. }
  2852. self.listView.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  2853. self.reloadAnnotation()
  2854. self.annotationSort(sortArray: [])
  2855. self.noteOutlineView.reloadData()
  2856. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2857. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  2858. }
  2859. }
  2860. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  2861. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2862. if (items.count == 1) {
  2863. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  2864. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  2865. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  2866. // return NO;
  2867. // }
  2868. }
  2869. return items.count > 0
  2870. }
  2871. return false
  2872. }
  2873. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  2874. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  2875. let pboard = NSPasteboard.general
  2876. var copiedItems: [Any] = []
  2877. var attrString = NSMutableAttributedString()
  2878. var isAttributed = false
  2879. var item: AnyObject?
  2880. // for (item in [self noteItems:items]) {
  2881. // if ([item isMovable])
  2882. // [copiedItems addObject:item];
  2883. // }
  2884. // for (item in items) {
  2885. // if ([attrString length])
  2886. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  2887. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  2888. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  2889. // isAttributed = YES;
  2890. // } else {
  2891. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  2892. // }
  2893. // }
  2894. //
  2895. // [pboard clearContents];
  2896. // if (isAttributed)
  2897. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  2898. // else
  2899. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  2900. // if ([copiedItems count] > 0)
  2901. // [pboard writeObjects:copiedItems];
  2902. }
  2903. }
  2904. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelperSelectionStrings aTypeSelectHelper: SKTypeSelectHelper) -> NSArray {
  2905. if self.noteOutlineView.isEqual(to: anOutlineView) {
  2906. let count = self.noteOutlineView.numberOfRows
  2907. var texts = NSMutableArray(capacity: count)
  2908. for i in 0 ..< count {
  2909. let item = self.noteOutlineView.item(atRow: i)
  2910. let string = (item as? CPDFAnnotation)?.string() ?? ""
  2911. texts.add(string)
  2912. }
  2913. return texts
  2914. } else if self.tocOutlineView.isEqual(to: anOutlineView) {
  2915. let count = self.tocOutlineView.numberOfRows
  2916. var array = NSMutableArray(capacity: count)
  2917. for i in 0 ..< count {
  2918. // [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  2919. let item = self.tocOutlineView.item(atRow: i) as? CPDFOutline
  2920. array.add(item?.label ?? "")
  2921. }
  2922. return array
  2923. }
  2924. return NSArray()
  2925. }
  2926. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelper aTypeSelectHelper: SKTypeSelectHelper, didFailToFindMatchForSearchString searchString: String) {
  2927. // if ([ov isEqual:rightSideController.noteOutlineView]) {
  2928. // [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  2929. // } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  2930. // [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  2931. // }
  2932. }
  2933. func tableView(_ aTableView: NSTableView, typeSelectHelper aTypeSelectHelper: SKTypeSelectHelper, updateSearchString searchString: String) {
  2934. // if ([typeSelectHelper isEqual:[leftSideController.thumbnailTableView typeSelectHelper]] || [typeSelectHelper isEqual:[pdfView typeSelectHelper]]) {
  2935. // if (searchString)
  2936. // [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  2937. // else
  2938. // [self updateLeftStatus];
  2939. // } else if ([typeSelectHelper isEqual:[rightSideController.noteOutlineView typeSelectHelper]]) {
  2940. // if (searchString)
  2941. // [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding note: \"%@\"", @"Status message"), searchString]];
  2942. // else
  2943. // [self updateRightStatus];
  2944. // } else if ([typeSelectHelper isEqual:[leftSideController.tocOutlineView typeSelectHelper]]) {
  2945. // if (searchString)
  2946. // [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding: \"%@\"", @"Status message"), searchString]];
  2947. // else
  2948. // [self updateLeftStatus];
  2949. // }
  2950. }
  2951. }
  2952. // MARK: - Other
  2953. extension KMLeftSideViewController {
  2954. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  2955. let outlineItem = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow)
  2956. let outline = self.tocOutlineView
  2957. if let cnt = outline?.selectedRowIndexes.count, cnt == 1 {
  2958. if outlineItem is CPDFOutline {
  2959. let outline = (outlineItem as! CPDFOutline)
  2960. if let des = outline.destination {
  2961. self.listView.go(to: des)
  2962. } else if let action = outline.action {
  2963. self.listView.perform(action)
  2964. }
  2965. } else if outlineItem is CPDFBookmark {
  2966. let bookmark = outlineItem as! CPDFBookmark
  2967. self.listView.go(toPageIndex: bookmark.pageIndex, animated: true)
  2968. }
  2969. }
  2970. }
  2971. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  2972. KMPrint("KMLeftSideViewController-goToSelectedFindResults...")
  2973. }
  2974. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  2975. if tv.isEqual(to: self.thumbnailTableView) {
  2976. guard let document = self.listView.document else {
  2977. return
  2978. }
  2979. var pages = NSMutableArray()
  2980. for idx in self.thumbnailTableView.selectedRowIndexes {
  2981. if (idx < document.pageCount) {
  2982. if let page = self.listView.document.page(at: UInt(idx)) {
  2983. pages.add(page)
  2984. }
  2985. }
  2986. }
  2987. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  2988. let saveAccessCtr = KMSavePanelAccessoryController()
  2989. let outputSavePanel = NSSavePanel()
  2990. outputSavePanel.allowedFileTypes = ["pdf"]
  2991. outputSavePanel.accessoryView = saveAccessCtr.view
  2992. outputSavePanel.nameFieldStringValue = fileName
  2993. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  2994. if (result == .OK) {
  2995. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  2996. let vc = KMProgressWindowController()
  2997. self.view.window?.beginSheet(vc.window!)
  2998. let saveFilePath = outputSavePanel.url?.path
  2999. DispatchQueue.global().async {
  3000. let pdf = CPDFDocument()
  3001. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  3002. DispatchQueue.main.async {
  3003. if (success) {
  3004. if (saveAccessCtr.openAutomaticButton.state == .on) {
  3005. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  3006. }
  3007. } else {
  3008. KMTools.viewFile(at: saveFilePath!)
  3009. }
  3010. }
  3011. NSApp.endSheet(vc.window!)
  3012. vc.close()
  3013. }
  3014. }
  3015. }
  3016. }
  3017. }
  3018. }
  3019. }
  3020. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  3021. var pagesName = ""
  3022. if (itemIndexes.count > 1) {
  3023. pagesName.append(" pages")
  3024. } else {
  3025. pagesName.append("page")
  3026. }
  3027. let docmentName = self.listView.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3028. var fileName = ""
  3029. if (itemIndexes.count > 0) {
  3030. if (itemIndexes.count == 1) {
  3031. let idx = itemIndexes.first! + 1
  3032. let tFileName = String(format: "%@ %@", pagesName, "\(idx)")
  3033. return String(format: "%@%@", docmentName, tFileName)
  3034. }
  3035. var sortIndex = IndexSet()
  3036. for idx in itemIndexes {
  3037. let _idx = idx + 1
  3038. sortIndex.insert(_idx)
  3039. }
  3040. // NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
  3041. // NSArray *sortDesc = @[sort];
  3042. // NSArray *sortArray = [sortIndex sortedArrayUsingDescriptors:sortDesc];
  3043. let sortArray = sortIndex.sorted()
  3044. var a = 0
  3045. var b = 0
  3046. for num in sortArray {
  3047. // for (NSNumber *num in sortArray) {
  3048. if (fileName.isEmpty == false) {
  3049. if (num == b+1) {
  3050. b = num
  3051. if (num == sortArray.last) {
  3052. fileName = "\(fileName)\(a)-\(b)"
  3053. }
  3054. } else {
  3055. if (a == b) {
  3056. fileName = "\(fileName)\(a),"
  3057. } else {
  3058. fileName = "\(fileName)\(a)-\(b),"
  3059. }
  3060. b = num
  3061. a = b
  3062. if (num == sortArray.last) {
  3063. fileName = "\(fileName)\(a)"
  3064. }
  3065. }
  3066. } else {
  3067. fileName = ""
  3068. b = num
  3069. a = b
  3070. }
  3071. }
  3072. let tFileName = String(format: "%@ %@", pagesName,fileName)
  3073. return String(format: "%@%@", docmentName,tFileName)
  3074. }
  3075. return ""
  3076. }
  3077. func draggedFileName(for page: CPDFPage) -> String {
  3078. let pageIndex = "\(page.pageIndex() + 1)"
  3079. var fileName = ""
  3080. if let doc = self.view.window?.windowController?.document as? NSDocument {
  3081. fileName = doc.displayName.deletingPathExtension
  3082. }
  3083. return "\(fileName)-Page \(pageIndex)"
  3084. }
  3085. func switchType(_ type: BotaType) {
  3086. if type == .Thumbnail {
  3087. self.leftView.segmentedControl.selectedSegment = 0
  3088. } else if type == .Outline {
  3089. self.leftView.segmentedControl.selectedSegment = 1
  3090. } else if type == .Annotation {
  3091. self.leftView.segmentedControl.selectedSegment = 2
  3092. } else if type == .snapshot {
  3093. self.leftView.segmentedControl.selectedSegment = 3
  3094. } else if type == .Search {
  3095. self.leftView.segmentedControl.selectedSegment = 4
  3096. }
  3097. }
  3098. var TINY_SIZE: Float {
  3099. get {
  3100. return 32.0
  3101. }
  3102. }
  3103. var SMALL_SIZE: Float {
  3104. get {
  3105. return 64.0
  3106. }
  3107. }
  3108. var LARGE_SIZE: Float {
  3109. get {
  3110. return 128.0
  3111. }
  3112. }
  3113. var HUGE_SIZE: Float {
  3114. get {
  3115. return 256.0
  3116. }
  3117. }
  3118. var FUDGE_SIZE: Float {
  3119. get {
  3120. return 0.1
  3121. }
  3122. }
  3123. func updateTableFont() {
  3124. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  3125. self.tocOutlineView.font = font
  3126. self.noteOutlineView.font = font
  3127. self.findTableView.font = font
  3128. self.groupedFindTableView.font = font
  3129. }
  3130. }