KMLeftSideViewController.swift 140 KB

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