KMLeftSideViewController.swift 158 KB

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