KMLeftSideViewController.swift 140 KB

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