KMLeftSideViewController.swift 162 KB

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