KMLeftSideViewController.swift 164 KB

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