KMLeftSideViewController.swift 163 KB

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