KMLeftSideViewController.swift 171 KB

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