KMLeftSideViewController.swift 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074
  1. //
  2. // KMLeftSideViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. @objc protocol KMLeftSideViewControllerDelegate {
  9. @objc optional func controlStateChange(_ obj: KMLeftSideViewController,show:Bool)
  10. @objc optional func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int])
  11. @objc optional func searchAction(searchString:String, isCase:Bool)
  12. @objc optional func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType)
  13. @objc optional func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  14. @objc optional func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem])
  15. @objc optional func controller(controller: KMLeftSideViewController, rotateType: KMRotateType)
  16. @objc optional func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?)
  17. }
  18. extension KMLeftSideViewController.Key {
  19. static let disableTableToolTipsKey = "SKDisableTableToolTips"
  20. }
  21. class KMLeftSideViewController: KMSideViewController {
  22. @IBOutlet var segmentedControl: KMSegmentedControl!
  23. @IBOutlet var thumbnailTableView: KMThumbnailTableView!
  24. @IBOutlet var tocOutlineView: KMTocOutlineView!
  25. @IBOutlet var noteOutlineView: KMNoteOutlineView!
  26. @IBOutlet var findTableView: KMBotaTableView!
  27. @IBOutlet var groupedFindTableView: KMBotaTableView!
  28. @IBOutlet var snapshotTableView: KMBotaTableView!
  29. @IBOutlet weak var leftListView: NSView!
  30. @IBOutlet var searchViewController: KMBotaSearchViewController!
  31. @IBOutlet weak var toolButtonBox: NSBox!
  32. @IBOutlet weak var toolButtonBoxLayoutConstraint: NSLayoutConstraint!
  33. @IBOutlet weak var snapshotNormalView: NSView!
  34. @IBOutlet weak var snapshotLabel: NSTextField!
  35. @IBOutlet weak var snapshotNormalMoreButton: NSButton!
  36. @IBOutlet weak var snapshotNormalSearchButton: NSButton!
  37. @IBOutlet weak var snapshotNormalZoomOutButton: NSButton!
  38. @IBOutlet weak var snapshotNormalZoomInButton: NSButton!
  39. @IBOutlet weak var snapshotSearchZoomOutButton: NSButton!
  40. @IBOutlet weak var snapshotSearchZoomInButton: NSButton!
  41. @IBOutlet weak var snapshotSearchField: KMLeftSideViewSearchField!
  42. @IBOutlet weak var snapshotDoneButton: NSButton!
  43. @IBOutlet weak var outlineView: NSView!
  44. @IBOutlet weak var outlineMoreButton: NSButton!
  45. @IBOutlet weak var outlineAddButton: NSButton!
  46. @IBOutlet weak var outlineSearchButton: NSButton!
  47. @IBOutlet weak var outlineLabel: NSTextField!
  48. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  49. @IBOutlet weak var outlineDoneButton: NSButton!
  50. @IBOutlet weak var noteView: NSView!
  51. @IBOutlet weak var noteMoreButton: NSButton!
  52. @IBOutlet weak var noteFilterButton: NSButton!
  53. @IBOutlet weak var noteSearchButton: NSButton!
  54. @IBOutlet weak var noteSearchField: KMLeftSideViewSearchField!
  55. @IBOutlet weak var noteTitleLabel: NSTextField!
  56. @IBOutlet weak var noteHeaderView: NSView!
  57. @IBOutlet weak var sortTypeBox: KMBox!
  58. @IBOutlet weak var sortTypeLabel: NSTextField!
  59. @IBOutlet weak var noteSortButton: NSButton!
  60. @IBOutlet weak var noteDoneButton: NSButton!
  61. @IBOutlet weak var thumbnailView: NSView!
  62. @IBOutlet weak var thumbnailZoomOutButton: NSButton!
  63. @IBOutlet weak var thumbnailZoomInButton: NSButton!
  64. @IBOutlet weak var thumbnailTitleLabel: NSTextField!
  65. @IBOutlet weak var emptySearchBox: NSBox!
  66. @IBOutlet weak var emptySearchLabel: NSTextField!
  67. var bookmarkViewC: KMBookMarkViewController?
  68. var noteFilterButtonHoverView = KMHoverView()
  69. var noteFilterSelected = false
  70. var stopRepeatLoad: Bool = false
  71. lazy var leftSideEmptyVC: KMLeftSideEmptyFileViewController = {
  72. let vc = KMLeftSideEmptyFileViewController(nibName: "KMLeftSideEmptyFileViewController", bundle: nil)
  73. vc.view.wantsLayer = true
  74. return vc
  75. }()
  76. lazy var leftView: KMBotaLeftView = {
  77. let view = KMBotaLeftView()
  78. return view
  79. }()
  80. static let kMinSidePaneWidth: CGFloat = 270
  81. static let kTinySize: Float = 32.0
  82. static let kSmallSize: Float = 64.0
  83. static let kLargeSize: Float = 128.0
  84. static let kHugeSize: Float = 256.0
  85. static let kFudgeSize: Float = 0.1
  86. static let kOutlineRootBookmarkItem = "Bookmarks"
  87. var isFirst = false //打开阅读页初始化
  88. var type : KMLeftMethodMode = KMLeftMethodMode()
  89. var isShowPanel : Bool = false
  90. weak var delegate: KMLeftSideViewControllerDelegate?
  91. let noteColumnId = NSUserInterfaceItemIdentifier(rawValue: "note")
  92. let authorColumnId = NSUserInterfaceItemIdentifier(rawValue: "author")
  93. struct Key {}
  94. var mwcFlags: MwcFlags = MwcFlags()
  95. let scalingIncrement: Float = 0.1
  96. var filterButtonLayer: NSView?
  97. var moreButtonLayer: KMButtonLayer?
  98. // 缩略图
  99. var thumbnails: [KMThumbnail] = []
  100. var isDisplayPageSize = false
  101. var thumbnailCacheSize: CGFloat = 32 * 3
  102. var updatingThumbnailSelection = false
  103. // 大纲
  104. var isSearchOutlineMode = false
  105. var outlineIgnoreCaseFlag = false
  106. var tocType: KMFoldType = .none
  107. var renamePDFOutline: CPDFOutline?
  108. var renamePDFOutlineTextField: NSTextField?
  109. private var _dragPDFOutline: CPDFOutline?
  110. var updatingOutlineSelection = false
  111. // 注释
  112. var noteTypeDict: [String : Any] = [:]
  113. private var _noteSortType: KMNoteSortType = .none
  114. var noteSortType: KMNoteSortType {
  115. get {
  116. return self._noteSortType
  117. }
  118. set {
  119. self._noteSortType = newValue
  120. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  121. }
  122. }
  123. var isAscendSort = false {
  124. didSet {
  125. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  126. }
  127. }
  128. var isRenameNoteOutline = false
  129. // 所有注释
  130. var allAnnotations: [CPDFAnnotation] = []
  131. // 注释搜索模式标记
  132. var noteSearchMode = false
  133. // 注释搜索数组
  134. var noteSearchArray: [KMBotaAnnotationBaseModel] = []
  135. // 注释搜索 忽略大小写标识
  136. var caseInsensitiveNoteSearch = false
  137. // 注释列表数据源
  138. var annoListModel: KMAnnotationListModel?
  139. var editNoteTextField: NSTextField?
  140. weak var editNote: CPDFAnnotation?
  141. // 快照
  142. var snapshotCacheSize: CGFloat = 32 * 3
  143. var isSearchSnapshotMode = false
  144. var snapshots: [KMSnapshotModel] = []
  145. var dirtySnapshots: [KMSnapshotWindowController] = []
  146. var searchSnapshots: [KMSnapshotModel] = []
  147. var dataUpdating = false
  148. // 搜索
  149. private var _findState: KMFindState = .none
  150. var findState: KMFindState {
  151. get {
  152. return self._findState
  153. }
  154. set {
  155. if self._findState != newValue {
  156. self._findState = newValue
  157. self.displayFindState()
  158. if self._findState == .content {
  159. self.search(self.searchField)
  160. } else if self.findState == .note {
  161. self.searchNotes(nil)
  162. } else if self.findState == .snapshot {
  163. self.searchNotes(self.searchField)
  164. }
  165. }
  166. }
  167. }
  168. var searchResults : [KMSearchMode] = [] {
  169. didSet {
  170. self.updataLeftSideFindView()
  171. }
  172. }
  173. var groupSearchResults: [KMSearchMode] = []
  174. var findPaneState: KMFindPaneState = .singular
  175. var searchResultIndex: Int = 0
  176. var leftMargin: CGFloat = 0
  177. private var _copysPages: [CPDFPage] = []
  178. var copyPages: [CPDFPage] {
  179. get {
  180. return self._copysPages
  181. }
  182. }
  183. var dragIn = false
  184. let model = KMBotaModel()
  185. private let KPDFThumbnailDoucumentURLForDraggedTypes = NSPasteboard.PasteboardType("KPDFThumbnailDoucumentURLForDraggedTypes")
  186. private var deletePages_ = Set<CPDFPage>()
  187. let userFbHanddler = KMUserFeekbackHanddler()
  188. let noteReplyHanddler = KMNoteReplyHanddler()
  189. deinit {
  190. KMPrint("KMLeftSideViewController deinit.")
  191. NotificationCenter.default.removeObserver(self)
  192. DistributedNotificationCenter.default().removeObserver(self)
  193. }
  194. override var nibName: NSNib.Name? {
  195. return "LeftSideView"
  196. }
  197. convenience init(type : KMLeftMethodMode) {
  198. self.init()
  199. self.type = type
  200. }
  201. override func viewDidLoad() {
  202. super.viewDidLoad()
  203. self.noteReplyHanddler.viewC = self
  204. self.reloadThumbnailSize()
  205. self.reloadSnapshotSize()
  206. }
  207. func showPanelView(show: Bool) {
  208. self.isShowPanel = show
  209. if show {
  210. self.leftView.segmentedControl.selectedSegment = 1
  211. } else {
  212. self.leftView.segmentedControl.selectedSegment = UInt8.max
  213. self.type.methodType = .None
  214. self.delegate?.controlStateChange?(self, show: false)
  215. }
  216. }
  217. func refreshMethodType(methodType: BotaType) {
  218. let newType = KMLeftMethodMode()
  219. var show = true
  220. if self.type.methodType != methodType {
  221. newType.methodType = methodType
  222. }
  223. if self.type.methodType == methodType {
  224. show = false
  225. } else if methodType == .None {
  226. show = false
  227. }
  228. self.type = newType;
  229. self.delegate?.controlStateChange?(self,show:show)
  230. }
  231. override func loadView() {
  232. super.loadView()
  233. self.initSubView()
  234. self.initDefalutValue()
  235. self.searchViewController.loadView()
  236. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  237. self.searchField = self.searchViewController.searchField
  238. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  239. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  240. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  241. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  242. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  243. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  244. self.searchViewController.segmentedControl.selectedSegment = 0
  245. self.searchViewController.segmentedControl.block = { [weak self] segIndex in
  246. if segIndex == 0 {
  247. self?.findPaneState = .singular
  248. self?.displayFindViewAnimating(false)
  249. } else {
  250. self?.findPaneState = .grouped
  251. self?.displayGroupedFindViewAnimating(false)
  252. }
  253. }
  254. self.leftView.helpButton.coverAction = { [weak self] button, action in
  255. if action == .enter {
  256. let hasEnterPageEdit = self?.mainViewController?.hasEnterPageEdit() ?? false
  257. if hasEnterPageEdit {
  258. return
  259. }
  260. let hasEnterRedact = self?.mainViewController?.hasEnterRedact() ?? false
  261. if hasEnterRedact {
  262. return
  263. }
  264. self?.userFbHanddler.showUserFbPopView(sender: button)
  265. }
  266. }
  267. self.leftView.itemClick = { [unowned self] itemV, idx in
  268. if idx == 1 { // TTS
  269. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_TTS"])
  270. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .tts, params: nil)
  271. } else if idx == 2 {
  272. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .newUserGuide, params: nil)
  273. }
  274. }
  275. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  276. if (segIndex == 1) {
  277. if self.type.methodType == .Thumbnail {
  278. self.leftView.segmentedControl.selectedSegment = UInt8.max
  279. self.refreshMethodType(methodType: .None)
  280. return
  281. }
  282. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Thumbnail"])
  283. self.refreshMethodType(methodType: .Thumbnail)
  284. KMMainThreadExecute {
  285. self.toolButtonBox.isHidden = false
  286. self.toolButtonBoxLayoutConstraint.constant = 40.0
  287. self.toolButtonBox.contentView = self.thumbnailView
  288. self.displayThumbnailViewAnimating(false)
  289. }
  290. } else if (segIndex == 2) {
  291. if self.type.methodType == .Outline {
  292. self.leftView.segmentedControl.selectedSegment = UInt8.max
  293. self.refreshMethodType(methodType: .None)
  294. return
  295. }
  296. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Outline"])
  297. self.refreshMethodType(methodType: .Outline)
  298. DispatchQueue.main.async {
  299. self.toolButtonBox.isHidden = false
  300. self.toolButtonBoxLayoutConstraint.constant = 40.0
  301. self.toolButtonBox.contentView = self.outlineView
  302. self.bookmarkViewC?.view.isHidden = true
  303. self.displayTocViewAnimating(false)
  304. }
  305. } else if (segIndex == 3) {
  306. if self.type.methodType == .Annotation {
  307. self.leftView.segmentedControl.selectedSegment = UInt8.max
  308. self.refreshMethodType(methodType: .None)
  309. return
  310. }
  311. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Annotation"])
  312. self.refreshMethodType(methodType: .Annotation)
  313. DispatchQueue.main.async {
  314. self.toolButtonBox.contentView = self.noteView
  315. self.toolButtonBox.isHidden = false
  316. self.toolButtonBoxLayoutConstraint.constant = 40.0
  317. self.bookmarkViewC?.view.isHidden = true
  318. self.displayNoteViewAnimating(false)
  319. }
  320. } else if (segIndex == 4) {
  321. if self.type.methodType == .BookMark {
  322. self.leftView.segmentedControl.selectedSegment = UInt8.max
  323. self.refreshMethodType(methodType: .None)
  324. return
  325. }
  326. // FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Snapshot"])
  327. self.refreshMethodType(methodType: .BookMark)
  328. KMMainThreadExecute {
  329. // DispatchQueue.main.async {
  330. self.toolButtonBox.isHidden = true
  331. self.toolButtonBox.contentView = nil
  332. self.toolButtonBoxLayoutConstraint.constant = 0
  333. self.displayBookmarkController()
  334. }
  335. } else if (segIndex == 5) {
  336. if self.type.methodType == .snapshot {
  337. self.leftView.segmentedControl.selectedSegment = UInt8.max
  338. self.refreshMethodType(methodType: .None)
  339. return
  340. }
  341. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Snapshot"])
  342. self.refreshMethodType(methodType: .snapshot)
  343. self.toolButtonBox.contentView = self.snapshotNormalView
  344. self.toolButtonBox.isHidden = false
  345. self.toolButtonBoxLayoutConstraint.constant = 40.0
  346. self.updateSnapshotFilterPredicate()
  347. self.displaySnapshotViewAnimating(false)
  348. self.updataLeftSideSnapView()
  349. } else if (segIndex == 0) {
  350. if self.type.methodType == .Search {
  351. self.leftView.segmentedControl.selectedSegment = UInt8.max
  352. self.refreshMethodType(methodType: .None)
  353. return
  354. }
  355. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Search"])
  356. self.refreshMethodType(methodType: .Search)
  357. DispatchQueue.main.async {
  358. self.toolButtonBox.isHidden = true
  359. self.toolButtonBox.contentView = nil
  360. self.toolButtonBoxLayoutConstraint.constant = 0
  361. self.bookmarkViewC?.view.isHidden = true
  362. self.displayFindViewAnimating(false)
  363. }
  364. }
  365. }
  366. let menu = NSMenu()
  367. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  368. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  369. (self.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  370. (self.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  371. self.searchField.action = #selector(search)
  372. self.searchField.target = self
  373. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  374. // //支持拖拽的文字类型
  375. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  376. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  377. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  378. if KMDataManager.ud_bool(forKey: Self.Key.disableTableToolTipsKey) == false {
  379. self.tocOutlineView.hasImageToolTips = true
  380. self.findTableView.hasImageToolTips = true
  381. self.groupedFindTableView.hasImageToolTips = true
  382. }
  383. self._updateViewColor()
  384. }
  385. func initSubView() {
  386. self.view.addSubview(self.leftView)
  387. // 阿拉伯语言需要设置布局
  388. // self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  389. // self.leftView.autoresizingMask = [.height]
  390. self.leftView.km_add_leading_constraint()
  391. self.leftView.km_add_top_constraint()
  392. self.leftView.km_add_height_constraint(equalTo: self.view)
  393. self.leftView.km_add_width_constraint(constant: 44)
  394. self.thumb_initSubViews()
  395. self.outline_initSubViews()
  396. self.note_initSubViews()
  397. self.snapshot_initSubViews()
  398. self.search_initSubViews()
  399. }
  400. func initDefalutValue() {
  401. self.view.wantsLayer = true
  402. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  403. self.leftView.wantsLayer = true
  404. self.leftView.layer?.backgroundColor = .white
  405. self.leftListView.wantsLayer = true
  406. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  407. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  408. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  409. self.emptySearchBox.isHidden = true
  410. self.thumb_initDefalutValue()
  411. self.outline_initDefalutValue()
  412. self.note_initDefalutValue()
  413. self.snapshot_initDefalutValue()
  414. self.search_initDefalutValue()
  415. }
  416. func displayThumbnailViewAnimating(_ animate: Bool) {
  417. self.bookmarkViewC?.view.isHidden = true
  418. if let enclosingScrollView = self.thumbnailTableView.enclosingScrollView {
  419. self.replaceSideView(enclosingScrollView, animate: animate)
  420. }
  421. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  422. frame.origin.y = 0
  423. frame.origin.x = self.leftMargin
  424. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  425. self.thumbnailTableView.enclosingScrollView?.frame = frame
  426. self.resetThumbnails()
  427. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  428. frame.origin.y = 0
  429. frame.origin.x = self.leftMargin
  430. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  431. self.noteOutlineView.enclosingScrollView?.frame = frame
  432. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  433. frame.origin.y = 0
  434. frame.origin.x = self.leftMargin
  435. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  436. self.snapshotTableView.enclosingScrollView?.frame = frame
  437. self.updateThumbnailSelection()
  438. }
  439. func displayFindViewAnimating(_ animate: Bool) {
  440. self.replaceSideView(self.searchViewController.view, animate: animate)
  441. if (self.findState != .content) {
  442. self.findState = .content
  443. } else {
  444. self.displayFindState()
  445. }
  446. var frame = self.searchViewController.view.frame
  447. frame.origin.y = 0
  448. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  449. self.searchViewController.view.frame = frame
  450. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  451. frame.origin.y = 0
  452. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  453. self.noteOutlineView.enclosingScrollView?.frame = frame
  454. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  455. frame.origin.y = 0
  456. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  457. self.snapshotTableView.enclosingScrollView?.frame = frame
  458. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  459. self.updataLeftSideSnapView()
  460. }
  461. func displayFindState() {
  462. if (self.findState == .content) {
  463. self.displayFind()
  464. } else if (self.findState == .note) {
  465. self.displayNoteFind()
  466. } else if (self.findState == .snapshot) {
  467. self.displaySnapshotFind()
  468. }
  469. }
  470. func updataLeftSideFindView() {
  471. if (self.findState != .content) {
  472. return
  473. }
  474. if (self.searchResults.count > 0) {
  475. self.searchViewController.emptyBox.isHidden = true
  476. self.searchViewController.searchResultsView.isHidden = false
  477. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  478. } else {
  479. self.searchViewController.emptyBox.isHidden = false
  480. self.searchViewController.searchResultsView.isHidden = true
  481. }
  482. }
  483. func displayGroupedFindViewAnimating(_ animate: Bool) {
  484. self.replaceSideView(self.searchViewController.view , animate: animate)
  485. if (self.findState != .content) {
  486. self.findState = .content
  487. } else {
  488. self.displayFindState()
  489. }
  490. var frame = self.searchViewController.view.frame
  491. frame.origin.y = 0
  492. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  493. self.searchViewController.view.frame = frame
  494. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  495. frame.origin.y = 0
  496. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  497. self.noteOutlineView.enclosingScrollView?.frame = frame
  498. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  499. frame.origin.y = 0
  500. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  501. self.snapshotTableView.enclosingScrollView?.frame = frame
  502. self.updataLeftSideSnapView()
  503. }
  504. func displayNoteViewAnimating(_ animate: Bool) {
  505. self.searchViewController.contentView = nil
  506. if let data = self.noteOutlineView.enclosingScrollView {
  507. self.replaceSideView(data, animate: animate)
  508. }
  509. if (self.findState != .note) {
  510. self.findState = .note
  511. } else {
  512. self.displayFindState()
  513. }
  514. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  515. frame.origin.y = 0
  516. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  517. self.noteOutlineView.enclosingScrollView?.frame = frame
  518. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  519. frame.origin.y = 0
  520. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  521. self.snapshotTableView.enclosingScrollView?.frame = frame
  522. let view = self.noteOutlineView.enclosingScrollView
  523. let viewFrame = view?.frame ?? .zero
  524. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  525. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  526. self.reloadAnnotation()
  527. }
  528. func displayBookmarkController() {
  529. if self.bookmarkViewC == nil {
  530. let viewC = KMBookMarkViewController(nibName: "KMBookMarkViewController", bundle: nil)
  531. self.bookmarkViewC = viewC
  532. self.bookmarkViewC?.listView = self.listView
  533. }
  534. if let view = self.bookmarkViewC?.view {
  535. self.bookmarkViewC?.view.isHidden = false
  536. self.bookmarkViewC?.listView = self.listView
  537. self.replaceSideView(view, animate: false)
  538. self.bookmarkViewC?.reloadData()
  539. }
  540. }
  541. func displaySnapshotViewAnimating(_ animate: Bool) {
  542. self.searchViewController.contentView = nil
  543. self.bookmarkViewC?.view.isHidden = true
  544. if let data = self.snapshotTableView.enclosingScrollView {
  545. self.replaceSideView(data, animate: animate)
  546. }
  547. if (self.findState != .snapshot) {
  548. self.findState = .snapshot
  549. } else {
  550. self.displayFindState()
  551. }
  552. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  553. frame.origin.y = 0
  554. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  555. self.snapshotTableView.enclosingScrollView?.frame = frame
  556. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  557. frame.origin.y = 0
  558. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  559. self.noteOutlineView.enclosingScrollView?.frame = frame
  560. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  561. frame.origin.y = 0
  562. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  563. self.tocOutlineView.enclosingScrollView?.frame = frame
  564. Task { @MainActor in
  565. self.snapshotTableView.reloadData()
  566. }
  567. }
  568. func displayFind() {
  569. self.searchField = self.searchViewController.searchField
  570. let menu = NSMenu()
  571. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  572. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  573. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  574. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  575. self.searchViewController.searchField.action = #selector(search)
  576. self.searchViewController.searchField.target = self
  577. if (self.findPaneState == .singular) {
  578. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  579. self.findTableView.wantsLayer = true
  580. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  581. DispatchQueue.main.async {
  582. self.findTableView.reloadData()
  583. }
  584. } else if (self.findPaneState == .grouped) {
  585. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  586. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  587. array.sort(){$0.datas.count > $1.datas.count}
  588. self.groupSearchResults = array
  589. self.groupedFindTableView.reloadData()
  590. }
  591. }
  592. func displayTocViewAnimating(_ animate: Bool) {
  593. if Thread.current.isMainThread {
  594. self.tocOutlineView.reloadData()
  595. } else {
  596. Task { @MainActor in
  597. self.tocOutlineView.reloadData()
  598. }
  599. }
  600. if let data = self.tocOutlineView.enclosingScrollView {
  601. self.replaceSideView(data, animate: animate)
  602. }
  603. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  604. frame.origin.y = 0
  605. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  606. self.tocOutlineView.enclosingScrollView?.frame = frame
  607. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  608. frame.origin.y = 0
  609. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  610. self.noteOutlineView.enclosingScrollView?.frame = frame
  611. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  612. frame.origin.y = 0
  613. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  614. self.snapshotTableView.enclosingScrollView?.frame = frame
  615. let view = self.tocOutlineView.enclosingScrollView
  616. let viewFrame = view?.frame ?? .zero
  617. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  618. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  619. DispatchQueue.main.async {
  620. self.tocOutlineView.reloadData()
  621. self.updateOutlineSelection()
  622. }
  623. }
  624. func displayNoteFind() {
  625. self.searchField = self.noteSearchField
  626. let menu = NSMenu()
  627. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  628. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  629. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  630. self.noteSearchField.action = #selector(searchNotes)
  631. self.noteSearchField.target = self
  632. }
  633. func displaySnapshotFind() {
  634. self.searchField = self.snapshotSearchField;
  635. let menu = NSMenu()
  636. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  637. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  638. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  639. self.snapshotSearchField.action = #selector(searchNotes)
  640. self.snapshotSearchField.target = self
  641. self.snapshotSearchField.delegate = self
  642. }
  643. func resetThumbnails(ks: Bool = true) {
  644. self.thumbnails.removeAll()
  645. KMThumbnailCache.shared.clearCache()
  646. let pageLabels = self.pdfDocument()?.pageLabels() ?? []
  647. if (pageLabels.isEmpty == false) {
  648. for (i, label) in pageLabels.enumerated() {
  649. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  650. thumbnail.dirty = true
  651. self.thumbnails.append(thumbnail)
  652. }
  653. }
  654. KMMainThreadExecute {
  655. let ris = self.thumbnailTableView.selectedRowIndexes
  656. self.thumbnailTableView.reloadData()
  657. if ks {
  658. self.thumbnailTableView.km_safe_selectRowIndexes(ris, byExtendingSelection: false)
  659. }
  660. }
  661. }
  662. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  663. let button = sender as? NSButton
  664. let tag = button?.tag ?? 0
  665. if (tag == 310) {
  666. self.outlineSearchField.isHidden = true
  667. self.outlineDoneButton.isHidden = true
  668. self.outlineLabel.isHidden = false
  669. self.outlineSearchButton.isHidden = false
  670. self.outlineMoreButton.isHidden = false
  671. self.outlineAddButton.isHidden = false
  672. } else if (tag == 311) {
  673. self.noteSearchField.isHidden = true
  674. self.noteTitleLabel.isHidden = false
  675. self.noteSearchButton.isHidden = false
  676. self.noteDoneButton.isHidden = true
  677. self.noteFilterButton.isHidden = false
  678. self.noteMoreButton.isHidden = false
  679. self.noteFilterButtonHoverView.isHidden = false
  680. } else if (tag == 312) {
  681. self.snapshotSearchField.isHidden = true
  682. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  683. self.snapshotNormalSearchButton.isHidden = false
  684. self.snapshotDoneButton.isHidden = true
  685. self.snapshotLabel.isHidden = false
  686. self.snapshotNormalZoomOutButton.isHidden = false
  687. self.snapshotNormalZoomInButton.isHidden = false
  688. }
  689. }
  690. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  691. let tag = sender.tag
  692. if (tag == 0 || tag == 1) {
  693. var scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  694. if (scaling <= 0) {
  695. scaling = 1
  696. }
  697. if (tag == 0) { // Zoom In
  698. scaling += self.scalingIncrement
  699. } else if (tag == 1) { // Zoom Out
  700. scaling -= self.scalingIncrement
  701. if scaling <= 0.4 {
  702. return
  703. }
  704. }
  705. KMDataManager.ud_set(scaling, forKey: Self.Key.thumbSizeScaling)
  706. let selectRow = self.thumbnailTableView.selectedRow
  707. self.thumbnailTableView.reloadData()
  708. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  709. } else if (tag == 2 || tag == 3) {
  710. var scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  711. if (scaling <= 0) {
  712. scaling = 1
  713. }
  714. if (tag == 2) { // Zoom In
  715. scaling += self.scalingIncrement
  716. } else if (tag == 3) { // Zoom Out
  717. scaling -= self.scalingIncrement
  718. }
  719. KMDataManager.ud_set(scaling, forKey: Self.Key.snapshotSizeScaling)
  720. let selectRow = self.snapshotTableView.selectedRow
  721. self.snapshotTableView.reloadData()
  722. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  723. }
  724. }
  725. func tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  726. if tv.isEqual(to: self.thumbnailTableView) {
  727. self._copysPages.removeAll()
  728. for idx in rowIndexes {
  729. if (idx != NSNotFound) {
  730. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  731. self._copysPages.append(page)
  732. }
  733. }
  734. }
  735. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  736. }
  737. }
  738. }
  739. // MARK: - KMBotaTableViewDelegate
  740. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  741. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  742. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  743. return rowIndexes.count > 0
  744. }
  745. return false
  746. }
  747. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  748. if aTableView.isEqual(to: self.thumbnailTableView) {
  749. if self._copysPages.count > 0 {
  750. return true
  751. }
  752. }
  753. return false
  754. }
  755. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  756. if aTableView.isEqual(to: self.snapshotTableView) {
  757. return rowIndexes.count > 0
  758. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  759. if self.pageCount() <= 1 {
  760. return false
  761. }
  762. return true
  763. }
  764. return false
  765. }
  766. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  767. if KMMemberInfo.shared.isMemberAllFunction == false {
  768. KMMemberInfo.shared.advancedFunctionUsage(type: .pdfEdit)
  769. return
  770. }
  771. if aTableView.isEqual(to: self.thumbnailTableView) {
  772. if self._copysPages.count > 0 {
  773. let index = self.currentPageIndex()
  774. if (index == NSNotFound) {
  775. return
  776. }
  777. let idx = index + 1
  778. for page in self._copysPages.reversed() {
  779. self.pdfDocument()?.insertPageObject(page, at: UInt(idx))
  780. self.layoutDocumentView()
  781. self.resetThumbnails()
  782. let pageIndex = min(idx, self.pageCount()-1)
  783. self.listView?.go(toPageIndex: Int(pageIndex), animated: true)
  784. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  785. }
  786. }
  787. }
  788. }
  789. func tableViewMoveLeft(_ aTableView: NSTableView) {
  790. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  791. self.updateFindResultHighlightsForDirection(.selectingPrevious)
  792. }
  793. }
  794. func tableViewMoveRight(_ aTableView: NSTableView) {
  795. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  796. self.updateFindResultHighlightsForDirection(.selectingNext)
  797. }
  798. }
  799. func tableViewMoveUp(_ aTableView: NSTableView) {
  800. if aTableView.isEqual(to: self.findTableView) {
  801. self.findTableView.km_safe_selectRowIndexes(.init(integer: self.findTableView.selectedRow-1), byExtendingSelection: false)
  802. self.findTableView.scrollRowToVisible(self.findTableView.selectedRow)
  803. }
  804. }
  805. func tableViewMoveDown(_ aTableView: NSTableView) {
  806. if aTableView.isEqual(to: self.findTableView) {
  807. self.findTableView.km_safe_selectRowIndexes(.init(integer: self.findTableView.selectedRow+1), byExtendingSelection: false)
  808. self.findTableView.scrollRowToVisible(self.findTableView.selectedRow)
  809. }
  810. }
  811. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  812. if aTableView.isEqual(to: self.findTableView) {
  813. if rowIndex >= self.searchResults.count {
  814. return nil
  815. }
  816. let model = self.searchResults[rowIndex]
  817. let selection = model.selection
  818. let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
  819. let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
  820. let point = NSPoint(x: x, y: y)
  821. return CPDFDestination(document: self.pdfDocument(), pageIndex: Int(model.selectionPageIndex), at: point, zoom: self.scaleFactor().cgFloat)
  822. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  823. if rowIndex >= self.groupSearchResults.count {
  824. return nil
  825. }
  826. // let model = self.groupSearchResults[rowIndex]
  827. // let selection = model.selection
  828. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  829. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  830. }
  831. return nil
  832. }
  833. }
  834. // MARK: - 扩展
  835. extension KMLeftSideViewController {
  836. public func selectType(_ type: BotaType) {
  837. // 更新 type
  838. var show = true
  839. if (self.type.methodType == .None) {
  840. show = true
  841. } else {
  842. if (self.type.methodType == type) {
  843. show = false
  844. } else {
  845. show = true
  846. }
  847. }
  848. self.type = self.getMethodMode(show ? type : .None)
  849. // 将事件传递出去
  850. self.delegate?.controlStateChange?(self,show:show)
  851. }
  852. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  853. let mode = KMLeftMethodMode()
  854. mode.methodType = type
  855. switch type {
  856. case .None:
  857. mode.methodName = ""
  858. break
  859. case .Thumbnail:
  860. mode.methodName = thumbnailMethodKey
  861. break
  862. case .Outline:
  863. mode.methodName = outlineMethodKey
  864. break
  865. case .BookMark:
  866. mode.methodName = bookMarkMethodKey
  867. break
  868. case .Annotation:
  869. mode.methodName = anntationMethodKey
  870. break
  871. case .Search:
  872. mode.methodName = searchMethodKey
  873. break
  874. case .From:
  875. mode.methodName = formMethodKey
  876. break
  877. case .Signature:
  878. mode.methodName = signatureMethodKey
  879. break
  880. case .snapshot:
  881. mode.methodName = snapshotMethodKey
  882. }
  883. return mode
  884. }
  885. }
  886. //MARK: Cache
  887. extension KMLeftSideViewController {
  888. func clearNotification() {}
  889. }
  890. // MARK: - Private Methods
  891. extension KMLeftSideViewController {
  892. func updateViewColor() {
  893. self._updateViewColor()
  894. }
  895. private func _updateViewColor() {
  896. if(KMAppearance.isDarkMode()){
  897. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  898. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  899. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  900. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  901. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  902. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  903. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  904. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  905. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  906. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  907. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  908. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  909. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  910. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  911. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  912. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  913. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  914. } else {
  915. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  916. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  917. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  918. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  919. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  920. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  921. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  922. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  923. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  924. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  925. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  926. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  927. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  928. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  929. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  930. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  931. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  932. }
  933. }
  934. func hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  935. var label = outline.label ?? ""
  936. var searchLabel = searchString
  937. if self.outlineIgnoreCaseFlag {
  938. label = label.lowercased()
  939. searchLabel = searchLabel.lowercased()
  940. }
  941. if label.contains(searchLabel) {
  942. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  943. return true
  944. } else {
  945. var subHas = false
  946. for i in 0 ..< outline.numberOfChildren {
  947. if let subOutline = outline.child(at: i) {
  948. subHas = self.hasContainString(searchString, rootOutline: subOutline)
  949. } else {
  950. continue
  951. }
  952. if (subHas) {
  953. break
  954. }
  955. }
  956. return subHas
  957. }
  958. }
  959. }
  960. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  961. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  962. func numberOfRows(in tableView: NSTableView) -> Int {
  963. if tableView.isEqual(to: self.thumbnailTableView) {
  964. return self.thumbnails.count
  965. } else if tableView.isEqual(to: self.findTableView) {
  966. return self.searchResults.count
  967. } else if tableView.isEqual(to: self.groupedFindTableView) {
  968. return self.groupSearchResults.count
  969. } else if tableView.isEqual(to: self.snapshotTableView) {
  970. if self.isSearchSnapshotMode {
  971. return self.searchSnapshots.count
  972. }
  973. return self.snapshots.count
  974. }
  975. return 0
  976. }
  977. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  978. if tableView.isEqual(to: self.thumbnailTableView) {
  979. let cell = tableView.makeView(withIdentifier: KMThumbnailTableviewCell.km_identifier, owner: self) as! KMThumbnailTableviewCell
  980. if self.thumbnails.count > row {
  981. let thumbnail = self.thumbnails[row]
  982. let page = self.pdfDocument()?.page(at: UInt(row))
  983. cell.pageNumLabel.stringValue = thumbnail.label
  984. cell.pageView.isThumb = true
  985. cell.pageView.page = page
  986. let bks = self.listView?.document.bookmarks()
  987. var hasBookmark = false
  988. for bk in bks ?? [] {
  989. if row == bk.pageIndex {
  990. hasBookmark = true
  991. break
  992. }
  993. }
  994. cell.bkIcon.isHidden = !hasBookmark
  995. if (self.isDisplayPageSize) {
  996. cell.sizeLabel.isHidden = false
  997. //获取Page的真实尺寸
  998. let rect = page?.bounds(for: .cropBox) ?? .zero
  999. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (NSWidth(rect)/595 * 210))
  1000. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (NSHeight(rect)/842 * 297))
  1001. if let data = page?.rotation, data == 90 || data == 270 {
  1002. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  1003. } else {
  1004. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  1005. }
  1006. } else {
  1007. cell.sizeLabel.stringValue = "0 mm"
  1008. cell.sizeLabel.isHidden = true
  1009. }
  1010. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  1011. if (self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  1012. cell.isSelectCell = true
  1013. } else {
  1014. cell.isSelectCell = false
  1015. }
  1016. }
  1017. return cell
  1018. } else if (tableView.isEqual(to: self.findTableView)) {
  1019. let cell = tableView.makeView(withIdentifier: KMFindTableviewCell.km_identifier, owner: self) as! KMFindTableviewCell
  1020. if searchResults.count > row {
  1021. let selection = searchResults[row]
  1022. if let data = tableColumn?.identifier.rawValue, data == kResultsColumnId.rawValue {
  1023. cell.resultLabel.attributedStringValue = selection.attributedString
  1024. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  1025. } else if let data = tableColumn?.identifier.rawValue, data == kPageColumnId.rawValue {
  1026. cell.resultLabel.stringValue = "\(Int(selection.selectionPageIndex) + 1)"
  1027. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  1028. }
  1029. }
  1030. return cell
  1031. } else if tableView.isEqual(to: self.snapshotTableView) {
  1032. let cell = tableView.makeView(withIdentifier: KMSnapshotTableViewCell.km_identifier, owner: self) as! KMSnapshotTableViewCell
  1033. var snapshot: KMSnapshotModel?
  1034. if self.isSearchSnapshotMode {
  1035. if self.searchSnapshots.count > row {
  1036. snapshot = self.searchSnapshots[row]
  1037. }
  1038. } else {
  1039. if self.snapshots.count > row {
  1040. snapshot = self.snapshots[row]
  1041. }
  1042. }
  1043. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  1044. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  1045. if let data = snapshot?.windowC?.hasWindow, data {
  1046. cell.snapshotImageView.isHidden = false
  1047. } else {
  1048. cell.snapshotImageView.isHidden = true
  1049. }
  1050. cell.isSelectCell = snapshot?.isSelected ?? false
  1051. if (row == tableView.selectedRow) {
  1052. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  1053. } else {
  1054. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  1055. }
  1056. return cell
  1057. }
  1058. return nil
  1059. }
  1060. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  1061. if tableView.isEqual(to: self.thumbnailTableView) {
  1062. let scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  1063. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  1064. let newScaling: CGFloat = scaling.cgFloat + 0.1
  1065. let newThumbnailHeight = thumbnailSize.width * newScaling
  1066. if (newThumbnailHeight > Self.kMinSidePaneWidth) {
  1067. self.thumbnailZoomOutButton.isEnabled = false
  1068. } else {
  1069. self.thumbnailZoomOutButton.isEnabled = true
  1070. }
  1071. if ((scaling - 0.1) < 0.4) {
  1072. self.thumbnailZoomInButton.isEnabled = false
  1073. } else {
  1074. self.thumbnailZoomInButton.isEnabled = true
  1075. }
  1076. var labelHeight = 0.0
  1077. if (self.isDisplayPageSize) {
  1078. labelHeight = 56.0
  1079. } else {
  1080. labelHeight = 41.5
  1081. }
  1082. let cellHeight = thumbnailSize.height + labelHeight
  1083. var thumbSize: NSSize = .zero
  1084. if (scaling > 0) {
  1085. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1086. } else {
  1087. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  1088. }
  1089. return thumbSize.height
  1090. } else if tableView.isEqual(to: self.snapshotTableView) {
  1091. let scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  1092. let snapshotSize = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC?.thumbnail?.size ?? NSMakeSize(120, 63)
  1093. var newScaling = scaling + 0.1
  1094. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat
  1095. if (newSnapshotHeight > Self.kMinSidePaneWidth) {
  1096. self.snapshotNormalZoomInButton.isEnabled = false
  1097. } else {
  1098. self.snapshotNormalZoomInButton.isEnabled = true
  1099. }
  1100. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  1101. self.snapshotNormalZoomOutButton.isEnabled = false
  1102. } else {
  1103. self.snapshotNormalZoomOutButton.isEnabled = true
  1104. }
  1105. let cellHeight = snapshotSize.height + 24.0
  1106. var thumbSize: NSSize = .zero
  1107. if (scaling > 0) {
  1108. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1109. } else {
  1110. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  1111. }
  1112. return thumbSize.height
  1113. } else if (tableView.isEqual(to: self.findTableView)) {
  1114. return 40.0
  1115. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1116. return 16
  1117. }
  1118. return tableView.rowHeight
  1119. }
  1120. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  1121. if (tableView.isEqual(to: self.findTableView)) {
  1122. let rowView = KMBotaTableRowView()
  1123. return rowView
  1124. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1125. let rowView = KMGroupFindTableRowView()
  1126. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  1127. let model = self.groupSearchResults[row]
  1128. rowView.number = model.datas.count
  1129. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  1130. return rowView
  1131. }
  1132. return nil
  1133. }
  1134. func tableViewSelectionIsChanging(_ notification: Notification) {
  1135. }
  1136. func tableViewSelectionDidChange(_ notification: Notification) {
  1137. if self.stopRepeatLoad == true {
  1138. } else {
  1139. self.delegate?.controller?(controller: self, listViewSelectionDidChange: notification.object, info: nil)
  1140. }
  1141. if self.findTableView.isEqual(to: notification.object) {
  1142. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1143. let row = self.findTableView.selectedRow
  1144. if row >= 0 {
  1145. let model = self.searchResults[row]
  1146. let isEditing = self.listView?.isEditing() ?? false
  1147. if isEditing {
  1148. self.mainViewController?.srHanddler.showSelection(model.selection)
  1149. return
  1150. }
  1151. self.listView?.go(to: model.selection, animated: true)
  1152. // self.listView?.setHighlightedSelection(model.selection, animated: true)
  1153. DispatchQueue.main.asyncAfter(deadline: .now()+0.3) {
  1154. self.listView?.setHighlightedSelections([model.selection])
  1155. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  1156. }
  1157. }
  1158. } else if self.groupedFindTableView.isEqual(to: notification.object) {
  1159. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1160. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  1161. self.thumbnailTableView.ks_reloadData()
  1162. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1163. let row = self.snapshotTableView.selectedRow
  1164. // 更新选中数据
  1165. for (i, model) in self.snapshots.enumerated() {
  1166. model.isSelected = i == row
  1167. }
  1168. if (row != -1) {
  1169. let controller = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC
  1170. if let data = controller?.window?.isVisible, data {
  1171. controller?.window?.orderFront(self)
  1172. }
  1173. }
  1174. self.snapshotTableView.ks_reloadData()
  1175. }
  1176. }
  1177. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  1178. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  1179. return NSDragOperation(rawValue: 0)
  1180. }
  1181. let pboard = info.draggingPasteboard
  1182. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  1183. return .move
  1184. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  1185. guard let pbItems = pboard.pasteboardItems else {
  1186. return NSDragOperation(rawValue: 0)
  1187. }
  1188. var hasValidFile = false
  1189. for item in pbItems {
  1190. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  1191. continue
  1192. }
  1193. let type = _url.pathExtension.lowercased()
  1194. if type == "pdf" || KMImageToPDFMethod.supportedImageTypes().contains(type) {
  1195. hasValidFile = true
  1196. }
  1197. }
  1198. if (!hasValidFile) {
  1199. return NSDragOperation(rawValue: 0)
  1200. } else {
  1201. return .move
  1202. }
  1203. }
  1204. return NSDragOperation(rawValue: 0)
  1205. }
  1206. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1207. var result = false
  1208. if tableView.isEqual(to: self.thumbnailTableView) == false {
  1209. return result
  1210. }
  1211. let pasteboard = info.draggingPasteboard
  1212. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  1213. result = true
  1214. guard let rowData = pasteboard.data(forType: .localDraggedTypes) else {
  1215. return false
  1216. }
  1217. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet ?? IndexSet()
  1218. guard let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes) else {
  1219. return false
  1220. }
  1221. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData) as? String
  1222. if url != nil && url != self.pdfDocument()?.documentURL.absoluteString {
  1223. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  1224. let fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  1225. if (fileNames.count == 1) {
  1226. let path = fileNames.first ?? ""
  1227. let pathExtension = path.pathExtension.lowercased()
  1228. if pathExtension == "pdf" {
  1229. var index = row
  1230. var insertIndexSet = IndexSet()
  1231. let pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  1232. if let data = pdf?.isEncrypted, data {
  1233. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: path), type: .owner) { success, resultPassword in
  1234. if success && resultPassword.isEmpty == false {
  1235. self.model.insertedDocumentSet.insert(pdf!)
  1236. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1237. if let page = pdf?.page(at: i).copy() as? CPDFPage {
  1238. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1239. insertIndexSet.insert(index)
  1240. index += 1
  1241. }
  1242. }
  1243. self.insertPages(insertIndexSet, pageAt: index-1)
  1244. }
  1245. }
  1246. } else {
  1247. if let data = pdf {
  1248. self.model.insertedDocumentSet.insert(data)
  1249. }
  1250. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1251. let page = pdf?.page(at: i)
  1252. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1253. insertIndexSet.insert(index)
  1254. index += 1
  1255. }
  1256. self.insertPages(insertIndexSet, pageAt: index-1)
  1257. }
  1258. }
  1259. return true
  1260. }
  1261. }
  1262. }
  1263. var pageIndex = 0
  1264. var pages: [CPDFPage] = []
  1265. for idx in rowIndexes {
  1266. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1267. pages.append(page)
  1268. }
  1269. }
  1270. var toPage: CPDFPage?
  1271. if row < self.pageCount() {
  1272. toPage = self.pdfDocument()?.page(at: UInt(row))
  1273. }
  1274. var toPageIndex = 0
  1275. if (toPage != nil) {
  1276. toPageIndex = Int(self.pdfDocument()?.index(for: toPage) ?? 0)
  1277. } else {
  1278. toPageIndex = self.pageCount()
  1279. }
  1280. for i in 0 ..< pages.count {
  1281. let page = pages[i]
  1282. self.pdfDocument()?.insertPageObject(page, at: UInt(toPageIndex+i))
  1283. pageIndex += 1
  1284. self.listView?.go(toPageIndex: toPageIndex+i-1, animated: false)
  1285. }
  1286. self.layoutDocumentView()
  1287. for idx in rowIndexes {
  1288. if idx < toPageIndex {
  1289. if((idx+pageIndex) < self.pageCount()) {
  1290. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1291. self.deletePages_.insert(page)
  1292. }
  1293. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1294. }
  1295. } else {
  1296. if((idx+pageIndex) < self.pageCount()) {
  1297. if let page = self.pdfDocument()?.page(at: UInt(idx+pageIndex)) {
  1298. self.deletePages_.insert(page)
  1299. }
  1300. self.pdfDocument()?.removePage(at: IndexSet(integer: idx+pageIndex))
  1301. }
  1302. }
  1303. }
  1304. if rowIndexes.isEmpty == false {
  1305. self.listView?.updateActiveAnnotations([])
  1306. if let win = self.view.window {
  1307. KMTools.setDocumentEditedState(window: win)
  1308. }
  1309. }
  1310. self.layoutDocumentView()
  1311. self.resetThumbnails()
  1312. } else if pasteboard.availableType(from: [.fileURL]) != nil && tableView.isEqual(to: self.thumbnailTableView) {
  1313. if KMMemberInfo.shared.isMemberAllFunction == false {
  1314. KMMemberInfo.shared.advancedFunctionUsage(type: .pdfEdit)
  1315. return false
  1316. }
  1317. let fileNames = pasteboard.propertyList(forType: .fileURL)
  1318. var insertIndexSet = IndexSet()
  1319. var index = row
  1320. if fileNames != nil {
  1321. let path = fileNames as? String ?? ""
  1322. let url = URL(string: path)
  1323. let pathExtension = url?.pathExtension.lowercased() ?? ""
  1324. if pathExtension == "pdf" {
  1325. let pdf = CPDFDocument(url: url!)
  1326. if let data = pdf?.isEncrypted, data {
  1327. self.view.window?.windowController?.kCheckPassword(url: url!, type: .owner, completion: { [weak self] success, resultPassword in
  1328. if success && resultPassword.isEmpty == false {
  1329. pdf?.unlock(withPassword: resultPassword)
  1330. self?.model.insertedDocumentSet.insert(pdf!)
  1331. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1332. if let page = pdf?.page(at: i) {
  1333. self?.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1334. insertIndexSet.insert(index)
  1335. index += 1
  1336. }
  1337. }
  1338. self?.insertPages(insertIndexSet, pageAt: index-1)
  1339. }
  1340. })
  1341. } else {
  1342. if let data = pdf {
  1343. self.model.insertedDocumentSet.insert(data)
  1344. }
  1345. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1346. if let page = pdf?.page(at: i) {
  1347. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1348. insertIndexSet.insert(index)
  1349. index += 1
  1350. }
  1351. }
  1352. self.insertPages(insertIndexSet, pageAt: index-1)
  1353. }
  1354. } else if KMImageToPDFMethod.supportedImageTypes().contains(pathExtension) {
  1355. if let image = NSImage(contentsOfFile: url?.path ?? "") {
  1356. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  1357. // [pdfView.document insertPage:page atIndex:index];
  1358. _ = self.pdfDocument()?.km_insert(image: image, at: UInt(index))
  1359. insertIndexSet.insert(index)
  1360. self.insertPages(insertIndexSet, pageAt: index-1)
  1361. }
  1362. }
  1363. result = true
  1364. } else {
  1365. result = false
  1366. }
  1367. }
  1368. return result == false
  1369. }
  1370. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  1371. if tableView.isEqual(to: self.thumbnailTableView) {
  1372. let idx = rowIndexes.first ?? NSNotFound
  1373. if (idx != NSNotFound && self.isLocked() == false) {
  1374. let page = self.pdfDocument()?.page(at: UInt(idx))
  1375. var fileExt: String?
  1376. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.displayBox()) ?? .zero)
  1377. if self.allowsPrinting() {
  1378. // NSData *pdfData = [page dataRepresentation];
  1379. fileExt = "pdf"
  1380. // filenames
  1381. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  1382. pboard.setData(tiffData, forType: .pdf)
  1383. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  1384. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  1385. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1386. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.pdfDocument()?.documentURL?.absoluteString)
  1387. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  1388. var docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1389. // __block NSMutableString *pagesName = nil;
  1390. var pagesName = ""
  1391. if (rowIndexes.count > 1) {
  1392. pagesName = " pages"
  1393. } else {
  1394. pagesName = " page"
  1395. }
  1396. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  1397. let pdf = CPDFDocument()
  1398. for idx in rowIndexes {
  1399. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1400. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1401. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1402. }
  1403. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  1404. var cachesDir = paths.first ?? ""
  1405. docmentName = String(format: "%@%@", docmentName, tFileName)
  1406. if (docmentName.count > 50) {
  1407. docmentName = docmentName.substring(to: 50)
  1408. }
  1409. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  1410. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  1411. let success = pdf?.write(toFile: cachesDir) ?? false
  1412. if (success) {
  1413. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  1414. pboard.setPropertyList([cachesDir], forType: .fileURL)
  1415. } else{
  1416. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  1417. pboard.setPropertyList([], forType: .fileURL)
  1418. }
  1419. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1420. } else {
  1421. fileExt = "tiff"
  1422. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1423. }
  1424. pboard.setData(tiffData, forType: .tiff)
  1425. // kPasteboardTypeFileURLPromise
  1426. pboard.setPropertyList([fileExt], forType: .filePromise)
  1427. return true
  1428. }
  1429. } else if self.snapshotTableView.isEqual(to: tableView) {
  1430. let idx = rowIndexes.first ?? NSNotFound
  1431. if (idx != NSNotFound) {
  1432. let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC
  1433. if let data = snapshot?.thumbnailWithSize(0)?.tiffRepresentation {
  1434. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1435. pboard.setData(data, forType: .tiff)
  1436. pboard.setPropertyList(["tiff"], forType: .filePromise)
  1437. return true
  1438. }
  1439. }
  1440. }
  1441. return false
  1442. }
  1443. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {
  1444. self.dragIn = true
  1445. }
  1446. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1447. self.dragIn = false
  1448. }
  1449. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  1450. if KMMemberInfo.shared.isMemberAllFunction == false {
  1451. KMMemberInfo.shared.advancedFunctionUsage(type: .pdfEdit)
  1452. return
  1453. }
  1454. if aTableView.isEqual(to: self.snapshotTableView) {
  1455. var controllers: [KMSnapshotWindowController] = []
  1456. for i in rowIndexes {
  1457. let model: KMSnapshotModel? = self.snapshots.safe_element(for: i) as? KMSnapshotModel
  1458. if let winC = model?.windowC {
  1459. controllers.append(winC)
  1460. }
  1461. }
  1462. for c in controllers {
  1463. c.close()
  1464. }
  1465. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  1466. guard let last = rowIndexes.last, last < self.pageCount() else {
  1467. return
  1468. }
  1469. //删除page时移除选中状态的annotation
  1470. self.listView?.activeAnnotations = []
  1471. for idx in rowIndexes {
  1472. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1473. // for anno in page.annotations {
  1474. // page.removeAnnotation(anno)
  1475. // }
  1476. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  1477. // self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1478. self.deletePages_.insert(page)
  1479. }
  1480. }
  1481. self.pdfDocument()?.removePage(at: rowIndexes)
  1482. self.layoutDocumentView()
  1483. self.resetThumbnails()
  1484. let idx = rowIndexes.first ?? -1
  1485. let index = min(idx, self.pageCount()-1)
  1486. self.listView?.go(toPageIndex: index, animated: false)
  1487. }
  1488. }
  1489. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  1490. if KMMemberInfo.shared.isMemberAllFunction == false {
  1491. KMMemberInfo.shared.advancedFunctionUsage(type: .pdfEdit)
  1492. return
  1493. }
  1494. if aTableView.isEqual(to: self.thumbnailTableView) {
  1495. self._copysPages.removeAll()
  1496. if self.isLocked() == false {
  1497. for idx in rowIndexes {
  1498. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1499. self._copysPages.append(page)
  1500. }
  1501. }
  1502. }
  1503. } else if aTableView.isEqual(to: self.findTableView) {
  1504. var string = ""
  1505. for idx in rowIndexes {
  1506. let match = self.searchResults[idx].selection
  1507. string.append("* ")
  1508. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  1509. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  1510. // [string appendFormat:@"", [[match contextString] string]];
  1511. string = string.appendingFormat(": %@\n", match.string() ?? "")
  1512. }
  1513. let pboard = NSPasteboard.general
  1514. pboard.clearContents()
  1515. pboard.writeObjects([string as NSPasteboardWriting])
  1516. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1517. var string = ""
  1518. for idx in rowIndexes {
  1519. let result = self.groupSearchResults[idx]
  1520. let matches = result.datas
  1521. string.append("* ")
  1522. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(result.selectionPageIndex)")
  1523. string.append(": ")
  1524. string = string.appendingFormat(KMLocalizedString("%ld Results", ""), matches.count)
  1525. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  1526. var tmpString = ""
  1527. for model in matches {
  1528. tmpString.append("\(model.selection.string() ?? "")")
  1529. }
  1530. string = string.appendingFormat(":\n\t%@\n", tmpString)
  1531. }
  1532. let pboard = NSPasteboard.general
  1533. pboard.clearContents()
  1534. pboard.writeObjects([string as NSPasteboardWriting])
  1535. }
  1536. }
  1537. func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
  1538. if self.thumbnailTableView.isEqual(to: tableView) {
  1539. var fileURLArray: [String] = []
  1540. if indexSet.count > 1 {
  1541. var docmentName = ""
  1542. let tFileName = String(format: "%@", self.fileNameWithSelectedPages(indexSet))
  1543. let pdf = CPDFDocument()
  1544. for idx in indexSet {
  1545. if idx != NSNotFound && self.isLocked() == false {
  1546. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1547. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1548. }
  1549. }
  1550. let fileURL = dropDestination.appendingPathComponent(tFileName).appendingPathExtension("pdf").uniqueFileURL()
  1551. docmentName = fileURL.path
  1552. let success = pdf?.write(toFile: docmentName) ?? false
  1553. if(success) {
  1554. fileURLArray.append(fileURL.lastPathComponent)
  1555. }
  1556. } else {
  1557. if let page = self.pdfDocument()?.page(at: UInt(indexSet.first ?? 0)) {
  1558. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page))
  1559. if self.allowsPrinting() {
  1560. fileURL = fileURL.appendingPathExtension("pdf").uniqueFileURL()
  1561. let pdf = CPDFDocument()
  1562. // let copyPage = page.copy() as? CPDFPage
  1563. let copyPage = page
  1564. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1565. let success = pdf?.write(toFile: fileURL.path) ?? false
  1566. if success {
  1567. fileURLArray.append(fileURL.lastPathComponent)
  1568. }
  1569. } else {
  1570. fileURL = fileURL.appendingPathExtension("tiff").uniqueFileURL()
  1571. let fileData = page.PDFListViewTIFFData(for: page.bounds(for: self.displayBox()))
  1572. let success = (try?fileData?.write(to: fileURL)) != nil
  1573. if success {
  1574. fileURLArray.append(fileURL.lastPathComponent)
  1575. }
  1576. }
  1577. }
  1578. }
  1579. return fileURLArray
  1580. } else if self.snapshotTableView.isEqual(to: tableView) {
  1581. let idx = indexSet.first ?? NSNotFound
  1582. if (idx != NSNotFound) {
  1583. if let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC {
  1584. if let page = self.pdfDocument()?.page(at: snapshot.pageIndex()) {
  1585. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page)).appendingPathExtension("tiff")
  1586. fileURL = fileURL.uniqueFileURL()
  1587. if ((try?snapshot.thumbnailWithSize(0)?.tiffRepresentation?.write(to: fileURL)) != nil) {
  1588. return [fileURL.lastPathComponent]
  1589. }
  1590. }
  1591. }
  1592. }
  1593. }
  1594. return []
  1595. }
  1596. func tableViewColumnDidResize(_ notification: Notification) {
  1597. guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else {
  1598. return
  1599. }
  1600. if column.identifier.rawValue == IMAGE_COLUMNID {
  1601. if self.thumbnailTableView.isEqual(to: notification.object) {
  1602. self.thumbnailTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.thumbnailTableView.numberOfRows)) as IndexSet)
  1603. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1604. self.snapshotTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.snapshotTableView.numberOfRows)) as IndexSet)
  1605. }
  1606. }
  1607. }
  1608. func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
  1609. if tableView.isEqual(to: self.groupedFindTableView) {
  1610. // [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  1611. }
  1612. }
  1613. /*
  1614. #pragma mark NSTableView delegate protocol
  1615. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  1616. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1617. NSUInteger idx = [rowIndexes firstIndex];
  1618. if (idx != NSNotFound) {
  1619. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  1620. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  1621. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1622. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  1623. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  1624. [self fileWithPage:page atPath:filePath];
  1625. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  1626. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  1627. } else {
  1628. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  1629. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  1630. }
  1631. }
  1632. }
  1633. }
  1634. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  1635. NSData *data = [page dataRepresentation];
  1636. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  1637. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1638. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  1639. if (success) {
  1640. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  1641. NSURL *url = [NSURL fileURLWithPath:filePath];
  1642. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  1643. }
  1644. [document release];
  1645. */
  1646. }
  1647. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  1648. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  1649. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  1650. if outlineView.isEqual(to: self.tocOutlineView) {
  1651. if self.isLocked() {
  1652. return 0
  1653. }
  1654. if item == nil { // 第一层
  1655. // let bks = self.bookmarks() ?? []
  1656. // let bkNum = bks.isEmpty ? 0 : 1
  1657. let bks: [CPDFBookmark] = []
  1658. let bkNum = 0
  1659. guard let rootOL = self.outlineRoot() else {
  1660. if bkNum > 0 {
  1661. } else {
  1662. self.showOutlineEmptyView()
  1663. }
  1664. return 0 + bkNum
  1665. }
  1666. // 搜索按钮
  1667. self.outlineSearchButton.isEnabled = rootOL.numberOfChildren > 0
  1668. if self.isSearchOutlineMode { // 是否为搜索模块
  1669. if self.hasContainString(self.outlineSearchField.stringValue, rootOutline: rootOL) == false {
  1670. self.showSearchOutlineBlankState(true)
  1671. return 0
  1672. }
  1673. self.showSearchOutlineBlankState(false)
  1674. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1675. return ols.count
  1676. }
  1677. if rootOL.numberOfChildren == 0 { // 没有数据
  1678. if bkNum > 0 {
  1679. } else {
  1680. self.showOutlineEmptyView()
  1681. }
  1682. return 0 + bkNum
  1683. }
  1684. // 有数据
  1685. self.hideOutlineEmptyView()
  1686. return Int(rootOL.numberOfChildren) + bkNum
  1687. } else { // 第二层 +
  1688. if item is CPDFBookmark { // 书签
  1689. return 0
  1690. }
  1691. if let data = item as? String, data == Self.kOutlineRootBookmarkItem { // 书签group
  1692. if self.isSearchOutlineMode {
  1693. return 0
  1694. }
  1695. return (self.bookmarks()?.count) ?? 0
  1696. }
  1697. guard let ol = item as? CPDFOutline, ol.numberOfChildren > 0 else {
  1698. return 0
  1699. }
  1700. if self.isSearchOutlineMode == false {
  1701. return Int(ol.numberOfChildren)
  1702. }
  1703. // 搜索模式
  1704. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1705. return ols.count
  1706. }
  1707. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1708. if self.noteSearchMode {
  1709. // return self.noteSearchArray.count
  1710. var cnt = 0
  1711. for model in self.noteSearchArray {
  1712. cnt += 2
  1713. guard let data = model as? KMBotaAnnotationModel else {
  1714. continue
  1715. }
  1716. if data.isExpand == false {
  1717. continue
  1718. }
  1719. for replyI in data.replyAnnos {
  1720. cnt += 1
  1721. }
  1722. }
  1723. return cnt
  1724. }
  1725. // let count = self.annoListModel?.datas.count ?? 0
  1726. var cnt = 0
  1727. for sectionM in self.annoListModel?.datas ?? [] {
  1728. if sectionM.items.count > 0 {
  1729. cnt += 1
  1730. if sectionM.isExpand == false {
  1731. continue
  1732. }
  1733. for item in sectionM.items {
  1734. cnt += 1
  1735. if let annoItem = item as? KMBotaAnnotationModel {
  1736. if annoItem.isExpand == false {
  1737. continue
  1738. }
  1739. for replyItem in annoItem.replyAnnos {
  1740. cnt += 1
  1741. }
  1742. }
  1743. }
  1744. }
  1745. }
  1746. let hasAnno = self.allAnnotations.count >= 1
  1747. self.noteSearchButton.isEnabled = hasAnno
  1748. self.noteFilterButton.isEnabled = hasAnno
  1749. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1750. if cnt < 1 {
  1751. self.showNoteEmptyView()
  1752. } else {
  1753. self.hideNoteEmptyView()
  1754. }
  1755. return cnt
  1756. }
  1757. return 0
  1758. }
  1759. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1760. if outlineView.isEqual(to: self.tocOutlineView) {
  1761. if self.isLocked() {
  1762. return ""
  1763. }
  1764. // let bks = self.bookmarks() ?? []
  1765. // let bkNum = bks.isEmpty ? 0 : 1
  1766. let bks: [CPDFBookmark] = []
  1767. let bkNum = 0
  1768. if item == nil {
  1769. if self.isSearchOutlineMode {
  1770. guard let rootOL = self.outlineRoot(), rootOL.numberOfChildren > 0 else {
  1771. return ""
  1772. }
  1773. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1774. return ols.safe_element(for: index) as Any
  1775. }
  1776. if index == 0 && bkNum == 1 {
  1777. return Self.kOutlineRootBookmarkItem
  1778. }
  1779. let idx = bkNum == 1 ? index-1 : index
  1780. let rootOL = self.outlineRoot()
  1781. return rootOL?.child(at: UInt(idx)) as Any
  1782. } else {
  1783. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1784. return bks[index]
  1785. }
  1786. if item is CPDFBookmark {
  1787. return ""
  1788. }
  1789. if let ol = item as? CPDFOutline {
  1790. if self.isSearchOutlineMode == false {
  1791. return ol.child(at: UInt(index)) as Any
  1792. }
  1793. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1794. return ols.safe_element(for: index) as Any
  1795. }
  1796. }
  1797. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1798. if self.noteSearchMode {
  1799. // return self.noteSearchArray[index]
  1800. var idx = 0
  1801. var models: [KMBotaAnnotationBaseModel] = []
  1802. for model in self.noteSearchArray {
  1803. models.append(model)
  1804. if let data = (model as? KMBotaAnnotationModel)?.footerModel {
  1805. models.append(data)
  1806. }
  1807. }
  1808. for model in models {
  1809. idx += 1
  1810. if index + 1 == idx {
  1811. return model
  1812. }
  1813. // if index + 2 == idx {
  1814. // return (model as? KMBotaAnnotationModel)?.footerModel
  1815. // }
  1816. guard let data = model as? KMBotaAnnotationModel else {
  1817. continue
  1818. }
  1819. if data.isExpand == false {
  1820. continue
  1821. }
  1822. for replyI in data.replyAnnos {
  1823. idx += 1
  1824. if index + 1 == idx {
  1825. return replyI
  1826. }
  1827. }
  1828. }
  1829. return 0
  1830. }
  1831. var idx = 0
  1832. var flagSectionM: KMBotaAnnotationSectionModel?
  1833. var flagItem: KMBotaAnnotationBaseModel?
  1834. var replyIten: KMBotaAnnotationReplyModel?
  1835. var isSection = false
  1836. var isReply = false
  1837. for sectionM in self.annoListModel?.datas ?? [] {
  1838. idx += 1
  1839. if index + 1 == idx {
  1840. flagSectionM = sectionM
  1841. isSection = true
  1842. break
  1843. }
  1844. if sectionM.isExpand == false {
  1845. continue
  1846. }
  1847. for item in sectionM.items {
  1848. idx += 1
  1849. if index + 1 == idx {
  1850. flagSectionM = sectionM
  1851. flagItem = item
  1852. break
  1853. }
  1854. guard let annoItem = item as? KMBotaAnnotationModel else {
  1855. continue
  1856. }
  1857. if annoItem.isExpand == false {
  1858. // flagItem = annoItem
  1859. continue
  1860. }
  1861. for replyI in annoItem.replyAnnos {
  1862. idx += 1
  1863. if index + 1 == idx {
  1864. flagSectionM = sectionM
  1865. flagItem = item
  1866. replyIten = replyI
  1867. isReply = true
  1868. break
  1869. }
  1870. }
  1871. }
  1872. }
  1873. if isSection {
  1874. return flagSectionM
  1875. }
  1876. if isReply {
  1877. return replyIten
  1878. }
  1879. return flagItem
  1880. }
  1881. return item as Any
  1882. }
  1883. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  1884. if outlineView.isEqual(to: self.tocOutlineView) {
  1885. let cell = outlineView.makeView(withIdentifier: KMTocTableCellView.km_identifier, owner: self) as! KMTocTableCellView
  1886. let columnId = tableColumn?.identifier.rawValue
  1887. var title = ""
  1888. var pageLabel = ""
  1889. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1890. title = NSLocalizedString("Bookmarks", comment: "")
  1891. } else if let ol = item as? CPDFOutline {
  1892. title = ol.label ?? ""
  1893. if ol.actionType == .page {
  1894. pageLabel = "\((ol.destination?.pageIndex ?? 0) + 1)"
  1895. }
  1896. } else if let bk = item as? CPDFBookmark {
  1897. title = bk.label ?? ""
  1898. pageLabel = "\(bk.pageIndex + 1)"
  1899. }
  1900. cell.pageLabel.stringValue = pageLabel
  1901. if columnId == kLabelColumnId.rawValue {
  1902. if self.isSearchOutlineMode {
  1903. let attriString = NSMutableAttributedString(string: title)
  1904. var searchString = self.outlineSearchField.stringValue
  1905. var roughString = title
  1906. if self.outlineIgnoreCaseFlag {
  1907. roughString = roughString.lowercased()
  1908. searchString = searchString.lowercased()
  1909. }
  1910. let ranges = roughString.ranges(of: searchString)
  1911. for range in ranges.nsRnage {
  1912. attriString.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: 13), range: range)
  1913. }
  1914. cell.tocLabel.attributedStringValue = attriString
  1915. } else {
  1916. cell.tocLabel.stringValue = title
  1917. }
  1918. }
  1919. cell.tocLabel.textColor = KMAppearance.titleColor()
  1920. return cell
  1921. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1922. if let data = item as? KMBotaAnnotationSectionModel {
  1923. var cell = outlineView.makeView(withIdentifier: KMSectionCellView.km_identifier, owner: nil) as? KMSectionCellView
  1924. if cell == nil {
  1925. cell = KMSectionCellView.createFromNib()
  1926. }
  1927. cell?.titleLabel.textColor = KMAppearance.titleColor()
  1928. cell?.countLabel.textColor = KMAppearance.titleColor()
  1929. cell?.isExpand = data.isExpand
  1930. cell?.contentInset = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
  1931. if self.noteSortType == .page {
  1932. let pageIndex = data.items.first?.anno?.page.pageIndex() ?? 0
  1933. cell?.titleLabel.stringValue = NSLocalizedString("Page", comment: "") + " \(pageIndex + 1)"
  1934. } else {
  1935. if let date = data.items.first?.anno?.modificationDate() {
  1936. let string = KMTools.timeString(timeDate: date, formatString: "yyyy-MM-dd")
  1937. cell?.titleLabel.stringValue = string
  1938. } else {
  1939. cell?.titleLabel.stringValue = ""
  1940. }
  1941. }
  1942. cell?.countLabel.stringValue = "\(data.itemCount / 2)"
  1943. cell?.itemClick = { idx, _ in
  1944. if idx == 1 { // 收取 & 展开
  1945. data.isExpand = !data.isExpand
  1946. self.noteOutlineView.reloadData()
  1947. }
  1948. }
  1949. return cell
  1950. }
  1951. if let data = item as? KMBotaAnnotationFooterModel {
  1952. var cell = outlineView.makeView(withIdentifier: KMNoteFooterCellView.km_identifier, owner: self) as? KMNoteFooterCellView
  1953. if cell == nil {
  1954. cell = KMNoteFooterCellView.createFromNib()
  1955. }
  1956. cell?.model = data
  1957. let cnt = self.noteReplyHanddler.fetchReplyAnnotations(data.anno)?.count ?? 0
  1958. if cnt == 0 {
  1959. cell?.commentNumberLabel.stringValue = ""
  1960. } else {
  1961. cell?.commentNumberLabel.stringValue = "\(cnt)"
  1962. }
  1963. let state = self.noteReplyHanddler.fetchReviewState(data.anno) ?? .none
  1964. if state == .none {
  1965. cell?.operationIv.image = NSImage(named: "KMImageNameBotaNoteStateNone")
  1966. } else if state == .completed {
  1967. cell?.operationIv.image = NSImage(named: "KMImageNameBotaNoteStateCompleted")
  1968. } else if state == .canceled {
  1969. cell?.operationIv.image = NSImage(named: "KMImageNameBotaNoteStateCancelled")
  1970. } else if state == .accepted {
  1971. cell?.operationIv.image = NSImage(named: "KMImageNameBotaNoteStateAccepted")
  1972. } else if state == .rejected {
  1973. cell?.operationIv.image = NSImage(named: "KMImageNameBotaNoteStateRejected")
  1974. }
  1975. cell?.operationBox.toolTip = KMPDFAnnotationStateGetString(state: state)
  1976. if let con = data.replyModel?.replyAnno?.contents, con.isEmpty == false {
  1977. cell?.inputTextF.stringValue = con
  1978. DispatchQueue.main.async {
  1979. self.view.window?.makeFirstResponder(cell?.inputTextF)
  1980. }
  1981. } else {
  1982. if let cont = data.inputContent {
  1983. cell?.inputTextF.stringValue = cont
  1984. } else {
  1985. cell?.inputTextF.stringValue = ""
  1986. }
  1987. }
  1988. cell?.updateUI(expand: data.isExpand, animated: data.animated)
  1989. data.animated = false
  1990. if data.isFirstResp {
  1991. DispatchQueue.main.async {
  1992. self.view.window?.makeFirstResponder(cell?.inputTextF)
  1993. }
  1994. data.isFirstResp = false
  1995. }
  1996. cell?.inputDidChanged = { value, _ in
  1997. data.inputContent = value as? String ?? ""
  1998. }
  1999. cell?.itemClick = { [weak self] idx, param in
  2000. if idx == 1 { // comment
  2001. data.isExpand = !data.isExpand
  2002. data.animated = true
  2003. data.isFirstResp = true
  2004. // data.annoModel?.isExpand = data.isExpand
  2005. self?.noteOutlineView.reloadItem(data)
  2006. // self?.noteOutlineView.reloadData()
  2007. } else if idx == 2 { //
  2008. self?.noteReplyHanddler.showStatePopView(sender: param.first as! NSView, anno: data.anno)
  2009. } else if idx == 3 { // reply
  2010. let content = param.first as? String ?? ""
  2011. if content.isEmpty {
  2012. // Task {
  2013. // _ = await KMAlertTool.runModel(message: NSLocalizedString("Error", comment: ""))
  2014. // }
  2015. return
  2016. }
  2017. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_AnnotationReply"])
  2018. if let con = data.replyModel?.replyAnno?.contents, con.isEmpty == false { // 编辑
  2019. let model = data.replyModel
  2020. model?.replyAnno?.contents = content
  2021. model?.replyAnno?.setUserName(KMPreference.shared.author)
  2022. model?.replyAnno?.setModificationDate(Date())
  2023. // 置空编辑状态
  2024. data.replyModel = nil
  2025. data.inputContent = nil
  2026. self?.noteOutlineView.reloadData()
  2027. if let row = self?.noteOutlineView.row(forItem: data) {
  2028. self?.noteOutlineView.scrollRowToVisible(row)
  2029. }
  2030. return
  2031. }
  2032. if let replyAnno = self?.noteReplyHanddler.createReplyAnnotation(data.anno, content: content, userName: KMPreference.shared.author) {
  2033. // self?.reloadAnnotation()
  2034. let model = KMBotaAnnotationReplyModel()
  2035. model.anno = data.anno
  2036. model.replyAnno = replyAnno
  2037. model.annoModel = data.annoModel
  2038. data.annoModel?.replyAnnos.append(model)
  2039. data.inputContent = nil
  2040. self?.noteOutlineView.reloadData()
  2041. if let row = self?.noteOutlineView.row(forItem: data) {
  2042. self?.noteOutlineView.scrollRowToVisible(row)
  2043. }
  2044. }
  2045. } else if idx == 4 { // cancel
  2046. data.isExpand = false
  2047. data.replyModel = nil
  2048. data.inputContent = nil
  2049. self?.noteOutlineView.reloadItem(data)
  2050. }
  2051. }
  2052. return cell
  2053. }
  2054. if let data = item as? KMBotaAnnotationReplyModel {
  2055. var cell = outlineView.makeView(withIdentifier: KMNoteReplyCellView.km_identifier, owner: self) as? KMNoteReplyCellView
  2056. if cell == nil {
  2057. cell = KMNoteReplyCellView.createFromNib()
  2058. }
  2059. cell?.model = data
  2060. cell?.titleLabel.stringValue = data.replyAnno?.userName() ?? ""
  2061. if let data = data.replyAnno?.modificationDate() {
  2062. cell?.timeLabel.stringValue = KMTools.timeString(timeDate: data)
  2063. } else {
  2064. cell?.timeLabel.stringValue = ""
  2065. }
  2066. cell?.contentLabel.stringValue = data.replyAnno?.contents ?? ""
  2067. cell?.itemClick = { [weak self] idx, params in
  2068. if idx == 1 { // 更多
  2069. self?.noteReplyHanddler.showReplyMorePopView(sender: params.first as! NSView, replyModel: data)
  2070. }
  2071. }
  2072. return cell
  2073. }
  2074. let model = item as? KMBotaAnnotationModel
  2075. let note = (item as? KMBotaAnnotationModel)?.anno
  2076. let cell = outlineView.makeView(withIdentifier: KMNoteTableViewCell.km_identifier, owner: self) as! KMNoteTableViewCell
  2077. cell.cellNote = note
  2078. cell.model = model
  2079. let state = self.noteReplyHanddler.fetchAnnoState(note) ?? .unMarked
  2080. cell.state = state
  2081. if let data = note {
  2082. if data.isKind(of: CPDFStampAnnotation.self) && data.isKind(of: KMSelfSignAnnotation.self) == false {
  2083. } else {
  2084. if data.isKind(of: CPDFMarkupAnnotation.self) {
  2085. if (!cell.isFold) {
  2086. // self.allFoldNotes.append(data)
  2087. } else {
  2088. cell.imageViewHeightConstraint.constant = 18.0 + 8
  2089. }
  2090. } else {
  2091. cell.imageViewHeightConstraint.constant = 18.0 + 8
  2092. }
  2093. }
  2094. }
  2095. cell.itemClick = { [weak self] idx , _ in
  2096. if idx == 1 { // Markup
  2097. let anno = model?.anno
  2098. guard let state = self?.noteReplyHanddler.fetchAnnoState(anno), state == .marked else {
  2099. self?.noteReplyHanddler.markAnnotation(anno)
  2100. // if let theA = anno {
  2101. // self?.note_reloadDataForAnnoIfNeed(anno: theA)
  2102. // }
  2103. self?.noteOutlineView.reloadItem(model)
  2104. return
  2105. }
  2106. self?.noteReplyHanddler.unMarkAnnotation(anno)
  2107. // if let theA = anno {
  2108. // self?.note_reloadDataForAnnoIfNeed(anno: theA)
  2109. // }
  2110. self?.noteOutlineView.reloadItem(model)
  2111. }
  2112. }
  2113. cell.isUnFoldNote = { [weak self] cellNote, isUnfold in
  2114. // 将折叠状态记录到模型
  2115. model?.foldType = isUnfold ? .unfold : .fold
  2116. // self?.note_reloadDataForAnnoIfNeed(anno: <#T##CPDFAnnotation#>)
  2117. model?.footerModel?.isExpand = isUnfold
  2118. model?.isExpand = isUnfold
  2119. // self?.noteOutlineView.reloadItem(model?.footerModel)
  2120. self?.noteOutlineView.reloadData()
  2121. DispatchQueue.main.async {
  2122. if let row = self?.noteOutlineView.row(forItem: item) {
  2123. self?.noteOutlineView.scrollRowToVisible(row)
  2124. }
  2125. }
  2126. }
  2127. return cell
  2128. }
  2129. return nil
  2130. }
  2131. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2132. if outlineView.isEqual(self.noteOutlineView) {
  2133. if let model = item as? KMBotaAnnotationModel {
  2134. if model.isExpand == false {
  2135. // if model.foldType == .fold {
  2136. return model.foldH
  2137. }
  2138. if let anno = model.anno {
  2139. return KMBOTAAnnotationTool.fetchCellHeight(annotation: anno, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  2140. }
  2141. }
  2142. return 30
  2143. } else if outlineView.isEqual(self.tocOutlineView) {
  2144. if let ol = item as? CPDFOutline {
  2145. let string: NSString = ol.label as NSString
  2146. let ps = NSMutableParagraphStyle()
  2147. ps.lineHeightMultiple = 1.32
  2148. ps.alignment = .left
  2149. let attris = [NSAttributedString.Key.paragraphStyle : ps,
  2150. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  2151. let size = string.boundingRect(with: NSMakeSize(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attris)
  2152. return max(40, size.height + 16)
  2153. }
  2154. return 40
  2155. }
  2156. return outlineView.rowHeight
  2157. }
  2158. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2159. if outlineView.isEqual(self.tocOutlineView) {
  2160. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  2161. return true
  2162. }
  2163. if item is CPDFBookmark {
  2164. return false
  2165. }
  2166. guard let ol = item as? CPDFOutline else {
  2167. return false
  2168. }
  2169. if self.isSearchOutlineMode == false {
  2170. return ol.numberOfChildren > 0
  2171. }
  2172. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  2173. return ols.count > 0
  2174. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2175. return false
  2176. }
  2177. return false
  2178. }
  2179. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2180. if outlineView.isEqual(self.tocOutlineView) {
  2181. let itemView = KMBotaTableRowView()
  2182. return itemView
  2183. } else if outlineView.isEqual(self.noteOutlineView) {
  2184. let itemView = KMBotaTableRowView()
  2185. if let data = item as? KMBotaAnnotationBaseModel {
  2186. itemView.isSelected = data.isSelected
  2187. }
  2188. itemView.selectCallback = { theView in
  2189. let isSelected = theView.isSelected
  2190. if theView.numberOfColumns > 0 {
  2191. let cellView = theView.view(atColumn: 0)
  2192. if let data = cellView as? KMSectionCellView {
  2193. return
  2194. }
  2195. var model: KMBotaAnnotationModel?
  2196. var indexs = IndexSet()
  2197. if let data = cellView as? KMNoteFooterCellView {
  2198. model = data.model?.annoModel
  2199. model?.isSelected = isSelected
  2200. self.view.window?.makeFirstResponder(data.inputTextF)
  2201. }
  2202. if let data = cellView as? KMNoteReplyCellView {
  2203. model = data.model?.annoModel
  2204. model?.isSelected = isSelected
  2205. }
  2206. if let data = cellView as? KMNoteTableViewCell {
  2207. model = data.model
  2208. model?.isSelected = isSelected
  2209. }
  2210. //
  2211. if let data = model {
  2212. // let row = self.noteOutlineView.row(for: cellView as! NSView)
  2213. let row = self.noteOutlineView.row(forItem: data)
  2214. indexs.insert(row)
  2215. var i = 1
  2216. for item in model?.replyAnnos ?? [] {
  2217. indexs.insert(row+i)
  2218. i += 1
  2219. }
  2220. indexs.insert(row+i)
  2221. // self.noteOutlineView.km_safe_selectRowIndexes(indexs, byExtendingSelection: false)
  2222. // self.noteOutlineView.selectRowIndexes(indexs, byExtendingSelection: false)
  2223. // self.noteOutlineView.km_selectRow(indexs.first!)
  2224. // self.noteOutlineView.selectedItem()
  2225. }
  2226. KMPrint("")
  2227. }
  2228. }
  2229. return itemView;
  2230. }
  2231. return nil
  2232. }
  2233. func outlineView(_ outlineView: NSOutlineView, selectionIndexesForProposedSelection proposedSelectionIndexes: IndexSet) -> IndexSet {
  2234. if outlineView.isEqual(to: self.noteOutlineView) {
  2235. var indexs = proposedSelectionIndexes
  2236. for i in proposedSelectionIndexes {
  2237. let item = self.noteOutlineView.item(atRow: i)
  2238. var model: KMBotaAnnotationModel?
  2239. if let data = item as? KMBotaAnnotationSectionModel {
  2240. }
  2241. if let data = item as? KMBotaAnnotationModel {
  2242. model = data
  2243. }
  2244. if let data = item as? KMBotaAnnotationReplyModel {
  2245. model = data.annoModel
  2246. }
  2247. if let data = item as? KMBotaAnnotationFooterModel {
  2248. model = data.annoModel
  2249. }
  2250. if let data = model {
  2251. // let row = self.noteOutlineView.row(for: cellView as! NSView)
  2252. let row = self.noteOutlineView.row(forItem: data)
  2253. indexs.insert(row)
  2254. var i = 1
  2255. if data.isExpand {
  2256. for item in data.replyAnnos {
  2257. indexs.insert(row+i)
  2258. i += 1
  2259. }
  2260. }
  2261. indexs.insert(row+i)
  2262. }
  2263. }
  2264. return indexs
  2265. }
  2266. return proposedSelectionIndexes
  2267. }
  2268. func outlineViewSelectionDidChange(_ notification: Notification) {
  2269. if self.tocOutlineView.isEqual(to: notification.object) {
  2270. if self.dragIn {
  2271. return
  2272. }
  2273. if self.updatingOutlineSelection == false {
  2274. self.updatingOutlineSelection = true
  2275. self.goToSelectedOutlineItem(nil)
  2276. self.updatingOutlineSelection = false
  2277. }
  2278. }
  2279. }
  2280. func outlineViewItemDidExpand(_ notification: Notification) {
  2281. // if self.tocOutlineView.isEqual(to: notification.object) {
  2282. // self.updateOutlineSelection()
  2283. // }
  2284. }
  2285. func outlineViewItemDidCollapse(_ notification: Notification) {
  2286. // if self.tocOutlineView.isEqual(to: notification.object) {
  2287. // self.updateOutlineSelection()
  2288. // }
  2289. }
  2290. func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
  2291. var dragOp = NSDragOperation(rawValue: 0)
  2292. if outlineView.isEqual(to: self.noteOutlineView) {
  2293. let pboard = info.draggingPasteboard
  2294. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) && index == NSOutlineViewDropOnItemIndex {
  2295. if let note = item as? CPDFAnnotation, note.type != nil {
  2296. dragOp = .every
  2297. }
  2298. }
  2299. } else if outlineView.isEqual(to: self.tocOutlineView) {
  2300. if (index == -1) {
  2301. dragOp = NSDragOperation(rawValue: 0)
  2302. } else {
  2303. dragOp = .move
  2304. }
  2305. }
  2306. return dragOp
  2307. }
  2308. func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
  2309. if outlineView.isEqual(to: self.tocOutlineView) {
  2310. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  2311. return false
  2312. }
  2313. let tIndex = IndexSet(integer: self.tocOutlineView.clickedRow)
  2314. self.tocOutlineView.deselectRow(tIndex.first ?? 0)
  2315. self._dragPDFOutline = items.first as? CPDFOutline
  2316. let set = IndexSet(integer: 0)
  2317. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: set)
  2318. // [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  2319. pasteboard.declareTypes([.localDraggedTypes], owner: self)
  2320. pasteboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  2321. return true
  2322. }
  2323. return false
  2324. }
  2325. func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
  2326. if outlineView.isEqual(to: self.noteOutlineView) {
  2327. let pboard = info.draggingPasteboard
  2328. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) {
  2329. // [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  2330. let isShift = NSEvent.modifierFlags.contains(.shift)
  2331. let isAlt = NSEvent.modifierFlags.contains(.option)
  2332. guard let note = item as? CPDFAnnotation else {
  2333. NSSound.beep()
  2334. return false
  2335. }
  2336. if let color = NSColor(from: pboard) {
  2337. note.setColor(color, alternate: isAlt, updateDefaults: isShift)
  2338. return true
  2339. }
  2340. return false
  2341. }
  2342. } else if outlineView.isEqual(to: self.tocOutlineView) {
  2343. if (index < 0) {
  2344. return false
  2345. }
  2346. let outline = item as? CPDFOutline
  2347. guard let dragPDFOL = self._dragPDFOutline else {
  2348. return false
  2349. }
  2350. //root,drag item to root
  2351. if ((outline?.parent == nil)) {
  2352. //fetch root
  2353. var root = dragPDFOL
  2354. while (root.parent != nil) {
  2355. root = root.parent
  2356. }
  2357. if dragPDFOL.parent.isEqual(to: root) {
  2358. if dragPDFOL.index > index {
  2359. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  2360. } else {
  2361. // if let bks = self.bookmarks(), bks.count > 0 {
  2362. // if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  2363. //
  2364. // } else {
  2365. // if index > 1 {
  2366. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index-2, newParentOutline: root)
  2367. // }
  2368. // }
  2369. // } else {
  2370. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: root)
  2371. // }
  2372. }
  2373. } else {
  2374. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  2375. }
  2376. } else {
  2377. //在同一个层级内移动
  2378. if dragPDFOL.parent.isEqual(to: item) {
  2379. if (dragPDFOL.index > 0) {
  2380. if dragPDFOL.index > index {
  2381. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  2382. }else{
  2383. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: outline)
  2384. }
  2385. } else {
  2386. return false
  2387. }
  2388. } else {
  2389. var tOutlline: CPDFOutline? = outline
  2390. var isContains = false
  2391. while (tOutlline != nil) {
  2392. if tOutlline!.isEqual(to: self._dragPDFOutline) {
  2393. isContains = true
  2394. break
  2395. }
  2396. tOutlline = tOutlline?.parent
  2397. }
  2398. if (!isContains) {
  2399. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  2400. }
  2401. }
  2402. }
  2403. return true
  2404. }
  2405. return false
  2406. }
  2407. func outlineView(_ outlineView: NSOutlineView, willDisplayOutlineCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
  2408. if outlineView.isEqual(to: self.tocOutlineView) {
  2409. if outlineView.selectionHighlightStyle == .regular && outlineView.isRowSelected(outlineView.row(forItem: item)) {
  2410. (cell as? NSCell)?.backgroundStyle = .lowered
  2411. }
  2412. }
  2413. }
  2414. func outlineView(_ outlineView: NSOutlineView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, byItem item: Any?) {
  2415. if outlineView.isEqual(to: self.noteOutlineView) {
  2416. var note: CPDFAnnotation?
  2417. if let data = item as? CPDFAnnotation {
  2418. note = data
  2419. } else if let data = item as? KMBotaAnnotationModel {
  2420. note = data.anno
  2421. }
  2422. if let data = note?.type, data.isEmpty == false {
  2423. if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2424. let string1 = (object as? String) ?? ""
  2425. let string2 = note?.string() ?? ""
  2426. if string1 != string2 {
  2427. note?.setString(string1)
  2428. }
  2429. } else if tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  2430. let string1 = (object as? String) ?? ""
  2431. let string2 = note?.userName() ?? ""
  2432. if string1 != string2 {
  2433. note?.setUserName(string1)
  2434. }
  2435. }
  2436. }
  2437. }
  2438. }
  2439. func outlineView(_ outlineView: NSOutlineView, dataCellFor tableColumn: NSTableColumn?, item: Any) -> NSCell? {
  2440. if self.noteOutlineView.isEqual(to: outlineView) {
  2441. if tableColumn == nil {
  2442. if let anno = item as? CPDFAnnotation, anno.type == nil {
  2443. return outlineView.tableColumn(withIdentifier: self.noteColumnId)?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  2444. }
  2445. }
  2446. }
  2447. return tableColumn?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  2448. }
  2449. func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool {
  2450. if outlineView.isEqual(to: self.noteOutlineView) {
  2451. if (tableColumn == nil) {
  2452. if self.hideNotes() == false {
  2453. if let anno = item as? CPDFAnnotation, anno.isNote() {
  2454. // if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  2455. // PDFAnnotation *annotation = [(SKNoteText *)item note];
  2456. self.listView?.scrollAnnotationToVisible(anno)
  2457. self.listView?.updateActiveAnnotations([anno])
  2458. // [self showNote:annotation];
  2459. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  2460. // [[noteController window] makeFirstResponder:[noteController textView]];
  2461. // [[noteController textView] selectAll:nil];
  2462. }
  2463. }
  2464. return false
  2465. } else if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue || tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  2466. return true
  2467. }
  2468. }
  2469. return false
  2470. }
  2471. func outlineView(_ outlineView: NSOutlineView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, item: Any, mouseLocation: NSPoint) -> String {
  2472. if outlineView.isEqual(to: self.noteOutlineView) {
  2473. if tableColumn == nil || tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2474. return (item as? CPDFAnnotation)?.string() ?? ""
  2475. }
  2476. }
  2477. return ""
  2478. }
  2479. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) {
  2480. self.dragIn = true
  2481. }
  2482. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  2483. self.dragIn = false
  2484. }
  2485. /*
  2486. #pragma mark NSOutlineView delegate protocol
  2487. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  2488. if ([ov isEqual:rightSideController.noteOutlineView]) {
  2489. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  2490. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  2491. NSMutableArray *sortDescriptors = nil;
  2492. BOOL ascending = YES;
  2493. if ([oldTableColumn isEqual:newTableColumn]) {
  2494. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  2495. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  2496. ascending = [[sortDescriptors firstObject] ascending];
  2497. } else {
  2498. NSString *tcID = [newTableColumn identifier];
  2499. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  2500. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  2501. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  2502. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  2503. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  2504. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  2505. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  2506. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  2507. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2508. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  2509. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2510. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  2511. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  2512. }
  2513. if (oldTableColumn)
  2514. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  2515. [ov setHighlightedTableColumn:newTableColumn];
  2516. }
  2517. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  2518. if (newTableColumn)
  2519. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  2520. inTableColumn:newTableColumn];
  2521. [ov reloadData];
  2522. }
  2523. }
  2524. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  2525. if (mwcFlags.autoResizeNoteRows &&
  2526. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  2527. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  2528. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  2529. [rowHeights removeAllFloats];
  2530. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  2531. }
  2532. }
  2533. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  2534. {
  2535. NSInteger rowCount = [outlineView numberOfRows];
  2536. for (NSInteger i = 0; i < rowCount; i++){
  2537. CGFloat rowHeight = 0;
  2538. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  2539. if (!outline){
  2540. continue;
  2541. }
  2542. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2543. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2544. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  2545. [attributedString appendAttributedString:attr1];
  2546. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  2547. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  2548. // id cell = [tableColumn dataCell];
  2549. id cell = [tableColumn dataCellForRow:i];
  2550. [cell setObjectValue:attributedString];
  2551. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  2552. NSInteger num = [self getNum:outline];
  2553. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  2554. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  2555. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  2556. [rowHeights setFloat:rowHeight forKey:outline];
  2557. if (@available(macOS 10.13, *)) {
  2558. } else {
  2559. rowHeight = 40.0;
  2560. }
  2561. // CGRect fram = viewS.frame;
  2562. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  2563. }
  2564. [leftSideController.tocOutlineView reloadData];
  2565. }
  2566. */
  2567. func noteItems(_ items: NSArray) -> NSArray {
  2568. let noteItems = NSMutableArray()
  2569. for item in items {
  2570. guard let anno = (item as? KMBotaAnnotationModel)?.anno else {
  2571. continue
  2572. }
  2573. if anno.type == nil {
  2574. // item = [(SKNoteText *)item note];
  2575. }
  2576. if noteItems.contains(anno) == false {
  2577. noteItems.add(anno)
  2578. }
  2579. }
  2580. return noteItems
  2581. }
  2582. }
  2583. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  2584. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  2585. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  2586. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2587. return self.hideNotes() == false && items.count > 0
  2588. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2589. return items.count > 0
  2590. }
  2591. return false
  2592. }
  2593. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  2594. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2595. if (items.isEmpty) {
  2596. return
  2597. }
  2598. self.dataUpdating = true
  2599. for item in self.noteItems(items as NSArray) {
  2600. guard let anno = item as? CPDFAnnotation else {
  2601. continue
  2602. }
  2603. if let data = anno as? CPDFFreeTextAnnotation {
  2604. self.listView?.commitEditAnnotationFreeText(data)
  2605. }
  2606. self.listView?.remove(anno)
  2607. }
  2608. for item in items {
  2609. if let data = item as? KMBotaAnnotationModel {
  2610. data.sectionModel?.items.removeObject(data)
  2611. if let footerModel = data.footerModel {
  2612. data.sectionModel?.items.removeObject(footerModel)
  2613. }
  2614. }
  2615. }
  2616. self.dataUpdating = false
  2617. self.listView?.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  2618. self.note_refrshUIIfNeed()
  2619. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2620. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  2621. }
  2622. }
  2623. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  2624. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2625. if (items.count == 1) {
  2626. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  2627. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  2628. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  2629. // return NO;
  2630. // }
  2631. }
  2632. return items.count > 0
  2633. }
  2634. return false
  2635. }
  2636. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  2637. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  2638. // let pboard = NSPasteboard.general
  2639. // var copiedItems: [Any] = []
  2640. // var attrString = NSMutableAttributedString()
  2641. // var isAttributed = false
  2642. // var item: AnyObject?
  2643. // for (item in [self noteItems:items]) {
  2644. // if ([item isMovable])
  2645. // [copiedItems addObject:item];
  2646. // }
  2647. // for (item in items) {
  2648. // if ([attrString length])
  2649. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  2650. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  2651. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  2652. // isAttributed = YES;
  2653. // } else {
  2654. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  2655. // }
  2656. // }
  2657. //
  2658. // [pboard clearContents];
  2659. // if (isAttributed)
  2660. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  2661. // else
  2662. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  2663. // if ([copiedItems count] > 0)
  2664. // [pboard writeObjects:copiedItems];
  2665. }
  2666. }
  2667. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelperSelectionStrings aTypeSelectHelper: SKTypeSelectHelper) -> NSArray {
  2668. if self.noteOutlineView.isEqual(to: anOutlineView) {
  2669. let count = self.noteOutlineView.numberOfRows
  2670. let texts = NSMutableArray(capacity: count)
  2671. for i in 0 ..< count {
  2672. let item = self.noteOutlineView.item(atRow: i)
  2673. let string = (item as? CPDFAnnotation)?.string() ?? ""
  2674. texts.add(string)
  2675. }
  2676. return texts
  2677. } else if self.tocOutlineView.isEqual(to: anOutlineView) {
  2678. let count = self.tocOutlineView.numberOfRows
  2679. let array = NSMutableArray(capacity: count)
  2680. for i in 0 ..< count {
  2681. // [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  2682. let item = self.tocOutlineView.item(atRow: i) as? CPDFOutline
  2683. array.add(item?.label ?? "")
  2684. }
  2685. return array
  2686. }
  2687. return NSArray()
  2688. }
  2689. }
  2690. // MARK: - Other
  2691. extension KMLeftSideViewController {
  2692. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  2693. if tv.isEqual(to: self.thumbnailTableView) {
  2694. guard let document = self.pdfDocument() else {
  2695. return
  2696. }
  2697. let pages = NSMutableArray()
  2698. for idx in self.thumbnailTableView.selectedRowIndexes {
  2699. if (idx < document.pageCount) {
  2700. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  2701. pages.add(page)
  2702. }
  2703. }
  2704. }
  2705. var fileName = document.documentURL.deletingPathExtension().lastPathComponent
  2706. fileName.append(" pages ")
  2707. fileName.append(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: self.thumbnailTableView.selectedRowIndexes.sorted()))
  2708. fileName.append(".pdf")
  2709. let saveAccessCtr = KMSavePanelAccessoryController()
  2710. let outputSavePanel = NSSavePanel()
  2711. outputSavePanel.allowedFileTypes = ["pdf"]
  2712. outputSavePanel.accessoryView = saveAccessCtr.view
  2713. outputSavePanel.nameFieldStringValue = fileName
  2714. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  2715. if (result == .OK) {
  2716. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  2717. let vc = KMProgressWindowController()
  2718. self.view.window?.beginSheet(vc.window!)
  2719. let saveFilePath = outputSavePanel.url?.path
  2720. DispatchQueue.global().async {
  2721. let pdf = CPDFDocument()
  2722. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  2723. DispatchQueue.main.async {
  2724. if (success) {
  2725. if (saveAccessCtr.openAutomaticButton.state == .on) {
  2726. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  2727. }
  2728. } else {
  2729. KMTools.viewFile(at: saveFilePath!)
  2730. }
  2731. }
  2732. NSApp.endSheet(vc.window!)
  2733. vc.close()
  2734. }
  2735. }
  2736. }
  2737. }
  2738. }
  2739. }
  2740. }
  2741. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  2742. var pagesName = ""
  2743. if (itemIndexes.count > 1) {
  2744. pagesName.append(" pages")
  2745. } else {
  2746. pagesName.append(" page")
  2747. }
  2748. let docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2749. let tFileName = String(format: "%@ %@", pagesName,KMTools.parseIndexSet(indexSet: itemIndexes))
  2750. return String(format: "%@%@", docmentName,tFileName)
  2751. }
  2752. func draggedFileName(for page: CPDFPage) -> String {
  2753. let pageIndex = "\(page.pageIndex() + 1)"
  2754. var fileName = ""
  2755. if let doc = self.view.window?.windowController?.document as? NSDocument {
  2756. // fileName = doc.displayName.deletingPathExtension
  2757. fileName = doc.fileURL?.deletingPathExtension().lastPathComponent ?? (MainBundle.nameSpaceName ?? "")
  2758. }
  2759. return "\(fileName)-Page \(pageIndex)"
  2760. }
  2761. func switchType(_ type: BotaType) {
  2762. if type == .Thumbnail {
  2763. self.leftView.segmentedControl.selectedSegment = 1
  2764. } else if type == .Outline {
  2765. self.leftView.segmentedControl.selectedSegment = 2
  2766. } else if type == .Annotation {
  2767. self.leftView.segmentedControl.selectedSegment = 3
  2768. } else if type == .snapshot {
  2769. self.leftView.segmentedControl.selectedSegment = 4
  2770. } else if type == .Search {
  2771. self.leftView.segmentedControl.selectedSegment = 0
  2772. }
  2773. }
  2774. func updateTableFont() {
  2775. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  2776. self.tocOutlineView.font = font
  2777. self.noteOutlineView.font = font
  2778. self.findTableView.font = font
  2779. self.groupedFindTableView.font = font
  2780. }
  2781. }