KMLeftSideViewController.swift 138 KB

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