KMLeftSideViewController.swift 139 KB

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