KMLeftSideViewController.swift 243 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075
  1. //
  2. // KMLeftSideViewController.swift
  3. // PDF Master
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. @objc protocol KMLeftSideViewControllerDelegate {
  9. @objc optional func controlStateChange(_ obj: KMLeftSideViewController,show:Bool)
  10. @objc optional func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int])
  11. @objc optional func searchAction(searchString:String, isCase:Bool)
  12. @objc optional func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType)
  13. @objc optional func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  14. @objc optional func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem])
  15. @objc optional func controller(controller: KMLeftSideViewController, rotateType: KMRotateType)
  16. }
  17. class KMLeftSideViewController: KMSideViewController {
  18. var dataSource : [KMLeftMethodMode] = [KMLeftMethodMode]()
  19. var type : KMLeftMethodMode = KMLeftMethodMode()
  20. var isShowPanel : Bool = false
  21. var norImage : [String] = []
  22. var selectImage : [String] = []
  23. var mainVC: KMMainViewController?
  24. var selectPages: [Int]?
  25. open weak var delegate: KMLeftSideViewControllerDelegate?
  26. deinit {
  27. KMPrint("KMLeftSideViewController deinit.")
  28. NotificationCenter.default.removeObserver(self)
  29. }
  30. override var nibName: NSNib.Name? {
  31. return "LeftSideView"
  32. }
  33. convenience init(type : KMLeftMethodMode) {
  34. self.init()
  35. self.type = type
  36. }
  37. override func viewDidLoad() {
  38. super.viewDidLoad()
  39. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  40. self.isDisplayPageSize = UserDefaults.standard.bool(forKey: "kKMThumbnailDisplayPageSizeKey")
  41. }
  42. func showPanelView(show: Bool) {
  43. self.isShowPanel = show
  44. if show {
  45. self.leftView.segmentedControl.selectedSegment = 0
  46. } else {
  47. self.leftView.segmentedControl.selectedSegment = UInt8.max
  48. self.delegate?.controlStateChange?(self, show: false)
  49. }
  50. }
  51. func refreshMethodType(methodType: BotaType) {
  52. let newType = KMLeftMethodMode()
  53. var show = true
  54. if self.type.methodType != methodType {
  55. newType.methodType = methodType
  56. }
  57. if self.type.methodType == methodType {
  58. show = false
  59. } else if methodType == .None {
  60. show = false
  61. }
  62. self.type = newType;
  63. self.delegate?.controlStateChange?(self,show:show)
  64. }
  65. // MARK: - New
  66. /*
  67. NSArrayController *findArrayController;
  68. NSArrayController *groupedFindArrayController;
  69. }
  70. - (void)applySearchTableHeader:(NSString *)message;
  71. */
  72. @IBOutlet var segmentedControl: KMSegmentedControl!
  73. @IBOutlet var thumbnailTableView: KMThumbnailTableView!
  74. @IBOutlet var tocOutlineView: KMTocOutlineView!
  75. @IBOutlet var noteOutlineView: KMNoteOutlineView!
  76. @IBOutlet var findTableView: KMBotaTableView!
  77. @IBOutlet var groupedFindTableView: KMBotaTableView!
  78. @IBOutlet var snapshotTableView: KMBotaTableView!
  79. @IBOutlet weak var leftListView: NSView!
  80. @IBOutlet var searchViewController: KMBotaSearchViewController!
  81. @IBOutlet weak var toolButtonBox: NSBox!
  82. @IBOutlet weak var toolButtonBoxLayoutConstraint: NSLayoutConstraint!
  83. @IBOutlet weak var snapshotNormalView: NSView!
  84. @IBOutlet weak var snapshotLabel: NSTextField!
  85. @IBOutlet weak var snapshotNormalMoreButton: NSButton!
  86. @IBOutlet weak var snapshotNormalSearchButton: NSButton!
  87. @IBOutlet weak var snapshotNormalZoomOutButton: NSButton!
  88. @IBOutlet weak var snapshotNormalZoomInButton: NSButton!
  89. @IBOutlet weak var snapshotSearchZoomOutButton: NSButton!
  90. @IBOutlet weak var snapshotSearchZoomInButton: NSButton!
  91. @IBOutlet weak var snapshotSearchField: KMLeftSideViewSearchField!
  92. @IBOutlet weak var snapshotDoneButton: NSButton!
  93. @IBOutlet weak var outlineView: NSView!
  94. @IBOutlet weak var outlineMoreButton: NSButton!
  95. @IBOutlet weak var outlineAddButton: NSButton!
  96. @IBOutlet weak var outlineSearchButton: NSButton!
  97. @IBOutlet weak var outlineLabel: NSTextField!
  98. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  99. @IBOutlet weak var outlineDoneButton: NSButton!
  100. @IBOutlet weak var noteView: NSView!
  101. @IBOutlet weak var noteMoreButton: NSButton!
  102. @IBOutlet weak var noteFilterButton: NSButton!
  103. @IBOutlet weak var noteSearchButton: NSButton!
  104. @IBOutlet weak var noteSearchField: KMLeftSideViewSearchField!
  105. @IBOutlet weak var noteTitleLabel: NSTextField!
  106. @IBOutlet weak var noteHeaderView: NSView!
  107. @IBOutlet weak var sortTypeBox: KMBox!
  108. @IBOutlet weak var sortTypeLabel: NSTextField!
  109. @IBOutlet weak var noteSortButton: NSButton!
  110. @IBOutlet weak var noteDoneButton: NSButton!
  111. @IBOutlet weak var thumbnailView: NSView!
  112. @IBOutlet weak var thumbnailZoomOutButton: NSButton!
  113. @IBOutlet weak var thumbnailZoomInButton: NSButton!
  114. @IBOutlet weak var thumbnailTitleLabel: NSTextField!
  115. @IBOutlet weak var emptySearchBox: NSBox!
  116. @IBOutlet weak var emptySearchLabel: NSTextField!
  117. var filterButtonLayer: NSView?
  118. var moreButtonLayer: KMButtonLayer?
  119. var thumbnails: [KMThumbnail] = []
  120. var isDisplayPageSize = false
  121. var thumbnailCacheSize: CGFloat = 32 * 3
  122. private var _findState: KMFindState = .none
  123. var findState: KMFindState {
  124. get {
  125. return self._findState
  126. }
  127. set {
  128. if self._findState != newValue {
  129. self._findState = newValue
  130. self.displayFindState()
  131. if self._findState == .content {
  132. self.search(self.searchField)
  133. } else if self.findState == .note {
  134. // self.searchNotes(self.searchField)
  135. self.searchNotes(nil)
  136. } else if self.findState == .snapshot {
  137. self.searchNotes(self.searchField)
  138. }
  139. }
  140. }
  141. }
  142. var searchResults : [KMSearchMode] = [] {
  143. didSet {
  144. self.updataLeftSideFindView()
  145. }
  146. }
  147. var groupSearchResults: [KMSearchMode] = []
  148. var findPaneState: KMFindPaneState = .singular
  149. var isSearchOutlineMode = false
  150. var isSearchSnapshotMode = false
  151. var outlineIgnoreCaseFlag = false
  152. var noteTypeDict: [String : Any] = [:]
  153. private let MIN_SIDE_PANE_WIDTH: CGFloat = 270
  154. private let LABEL_COLUMNID = "label"
  155. var foldType: KMFoldAllAnnotationType = .none
  156. private let KMLeftSideViewNoteSortTypeKey = "KMLeftSideViewNoteSortTypeKey"
  157. private let KMLeftSideViewAscendSortBoolKey = "KMLeftSideViewAscendSortBoolKey"
  158. private let SKDisableTableToolTipsKey = "SKDisableTableToolTips"
  159. var tocType: KMFoldType = .none
  160. var snapshots: [KMSnapshotModel] = []
  161. var searchSnapshots: [KMSnapshotModel] = []
  162. private var _noteSortType: KMNoteSortType = .none
  163. var noteSortType: KMNoteSortType {
  164. get {
  165. return self._noteSortType
  166. }
  167. set {
  168. self._noteSortType = newValue
  169. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  170. }
  171. }
  172. var isAscendSort = false {
  173. didSet {
  174. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  175. }
  176. }
  177. lazy var leftSideEmptyVC: KMLeftSideEmptyFileViewController = {
  178. let vc = KMLeftSideEmptyFileViewController(nibName: "KMLeftSideEmptyFileViewController", bundle: nil)
  179. vc.view.wantsLayer = true
  180. return vc
  181. }()
  182. var preThumbnailRow: Int = 0
  183. var leftMargin: CGFloat = 0
  184. lazy var leftView: KMBotaLeftView = {
  185. let view = KMBotaLeftView()
  186. return view
  187. }()
  188. private var _copysPages: [CPDFPage] = []
  189. var copyPages: [CPDFPage] {
  190. get {
  191. return self._copysPages
  192. }
  193. }
  194. private var _annotations: [KMBOTAAnnotationSection] = []
  195. private var _allAnnotations: [CPDFAnnotation] = []
  196. var allAnnotations: [CPDFAnnotation] {
  197. get {
  198. return self._allAnnotations
  199. }
  200. }
  201. private let kKMPDFViewOutlineDragDataType = "kKMPDFViewOutlineDragDataType"
  202. private let KPDFThumbnailDoucumentURLForDraggedTypes = "KPDFThumbnailDoucumentURLForDraggedTypes"
  203. var renamePDFOutline: CPDFOutline?
  204. var renamePDFOutlineTextField: NSTextField?
  205. var allFoldNotes: [CPDFAnnotation] = []
  206. var notes: [CPDFAnnotation] = []
  207. var canFoldNotes: [CPDFAnnotation] = []
  208. var isRenameNoteOutline = false
  209. var caseInsensitiveNoteSearch = false
  210. var noteSearchArray: [CPDFAnnotation] = []
  211. var noteSearchMode = false
  212. var mwcFlags: MwcFlags = MwcFlags()
  213. override func loadView() {
  214. super.loadView()
  215. self.view.wantsLayer = true
  216. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  217. self.view.addSubview(self.leftView)
  218. self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  219. self.leftView.autoresizingMask = [.height]
  220. self.leftView.wantsLayer = true
  221. self.leftView.layer?.backgroundColor = .white
  222. self.outlineView.wantsLayer = true
  223. self.outlineView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  224. self.noteView.wantsLayer = true
  225. self.noteView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  226. self.thumbnailView.wantsLayer = true
  227. self.thumbnailView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  228. self.snapshotNormalView.wantsLayer = true
  229. self.snapshotNormalView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  230. self.tocOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  231. self.noteOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  232. self.findTableView.backgroundColor = KMAppearance.Layout.l0Color()
  233. self.groupedFindTableView.backgroundColor = KMAppearance.Layout.l0Color()
  234. self.snapshotTableView.backgroundColor = KMAppearance.Layout.l0Color()
  235. self.thumbnailTableView.backgroundColor = KMAppearance.Layout.l0Color()
  236. self.leftListView.wantsLayer = true
  237. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  238. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  239. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  240. self.emptySearchBox.isHidden = true
  241. self.thumbnailTitleLabel.stringValue = KMLocalizedString("Thumbnails", nil)
  242. self.thumbnailTitleLabel.textColor = KMAppearance.Layout.h0Color()
  243. self.thumbnailZoomInButton.action = #selector(thumbnailSizeScaling)
  244. self.thumbnailZoomInButton.target = self
  245. self.thumbnailZoomInButton.tag = 1
  246. self.thumbnailZoomOutButton.action = #selector(thumbnailSizeScaling)
  247. self.thumbnailZoomOutButton.target = self
  248. self.thumbnailZoomOutButton.tag = 0
  249. self.snapshotTableView.delegate = self
  250. self.snapshotTableView.dataSource = self
  251. self.snapshotTableView.menu = NSMenu()
  252. self.snapshotTableView.menu?.delegate = self
  253. self.snapshotTableView.doubleAction = #selector(toggleSelectedSnapshots)
  254. self.snapshotTableView.target = self
  255. self.snapshotTableView.backgroundColor = .clear
  256. // [snapshotTableView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
  257. self.snapshotLabel.stringValue = KMLocalizedString("Snapshots", nil)
  258. self.snapshotLabel.textColor = KMAppearance.Layout.h0Color()
  259. self.snapshotNormalZoomInButton.action = #selector(thumbnailSizeScaling)
  260. self.snapshotNormalZoomInButton.target = self
  261. self.snapshotNormalZoomInButton.tag = 2
  262. self.snapshotNormalZoomOutButton.action = #selector(thumbnailSizeScaling)
  263. self.snapshotNormalZoomOutButton.target = self
  264. self.snapshotNormalZoomOutButton.tag = 3
  265. self.snapshotNormalSearchButton.toolTip = KMLocalizedString("Search", nil)
  266. self.snapshotNormalMoreButton.action = #selector(leftSideViewMoreButtonAction)
  267. self.snapshotNormalMoreButton.target = self
  268. self.snapshotNormalMoreButton.tag = 300
  269. self.snapshotSearchZoomInButton.action = #selector(thumbnailSizeScaling)
  270. self.snapshotSearchZoomInButton.target = self
  271. self.snapshotSearchZoomInButton.tag = 2
  272. self.snapshotSearchZoomOutButton.action = #selector(thumbnailSizeScaling)
  273. self.snapshotSearchZoomOutButton.target = self
  274. self.snapshotSearchZoomOutButton.tag = 3
  275. self.snapshotDoneButton.title = KMLocalizedString("Done", nil)
  276. self.snapshotDoneButton.toolTip = KMLocalizedString("Done", nil)
  277. self.snapshotDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  278. self.snapshotDoneButton.wantsLayer = true
  279. self.snapshotDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  280. self.snapshotDoneButton.layer?.cornerRadius = 4.0
  281. self.snapshotDoneButton.action = #selector(leftSideViewDoneButtonAction)
  282. self.snapshotDoneButton.target = self
  283. self.snapshotDoneButton.tag = 312
  284. self.snapshotDoneButton.isHidden = true
  285. self.noteOutlineView.autoresizesOutlineColumn = false
  286. self.noteOutlineView.delegate = self
  287. self.noteOutlineView.dataSource = self
  288. self.noteOutlineView.botaDelegate = self
  289. self.noteOutlineView.botaDataSource = self
  290. self.noteOutlineView.noteDelegate = self
  291. self.noteOutlineView.menu = NSMenu()
  292. self.noteOutlineView.menu?.delegate = self
  293. // [noteOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  294. self.noteOutlineView.indentationPerLevel = 0
  295. // [noteOutlineView registerForDraggedTypes:[NSColor readableTypesForPasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]]];
  296. self.noteOutlineView.target = self
  297. self.noteOutlineView.doubleAction = #selector(selectSelectedNote)
  298. self.tocOutlineView.menu = NSMenu()
  299. self.tocOutlineView.menu?.delegate = self
  300. self.outlineSearchField.delegate = self
  301. self.snapshotSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  302. self.outlineSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  303. self.noteSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  304. self.snapshotSearchField.wantsLayer = true
  305. self.outlineSearchField.wantsLayer = true
  306. self.noteSearchField.wantsLayer = true
  307. self.snapshotSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  308. self.outlineSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  309. self.noteSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  310. self.snapshotSearchField.layer?.borderWidth = 1.0
  311. self.outlineSearchField.layer?.borderWidth = 1.0
  312. self.noteSearchField.layer?.borderWidth = 1.0
  313. self.snapshotSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  314. self.outlineSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  315. self.noteSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  316. // __block typeof(self) blockSelf = self;
  317. // _snapshotSearchField.changeCallBack = ^(NSString *changeContent) {
  318. // NSString *editContent = @"";
  319. // if (changeContent) {
  320. // editContent = changeContent;
  321. // }
  322. // [blockSelf.mainController searchFieldChangeAction:editContent];
  323. // };
  324. self.snapshotSearchField.isHidden = true
  325. self.snapshotSearchZoomOutButton.isHidden = true
  326. self.snapshotSearchZoomInButton.isHidden = true
  327. // _snapshotSearchField.endEditCallBack = ^(BOOL isEndEdit) {
  328. // if (isEndEdit/* && searchViewController.segmentedControl.segmentCount == 3*/) {
  329. // _snapshotSearchField.hidden = YES;
  330. // _snapshotSearchZoomOutButton.hidden = YES;
  331. // _snapshotSearchZoomInButton.hidden = YES;
  332. // _snapshotLabel.hidden = NO;
  333. // _snapshotNormalZoomOutButton.hidden = NO;
  334. // _snapshotNormalZoomInButton.hidden = NO;
  335. // }
  336. // };
  337. self.thumbnailZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  338. self.snapshotNormalZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  339. self.snapshotSearchZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  340. self.thumbnailZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  341. self.snapshotNormalZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  342. self.snapshotSearchZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  343. self.outlineLabel.stringValue = KMLocalizedString("Outline", nil);
  344. self.outlineLabel.textColor = KMAppearance.Layout.h0Color()
  345. self.outlineAddButton.toolTip = KMLocalizedString("Add Item", nil)
  346. self.outlineAddButton.action = #selector(outlineContextMenuItemClicked_AddEntry)
  347. self.outlineAddButton.target = self
  348. self.outlineSearchButton.toolTip = KMLocalizedString("Search", nil)
  349. self.outlineMoreButton.action = #selector(leftSideViewMoreButtonAction)
  350. self.outlineMoreButton.target = self
  351. self.outlineMoreButton.tag = 302
  352. self.outlineDoneButton.title = KMLocalizedString("Done", nil);
  353. self.outlineDoneButton.toolTip = KMLocalizedString("Done", nil);
  354. self.outlineDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  355. self.outlineDoneButton.wantsLayer = true
  356. self.outlineDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  357. self.outlineDoneButton.layer?.cornerRadius = 4.0
  358. self.outlineDoneButton.action = #selector(leftSideViewDoneButtonAction)
  359. self.outlineDoneButton.target = self
  360. self.outlineDoneButton.tag = 310
  361. self.outlineDoneButton.isHidden = true
  362. self.outlineSearchField.isHidden = true
  363. // _outlineSearchField.endEditCallBack = ^(BOOL isEndEdit) {
  364. // if (isEndEdit) {
  365. // _outlineSearchField.hidden = YES;
  366. // _outlineLabel.hidden = NO;
  367. // _outlineSearchButton.hidden = NO;
  368. // }
  369. // };
  370. let menuOutline = NSMenu()
  371. menuOutline.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleOutlineCaseInsensitiveSearch), target: self)
  372. (self.outlineSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menuOutline
  373. (self.outlineSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Outline", nil)
  374. self.outlineSearchField.target = self
  375. let sud = UserDefaults.standard
  376. self.noteTitleLabel.stringValue = KMLocalizedString("Notes", nil);
  377. self.noteTitleLabel.textColor = KMAppearance.Layout.h0Color()
  378. self.noteMoreButton.action = #selector(leftSideViewMoreButtonAction)
  379. self.noteMoreButton.target = self
  380. self.noteMoreButton.tag = 304
  381. self.noteMoreButton.wantsLayer = true
  382. self.moreButtonLayer = KMButtonLayer()
  383. self.noteMoreButton.layer?.addSublayer(self.moreButtonLayer!)
  384. self.moreButtonLayer?.frame = CGRectMake(0, 0, CGRectGetWidth(self.noteMoreButton.bounds), CGRectGetHeight(self.noteMoreButton.bounds))
  385. self.moreButtonLayer?.layerType = .none
  386. self.moreButtonLayer?.isHidden = true
  387. self.noteFilterButton.action = #selector(noteFilterAction)
  388. self.noteFilterButton.target = self
  389. self.noteFilterButton.toolTip = KMLocalizedString("Sort", nil)
  390. self.noteFilterButton.wantsLayer = true
  391. self.filterButtonLayer = NSView()
  392. self.noteFilterButton.addSubview(self.filterButtonLayer!)
  393. self.filterButtonLayer?.frame = CGRectMake(14, 2, 8, 8)
  394. self.filterButtonLayer?.isHidden = true
  395. self.filterButtonLayer?.wantsLayer = true
  396. self.filterButtonLayer?.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  397. self.filterButtonLayer?.layer?.cornerRadius = 4.0
  398. self.noteDoneButton.title = KMLocalizedString("Done", nil)
  399. self.noteDoneButton.toolTip = KMLocalizedString("Done", nil)
  400. self.noteDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  401. self.noteDoneButton.wantsLayer = true
  402. self.noteDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  403. self.noteDoneButton.layer?.cornerRadius = 4.0
  404. self.noteDoneButton.action = #selector(leftSideViewDoneButtonAction)
  405. self.noteDoneButton.target = self
  406. self.noteDoneButton.tag = 311
  407. self.noteDoneButton.isHidden = true
  408. self.noteSearchButton.toolTip = KMLocalizedString("Search", nil)
  409. self.noteSearchField.delegate = self
  410. self.noteSearchField.isHidden = true
  411. self.noteSearchField.endEditCallBack = { [unowned self] isEndEdit in
  412. if (isEndEdit) {
  413. self.noteSearchField.isHidden = true
  414. self.noteSearchButton.isHidden = false
  415. self.noteTitleLabel.isHidden = false
  416. }
  417. };
  418. self.noteHeaderView.wantsLayer = true
  419. self.noteHeaderView.layer?.backgroundColor = KMAppearance.Else.textTagColor().cgColor
  420. self.noteHeaderView.layer?.cornerRadius = 1.0
  421. let sortType = sud.integer(forKey: KMLeftSideViewNoteSortTypeKey)
  422. if (sortType == 1) {
  423. self.noteSortType = KMNoteSortType(rawValue: sortType)!
  424. if (self.noteSortType == .time) {
  425. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  426. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  427. } else if (self._noteSortType == .page) {
  428. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  429. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  430. }
  431. } else {
  432. self.noteSortType = .time
  433. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  434. }
  435. self.sortTypeLabel.textColor = KMAppearance.Layout.h1Color()
  436. self.isAscendSort = sud.bool(forKey: KMLeftSideViewAscendSortBoolKey)
  437. if (self.isAscendSort) {
  438. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  439. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  440. } else {
  441. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  442. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  443. }
  444. self.sortTypeBox.downCallback = { [unowned self] downEntered, mouseBox, _ in
  445. if (downEntered) {
  446. let menu = NSMenu()
  447. let timeItem = menu.addItem(title: KMLocalizedString("Time", nil), action: #selector(sortTypeAction), target: self)
  448. timeItem?.representedObject = self
  449. timeItem?.tag = 0
  450. let pageItem = menu.addItem(title: KMLocalizedString("Page", nil), action: #selector(sortTypeAction), target: self)
  451. pageItem?.representedObject = self
  452. timeItem?.tag = 1
  453. if (self.noteSortType == .time) {
  454. timeItem?.state = .on
  455. pageItem?.state = .off
  456. } else if (self.noteSortType == .page) {
  457. timeItem?.state = .off
  458. pageItem?.state = .on
  459. }
  460. menu.popUp(positioning: nil, at: CGPointMake(-10, 0), in: self.sortTypeBox)
  461. }
  462. }
  463. self.searchViewController.loadView()
  464. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  465. self.searchField = self.searchViewController.searchField
  466. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  467. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  468. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  469. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  470. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  471. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  472. self.searchViewController.segmentedControl.selectedSegment = 0
  473. self.searchViewController.segmentedControl.block = { [unowned self] segIndex in
  474. if segIndex == 0 {
  475. self.findPaneState = .singular
  476. self.displayFindViewAnimating(false)
  477. } else {
  478. self.findPaneState = .grouped
  479. self.displayGroupedFindViewAnimating(false)
  480. }
  481. }
  482. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  483. self.toolButtonBox.isHidden = false
  484. self.toolButtonBoxLayoutConstraint.constant = 40.0
  485. if (segIndex == 0) {
  486. if self.type.methodType == .Thumbnail {
  487. self.leftView.segmentedControl.selectedSegment = UInt8.max
  488. self.refreshMethodType(methodType: .None)
  489. return
  490. }
  491. self.refreshMethodType(methodType: .Thumbnail)
  492. DispatchQueue.main.async {
  493. self.toolButtonBox.contentView = self.thumbnailView
  494. self.displayThumbnailViewAnimating(false)
  495. }
  496. } else if (segIndex == 1) {
  497. if self.type.methodType == .Outline {
  498. self.leftView.segmentedControl.selectedSegment = UInt8.max
  499. self.refreshMethodType(methodType: .None)
  500. return
  501. }
  502. self.refreshMethodType(methodType: .Outline)
  503. DispatchQueue.main.async {
  504. self.toolButtonBox.contentView = self.outlineView
  505. self.displayTocViewAnimating(false)
  506. }
  507. } else if (segIndex == 2) {
  508. if self.type.methodType == .Annotation {
  509. self.leftView.segmentedControl.selectedSegment = UInt8.max
  510. self.refreshMethodType(methodType: .None)
  511. return
  512. }
  513. self.refreshMethodType(methodType: .Annotation)
  514. DispatchQueue.main.async {
  515. self.toolButtonBox.contentView = self.noteView
  516. self.displayNoteViewAnimating(false)
  517. }
  518. } else if (segIndex == 3) {
  519. self.toolButtonBox.contentView = self.snapshotNormalView
  520. self.updateSnapshotFilterPredicate()
  521. self.displaySnapshotViewAnimating(false)
  522. self.updataLeftSideSnapView()
  523. } else if (segIndex == 4) {
  524. if self.type.methodType == .Search {
  525. self.leftView.segmentedControl.selectedSegment = UInt8.max
  526. self.refreshMethodType(methodType: .None)
  527. return
  528. }
  529. self.refreshMethodType(methodType: .Search)
  530. DispatchQueue.main.async {
  531. self.toolButtonBox.isHidden = true
  532. self.toolButtonBoxLayoutConstraint.constant = 0
  533. self.displayFindViewAnimating(false)
  534. }
  535. }
  536. }
  537. // self.button.setHelp(KMLocalizedString("View Thumbnails", "Tool tip message"), for: KMLeftSidePaneState.thumbnail.rawValue)
  538. // self.button.setHelp(KMLocalizedString("View Outline", "Tool tip message"), for: KMLeftSidePaneState.outline.rawValue)
  539. // self.alternateButton.setHelp(KMLocalizedString("Separate search results", "Tool tip message"), for: KMFindPaneState.singular.rawValue)
  540. // self.alternateButton.setHelp(KMLocalizedString("Group search results by page", "Tool tip message"), for: KMFindPaneState.grouped.rawValue)
  541. let menu = NSMenu()
  542. menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  543. menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  544. (self.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  545. (self.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  546. self.searchField.action = #selector(search)
  547. self.searchField.target = self
  548. self.tocOutlineView.autoresizesOutlineColumn = false
  549. self.tocOutlineView.allowsMultipleSelection = true
  550. self.tocOutlineView.allowsEmptySelection = true
  551. self.tocOutlineView.delegate = self
  552. self.tocOutlineView.dataSource = self
  553. self.tocOutlineView.botaDelegate = self
  554. self.tocOutlineView.botaDataSource = self
  555. self.tocOutlineView.tocDelegate = self
  556. self.thumbnailTableView.delegate = self
  557. self.thumbnailTableView.dataSource = self
  558. self.thumbnailTableView.thumbDelegate = self
  559. self.thumbnailTableView.allowsMultipleSelection = true
  560. self.findTableView.delegate = self
  561. self.findTableView.dataSource = self
  562. self.findTableView.botaDelegate = self
  563. self.groupedFindTableView.delegate = self
  564. self.groupedFindTableView.dataSource = self
  565. self.groupedFindTableView.botaDelegate = self
  566. self.thumbnailTableView.menu?.delegate = self
  567. self.findTableView.menu?.delegate = self
  568. self.groupedFindTableView.menu?.delegate = self
  569. self.tocOutlineView.doubleAction = #selector(goToSelectedOutlineItem)
  570. self.tocOutlineView.target = self
  571. self.findTableView.doubleAction = #selector(goToSelectedFindResults)
  572. self.findTableView.target = self
  573. self.groupedFindTableView.doubleAction = #selector(goToSelectedFindResults)
  574. self.groupedFindTableView.target = self
  575. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  576. // //支持拖拽的文字类型
  577. // [thumbnailTableView registerForDraggedTypes:@[KPDFThumbnailLocalForDraggedTypes,NSFilenamesPboardType]];
  578. // self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL])
  579. self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL,.string,.pdf])
  580. // self.thumbnailTableView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
  581. // self.thumbnailTableView.setDraggingSourceOperationMask([.copy, .delete], forLocal: true)
  582. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  583. // [tocOutlineView registerForDraggedTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType]];
  584. // [[[findTableView tableColumnWithIdentifier:PAGE_COLUMNID] headerCell] setTitle:NSLocalizedString(@"Page", @"Table header title")];
  585. // [[[groupedFindTableView tableColumnWithIdentifier:PAGE_COLUMNID] headerCell] setTitle:NSLocalizedString(@"Page", @"Table header title")];
  586. // [[[groupedFindTableView tableColumnWithIdentifier:RELEVANCE_COLUMNID] dataCell] setEnabled:NO];
  587. self.thumbnailTableView.selectionHighlightStyle = .none
  588. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  589. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  590. //
  591. // self.thumbnailTableView.setDraggingSourceOperationMask(.every, forLocal: false)
  592. if UserDefaults.standard.bool(forKey: SKDisableTableToolTipsKey) == false {
  593. self.tocOutlineView.hasImageToolTips = true
  594. self.findTableView.hasImageToolTips = true
  595. self.groupedFindTableView.hasImageToolTips = true
  596. }
  597. self._updateViewColor()
  598. self.mwcFlags.wholeWordSearch = UserDefaults.standard.integer(forKey: SKWholeWordSearchKey)
  599. }
  600. func displayThumbnailViewAnimating(_ animate: Bool) {
  601. self.replaceSideView(self.thumbnailTableView.enclosingScrollView!, animate: animate)
  602. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  603. frame.origin.y = 0
  604. frame.origin.x = self.leftMargin
  605. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  606. self.thumbnailTableView.enclosingScrollView?.frame = frame
  607. self.resetThumbnails()
  608. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  609. frame.origin.y = 0
  610. frame.origin.x = self.leftMargin
  611. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  612. self.noteOutlineView.enclosingScrollView?.frame = frame
  613. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  614. frame.origin.y = 0
  615. frame.origin.x = self.leftMargin
  616. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  617. self.snapshotTableView.enclosingScrollView?.frame = frame
  618. // [self updateThumbnailSelection];
  619. }
  620. func displayFindViewAnimating(_ animate: Bool) {
  621. self.replaceSideView(self.searchViewController.view, animate: animate)
  622. if (self.findState != .content) {
  623. self.findState = .content
  624. } else {
  625. self.displayFindState()
  626. }
  627. var frame = self.searchViewController.view.frame
  628. frame.origin.y = 0
  629. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  630. self.searchViewController.view.frame = frame
  631. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  632. frame.origin.y = 0
  633. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  634. self.noteOutlineView.enclosingScrollView?.frame = frame
  635. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  636. frame.origin.y = 0
  637. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  638. self.snapshotTableView.enclosingScrollView?.frame = frame
  639. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  640. self.updataLeftSideSnapView()
  641. }
  642. func displayFindState() {
  643. if (self.findState == .content) {
  644. self.displayFind()
  645. } else if (self.findState == .note) {
  646. self.displayNoteFind()
  647. } else if (self.findState == .snapshot) {
  648. self.displaySnapshotFind()
  649. }
  650. }
  651. func updataLeftSideSnapView() {
  652. if (snapshots.count < 1) {
  653. self.snapshotNormalSearchButton.isEnabled = false
  654. // leftSideController.snapshotSearchZoomOutButton.enabled = NO;
  655. self.snapshotNormalZoomOutButton.isEnabled = false
  656. // leftSideController.snapshotSearchZoomInButton.enabled = NO;
  657. self.snapshotNormalZoomInButton.isEnabled = false
  658. self.snapshotNormalMoreButton.isEnabled = false
  659. self.leftSideEmptyVC.deleteSnapBtn.isEnabled = false
  660. self.leftSideEmptyVC.exportSnapBtn.isEnabled = false
  661. self.leftSideEmptyVC.printSnapBtn.isEnabled = false
  662. self.snapshotTableView.usesAlternatingRowBackgroundColors = false
  663. let view = self.snapshotTableView.enclosingScrollView!
  664. let emptyVcSize = self.leftSideEmptyVC.emptySnapView.frame.size
  665. self.leftSideEmptyVC.emptySnapView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  666. self.leftSideEmptyVC.emptySnapView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  667. self.snapshotTableView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptySnapView)
  668. } else {
  669. self.snapshotNormalSearchButton.isEnabled = true
  670. // leftSideController.snapshotSearchZoomOutButton.enabled = YES;
  671. self.snapshotNormalZoomOutButton.isEnabled = true
  672. // leftSideController.snapshotSearchZoomInButton.enabled = YES;
  673. self.snapshotNormalZoomInButton.isEnabled = true
  674. self.snapshotNormalMoreButton.isEnabled = true
  675. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  676. self.leftSideEmptyVC.deleteSnapBtn.isEnabled = true
  677. self.leftSideEmptyVC.exportSnapBtn.isEnabled = true
  678. self.leftSideEmptyVC.printSnapBtn.isEnabled = true
  679. }
  680. }
  681. func updataLeftSideFindView() {
  682. if (self.findState != .content) {
  683. return
  684. }
  685. if (self.searchResults.count > 0) {
  686. self.searchViewController.emptyBox.isHidden = true
  687. self.searchViewController.searchResultsView.isHidden = false
  688. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  689. } else {
  690. self.searchViewController.emptyBox.isHidden = false
  691. self.searchViewController.searchResultsView.isHidden = true
  692. }
  693. }
  694. func displayGroupedFindViewAnimating(_ animate: Bool) {
  695. self.replaceSideView(self.searchViewController.view , animate: animate)
  696. if (self.findState != .content) {
  697. self.findState = .content
  698. } else {
  699. self.displayFindState()
  700. }
  701. var frame = self.searchViewController.view.frame
  702. frame.origin.y = 0
  703. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  704. self.searchViewController.view.frame = frame
  705. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  706. frame.origin.y = 0
  707. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  708. self.noteOutlineView.enclosingScrollView?.frame = frame
  709. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  710. frame.origin.y = 0
  711. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  712. self.snapshotTableView.enclosingScrollView?.frame = frame
  713. self.updataLeftSideSnapView()
  714. }
  715. func displayNoteViewAnimating(_ animate: Bool) {
  716. self.reloadAnnotation()
  717. self.searchViewController.contentView = nil
  718. self.replaceSideView(self.noteOutlineView.enclosingScrollView!, animate: animate)
  719. if (self.findState != .note) {
  720. self.findState = .note
  721. } else {
  722. self.displayFindState()
  723. }
  724. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  725. frame.origin.y = 0
  726. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  727. self.noteOutlineView.enclosingScrollView?.frame = frame
  728. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  729. frame.origin.y = 0
  730. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  731. self.noteOutlineView.enclosingScrollView?.frame = frame
  732. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  733. frame.origin.y = 0
  734. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  735. self.snapshotTableView.enclosingScrollView?.frame = frame
  736. let view = self.noteOutlineView.enclosingScrollView!
  737. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  738. 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)
  739. DispatchQueue.main.async {
  740. self.noteOutlineView.reloadData()
  741. }
  742. }
  743. func displaySnapshotViewAnimating(_ animate: Bool) {
  744. self.searchViewController.contentView = nil
  745. self.replaceSideView(self.snapshotTableView.enclosingScrollView!, animate: animate)
  746. if (self.findState != .snapshot) {
  747. self.findState = .snapshot
  748. } else {
  749. self.displayFindState()
  750. }
  751. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  752. frame.origin.y = 0
  753. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  754. self.snapshotTableView.enclosingScrollView?.frame = frame
  755. // frame = rightSideController.noteOutlineView.enclosingScrollView.frame;
  756. // frame.origin.y = 0;
  757. // frame.size.height = rightSideController.noteOutlineView.enclosingScrollView.superview.frame.size.height;
  758. // rightSideController.noteOutlineView.enclosingScrollView.frame = frame;
  759. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  760. frame.origin.y = 0
  761. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  762. self.tocOutlineView.enclosingScrollView?.frame = frame
  763. // [self updateSnapshotsIfNeeded];
  764. Task { @MainActor in
  765. self.snapshotTableView.reloadData()
  766. }
  767. }
  768. func displayFind() {
  769. self.searchField = self.searchViewController.searchField
  770. let menu = NSMenu()
  771. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  772. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  773. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  774. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  775. self.searchViewController.searchField.action = #selector(search)
  776. self.searchViewController.searchField.target = self
  777. if (self.findPaneState == .singular) {
  778. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  779. self.findTableView.wantsLayer = true
  780. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  781. DispatchQueue.main.async {
  782. self.findTableView.reloadData()
  783. }
  784. } else if (self.findPaneState == .grouped) {
  785. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  786. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  787. array.sort(){$0.datas.count > $1.datas.count}
  788. self.groupSearchResults = array
  789. self.groupedFindTableView.reloadData()
  790. }
  791. }
  792. func displayTocViewAnimating(_ animate: Bool) {
  793. self.replaceSideView(self.tocOutlineView.enclosingScrollView!, animate: animate)
  794. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  795. frame.origin.y = 0
  796. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  797. self.tocOutlineView.enclosingScrollView?.frame = frame
  798. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  799. frame.origin.y = 0
  800. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  801. self.noteOutlineView.enclosingScrollView?.frame = frame
  802. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  803. frame.origin.y = 0
  804. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  805. self.snapshotTableView.enclosingScrollView?.frame = frame
  806. let view = self.tocOutlineView.enclosingScrollView!
  807. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  808. 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);
  809. DispatchQueue.main.async {
  810. self.tocOutlineView.reloadData()
  811. self.updateOutlineSelection()
  812. }
  813. }
  814. override func requiresAlternateButton(forView aview: NSView?) -> Bool {
  815. return false
  816. }
  817. func displayNoteFind() {
  818. self.searchField = self.noteSearchField
  819. let menu = NSMenu()
  820. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  821. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  822. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  823. self.noteSearchField.action = #selector(searchNotes)
  824. self.noteSearchField.target = self
  825. }
  826. func displaySnapshotFind() {
  827. self.searchField = self.snapshotSearchField;
  828. let menu = NSMenu()
  829. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  830. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  831. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  832. self.snapshotSearchField.action = #selector(searchNotes)
  833. self.snapshotSearchField.target = self
  834. self.snapshotSearchField.delegate = self
  835. }
  836. /*
  837. - (void)applySearchTableHeader:(NSString *)message {
  838. [[[findTableView tableColumnWithIdentifier:RESULTS_COLUMNID] headerCell] setStringValue:message];
  839. [[findTableView headerView] setNeedsDisplay:YES];
  840. [[[groupedFindTableView tableColumnWithIdentifier:RELEVANCE_COLUMNID] headerCell] setStringValue:message];
  841. [[groupedFindTableView headerView] setNeedsDisplay:YES];
  842. }
  843. */
  844. @IBAction func search(_ sender: NSSearchField) {
  845. self.delegate?.searchAction?(searchString: sender.stringValue, isCase: false)
  846. }
  847. @IBAction func snapshotNormalSearchButtonAction(_ sender: NSButton) {
  848. self.snapshotSearchField.isHidden = false
  849. // _snapshotSearchZoomOutButton.hidden = YES;
  850. self.snapshotSearchZoomInButton.isHidden = true
  851. self.snapshotNormalSearchButton.isHidden = true
  852. self.snapshotDoneButton.isHidden = false
  853. self.snapshotLabel.isHidden = true
  854. self.snapshotNormalZoomOutButton.isHidden = true
  855. self.snapshotNormalZoomInButton.isHidden = true
  856. self.snapshotSearchField.becomeFirstResponder()
  857. }
  858. func resetThumbnails() {
  859. // [self willChangeValueForKey:THUMBNAILS_KEY];
  860. // self.thumbnailCacheSize = 160
  861. self.thumbnails.removeAll()
  862. let pageLabels = self.listView.document.pageLabels()
  863. if (pageLabels.isEmpty == false) {
  864. let isLocked = self.listView.document.isLocked
  865. let firstPage = self.listView.document.page(at: 0)
  866. let emptyPage = CPDFPage()
  867. let firstFrame = firstPage?.bounds(for: .cropBox) ?? .zero
  868. let firstFrame2 = firstPage?.bounds(for: .mediaBox) ?? .zero
  869. emptyPage.setBounds(firstFrame, for: .cropBox)
  870. emptyPage.setBounds(firstFrame2, for: .mediaBox)
  871. emptyPage.rotation = firstPage?.rotation ?? 0
  872. let pageImage = firstPage!.thumbnail(of: NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize))
  873. // NSImage * = [emptyPage thumbnailWithSize:thumbnailCacheSize forBox:[pdfView displayBox]];
  874. var rect: NSRect = .zero
  875. rect.size = pageImage?.size ?? .zero
  876. let width = 1.2 * fmin(NSWidth(rect), NSHeight(rect))
  877. rect = NSInsetRect(rect, 0.5 * (NSWidth(rect) - width), 0.5 * (NSHeight(rect) - width));
  878. pageImage?.lockFocus()
  879. // NSImage(named: NSImage.applicationIconName)?.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  880. if (isLocked) {
  881. NSWorkspace.shared.icon(forFileType: NSFileTypeForHFSTypeCode(OSType(kLockedBadgeIcon))).draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  882. // [[[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kLockedBadgeIcon)] drawInRect:rect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:0.5];
  883. }
  884. pageImage?.unlockFocus()
  885. for (i, label) in pageLabels.enumerated() {
  886. let firstPage = self.listView.document.page(at: UInt(i))
  887. let size = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  888. // let pageImage = firstPage!.thumbnail(of: size)
  889. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  890. // thumbnail.delegate = self
  891. thumbnail.dirty = true
  892. self.thumbnails.append(thumbnail)
  893. }
  894. }
  895. // [self didChangeValueForKey:THUMBNAILS_KEY];
  896. // [self allThumbnailsNeedUpdate];
  897. DispatchQueue.main.async {
  898. self.thumbnailTableView.reloadData()
  899. }
  900. }
  901. @IBAction @objc func sortTypeAction(_ sender: NSMenuItem) {
  902. let item = sender
  903. let tag = item.tag
  904. if (item.state == .on) {
  905. item.state = .off
  906. } else {
  907. item.state = .on
  908. }
  909. if (tag == 0) {
  910. self.noteSortType = .page
  911. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  912. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  913. } else if (tag == 1) {
  914. self.noteSortType = .time
  915. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  916. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  917. }
  918. UserDefaults.standard.set(self.noteSortType.rawValue, forKey: KMLeftSideViewNoteSortTypeKey)
  919. UserDefaults.standard.synchronize()
  920. }
  921. @IBAction func noteSortAction(_ sender: AnyObject?) {
  922. if (self.isAscendSort) {
  923. self.isAscendSort = false
  924. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  925. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  926. } else {
  927. self.isAscendSort = true
  928. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  929. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  930. }
  931. UserDefaults.standard.setValue(self.isAscendSort, forKey: KMLeftSideViewAscendSortBoolKey)
  932. UserDefaults.standard.synchronize()
  933. }
  934. @IBAction func noteSearchAction(_ sender: NSButton) {
  935. self.noteSearchField.isHidden = false
  936. self.noteTitleLabel.isHidden = true
  937. self.noteSearchButton.isHidden = true
  938. self.noteDoneButton.isHidden = false
  939. self.noteFilterButton.isHidden = true
  940. self.noteMoreButton.isHidden = true
  941. self.noteSearchField.becomeFirstResponder()
  942. }
  943. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  944. let button = sender as? NSButton
  945. let tag = button?.tag ?? 0
  946. if (tag == 310) {
  947. self.outlineSearchField.isHidden = true
  948. self.outlineDoneButton.isHidden = true
  949. self.outlineLabel.isHidden = false
  950. self.outlineSearchButton.isHidden = false
  951. self.outlineMoreButton.isHidden = false
  952. self.outlineAddButton.isHidden = false
  953. } else if (tag == 311) {
  954. self.noteSearchField.isHidden = true
  955. self.noteTitleLabel.isHidden = false
  956. self.noteSearchButton.isHidden = false
  957. self.noteDoneButton.isHidden = true
  958. self.noteFilterButton.isHidden = false
  959. self.noteMoreButton.isHidden = false
  960. } else if (tag == 312) {
  961. self.snapshotSearchField.isHidden = true
  962. // leftSideController.snapshotSearchZoomOutButton.hidden = YES;
  963. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  964. self.snapshotNormalSearchButton.isHidden = false
  965. self.snapshotDoneButton.isHidden = true
  966. self.snapshotLabel.isHidden = false
  967. self.snapshotNormalZoomOutButton.isHidden = false
  968. self.snapshotNormalZoomInButton.isHidden = false
  969. }
  970. }
  971. @IBAction func leftSideViewMoreButtonAction(_ sender: AnyObject?) {
  972. let button = sender as? NSButton
  973. let tag = button?.tag ?? 0
  974. if (tag == 300) {
  975. var selectedRow = 0
  976. if (self.snapshotTableView.selectedRow >= 0) {
  977. selectedRow = self.snapshotTableView.selectedRow;
  978. } else {
  979. return
  980. }
  981. let model = self.snapshots[selectedRow]
  982. let controller = model.windowC
  983. let menu = NSMenu()
  984. let itemExport = menu.addItem(title: KMLocalizedString("Export", "Menu item title"), action: nil, target: self)
  985. let subMenu = NSMenu()
  986. var t = subMenu.addItem(title: KMLocalizedString("PNG", "Menu item title"), action: #selector(menuItemClick_ExportPNG), target: self)
  987. t?.representedObject = controller
  988. t = subMenu.addItem(title: KMLocalizedString("JPG", "Menu item title"), action: #selector(menuItemClick_ExportJPG), target: self)
  989. t?.representedObject = controller
  990. t = subMenu.addItem(title: KMLocalizedString("PDF", "Menu item title"), action: #selector(menuItemClick_ExportPDF), target: self)
  991. t?.representedObject = controller
  992. itemExport?.submenu = subMenu
  993. let itemPrint = menu.addItem(title: KMLocalizedString("Print", "Menu item title"), action: #selector(menuItemClick_Print), target: self)
  994. itemPrint?.representedObject = controller
  995. menu.addItem(.separator())
  996. let itemSelectAll = menu.addItem(title: KMLocalizedString("Select All", "Menu item title"), action: #selector(menuItemClick_SelectAll), target: self)
  997. itemSelectAll?.representedObject = controller
  998. menu.addItem(.separator())
  999. let itemDeleteAllSnapshot = menu.addItem(title: KMLocalizedString("Delete All Snapshots", "Menu item title"), action: #selector(deleteAllSnapshot), target: self)
  1000. itemDeleteAllSnapshot?.representedObject = controller
  1001. //
  1002. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender as! NSButton)
  1003. } else if (tag == 302) {
  1004. let menu = NSMenu()
  1005. let expandAllCommentsItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(toc_expandAllComments), target: self)
  1006. expandAllCommentsItem?.representedObject = self.tocOutlineView
  1007. let foldAllCommentsItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(toc_foldAllComments), target: self)
  1008. expandAllCommentsItem?.representedObject = self.tocOutlineView
  1009. let item = self.listView.document.outlineRoot()
  1010. var num = 0
  1011. for i in 0 ..< Int(item?.numberOfChildren ?? 0) {
  1012. let outline = item?.child(at: UInt(i))
  1013. if self.tocOutlineView.isItemExpanded(outline) {
  1014. num += 1
  1015. }
  1016. }
  1017. if let cnt = item?.numberOfChildren, cnt > 0 && num == 0 {
  1018. self.tocType = .fold
  1019. } else if let cnt = item?.numberOfChildren, cnt > 0 && num == cnt {
  1020. self.tocType = .unfold
  1021. } else {
  1022. self.tocType = .none
  1023. }
  1024. if (self.tocType == .unfold) {
  1025. expandAllCommentsItem?.state = .on
  1026. foldAllCommentsItem?.state = .off
  1027. } else if (self.tocType == .fold) {
  1028. expandAllCommentsItem?.state = .off
  1029. foldAllCommentsItem?.state = .on
  1030. } else {
  1031. expandAllCommentsItem?.state = .off
  1032. foldAllCommentsItem?.state = .off
  1033. }
  1034. let removeEntryItem = menu.addItem(title: KMLocalizedString("Remove All Outlines", nil), action: #selector(leftSideEmptyAnnotationClick_DeleteOutline), target: self)
  1035. removeEntryItem?.representedObject = self.tocOutlineView
  1036. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender as! NSButton)
  1037. } else if (tag == 304) {
  1038. let menu = NSMenu()
  1039. let object = KMPopupMenuObject()
  1040. object.menuTag = 1001
  1041. menu.delegate = object
  1042. object.enterControllerCallback = { [weak self] isEnter in
  1043. if (isEnter) {
  1044. self?.moreButtonLayer?.isHidden = false
  1045. } else {
  1046. self?.moreButtonLayer?.isHidden = true
  1047. }
  1048. }
  1049. let expandAllCommentsItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(note_expandAllComments), target: self)
  1050. expandAllCommentsItem?.representedObject = self.noteOutlineView
  1051. let foldAllCommentsItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(note_foldAllComments), target: self)
  1052. foldAllCommentsItem?.representedObject = self.noteOutlineView
  1053. if (self.foldType == .unfold) {
  1054. expandAllCommentsItem?.state = .on
  1055. foldAllCommentsItem?.state = .off
  1056. } else if (self.foldType == .fold) {
  1057. expandAllCommentsItem?.state = .off
  1058. foldAllCommentsItem?.state = .on
  1059. } else {
  1060. expandAllCommentsItem?.state = .off
  1061. foldAllCommentsItem?.state = .off
  1062. }
  1063. let showAnnotationItem = menu.addItem(title: KMLocalizedString("Show Note", nil), action: nil, target: self)
  1064. let subMenu = NSMenu()
  1065. var t = subMenu.addItem(title: KMLocalizedString("Page", nil), action: #selector(noteShowNoteAction), target: self)
  1066. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool ?? false
  1067. if pageKey {
  1068. t?.state = .off
  1069. } else {
  1070. t?.state = .on
  1071. }
  1072. t?.representedObject = self.noteOutlineView
  1073. t?.tag = 101
  1074. t = subMenu.addItem(title: KMLocalizedString("Time", nil) , action: #selector(noteShowNoteAction), target: self)
  1075. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool ?? false
  1076. if timeKey {
  1077. t?.state = .off
  1078. } else {
  1079. t?.state = .on
  1080. }
  1081. t?.representedObject = self.noteOutlineView
  1082. t?.tag = 102
  1083. t = subMenu.addItem(title: KMLocalizedString("Author", nil) , action: #selector(noteShowNoteAction), target: self)
  1084. let authorKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool ?? false
  1085. if authorKey {
  1086. t?.state = .off
  1087. } else {
  1088. t?.state = .on
  1089. }
  1090. t?.representedObject = self.noteOutlineView
  1091. t?.tag = 103
  1092. showAnnotationItem?.submenu = subMenu
  1093. menu.addItem(.separator())
  1094. let exportAnnotationsItem = menu.addItem(title: NSLocalizedString("Export Annotations…", tableName: "MainMenu", comment: ""), action: nil, target: self)
  1095. let subMenu2 = NSMenu()
  1096. var t2 = subMenu2.addItem(title: NSLocalizedString("PDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1097. t2?.representedObject = self.noteOutlineView
  1098. t2?.tag = 0
  1099. t2 = subMenu2.addItem(title: NSLocalizedString("PDF Bundle", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1100. t2?.representedObject = self.noteOutlineView
  1101. t2?.tag = 1
  1102. t2 = subMenu2.addItem(title: NSLocalizedString("PDF Reader Pro Edition Notes", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1103. t2?.representedObject = self.noteOutlineView
  1104. t2?.tag = 2
  1105. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as Text", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1106. t2?.representedObject = self.noteOutlineView
  1107. t2?.tag = 3
  1108. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as RTF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1109. t2?.representedObject = self.noteOutlineView
  1110. t2?.tag = 4
  1111. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as RTFD", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1112. t2?.representedObject = self.noteOutlineView
  1113. t2?.tag = 5
  1114. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as FDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1115. t2?.representedObject = self.noteOutlineView
  1116. t2?.tag = 6
  1117. exportAnnotationsItem?.submenu = subMenu2
  1118. menu.addItem(.separator())
  1119. let removeAllAnnotationsItem = menu.addItem(title: NSLocalizedString("Remove All Annotations", tableName: "MainMenu", comment: ""), action: #selector(leftSideEmptyAnnotationClick_DeleteAnnotation), target: self)
  1120. removeAllAnnotationsItem?.representedObject = self.noteOutlineView
  1121. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: button!, with: nil)
  1122. }
  1123. }
  1124. @IBAction func noteFilterAction(_ sender: AnyObject?) {
  1125. let button = sender as? NSButton
  1126. let menu = NSMenu()
  1127. let filterViewController = KMNoteOutlineFilterViewController()
  1128. filterViewController.view.layer?.backgroundColor = .clear
  1129. var notes = NSMutableArray()
  1130. for section in self._annotations {
  1131. if section.annotations?.count != 0 {
  1132. for item in section.annotations! {
  1133. notes.add(item.annotation!)
  1134. }
  1135. }
  1136. }
  1137. filterViewController.setNotesArray(notes)
  1138. filterViewController.applyFilterCallback = { [weak self] typeArr, colorArr, authorArr, isEmpty in
  1139. menu.cancelTracking()
  1140. if (isEmpty) {
  1141. self?.filterButtonLayer?.isHidden = true
  1142. } else {
  1143. self?.filterButtonLayer?.isHidden = false
  1144. }
  1145. self?.annotationSort(sortArray: [])
  1146. }
  1147. filterViewController.cancelCallback = { isCancel in
  1148. if (isCancel) {
  1149. menu.cancelTracking()
  1150. }
  1151. }
  1152. let item = menu.addItem(withTitle: "", action: nil, keyEquivalent: "")
  1153. item.target = self
  1154. item.representedObject = filterViewController
  1155. item.view = filterViewController.view
  1156. menu.popUp(positioning: nil, at: CGPointMake(-130, 30), in: button)
  1157. }
  1158. @IBAction func outlineNormalSearchButtonAction(_ sender: NSButton) {
  1159. self.outlineSearchField.isHidden = false
  1160. self.outlineDoneButton.isHidden = false
  1161. self.outlineLabel.isHidden = true
  1162. self.outlineSearchButton.isHidden = true
  1163. self.outlineMoreButton.isHidden = true
  1164. self.outlineAddButton.isHidden = true
  1165. self.outlineSearchField.becomeFirstResponder()
  1166. }
  1167. @IBAction func toc_expandAllComments(_ sender: AnyObject?) {
  1168. if (self.tocType == .unfold) {
  1169. return
  1170. }
  1171. self.tocType = .unfold
  1172. self.tocOutlineView.reloadData()
  1173. self.tocOutlineView.expandItem(nil, expandChildren: true)
  1174. }
  1175. @IBAction func toc_foldAllComments(_ sender: AnyObject?) {
  1176. if (self.tocType == .fold) {
  1177. return
  1178. }
  1179. self.tocType = .fold
  1180. self.tocOutlineView.reloadData()
  1181. self.tocOutlineView.collapseItem(nil, collapseChildren: true)
  1182. }
  1183. @objc func leftSideEmptyAnnotationClick_DeleteOutline(_ sender: AnyObject?) {
  1184. let alert = NSAlert()
  1185. alert.alertStyle = .critical
  1186. alert.messageText = ""
  1187. alert.informativeText = KMLocalizedString("This will permanently remove all outlines. Are you sure to continue?", nil)
  1188. alert.addButton(withTitle: KMLocalizedString("Yes", nil))
  1189. alert.addButton(withTitle: KMLocalizedString("No", nil))
  1190. let response = alert.runModal()
  1191. if response == .alertFirstButtonReturn {
  1192. if let item = self.listView.document.outlineRoot() {
  1193. self.removeAllOutline(item)
  1194. }
  1195. }
  1196. }
  1197. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  1198. let sud = UserDefaults.standard
  1199. let tag = sender.tag
  1200. if (tag == 0 || tag == 1) {
  1201. var scaling = sud.float(forKey: "KMThumbnailSizeScalingKey")
  1202. if (scaling <= 0) {
  1203. scaling = 1
  1204. }
  1205. if (tag == 0) { // thumbnail Zoom In
  1206. scaling += 0.1
  1207. if scaling >= 2.2 {
  1208. return
  1209. }
  1210. } else if (tag == 1) { // thumbnail Zoom Out
  1211. scaling -= 0.1
  1212. if scaling <= 0.4 {
  1213. return
  1214. }
  1215. }
  1216. sud.setValue(scaling, forKey: "KMThumbnailSizeScalingKey")
  1217. let selectRow = self.thumbnailTableView.selectedRow
  1218. self.thumbnailTableView.reloadData()
  1219. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1220. } else if (tag == 2 || tag == 3) {
  1221. var scaling = sud.float(forKey: "KMSnapshotSizeScalingKey")
  1222. if (scaling <= 0) {
  1223. scaling = 1
  1224. }
  1225. if (tag == 2) { // snapshot Zoom In
  1226. scaling += 0.1
  1227. } else if (tag == 3) { // snapshot Zoom Out
  1228. scaling -= 0.1
  1229. }
  1230. sud.setValue(scaling, forKey: "KMSnapshotSizeScalingKey")
  1231. let selectRow = self.snapshotTableView.selectedRow
  1232. self.snapshotTableView.reloadData()
  1233. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1234. }
  1235. }
  1236. func reloadAnnotation() {
  1237. if self.listView != nil {
  1238. var dataArray: [KMBOTAAnnotationSection] = []
  1239. var annotationArray: [CPDFAnnotation] = []
  1240. for i in 0 ..< self.listView.document.pageCount {
  1241. var annotationItemArray: [KMBOTAAnnotationItem] = []
  1242. let page = self.listView.document.page(at: i)
  1243. let types = ["Highlight","Underline","Strikeout","Freehand","FreeText","Note","Square","Circle","Line","Stamp","Arrow","Image","Redact","Sign"]
  1244. var pageAnnotations: [CPDFAnnotation] = KMOCToolClass.filterAnnotation(annotations: page!.annotations,types: types) as! [CPDFAnnotation]
  1245. //添加签名注释
  1246. for annotation in page!.annotations {
  1247. if annotation.isKind(of: CPDFSignatureAnnotation.self) {
  1248. pageAnnotations.append(annotation)
  1249. }
  1250. }
  1251. for annotation in pageAnnotations {
  1252. if annotation.annotationShouldDisplay() == false {
  1253. pageAnnotations.removeObject(annotation)
  1254. }
  1255. }
  1256. //转换所有annotation类型
  1257. let section = KMBOTAAnnotationSection()
  1258. for annotation in pageAnnotations {
  1259. let item = KMBOTAAnnotationItem()
  1260. item.section = section
  1261. item.annotation = annotation
  1262. item.index = Int(annotation.page.pageIndex())
  1263. annotationItemArray.append(item)
  1264. }
  1265. if annotationItemArray.count != 0 {
  1266. section.annotations = annotationItemArray
  1267. section.page = page
  1268. section.isItemExpanded = true
  1269. dataArray.append(section)
  1270. }
  1271. //添加所有annotation 用于筛选
  1272. annotationArray += pageAnnotations
  1273. }
  1274. //转换对象,用于数据显示
  1275. self._annotations = dataArray
  1276. self._allAnnotations = annotationArray
  1277. // if self.annotations.count < 1 {
  1278. // self.filtrateButton.isEnabled = false
  1279. // } else {
  1280. // self.filtrateButton.isEnabled = true
  1281. // }
  1282. }
  1283. }
  1284. func annotationSort(sortArray:[[Any]]) {
  1285. if self.listView != nil {
  1286. var typeArr: [Any] = []
  1287. var colorArr: [Any] = []
  1288. var authorArr: [Any] = []
  1289. let sud = UserDefaults.standard
  1290. // let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type" + self.listView.document.documentURL.path) as? Data
  1291. let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type") as? Data
  1292. if typeData != nil {
  1293. typeArr = NSKeyedUnarchiver.unarchiveObject(with: typeData!) as! [Any]
  1294. }
  1295. // let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color" + self.listView.document.documentURL.path) as? Data
  1296. let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color") as? Data
  1297. if colorData != nil {
  1298. colorArr = NSKeyedUnarchiver.unarchiveObject(with: colorData!) as! [Any]
  1299. }
  1300. // let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author" + self.listView.document.documentURL.path) as? Data
  1301. let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author") as? Data
  1302. if authorData != nil {
  1303. authorArr = NSKeyedUnarchiver.unarchiveObject(with: authorData!) as! [Any]
  1304. }
  1305. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  1306. // self.filtrateButton.image = NSImage(named: "KMImageNameAnnotationsFiltrate")
  1307. self.reloadAnnotation()
  1308. } else {
  1309. // self.filtrateButton.image = NSImage(named: "icon_annotation_screening_select")
  1310. var dataArray: [KMBOTAAnnotationSection] = []
  1311. for i in 0 ..< self.listView.document.pageCount {
  1312. var annotationItemArray: [KMBOTAAnnotationItem] = []
  1313. let page = self.listView.document.page(at: i)
  1314. if page!.annotations.count > 0 {
  1315. var filterAnnotations: [CPDFAnnotation] = page!.annotations
  1316. if typeArr.count > 0 {
  1317. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations, types: typeArr) as! [CPDFAnnotation])
  1318. }
  1319. if (colorArr.count > 0) {
  1320. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,colors: colorArr) as! [CPDFAnnotation])
  1321. }
  1322. if (authorArr.count > 0) {
  1323. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,authors: authorArr) as! [CPDFAnnotation])
  1324. }
  1325. let section = KMBOTAAnnotationSection()
  1326. for annotation in filterAnnotations {
  1327. let item = KMBOTAAnnotationItem()
  1328. item.section = section
  1329. item.annotation = annotation
  1330. item.index = Int(page!.pageIndex())
  1331. annotationItemArray.append(item)
  1332. }
  1333. if annotationItemArray.count != 0 {
  1334. section.annotations = annotationItemArray
  1335. section.page = page
  1336. section.isItemExpanded = true
  1337. dataArray.append(section)
  1338. }
  1339. }
  1340. }
  1341. self._annotations = dataArray
  1342. }
  1343. Task { @MainActor in
  1344. self.noteOutlineView.reloadData()
  1345. }
  1346. }
  1347. }
  1348. func showSearchOutlineBlankState(_ toShowState: Bool) {
  1349. if (toShowState) {
  1350. self.leftSideEmptyVC.outlineSearchView.frame = CGRectMake((self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.width - self.leftSideEmptyVC.outlineSearchView.bounds.size.width)/2.0, (self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.height - self.leftSideEmptyVC.outlineSearchView.bounds.size.height)/2.0, self.leftSideEmptyVC.outlineSearchView.bounds.size.width, self.leftSideEmptyVC.outlineSearchView.bounds.size.height);
  1351. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  1352. self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1353. } else {
  1354. self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  1355. }
  1356. }
  1357. // func allRangeOfRoughString(_ roughString: String, searchString: String) -> [NSRange] {
  1358. //
  1359. // }
  1360. func removeAllOutline(_ outline: CPDFOutline) {
  1361. self.listView.document.setNewOutlineRoot()
  1362. for i in 0 ..< self.listView.document.pageCount {
  1363. self.listView.document.removeBookmark(forPageIndex: i)
  1364. }
  1365. self.listView.layoutDocumentView()
  1366. DispatchQueue.main.async {
  1367. self.tocOutlineView.reloadData()
  1368. }
  1369. }
  1370. func updateNoteFilterPredicate() {
  1371. //注释筛选
  1372. // [rightSideController.noteArrayController setFilterPredicate:[noteTypeSheetController filterPredicateForSearchString:[rightSideController.searchField stringValue] caseInsensitive:mwcFlags.caseInsensitiveNoteSearch]];
  1373. let stringValue = self.noteSearchField.stringValue
  1374. // NSPredicate *predicate = [noteTypeSheetController filterPredicateForSearchString:[rightSideController.searchField stringValue] caseInsensitive:mwcFlags.caseInsensitiveNoteSearch];
  1375. // [self loadAnnotationSortData:[NSArray arrayWithObjects:predicate, nil]];
  1376. self.noteSearchArray.removeAll()
  1377. if stringValue.isEmpty {
  1378. self.noteSearchArray = self.allAnnotations
  1379. } else {
  1380. for note in self.allAnnotations {
  1381. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  1382. if let anno = note as? CPDFMarkupAnnotation {
  1383. noteString = anno.markupContent()
  1384. }
  1385. if noteString.contains(stringValue) {
  1386. self.noteSearchArray.append(note)
  1387. }
  1388. }
  1389. }
  1390. Task { @MainActor in
  1391. self.noteOutlineView.reloadData()
  1392. }
  1393. }
  1394. @objc func selectSelectedNote(_ sender: AnyObject?) {
  1395. if self.listView.hideNotes == false {
  1396. let selectedNotes = self.selectedNotes()
  1397. if selectedNotes.count == 1 {
  1398. let annotation = selectedNotes.last!
  1399. self.listView.go(to: annotation.bounds, on: annotation.page, animated: true)
  1400. // [pdfView scrollAnnotationToVisible:annotation];
  1401. // [pdfView setActiveAnnotation:annotation];
  1402. self.listView.updateActiveAnnotations([annotation])
  1403. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  1404. // }
  1405. }
  1406. // NSInteger column = [sender clickedColumn];
  1407. // if (column != -1) {
  1408. // NSString *colID = [[[sender tableColumns] objectAtIndex:column] identifier];
  1409. //
  1410. // if ([colID isEqualToString:@"color"]){
  1411. // for (PDFAnnotation *annotation in self.pdfView.activeAnnotations) {
  1412. // if (![annotation isKindOfClass:[PDFAnnotationChoiceWidget class]] &&
  1413. // ![annotation isKindOfClass:[PDFAnnotationButtonWidget class]] &&
  1414. // ![annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  1415. // [[NSColorPanel sharedColorPanel] orderFront:nil];
  1416. // break;
  1417. // }
  1418. //
  1419. // }
  1420. // }
  1421. // }
  1422. }
  1423. }
  1424. func selectedNotes() -> [CPDFAnnotation] {
  1425. var selectedNotes: [CPDFAnnotation] = []
  1426. let rowIndexes = self.noteOutlineView.selectedRowIndexes
  1427. for row in rowIndexes {
  1428. let item = self.noteOutlineView.item(atRow: row)
  1429. if item is KMBOTAAnnotationItem {
  1430. if let anno = (item as! KMBOTAAnnotationItem).annotation {
  1431. // if anno.type == nil {
  1432. // item = [(SKNoteText *)item note];
  1433. // }
  1434. if selectedNotes.contains(anno) == false {
  1435. selectedNotes.append(anno)
  1436. }
  1437. }
  1438. }
  1439. }
  1440. return selectedNotes
  1441. }
  1442. }
  1443. // MARK: - Note
  1444. extension KMLeftSideViewController {
  1445. func loadAnnotationSortData(_ morePredicates: NSArray) {
  1446. var isLink = false
  1447. var typeMutableArr = NSMutableArray()
  1448. if self.allAnnotations.count > 0 {
  1449. for annotation in self.allAnnotations {
  1450. if annotation is CPDFLinkAnnotation || annotation is CPDFTextWidgetAnnotation || annotation is CPDFButtonWidgetAnnotation || annotation is CPDFChoiceWidgetAnnotation {
  1451. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature] ||
  1452. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeText] ||
  1453. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeButton] ||
  1454. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeChoice]) {
  1455. isLink = true
  1456. } else {
  1457. if typeMutableArr.contains(annotation.type) == false {
  1458. typeMutableArr.add(annotation.type)
  1459. }
  1460. }
  1461. }
  1462. }
  1463. var colorMutableArray = NSMutableArray()
  1464. var typeMutableArray = NSMutableArray()
  1465. var authorMutableArray = NSMutableArray()
  1466. for annotation in self.allAnnotations {
  1467. if annotation is CPDFLinkAnnotation || annotation is CPDFTextWidgetAnnotation || annotation is CPDFButtonWidgetAnnotation || annotation is CPDFChoiceWidgetAnnotation {
  1468. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature] ||
  1469. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeText] ||
  1470. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeButton] ||
  1471. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeChoice]) {
  1472. let noteColor = annotation.color ?? .clear
  1473. let noteType = annotation.type ?? ""
  1474. let authorString = annotation.userName() ?? ""
  1475. if (noteColor != nil) {
  1476. if (colorMutableArray.count > 0) {
  1477. if colorMutableArray.contains(noteColor) == false {
  1478. colorMutableArray.add(noteColor)
  1479. }
  1480. } else {
  1481. colorMutableArray.add(noteColor)
  1482. }
  1483. }
  1484. if noteType.isEmpty == false {
  1485. if typeMutableArray.count > 0 {
  1486. if typeMutableArray.contains(noteType) == false {
  1487. typeMutableArray.add(noteType)
  1488. }
  1489. } else {
  1490. typeMutableArray.add(noteType)
  1491. }
  1492. }
  1493. if authorString.isEmpty == false {
  1494. if authorString.count > 0 {
  1495. if authorMutableArray.contains(authorString) == false {
  1496. authorMutableArray.add(authorString)
  1497. }
  1498. } else {
  1499. authorMutableArray.add(authorString)
  1500. }
  1501. }
  1502. } else {
  1503. if typeMutableArr.contains(annotation.type) == false {
  1504. typeMutableArr.add(annotation.type)
  1505. }
  1506. }
  1507. }
  1508. let sud = UserDefaults.standard
  1509. var typeArr = NSMutableArray()
  1510. if let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type") as? Data {
  1511. if let data = NSKeyedUnarchiver.unarchiveObject(with: typeData) as? NSArray {
  1512. typeArr = NSMutableArray(array: data)
  1513. }
  1514. }
  1515. var colorArr = NSMutableArray()
  1516. if let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color") as? Data {
  1517. if let data = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? NSArray {
  1518. colorArr = NSMutableArray(array: data)
  1519. }
  1520. }
  1521. var authorArr = NSMutableArray()
  1522. if let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author") as? Data {
  1523. if let data = NSKeyedUnarchiver.unarchiveObject(with: authorData) as? NSArray {
  1524. authorArr = NSMutableArray(array: data)
  1525. }
  1526. }
  1527. var temporaryArr1 = NSMutableArray()
  1528. var temporaryArr2 = NSMutableArray()
  1529. var temporaryArr3 = NSMutableArray()
  1530. if (typeArr.count > 0) {
  1531. for type in typeArr {
  1532. if typeMutableArray.contains(type) == false {
  1533. temporaryArr1.add(type)
  1534. }
  1535. }
  1536. }
  1537. if (colorArr.count > 0) {
  1538. for color in colorArr {
  1539. if colorMutableArray.contains(color) == false {
  1540. temporaryArr2.add(color)
  1541. }
  1542. }
  1543. }
  1544. if (authorArr.count > 0) {
  1545. for author in authorArr {
  1546. if authorMutableArray.contains(author) == false {
  1547. temporaryArr3.add(author)
  1548. }
  1549. }
  1550. }
  1551. if (temporaryArr1.count > 0) {
  1552. for type in temporaryArr1 {
  1553. typeArr.remove(type)
  1554. }
  1555. }
  1556. if (temporaryArr2.count > 0) {
  1557. for color in temporaryArr2 {
  1558. colorArr.remove(color)
  1559. }
  1560. }
  1561. if (temporaryArr3.count > 0) {
  1562. for author in temporaryArr3 {
  1563. authorArr.remove(author)
  1564. }
  1565. }
  1566. var predicateMutableArr = NSMutableArray()
  1567. // predicateMutableArr.add
  1568. }
  1569. }
  1570. // MARK: - KMBotaTableViewDelegate
  1571. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  1572. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  1573. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1574. return rowIndexes.count > 0
  1575. }
  1576. return false
  1577. }
  1578. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  1579. if aTableView.isEqual(to: self.thumbnailTableView) {
  1580. if self._copysPages.count > 0 {
  1581. return true
  1582. }
  1583. }
  1584. return false
  1585. }
  1586. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  1587. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  1588. // return [rowIndexes count] > 0;
  1589. // } else
  1590. if aTableView.isEqual(to: self.thumbnailTableView) {
  1591. if self.listView.document.pageCount <= 1 {
  1592. return false
  1593. }
  1594. return true
  1595. }
  1596. return false
  1597. }
  1598. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  1599. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  1600. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1601. // return;
  1602. // }
  1603. if aTableView.isEqual(to: self.thumbnailTableView) {
  1604. if self._copysPages.count > 0 {
  1605. let index = self.listView.document.index(for: self.listView.currentPage()) + 1
  1606. if (index == NSNotFound) {
  1607. return
  1608. }
  1609. for page in self._copysPages.reversed() {
  1610. // if let newPage = page.copy() as? CPDFPage {
  1611. self.listView.document.insertPageObject(page, at: index)
  1612. // }
  1613. self.listView.layoutDocumentView()
  1614. // [pageLabels setArray:[[pdfView document] pageLabels]];
  1615. self.resetThumbnails()
  1616. let pageIndex = min(index, self.listView.document.pageCount-1)
  1617. self.listView.go(toPageIndex: Int(pageIndex), animated: true)
  1618. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  1619. }
  1620. }
  1621. }
  1622. }
  1623. func tableViewMoveLeft(_ aTableView: NSTableView) {
  1624. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1625. // [self updateFindResultHighlightsForDirection:NSSelectingPrevious];
  1626. }
  1627. }
  1628. func tableViewMoveRight(_ aTableView: NSTableView) {
  1629. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1630. // [self updateFindResultHighlightsForDirection:NSSelectingNext];
  1631. }
  1632. }
  1633. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  1634. if aTableView.isEqual(to: self.findTableView) {
  1635. if rowIndex >= self.searchResults.count {
  1636. return nil
  1637. }
  1638. let model = self.searchResults[rowIndex]
  1639. let selection = model.selection
  1640. let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  1641. return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  1642. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1643. if rowIndex >= self.groupSearchResults.count {
  1644. return nil
  1645. }
  1646. // let model = self.groupSearchResults[rowIndex]
  1647. // let selection = model.selection
  1648. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  1649. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  1650. }
  1651. return nil
  1652. }
  1653. /*
  1654. - (NSArray *)tableView:(NSTableView *)tv typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  1655. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1656. return pageLabels;
  1657. }
  1658. return nil;
  1659. }
  1660. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  1661. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1662. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  1663. }
  1664. }
  1665. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  1666. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1667. if (searchString.length > 0)
  1668. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  1669. else
  1670. [self updateLeftStatus];
  1671. }
  1672. }
  1673. */
  1674. }
  1675. // MARK: - KMThumbnailTableViewDelegate
  1676. extension KMLeftSideViewController: KMThumbnailTableViewDelegate {
  1677. func tableView(_ tableView: NSTableView, highlightLevelForRow row: Int) -> UInt {
  1678. if tableView.isEqual(to: self.thumbnailTableView) {
  1679. // NSUInteger i, iMax = [lastViewedPages count];
  1680. // for (i = 0; i < iMax; i++) {
  1681. // if (row == (NSInteger)[lastViewedPages pointerAtIndex:i])
  1682. // return i;
  1683. // }
  1684. }
  1685. return UInt.max
  1686. }
  1687. func tableView(_ tableView: NSTableView, commandSelectRow rowIndex: Int) -> Bool {
  1688. if tableView.isEqual(to: self.thumbnailTableView) {
  1689. // NSRect rect = [[[pdfView document] pageAtIndex:row] boundsForBox:kPDFDisplayBoxCropBox];
  1690. //
  1691. // rect.origin.y = NSMidY(rect) - 0.5 * SNAPSHOT_HEIGHT;
  1692. // rect.size.height = SNAPSHOT_HEIGHT;
  1693. // [self showSnapshotAtPageNumber:row forRect:rect scaleFactor:[pdfView scaleFactor] autoFits:NO];
  1694. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  1695. thumbailTabCell?.isSelectCell = true
  1696. var rowIndexSet = IndexSet()
  1697. for i in self.thumbnailTableView.selectedRowIndexes {
  1698. rowIndexSet.insert(i)
  1699. }
  1700. rowIndexSet.insert(rowIndex)
  1701. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1702. return true
  1703. }
  1704. return false
  1705. }
  1706. func tableView(_ tableView: NSTableView, shiftSelectRow rowIndex: Int) -> Bool {
  1707. if tableView.isEqual(to: self.thumbnailTableView) {
  1708. if (self.thumbnailTableView.selectedRowIndexes.count == 0) {
  1709. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  1710. thumbailTabCell?.isSelectCell = true
  1711. var rowIndexSet = IndexSet()
  1712. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1713. return true
  1714. } else if (self.thumbnailTableView.selectedRowIndexes.count == 1 && self.thumbnailTableView.selectedRowIndexes.first == rowIndex) {
  1715. return false
  1716. } else {
  1717. var fristIndex = self.thumbnailTableView.selectedRowIndexes.first ?? Int.min
  1718. var lastIndex = self.thumbnailTableView.selectedRowIndexes.last ?? Int.max
  1719. for idx in self.thumbnailTableView.selectedRowIndexes {
  1720. // [leftSideController.thumbnailTableView.selectedRowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  1721. if(idx < fristIndex) {
  1722. fristIndex = idx
  1723. }
  1724. if(idx > lastIndex) {
  1725. lastIndex = idx
  1726. }
  1727. }
  1728. if(rowIndex < fristIndex) {
  1729. fristIndex = rowIndex
  1730. } else if (rowIndex > lastIndex) {
  1731. lastIndex = rowIndex
  1732. }
  1733. var rowIndexSet = IndexSet()
  1734. for i in fristIndex ... lastIndex {
  1735. rowIndexSet.insert(i)
  1736. }
  1737. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1738. return true
  1739. }
  1740. }
  1741. return false
  1742. }
  1743. }
  1744. // MARK: - 扩展
  1745. extension KMLeftSideViewController {
  1746. public func selectType(_ type: BotaType) {
  1747. // 更新 type
  1748. var show = true
  1749. if (self.type.methodType == .None) {
  1750. show = true
  1751. } else {
  1752. if (self.type.methodType == type) {
  1753. show = false
  1754. } else {
  1755. show = true
  1756. }
  1757. }
  1758. var index: Int = NSNotFound
  1759. switch type {
  1760. case .None:
  1761. index = NSNotFound
  1762. break
  1763. case .Thumbnail:
  1764. index = 0
  1765. break
  1766. case .Outline:
  1767. index = 1
  1768. break
  1769. case .BookMark:
  1770. index = 2
  1771. break
  1772. case .Annotation:
  1773. index = 3
  1774. break
  1775. case .Search:
  1776. index = 4
  1777. break
  1778. case .From:
  1779. index = 5
  1780. break
  1781. case .Signature:
  1782. index = 6
  1783. break
  1784. case .snapshot:
  1785. index = 7
  1786. break
  1787. }
  1788. self.type = self.getMethodMode(show ? type : .None)
  1789. // 更新按钮状态
  1790. // self.updateViewButtonState()
  1791. // 将事件传递出去
  1792. self.delegate?.controlStateChange?(self,show:show)
  1793. if (index != NSNotFound) {
  1794. // 记录当前选中
  1795. UserDefaults.standard.set(index, forKey: "KMBOTASelectedIndexKey")
  1796. UserDefaults.standard.synchronize()
  1797. }
  1798. }
  1799. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  1800. let mode = KMLeftMethodMode()
  1801. mode.methodType = type
  1802. switch type {
  1803. case .None:
  1804. mode.methodName = ""
  1805. break
  1806. case .Thumbnail:
  1807. mode.methodName = thumbnailMethodKey
  1808. break
  1809. case .Outline:
  1810. mode.methodName = outlineMethodKey
  1811. break
  1812. case .BookMark:
  1813. mode.methodName = bookMarkMethodKey
  1814. break
  1815. case .Annotation:
  1816. mode.methodName = anntationMethodKey
  1817. break
  1818. case .Search:
  1819. mode.methodName = searchMethodKey
  1820. break
  1821. case .From:
  1822. mode.methodName = formMethodKey
  1823. break
  1824. case .Signature:
  1825. mode.methodName = signatureMethodKey
  1826. break
  1827. case .snapshot:
  1828. mode.methodName = snapshotMethodKey
  1829. }
  1830. return mode
  1831. }
  1832. }
  1833. //MARK: Cache
  1834. extension KMLeftSideViewController {
  1835. func clearAnnotationFilterData() {
  1836. if let _key = self.listView?.document?.documentURL?.path {
  1837. let userDefaults = UserDefaults.standard
  1838. let typeData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  1839. userDefaults.set(typeData, forKey: "KMNoteOutlineFilterSelectArray_Type" + _key)
  1840. let colorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  1841. userDefaults.set(colorData, forKey: "KMNoteOutlineFilterSelectArray_Color" + _key)
  1842. let authorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  1843. userDefaults.set(authorData, forKey: "KMNoteOutlineFilterSelectArray_Author" + _key)
  1844. userDefaults.synchronize()
  1845. }
  1846. }
  1847. func clearNotification() {
  1848. }
  1849. }
  1850. // MARK: - Analytics (埋点)
  1851. extension KMLeftSideViewController {
  1852. func trackEvent(type: BotaType) -> Void {
  1853. if (type == .Thumbnail) {
  1854. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Thumbnail", parameters: [
  1855. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1856. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1857. } else if (type == .Outline) {
  1858. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Outline", parameters: [
  1859. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1860. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1861. } else if (type == .BookMark) {
  1862. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_BookMark", parameters: [
  1863. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1864. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1865. } else if (type == .Annotation) {
  1866. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Annotation", parameters: [
  1867. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1868. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1869. } else if (type == .Search) {
  1870. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Search", parameters: [
  1871. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  1872. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  1873. }
  1874. }
  1875. }
  1876. // MARK: - Private Methods
  1877. extension KMLeftSideViewController {
  1878. @objc private func _themeChanged(_ notification: NSNotification) {
  1879. DispatchQueue.main.asyncAfter(deadline: .now()+0.3) {
  1880. self._updateViewColor()
  1881. }
  1882. }
  1883. private func _updateViewColor() {
  1884. if(KMAppearance.isDarkMode()){
  1885. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1886. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1887. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1888. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1889. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1890. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  1891. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1892. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1893. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1894. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  1895. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1896. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1897. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1898. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  1899. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  1900. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  1901. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  1902. } else {
  1903. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1904. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1905. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1906. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1907. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1908. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  1909. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1910. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1911. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1912. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  1913. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1914. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1915. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1916. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  1917. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  1918. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  1919. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  1920. }
  1921. }
  1922. private func _hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  1923. let label_low = outline.label.lowercased()
  1924. let searchString_low = searchString.lowercased()
  1925. if label_low.contains(searchString_low) {
  1926. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  1927. return true
  1928. } else {
  1929. var subHas = false
  1930. for i in 0 ..< outline.numberOfChildren {
  1931. if let subOutline = outline.child(at: i) {
  1932. subHas = self._hasContainString(searchString, rootOutline: subOutline)
  1933. } else {
  1934. continue
  1935. }
  1936. if (subHas) {
  1937. break
  1938. }
  1939. }
  1940. return subHas
  1941. }
  1942. return false
  1943. }
  1944. }
  1945. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  1946. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  1947. func numberOfRows(in tableView: NSTableView) -> Int {
  1948. if tableView.isEqual(to: self.thumbnailTableView) {
  1949. return self.thumbnails.count
  1950. } else if tableView.isEqual(to: self.findTableView) {
  1951. return self.searchResults.count
  1952. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1953. return self.groupSearchResults.count
  1954. } else if tableView.isEqual(to: self.snapshotTableView) {
  1955. if self.isSearchSnapshotMode {
  1956. return self.searchSnapshots.count
  1957. }
  1958. return self.snapshots.count
  1959. }
  1960. return 0
  1961. }
  1962. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  1963. if tableView.isEqual(to: self.thumbnailTableView) {
  1964. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMThumbnailTableviewCell"), owner: self) as! KMThumbnailTableviewCell
  1965. let thumbnail = self.thumbnails[row]
  1966. cell.pageNumLabel.stringValue = thumbnail.label
  1967. // cell.thumImage.image = thumbnail.image
  1968. cell.pageView.page = self.listView.document.page(at: UInt(row))
  1969. if let _image = thumbnail.image {
  1970. let multiplierHToW = _image.size.height / (_image.size.width == 0 ? 1 : _image.size.width)
  1971. let multiplierWToH = _image.size.width / (_image.size.height == 0 ? 1 : _image.size.height)
  1972. if (_image.size.height > _image.size.width) {
  1973. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  1974. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .height, relatedBy: .equal, toItem: cell.thumImage, attribute: .width, multiplier: multiplierHToW, constant: 0)
  1975. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  1976. } else {
  1977. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  1978. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .width, relatedBy: .equal, toItem: cell.thumImage, attribute: .height, multiplier: multiplierWToH, constant: 0)
  1979. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  1980. }
  1981. }
  1982. if (self.isDisplayPageSize) {
  1983. cell.sizeLabel.isHidden = false
  1984. //获取Page的真实尺寸
  1985. let page = self.listView.document.page(at: UInt(row))
  1986. let rect = page?.bounds(for: .cropBox) ?? .zero
  1987. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetWidth(rect)/595 * 210))
  1988. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetHeight(rect)/842 * 297))
  1989. if let data = page?.rotation, data == 90 || data == 270 {
  1990. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  1991. } else {
  1992. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  1993. }
  1994. } else {
  1995. cell.sizeLabel.isHidden = true
  1996. }
  1997. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  1998. if(self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  1999. cell.isSelectCell = true
  2000. } else {
  2001. cell.isSelectCell = false
  2002. }
  2003. return cell
  2004. } else if (tableView.isEqual(to: self.findTableView)) {
  2005. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMFindTableviewCell"), owner: self) as! KMFindTableviewCell
  2006. let selection = searchResults[row]
  2007. if let data = tableColumn?.identifier.rawValue, data == "results" {
  2008. cell.resultLabel.attributedStringValue = selection.attributedString
  2009. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  2010. } else if let data = tableColumn?.identifier.rawValue, data == "page" {
  2011. cell.resultLabel.stringValue = "\(Int(selection.selection.page?.pageIndex() ?? 0) + 1)"
  2012. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  2013. }
  2014. return cell
  2015. } else if tableView.isEqual(to: self.snapshotTableView) {
  2016. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMSnapshotTableViewCell"), owner: self) as! KMSnapshotTableViewCell
  2017. var snapshot: KMSnapshotModel?
  2018. if self.isSearchSnapshotMode {
  2019. snapshot = self.searchSnapshots[row]
  2020. } else {
  2021. snapshot = self.snapshots[row]
  2022. }
  2023. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  2024. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  2025. if let data = snapshot?.windowC?.hasWindow, data {
  2026. cell.snapshotImageView.isHidden = false
  2027. } else {
  2028. cell.snapshotImageView.isHidden = true
  2029. }
  2030. cell.isSelectCell = snapshot?.isSelected ?? false
  2031. if (row == tableView.selectedRow) {
  2032. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  2033. } else {
  2034. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  2035. }
  2036. return cell
  2037. }
  2038. return nil
  2039. }
  2040. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  2041. if tableView.isEqual(to: self.thumbnailTableView) {
  2042. let scaling = UserDefaults.standard.float(forKey: "KMThumbnailSizeScalingKey")
  2043. // let thumbnailSize = self.thumbnails[row].size
  2044. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  2045. let newScaling: CGFloat = scaling.cgFloat + 0.1
  2046. let newThumbnailHeight = thumbnailSize.width * newScaling
  2047. if (newThumbnailHeight > MIN_SIDE_PANE_WIDTH) {
  2048. self.thumbnailZoomOutButton.isEnabled = false
  2049. } else {
  2050. self.thumbnailZoomOutButton.isEnabled = true
  2051. }
  2052. if ((scaling - 0.1) < 0.3) {
  2053. self.thumbnailZoomInButton.isEnabled = false
  2054. } else {
  2055. self.thumbnailZoomInButton.isEnabled = true
  2056. }
  2057. var labelHeight = 0.0
  2058. if (self.isDisplayPageSize) {
  2059. labelHeight = 56.0
  2060. } else {
  2061. labelHeight = 41.5
  2062. }
  2063. let cellHeight = thumbnailSize.height + labelHeight
  2064. var thumbSize: NSSize = .zero
  2065. if (scaling != nil && scaling > 0) {
  2066. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  2067. } else {
  2068. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  2069. }
  2070. return thumbSize.height
  2071. // NSSize cellSize = NSMakeSize([[tv tableColumnWithIdentifier:IMAGE_COLUMNID] width], fmin(thumbSize.height, roundedThumbnailSize));
  2072. // if (thumbSize.height < [tv rowHeight])
  2073. // return [tv rowHeight];
  2074. // else if (thumbSize.width / thumbSize.height < cellSize.width / cellSize.height)
  2075. // return cellSize.height;
  2076. // else
  2077. // return fmax([tv rowHeight], fmin(cellSize.width, thumbSize.width) * thumbSize.height / thumbSize.width);
  2078. } else if tableView.isEqual(to: self.snapshotTableView) {
  2079. let scaling = UserDefaults.standard.float(forKey: "KMSnapshotSizeScalingKey")
  2080. // NSSize snapshotSize = [[[[rightSideController.snapshotArrayController arrangedObjects] objectAtIndex:row] thumbnail] size];
  2081. let snapshotSize = CGSizeMake(120, 63)
  2082. var newScaling = scaling + 0.1
  2083. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat;
  2084. if (newSnapshotHeight > MIN_SIDE_PANE_WIDTH) {
  2085. self.snapshotNormalZoomInButton.isEnabled = false
  2086. } else {
  2087. self.snapshotNormalZoomInButton.isEnabled = true
  2088. }
  2089. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  2090. self.snapshotNormalZoomOutButton.isEnabled = false
  2091. } else {
  2092. self.snapshotNormalZoomOutButton.isEnabled = true
  2093. }
  2094. let cellHeight = snapshotSize.height + 24.0
  2095. var thumbSize: NSSize = .zero
  2096. if (scaling > 0) {
  2097. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  2098. } else {
  2099. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  2100. }
  2101. return thumbSize.height
  2102. } else if (tableView.isEqual(to: self.findTableView)) {
  2103. return 40.0
  2104. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2105. return 16
  2106. }
  2107. return tableView.rowHeight
  2108. }
  2109. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  2110. if (tableView.isEqual(to: self.findTableView)) {
  2111. let rowView = KMBotaTableRowView()
  2112. return rowView
  2113. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2114. let rowView = KMGroupFindTableRowView()
  2115. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  2116. let model = self.groupSearchResults[row]
  2117. rowView.number = model.datas.count
  2118. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  2119. return rowView
  2120. }
  2121. return nil
  2122. }
  2123. func tableViewSelectionIsChanging(_ notification: Notification) {
  2124. }
  2125. func tableViewSelectionDidChange(_ notification: Notification) {
  2126. // if ([[aNotification object] isEqual:leftSideController.findTableView] || [[aNotification object] isEqual:leftSideController.groupedFindTableView]) {
  2127. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  2128. //
  2129. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2130. // [self hideLeftSideWindow];
  2131. // } else
  2132. if self.findTableView.isEqual(to: notification.object) {
  2133. let row = self.findTableView.selectedRow
  2134. if row >= 0 {
  2135. let model = self.searchResults[row]
  2136. if model.selection != nil {
  2137. self.listView.go(to: model.selection, animated: true)
  2138. self.listView.setHighlightedSelection(model.selection, animated: true)
  2139. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2140. }
  2141. }
  2142. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  2143. // if (mwcFlags.updatingThumbnailSelection == 0) {
  2144. let row = self.thumbnailTableView.selectedRow
  2145. let curPage = self.listView.document.index(for: self.listView.currentPage())
  2146. if (row != -1 && row != curPage) {
  2147. // [pdfView goToPage:[[pdfView document] pageAtIndex:row]];
  2148. self.listView.go(toPageIndex: row, animated: true)
  2149. }
  2150. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2151. // [self hideLeftSideWindow];
  2152. // thumbnailSelectCount = row;
  2153. // var rowIndexSet = IndexSet()
  2154. // for i in 0 ..< self.thumbnailTableView.numberOfRows {
  2155. // rowIndexSet.insert(i)
  2156. // }
  2157. // self.thumbnailTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: IndexSet(integer: 0))
  2158. // }
  2159. let view = self.thumbnailTableView.view(atColumn: 0, row: self.preThumbnailRow, makeIfNecessary: false) as? KMThumbnailTableviewCell
  2160. view?.isSelectCell = false
  2161. let view2 = self.thumbnailTableView.view(atColumn: 0, row: row, makeIfNecessary: false) as? KMThumbnailTableviewCell
  2162. view2?.isSelectCell = true
  2163. self.preThumbnailRow = row
  2164. }
  2165. // else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2166. // NSInteger row = [rightSideController.snapshotTableView selectedRow];
  2167. // [selectCellList removeAllObjects];
  2168. // [selectCellList addObject:[NSString stringWithFormat:@"%ld",row]];
  2169. // if (row != -1) {
  2170. // SKSnapshotWindowController *controller = [[rightSideController.snapshotArrayController arrangedObjects] objectAtIndex:row];
  2171. // if ([[controller window] isVisible])
  2172. // [[controller window] orderFront:self];
  2173. // }
  2174. // NSMutableIndexSet *rowIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2175. // for (NSInteger i = 0; i < rightSideController.snapshotTableView.numberOfRows; i ++) {
  2176. // [rowIndexSet addIndex:i];
  2177. // }
  2178. // NSMutableIndexSet *columnIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2179. // [columnIndexSet addIndex:0];
  2180. // [rightSideController.snapshotTableView reloadDataForRowIndexes:rowIndexSet columnIndexes:columnIndexSet];
  2181. //
  2182. // }
  2183. }
  2184. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  2185. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  2186. return NSDragOperation(rawValue: 0)
  2187. }
  2188. let pboard = info.draggingPasteboard
  2189. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  2190. return .move
  2191. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  2192. guard let pbItems = pboard.pasteboardItems else {
  2193. return NSDragOperation(rawValue: 0)
  2194. }
  2195. // guard let _allowedFileTypes = self.kmAllowedFileTypes else {
  2196. // return .generic
  2197. // }
  2198. var hasValidFile = false
  2199. for item in pbItems {
  2200. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  2201. continue
  2202. }
  2203. let type = _url.pathExtension.lowercased()
  2204. // if (_allowedFileTypes.contains(type)) {
  2205. hasValidFile = true
  2206. // break
  2207. // }
  2208. }
  2209. if (!hasValidFile) {
  2210. return NSDragOperation(rawValue: 0)
  2211. }
  2212. }
  2213. return NSDragOperation(rawValue: 0)
  2214. }
  2215. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  2216. var result = false
  2217. if tableView.isEqual(to: self.thumbnailTableView) == false {
  2218. return result
  2219. }
  2220. // let pasteboard = info.draggingPasteboard
  2221. //
  2222. // if pasteboard.availableType(from: [.localDraggedTypes]) {
  2223. // result = true
  2224. // let rowData = pasteboard.data(forType: .localDraggedTypes)
  2225. // let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData!)
  2226. // NSData *urlData = [pasteboard dataForType:KPDFThumbnailDoucumentURLForDraggedTypes];
  2227. // NSString *url = [NSKeyedUnarchiver unarchiveObjectWithData:urlData];
  2228. // if(![url isEqualToString:[pdfView document].documentURL.absoluteString] && url) {
  2229. // if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]){
  2230. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2231. // if (fileNames.count == 1) {
  2232. // NSString *path = fileNames.firstObject;
  2233. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2234. // if ([pathExtension isEqualToString:@"pdf"]) {
  2235. // __block NSInteger index = row;
  2236. // __block NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2237. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]] autorelease];
  2238. // if ([pdf isEncrypted]) {
  2239. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2240. // vc.filePath = url;
  2241. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2242. // if (password) {
  2243. // [pdf unlockWithPassword:password];
  2244. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2245. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2246. // [self.pdfView.document insertPage:page atIndex:index];
  2247. // [insertIndexSet addIndex:index];
  2248. // index++;
  2249. // [page release];
  2250. // }
  2251. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2252. // }
  2253. // }];
  2254. // [vc release];
  2255. // } else {
  2256. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2257. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2258. // [self.pdfView.document insertPage:page atIndex:index];
  2259. // [insertIndexSet addIndex:index];
  2260. // index++;
  2261. // [page release];
  2262. // }
  2263. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2264. // }
  2265. // return YES;
  2266. // }
  2267. // }
  2268. // }
  2269. // }
  2270. // __block NSInteger pageIndex = 0;
  2271. // __block NSMutableArray *pages = [NSMutableArray array];
  2272. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2273. // PDFPage *page = [[[pdfView document] pageAtIndex:idx] copy];
  2274. // [pages addObject:page];
  2275. // [page release];
  2276. // }];
  2277. // PDFPage *toPage = nil;
  2278. // if (row < (NSInteger)pdfView.document.pageCount) {
  2279. // toPage = [pdfView.document pageAtIndex:row];
  2280. // }
  2281. // __block NSInteger toPageIndex = 0;
  2282. // if (toPage) {
  2283. // toPageIndex = [pdfView.document indexForPage:toPage];
  2284. // } else {
  2285. // toPageIndex = pdfView.document.pageCount;
  2286. // }
  2287. // for(NSUInteger i = 0;i<pages.count;i++) {
  2288. // PDFPage *page = pages[i];
  2289. // [pdfView.document insertPage:page atIndex:toPageIndex+i];
  2290. // pageIndex += 1;
  2291. // [self.pdfView goToPage:page];
  2292. // }
  2293. // [self.pdfView layoutDocumentView];
  2294. // __block NSMutableArray *deletepages = [NSMutableArray array];
  2295. // [rowIndexes enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2296. // if((NSInteger)idx < toPageIndex) {
  2297. // if((idx+pageIndex) < pdfView.document.pageCount) {
  2298. // PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2299. // [deletepages addObject:page];
  2300. // [pdfView.document removePageAtIndex:idx];
  2301. // }
  2302. // } else {
  2303. // if((idx+pageIndex) < pdfView.document.pageCount) {
  2304. // PDFPage *page = [[pdfView document] pageAtIndex:idx+pageIndex];
  2305. // [deletepages addObject:page];
  2306. // [pdfView.document removePageAtIndex:idx+pageIndex];
  2307. // }
  2308. // }
  2309. // }];
  2310. // [[[[self document] undoManager] prepareWithInvocationTarget:self] undoClick];
  2311. // [self.pageLabels setArray:[[self.pdfView document] pageLabels]];
  2312. // [self.pdfView layoutDocumentView];
  2313. // [self resetThumbnails];
  2314. //
  2315. // } else if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]] && [tableView isEqual:leftSideController.thumbnailTableView]) {
  2316. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2317. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2318. //
  2319. // return NO;
  2320. // }
  2321. //
  2322. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2323. // NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2324. // __block NSInteger index = row;
  2325. //
  2326. // if (fileNames.count == 1) {
  2327. // NSString *path = fileNames.firstObject;
  2328. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2329. // if ([pathExtension isEqualToString:@"pdf"]) {
  2330. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]]autorelease];
  2331. // if ([pdf isEncrypted]) {
  2332. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2333. // vc.filePath = path;
  2334. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2335. // if (password) {
  2336. // [pdf unlockWithPassword:password];
  2337. // for (NSUInteger i = 0; i< pdf.pageCount; i++) {
  2338. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2339. // [self.pdfView.document insertPage:page atIndex:index];
  2340. // [insertIndexSet addIndex:index];
  2341. // index++;
  2342. // [page release];
  2343. // }
  2344. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2345. // }
  2346. // }];
  2347. // [vc release];
  2348. // } else {
  2349. // for (NSUInteger i = 0; i < pdf.pageCount; i++) {
  2350. // PDFPage * page = [[pdf pageAtIndex:i] copy];
  2351. // [self.pdfView.document insertPage:page atIndex:index];
  2352. // [insertIndexSet addIndex:index];
  2353. // index++;
  2354. // [page release];
  2355. // }
  2356. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2357. //
  2358. // }
  2359. // } else if ([[KMImageToPDFMethod supportedImageTypes] containsObject:pathExtension]) {
  2360. // NSImage *image = [[[NSImage alloc] initWithContentsOfFile:path] autorelease];
  2361. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  2362. // [pdfView.document insertPage:page atIndex:index];
  2363. // [insertIndexSet addIndex:index];
  2364. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2365. // }
  2366. // result = YES;
  2367. // } else {
  2368. // result = NO;
  2369. // }
  2370. // }
  2371. return result == false
  2372. }
  2373. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  2374. if tableView.isEqual(to: self.thumbnailTableView) {
  2375. // let idx = rowIndexes.first
  2376. // if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2377. // PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2378. // NSString *fileExt = nil;
  2379. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2380. //
  2381. // if ([[pdfView document] allowsPrinting]) {
  2382. // NSData *pdfData = [page dataRepresentation];
  2383. // fileExt = @"pdf";
  2384. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypePDF, NSPasteboardTypeTIFF,NSFilenamesPboardType, NSFilesPromisePboardType, KPDFThumbnailLocalForDraggedTypes,KPDFThumbnailDoucumentURLForDraggedTypes,nil] owner:self];
  2385. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  2386. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  2387. // [pboard setData:zNSIndexSetData forType:KPDFThumbnailLocalForDraggedTypes];
  2388. // NSData *documentURL = [NSKeyedArchiver archivedDataWithRootObject:[[pdfView document].documentURL absoluteString]];
  2389. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  2390. // __block NSMutableString *pagesName = nil;
  2391. // if (rowIndexes.count > 1) {
  2392. // pagesName = [NSMutableString stringWithString:@" pages"];
  2393. //
  2394. // } else {
  2395. // pagesName = [NSMutableString stringWithString:@" page"];
  2396. //
  2397. // }
  2398. // NSString * tFileName = [NSString stringWithFormat:@"%@ %@",pagesName,[self fileNameWithSelectedPages:rowIndexes]];
  2399. // PDFDocument * pdf = [[[PDFDocument alloc] init] autorelease];
  2400. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2401. // PDFPage *copyPage = [[pdfView.document pageAtIndex:idx] copy];
  2402. // [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2403. // [copyPage release];
  2404. // }];
  2405. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2406. // NSString *cachesDir = [paths objectAtIndex:0];
  2407. // docmentName = [NSString stringWithFormat:@"%@%@",docmentName,tFileName];
  2408. // if (docmentName.length > 50) {
  2409. // [docmentName substringWithRange:NSMakeRange(0, 50)];
  2410. // }
  2411. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  2412. //
  2413. // BOOL success = [pdf writeToFile:cachesDir];
  2414. // if (success) {
  2415. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  2416. // }else{
  2417. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  2418. // }
  2419. // [pboard setData:documentURL forType:KPDFThumbnailDoucumentURLForDraggedTypes];
  2420. // } else {
  2421. // fileExt = @"tiff";
  2422. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2423. // }
  2424. // [pboard setData:tiffData forType:NSPasteboardTypeTIFF];
  2425. // [pboard setPropertyList:[NSArray arrayWithObject:fileExt] forType:NSFilesPromisePboardType];
  2426. let data: Data = try! NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  2427. pboard.declareTypes([.localDraggedTypes], owner: self)
  2428. pboard.setData(data, forType: .localDraggedTypes)
  2429. return true
  2430. // }
  2431. }
  2432. // else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2433. // NSUInteger idx = [rowIndexes firstIndex];
  2434. // if (idx != NSNotFound) {
  2435. // SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2436. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2437. // [pboard setData:[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] forType:NSPasteboardTypeTIFF];
  2438. // [pboard setPropertyList:[NSArray arrayWithObject:@"tiff"] forType:NSFilesPromisePboardType];
  2439. // return YES;
  2440. // }
  2441. // }
  2442. return false
  2443. }
  2444. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  2445. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2446. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2447. // return;
  2448. // }
  2449. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  2450. // NSArray *controllers = [[rightSideController.snapshotArrayController arrangedObjects] objectsAtIndexes:rowIndexes];
  2451. // [controllers makeObjectsPerformSelector:@selector(close)];
  2452. // } else
  2453. if aTableView.isEqual(to: self.thumbnailTableView) {
  2454. for idx in rowIndexes {
  2455. if idx >= self.listView.document.pageCount {
  2456. return
  2457. }
  2458. if let page = self.listView.document.page(at: UInt(idx)) {
  2459. for anno in page.annotations {
  2460. page.removeAnnotation(anno)
  2461. }
  2462. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  2463. self.listView.document.removePage(at: IndexSet(integer: idx))
  2464. }
  2465. }
  2466. self.listView.layoutDocumentView()
  2467. // [pageLabels setArray:[[pdfView document] pageLabels]];
  2468. self.resetThumbnails()
  2469. let idx = rowIndexes.first ?? -1
  2470. let index = min(idx, Int(self.listView.document.pageCount)-1)
  2471. self.listView.go(toPageIndex: index, animated: false)
  2472. }
  2473. }
  2474. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  2475. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  2476. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2477. // return;
  2478. // }
  2479. if aTableView.isEqual(to: self.thumbnailTableView) {
  2480. self._copysPages.removeAll()
  2481. if self.listView.document.isLocked == false {
  2482. for idx in rowIndexes {
  2483. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  2484. self._copysPages.append(page)
  2485. }
  2486. }
  2487. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2488. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2489. // NSPasteboardItem *pboardItem = [[[NSPasteboardItem alloc] init] autorelease];
  2490. // if ([[pdfView document] allowsPrinting])
  2491. // [pboardItem setData:[page dataRepresentation] forType:NSPasteboardTypePDF];
  2492. // [pboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
  2493. // [pboard clearContents];
  2494. // [pboard writeObjects:[NSArray arrayWithObjects:pboardItem, nil]];
  2495. }
  2496. }
  2497. // else if ([tv isEqual:leftSideController.findTableView]) {
  2498. // NSMutableString *string = [NSMutableString string];
  2499. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2500. // PDFSelection *match = [searchResults objectAtIndex:idx];
  2501. // [string appendString:@"* "];
  2502. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  2503. // [string appendFormat:@": %@\n", [[match contextString] string]];
  2504. // }];
  2505. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2506. // [pboard clearContents];
  2507. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2508. // } else if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2509. // NSMutableString *string = [NSMutableString string];
  2510. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2511. // SKGroupedSearchResult *result = [groupedSearchResults objectAtIndex:idx];
  2512. // NSArray *matches = [result matches];
  2513. // [string appendString:@"* "];
  2514. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [[result page] displayLabel]];
  2515. // [string appendString:@": "];
  2516. // [string appendFormat:NSLocalizedString(@"%ld Results", @""), (long)[matches count]];
  2517. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  2518. // }];
  2519. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2520. // [pboard clearContents];
  2521. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2522. // }
  2523. }
  2524. /*
  2525. #pragma mark dragging
  2526. - (NSArray *)tableView:(NSTableView *)tv namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2527. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2528. __block NSMutableArray *fileURLArray = [NSMutableArray array];
  2529. if (rowIndexes.count > 1) {
  2530. NSString *docmentName = @"";
  2531. NSString * tFileName = [NSString stringWithFormat:@"%@",[self fileNameWithSelectedPages:rowIndexes]];
  2532. PDFDocument *pdf = [[[PDFDocument alloc] init] autorelease];
  2533. [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2534. if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2535. PDFPage *copyPage = [[[pdfView document] pageAtIndex:idx] copy];
  2536. [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2537. [copyPage release];
  2538. }
  2539. }];
  2540. NSURL *fileURL = [[[dropDestination URLByAppendingPathComponent:tFileName] URLByAppendingPathExtension:@"pdf"] uniqueFileURL];
  2541. docmentName = fileURL.path;
  2542. BOOL success = [pdf writeToFile:docmentName];
  2543. if(success) {
  2544. [fileURLArray addObject:[fileURL lastPathComponent]];
  2545. }
  2546. } else {
  2547. PDFPage *page = [[pdfView document] pageAtIndex:rowIndexes.firstIndex];
  2548. NSURL *fileURL = [dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]];
  2549. NSString *pathExt = nil;
  2550. NSData *data = nil;
  2551. if ([[pdfView document] allowsPrinting]) {
  2552. pathExt = @"pdf";
  2553. data = [page dataRepresentation];
  2554. } else {
  2555. pathExt = @"tiff";
  2556. data = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2557. }
  2558. fileURL = [[fileURL URLByAppendingPathExtension:pathExt] uniqueFileURL];
  2559. if ([data writeToURL:fileURL atomically:YES]) {
  2560. [fileURLArray addObject:[fileURL lastPathComponent]];
  2561. }
  2562. }
  2563. return fileURLArray;
  2564. } else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2565. NSUInteger idx = [rowIndexes firstIndex];
  2566. if (idx != NSNotFound) {
  2567. SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2568. PDFPage *page = [[pdfView document] pageAtIndex:[snapshot pageIndex]];
  2569. NSURL *fileURL = [[dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]] URLByAppendingPathExtension:@"tiff"];
  2570. fileURL = [fileURL uniqueFileURL];
  2571. if ([[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] writeToURL:fileURL atomically:YES])
  2572. return [NSArray arrayWithObjects:[fileURL lastPathComponent], nil];
  2573. }
  2574. }
  2575. return [NSArray array];
  2576. }
  2577. - (void)tableView:(NSTableView *)tv sortDescriptorsDidChange:(NSArray *)oldDescriptors {
  2578. if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2579. [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  2580. }
  2581. }
  2582. #pragma mark NSTableView delegate protocol
  2583. - (void)tableViewColumnDidResize:(NSNotification *)aNotification {
  2584. if ([[[[aNotification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:IMAGE_COLUMNID]) {
  2585. if ([[aNotification object] isEqual:leftSideController.thumbnailTableView]) {
  2586. [leftSideController.thumbnailTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [leftSideController.thumbnailTableView numberOfRows])]];
  2587. } else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2588. [rightSideController.snapshotTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.snapshotTableView numberOfRows])]];
  2589. }
  2590. }
  2591. }
  2592. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2593. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2594. NSUInteger idx = [rowIndexes firstIndex];
  2595. if (idx != NSNotFound) {
  2596. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2597. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  2598. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  2599. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  2600. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  2601. [self fileWithPage:page atPath:filePath];
  2602. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  2603. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  2604. } else {
  2605. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  2606. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  2607. }
  2608. }
  2609. }
  2610. }
  2611. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  2612. NSData *data = [page dataRepresentation];
  2613. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  2614. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  2615. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  2616. if (success) {
  2617. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  2618. NSURL *url = [NSURL fileURLWithPath:filePath];
  2619. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  2620. }
  2621. [document release];
  2622. */
  2623. }
  2624. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  2625. /*
  2626. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  2627. if item is KMBOTAAnnotationSection {
  2628. let section = item as? KMBOTAAnnotationSection
  2629. return section!.annotations?[index] as Any
  2630. } else if item is KMBOTAAnnotationItem {
  2631. return item as Any
  2632. } else {
  2633. var tempArray: [KMBOTAAnnotationSection] = []
  2634. for temp in self.data {
  2635. if temp.annotations?.count != 0 {
  2636. tempArray.append(temp)
  2637. }
  2638. }
  2639. let section = tempArray[index]
  2640. return section as Any
  2641. }
  2642. }
  2643. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  2644. if item is KMBOTAAnnotationItem {
  2645. let cell : KMAnnotationOutlineCellView = KMAnnotationOutlineCellView.init()
  2646. cell.delegate = self
  2647. cell.model = item as? KMBOTAAnnotationItem
  2648. return cell
  2649. } else if item is KMBOTAAnnotationSection {
  2650. let section = item as? KMBOTAAnnotationSection
  2651. let cell : KMAnnotationOutlineSectionView = KMAnnotationOutlineSectionView.init()
  2652. cell.model = section
  2653. return cell
  2654. }
  2655. return NSTableCellView()
  2656. }
  2657. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2658. let rowView = KMAnnotationOutlineRowView()
  2659. if item is KMBOTAAnnotationItem {
  2660. rowView.model = (item as? KMBOTAAnnotationItem)
  2661. } else if item is KMBOTAAnnotationSection {
  2662. rowView.section = (item as? KMBOTAAnnotationSection)
  2663. }
  2664. rowView.mouseDownAction = { [unowned self] view, event in
  2665. if rowView.section != nil {
  2666. let expanded = outlineView.isItemExpanded(outlineView.item(atRow: outlineView.selectedRow))
  2667. if expanded {
  2668. outlineView.collapseItem(outlineView.item(atRow: outlineView.selectedRow), collapseChildren: true)
  2669. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2670. } else {
  2671. outlineView.expandItem(outlineView.item(atRow: outlineView.selectedRow), expandChildren: true)
  2672. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2673. }
  2674. } else if rowView.model != nil {
  2675. self.didSelectItem(view: rowView, event: event)
  2676. }
  2677. }
  2678. rowView.rightMouseDownAction = { [unowned self] view, event in
  2679. if rowView.section != nil {
  2680. } else if rowView.model != nil {
  2681. if !KMOCToolClass.arrayContains(array: self.selectItems, annotation: item) ||
  2682. self.selectItems.count == 1 {
  2683. self.selectItem(item: item as! KMBOTAAnnotationItem)
  2684. }
  2685. DispatchQueue.main.async {
  2686. self.delegate?.annotationOutlineView(self, rightMouseDownDidSelectView: view, evnet: event)
  2687. }
  2688. }
  2689. }
  2690. rowView.hoverCallback = { [unowned self] (mouseEntered, mouseBox) in
  2691. self.outlineView.enumerateAvailableRowViews { view, row in
  2692. if view is KMAnnotationOutlineRowView {
  2693. (view as? KMAnnotationOutlineRowView)?.model?.hover = false
  2694. (view as? KMAnnotationOutlineRowView)?.reloadData()
  2695. }
  2696. }
  2697. if mouseEntered {
  2698. rowView.model?.hover = true
  2699. } else {
  2700. rowView.model?.hover = false
  2701. }
  2702. }
  2703. return rowView
  2704. }
  2705. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2706. if item is KMBOTAAnnotationItem {
  2707. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: self.maxWidth - 16, height: 1000))
  2708. } else if item is KMBOTAAnnotationSection {
  2709. return 40
  2710. } else {
  2711. return 30
  2712. }
  2713. }
  2714. func outlineViewSelectionDidChange(_ notification: Notification) {
  2715. if self.outlineView.selectedRow == -1 {
  2716. self.cancelSelect()
  2717. }
  2718. }
  2719. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2720. if item is KMBOTAAnnotationItem {
  2721. return false
  2722. } else if item is KMBOTAAnnotationSection {
  2723. let section = item as? KMBOTAAnnotationSection
  2724. return section!.annotations?.count ?? 0 > 0
  2725. }
  2726. return false
  2727. }
  2728. func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
  2729. if let item = item as? KMBOTAAnnotationSection {
  2730. if !item.isItemExpanded {
  2731. item.isItemExpanded = true
  2732. outlineView.animator().expandItem(item, expandChildren: true)
  2733. return false
  2734. }
  2735. }
  2736. return true
  2737. }
  2738. func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
  2739. if let item = item as? KMBOTAAnnotationSection {
  2740. if item.isItemExpanded {
  2741. item.isItemExpanded = false
  2742. outlineView.animator().collapseItem(item, collapseChildren: true)
  2743. return false
  2744. }
  2745. }
  2746. return true
  2747. }
  2748. */
  2749. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  2750. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  2751. if outlineView.isEqual(to: self.tocOutlineView) {
  2752. let isLocked = self.listView.document?.isLocked ?? true
  2753. if isLocked { // 文档不存在 或 已加锁
  2754. return 0
  2755. }
  2756. if item == nil { // 第一层
  2757. // 获取根
  2758. guard let outline = self.listView.document.outlineRoot() else {
  2759. let view = self.tocOutlineView.enclosingScrollView!
  2760. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2761. //
  2762. 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)
  2763. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2764. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2765. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  2766. return 0
  2767. }
  2768. if outline.numberOfChildren == 0 {
  2769. // return 0
  2770. }
  2771. if self.isSearchOutlineMode { // 是否为搜索模块
  2772. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: outline) {
  2773. self.showSearchOutlineBlankState(false)
  2774. } else {
  2775. self.showSearchOutlineBlankState(true)
  2776. return 0
  2777. }
  2778. } else {
  2779. if outline.numberOfChildren > 0 { // 有数据
  2780. self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  2781. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  2782. } else { // 没有数据
  2783. let view = self.tocOutlineView.enclosingScrollView!
  2784. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2785. //
  2786. 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)
  2787. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2788. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2789. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  2790. return 0
  2791. }
  2792. }
  2793. // 搜索按钮
  2794. if outline.numberOfChildren > 0 {
  2795. self.outlineSearchButton.isEnabled = true
  2796. } else {
  2797. self.outlineSearchButton.isEnabled = false
  2798. }
  2799. if (self.isSearchOutlineMode) {
  2800. var num = 0
  2801. for i in 0 ..< outline.numberOfChildren {
  2802. if let child = outline.child(at: i) {
  2803. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  2804. num += 1
  2805. }
  2806. }
  2807. }
  2808. return num
  2809. } else {
  2810. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  2811. var bookmarkNum = 0
  2812. if array.isEmpty == false {
  2813. bookmarkNum = 1
  2814. }
  2815. return Int(outline.numberOfChildren) + bookmarkNum
  2816. }
  2817. } else { // 第二层 +
  2818. if self.isSearchOutlineMode {
  2819. if let data = item as? String, data == "Bookmarks" { // 书签group
  2820. return 0
  2821. } else if item is CPDFOutline { // 大纲
  2822. let child = item as! CPDFOutline
  2823. if child.numberOfChildren == 0 {
  2824. return 0
  2825. }
  2826. var num = 0
  2827. for i in 0 ..< child.numberOfChildren {
  2828. if let _child = child.child(at: i) {
  2829. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: _child) {
  2830. num += 1
  2831. }
  2832. }
  2833. }
  2834. return num
  2835. } else if item is CPDFBookmark { // 书签
  2836. return 0
  2837. }
  2838. } else {
  2839. if let data = item as? String, data == "Bookmarks" { // 书签group
  2840. return (self.listView.document?.bookmarks().count) ?? 0
  2841. } else if item is CPDFOutline { // 大纲
  2842. return Int((item as? CPDFOutline)?.numberOfChildren ?? 0)
  2843. } else if item is CPDFBookmark { // 书签
  2844. return 0
  2845. }
  2846. }
  2847. }
  2848. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2849. if self.noteSearchMode {
  2850. return self.noteSearchArray.count
  2851. }
  2852. var count = 0
  2853. for section in self._annotations {
  2854. if section.annotations?.count != 0 {
  2855. count += section.annotations!.count
  2856. }
  2857. }
  2858. // if (item == nil){
  2859. // NSInteger count = [[rightSideController.noteArrayController arrangedObjects] count];
  2860. if (count < 1) {
  2861. // if (notes.count < 1) {
  2862. self.noteSearchButton.isEnabled = false
  2863. self.noteFilterButton.isEnabled = false
  2864. // }
  2865. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  2866. let view = self.noteOutlineView.enclosingScrollView!
  2867. var emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  2868. 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)
  2869. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2870. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  2871. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  2872. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  2873. //
  2874. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  2875. self.noteHeaderView.isHidden = true
  2876. self.toolButtonBoxLayoutConstraint.constant = 40.0
  2877. }
  2878. } else {
  2879. self.noteSearchButton.isEnabled = true
  2880. self.noteFilterButton.isEnabled = true
  2881. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  2882. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  2883. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  2884. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  2885. //
  2886. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  2887. self.noteHeaderView.isHidden = false
  2888. self.toolButtonBoxLayoutConstraint.constant = 64.0
  2889. }
  2890. }
  2891. return count
  2892. // } else {
  2893. // return [item hasNoteText];
  2894. // }
  2895. }
  2896. return 0
  2897. }
  2898. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  2899. if outlineView.isEqual(to: self.tocOutlineView) {
  2900. let isLocked = self.listView.document?.isLocked ?? true
  2901. if isLocked { // 文档不存在 或 已加锁
  2902. return ""
  2903. }
  2904. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  2905. var bookmarkNum = 0
  2906. if array.isEmpty == false {
  2907. bookmarkNum = 1
  2908. }
  2909. if item == nil {
  2910. if self.isSearchOutlineMode {
  2911. guard let outline = self.listView.document.outlineRoot() else {
  2912. return ""
  2913. }
  2914. if outline.numberOfChildren == 0 {
  2915. return ""
  2916. }
  2917. var array: [CPDFOutline] = []
  2918. for i in 0 ..< outline.numberOfChildren {
  2919. if let child = outline.child(at: i) {
  2920. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  2921. array.append(child)
  2922. }
  2923. }
  2924. }
  2925. if index < array.count {
  2926. return array[index]
  2927. }
  2928. return ""
  2929. } else {
  2930. if index == 0 && bookmarkNum == 1 {
  2931. return "Bookmarks"
  2932. } else {
  2933. var _index = bookmarkNum == 1 ? index-1 : index
  2934. let outline = self.listView.document.outlineRoot()
  2935. var obj = outline?.child(at: UInt(_index))
  2936. return obj as Any
  2937. }
  2938. }
  2939. } else {
  2940. if let data = item as? String, data == "Bookmarks" {
  2941. return array[index]
  2942. } else if item is CPDFOutline {
  2943. return (item as! CPDFOutline).child(at: UInt(index))
  2944. } else if item is CPDFBookmark {
  2945. return ""
  2946. }
  2947. }
  2948. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2949. // if (item == nil)
  2950. // {
  2951. // return [[rightSideController.noteArrayController arrangedObjects] objectAtIndex:anIndex];
  2952. // // return [self.notes objectAtIndex:anIndex];
  2953. // }
  2954. // else
  2955. // return [item noteText];
  2956. if self.noteSearchMode {
  2957. return self.noteSearchArray[index]
  2958. }
  2959. var tempArray: [KMBOTAAnnotationItem] = []
  2960. for secion in self._annotations {
  2961. if secion.annotations?.count != 0 {
  2962. for _item in secion.annotations! {
  2963. tempArray.append(_item)
  2964. }
  2965. }
  2966. }
  2967. return tempArray[index] as Any
  2968. }
  2969. return item
  2970. }
  2971. func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
  2972. if outlineView.isEqual(to: self.tocOutlineView) {
  2973. // let tcID = tableColumn?.identifier.rawValue ?? ""
  2974. // var ol = item as? CPDFOutline
  2975. // if(tcID == LABEL_COLUMNID) {
  2976. // if (self.isSearchOutlineMode) {
  2977. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  2978. //// NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  2979. //// NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  2980. //// for (NSUInteger i = 0; i <arr.count ; i++) {
  2981. //// NSValue * rangeValue = arr[i];
  2982. //// NSRange range = rangeValue.rangeValue;
  2983. //// range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  2984. //// [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  2985. //// }
  2986. //// [attributeString addAttribute:NSForegroundColorAttributeName value:[KMAppearance KMColor_Layout_H0] range:NSMakeRange(0, roughString.length)];
  2987. //// return attributeString;
  2988. // } else {
  2989. // var attributedString = NSMutableAttributedString()
  2990. //// attributedString
  2991. // attributedString.append(.init(string: ol?.label ?? "", attributes: [.foregroundColor : KMAppearance.Layout.h0Color()]))
  2992. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  2993. //// NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2994. //// NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  2995. //// [attributedString appendAttributedString:attr1];
  2996. //
  2997. // return attributedString
  2998. // }
  2999. //
  3000. // }
  3001. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3002. // NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3003. // NSString *roughString = [ol pageLabel]? : @"";
  3004. // NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3005. // NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  3006. // [attributedString appendAttributedString:attr1];
  3007. //
  3008. // return attributedString;
  3009. // }
  3010. }
  3011. // else if ([ov isEqual:rightSideController.noteOutlineView]) {
  3012. // NSString *tcID = [tableColumn identifier];
  3013. // PDFAnnotation *note = item;
  3014. // if (tableColumn == nil || [tcID isEqualToString:NOTE_COLUMNID])
  3015. // return [note objectValue];
  3016. // else if([tcID isEqualToString:TYPE_COLUMNID]){
  3017. // NSString *noteType = [note type];
  3018. // if ([note isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  3019. // PDFAnnotationButtonWidget *buttonWidget = (PDFAnnotationButtonWidget *)note;
  3020. // if (buttonWidget.controlType == kPDFWidgetRadioButtonControl) {
  3021. // noteType = SKAnnotationFormRadioButtonKey;
  3022. // } else if (buttonWidget.controlType == kPDFWidgetCheckBoxControl){
  3023. // noteType = SKAnnotationFormCheckBoxKey;
  3024. // } else if (buttonWidget.controlType == kPDFWidgetPushButtonControl){
  3025. // noteType = SKAnnotationFormActionButtonKey;
  3026. // }
  3027. // } else if ([note isKindOfClass:[PDFAnnotationTextWidget class]]){
  3028. // noteType = SKAnnotationFormTextFieldKey;
  3029. // } else if ([note isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  3030. // PDFAnnotationChoiceWidget *choiceWidget = (PDFAnnotationChoiceWidget *)note;
  3031. // if (choiceWidget.isListChoice) {
  3032. // noteType = SKAnnotationFormListMenuKey;
  3033. // } else {
  3034. // noteType = SKAnnotationFormComboBoxKey;
  3035. // }
  3036. //
  3037. // }
  3038. // return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:note == [pdfView activeAnnotation]], SKAnnotationTypeImageCellActiveKey, noteType, SKAnnotationTypeImageCellTypeKey,[note color],SKAnnotationTypeImageCellColorKey, nil];
  3039. // }
  3040. // else if([tcID isEqualToString:COLOR_COLUMNID])
  3041. // return [note type] ? [note color] : nil;
  3042. // else if([tcID isEqualToString:PAGE_COLUMNID])
  3043. // return [[note page] displayLabel];
  3044. // else if([tcID isEqualToString:AUTHOR_COLUMNID])
  3045. // return [note type] ? [note userName] : nil;
  3046. // else if([tcID isEqualToString:DATE_COLUMNID])
  3047. // return [note type] ? [note modificationDate] : nil;
  3048. // }
  3049. return nil
  3050. }
  3051. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  3052. if outlineView.isEqual(to: self.tocOutlineView) {
  3053. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMTocTableCellView"), owner: self) as! KMTocTableCellView
  3054. let tcID = tableColumn?.identifier.rawValue
  3055. var title = ""
  3056. var pageLabel = ""
  3057. if let data = item as? String, data == "Bookmarks" {
  3058. title = NSLocalizedString("Bookmarks", comment: "")
  3059. } else if item is CPDFOutline {
  3060. title = (item as! CPDFOutline).label
  3061. pageLabel = "\(((item as! CPDFOutline).destination?.pageIndex ?? 0) + 1)"
  3062. } else if item is CPDFBookmark {
  3063. title = (item as! CPDFBookmark).label
  3064. pageLabel = "\((item as! CPDFBookmark).pageIndex + 1)"
  3065. }
  3066. if tcID == LABEL_COLUMNID {
  3067. if (self.isSearchOutlineMode) {
  3068. // NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines];
  3069. let roughString = title
  3070. // NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  3071. // NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  3072. //
  3073. // for (NSUInteger i = 0; i <arr.count ; i++) {
  3074. // NSValue * rangeValue = arr[i];
  3075. // NSRange range = rangeValue.rangeValue;
  3076. // range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  3077. // [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  3078. // }
  3079. // cell.tocLabel.attributedStringValue = attributeString;
  3080. cell.tocLabel.stringValue = title
  3081. } else {
  3082. cell.tocLabel.stringValue = title
  3083. }
  3084. cell.pageLabel.stringValue = pageLabel
  3085. }
  3086. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3087. // cell.pageLabel.stringValue = [ol pageLabel];
  3088. // }
  3089. return cell
  3090. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3091. let model = item as? KMBOTAAnnotationItem
  3092. var note: CPDFAnnotation!
  3093. if self.noteSearchMode {
  3094. note = item as! CPDFAnnotation
  3095. } else {
  3096. note = (item as! KMBOTAAnnotationItem).annotation!
  3097. }
  3098. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMNoteTableViewCell"), owner: self) as! KMNoteTableViewCell
  3099. cell.cellNote = note
  3100. let noteColor = note.color
  3101. var noteType = note.type ?? ""
  3102. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  3103. // NSString *pageString = [[note page] displayLabel] ? : @"";
  3104. var pageString = "\((note.page?.pageIndex() ?? 0) + 1)"
  3105. let formatter = DateFormatter()
  3106. formatter.dateFormat = "hh:mm"
  3107. var dateString = ""
  3108. if let date = note.modificationDate() {
  3109. dateString = formatter.string(from: date)
  3110. }
  3111. var authorString = note.userName() ?? ""
  3112. // NSString *noteTextString = [note noteText].string ? : @"";
  3113. var noteTextString = note.string() ?? ""
  3114. //
  3115. // if([noteType isEqualToString:@"Redact"]) {
  3116. // noteString = @"Redact";
  3117. // }
  3118. //
  3119. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool
  3120. if timeKey == nil || timeKey == false {
  3121. // if (date != nil) {
  3122. cell.timeLabel.stringValue = dateString
  3123. //
  3124. // } else {
  3125. // cell.timeLabel.stringValue = ""
  3126. // }
  3127. cell.timeLabel.isHidden = false
  3128. } else {
  3129. cell.timeLabel.isHidden = true
  3130. }
  3131. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool
  3132. if pageKey == nil || pageKey == false {
  3133. let labelsize = cell.pageLabel.stringValue.boundingRect(with: CGSizeMake(CGFloat(MAXFLOAT),CGRectGetHeight(cell.pageLabel.bounds)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font : NSFont.systemFont(ofSize: 12)])
  3134. cell.pageLabelWidthConstraint.constant = labelsize.size.width + 5
  3135. cell.pageLabel.stringValue = pageString
  3136. cell.pageLabel.isHidden = false
  3137. } else {
  3138. cell.pageLabel.isHidden = true
  3139. }
  3140. let autherKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool
  3141. if pageKey == nil || pageKey == false {
  3142. cell.autherLabel.stringValue = authorString
  3143. cell.autherLabel.isHidden = false
  3144. } else {
  3145. cell.autherLabel.isHidden = true
  3146. }
  3147. let imageView = KMNoteTypeImageView()
  3148. if note.isKind(of: CPDFStampAnnotation.self) {
  3149. let annotation_stamp = note as! CPDFStampAnnotation
  3150. if (annotation_stamp.stampImage() != nil) {
  3151. noteType = SKNStampString
  3152. }
  3153. } else if note.isKind(of: CPDFLineAnnotation.self) {
  3154. let annotation_line = note as! CPDFLineAnnotation
  3155. if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .none {
  3156. noteType = SKNLine_NoneString
  3157. } else if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .openArrow {
  3158. noteType = SKNLine_OpenArrowString
  3159. } else {
  3160. noteType = SKNLine_NoneString
  3161. }
  3162. } else if note.isKind(of: CPDFButtonWidgetAnnotation.self) {
  3163. let buttonWidget = note as! CPDFButtonWidgetAnnotation
  3164. if buttonWidget.controlType() == .radioButtonControl {
  3165. noteType = KMAnnotationFormRadioButtonKey
  3166. } else if buttonWidget.controlType() == .checkBoxControl {
  3167. noteType = KMAnnotationFormCheckBoxKey
  3168. } else if buttonWidget.controlType() == .pushButtonControl {
  3169. noteType = KMAnnotationFormActionButtonKey
  3170. }
  3171. } else if note.isKind(of: CPDFTextWidgetAnnotation.self) {
  3172. noteType = KMAnnotationFormTextFieldKey
  3173. } else if note.isKind(of: CPDFChoiceWidgetAnnotation.self) {
  3174. let choiceWidget = note as! CPDFChoiceWidgetAnnotation
  3175. if choiceWidget.isListChoice {
  3176. noteType = KMAnnotationFormListMenuKey
  3177. } else {
  3178. noteType = KMAnnotationFormComboBoxKey
  3179. }
  3180. } else if note.isKind(of: KMTableAnnotation.self) {
  3181. noteType = "Ink_Table"
  3182. } else if note.isKind(of: KMSelfSignAnnotation.self) {
  3183. let selfSignNote = note as! KMSelfSignAnnotation
  3184. if selfSignNote.annotationType == .signFalse {
  3185. noteType = "KMSelfSignTypeFalseActionButtonKey"
  3186. } else if (selfSignNote.annotationType == .signature) {
  3187. noteType = "KMSelfSignTypeTureActionButtonKey"
  3188. } else if (selfSignNote.annotationType == .signCircle) {
  3189. noteType = "KMSelfSignTypeCircleActionButtonKey"
  3190. } else if (selfSignNote.annotationType == .signLine) {
  3191. noteType = "KMSelfSignTypeLineActionButtonKey"
  3192. } else if (selfSignNote.annotationType == .signDot) {
  3193. noteType = "KMSelfSignTypeDotActionButtonKey"
  3194. } else if (selfSignNote.annotationType == .signText) {
  3195. noteType = "KMSelfSignTypeTextActionButtonKey"
  3196. }
  3197. } else if note.isKind(of: CPDFSquareAnnotation.self) {
  3198. noteType = SKNSquareString
  3199. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3200. noteType = SKNNoteString
  3201. } else if note.isKind(of: CPDFFreeTextAnnotation.self) {
  3202. noteType = SKNFreeTextString
  3203. } else if note.isKind(of: CPDFCircleAnnotation.self) {
  3204. noteType = SKNCircleString
  3205. } else if note.isKind(of: CPDFSignatureAnnotation.self) {
  3206. noteType = SKNSignatureString
  3207. } else if note.isKind(of: CPDFInkAnnotation.self) {
  3208. noteType = SKNInkString
  3209. } else if note.isKind(of: CPDFMarkupAnnotation.self) {
  3210. let anno = note as! CPDFMarkupAnnotation
  3211. if anno.markupType() == .highlight {
  3212. noteType = SKNHighlightString
  3213. } else if anno.markupType() == .underline {
  3214. noteType = SKNUnderlineString
  3215. } else if anno.markupType() == .strikeOut {
  3216. noteType = SKNStrikeOutString
  3217. }
  3218. }
  3219. cell.typeImageView.image = imageView.noteTypeImage(withType: noteType, color: noteColor ?? .red)
  3220. cell.typeImageView.isHidden = false
  3221. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3222. cell.isFold = true
  3223. }
  3224. cell.noteContentBox.isHidden = true
  3225. cell.noteImageView.isHidden = true
  3226. cell.foldButton.isHidden = true
  3227. cell.annotationContentLabel.isHidden = false
  3228. cell.noteContentLabel.stringValue = noteString
  3229. cell.contentView.isHidden = false
  3230. cell.contentViewHidden(false)
  3231. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3232. let markup = note as! CPDFMarkupAnnotation
  3233. var contentString = KMBOTAAnnotationTool.fetchText(text: markup.markupContent() ?? "")
  3234. contentString = contentString.replacingOccurrences(of: "\r", with: "")
  3235. contentString = contentString.replacingOccurrences(of: "\n", with: "")
  3236. cell.noteContentLabel.stringValue = contentString
  3237. if(contentString.isEmpty == false) {
  3238. cell.foldButton.isHidden = false
  3239. }
  3240. var attributeStr = NSMutableAttributedString(string: contentString)
  3241. if (markup.markupType() == .highlight) {
  3242. attributeStr.addAttribute(.backgroundColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3243. } else if (markup.markupType() == .strikeOut) {
  3244. attributeStr.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3245. attributeStr.addAttribute(.strikethroughColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3246. } else if (markup.markupType() == .underline) {
  3247. attributeStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3248. attributeStr.addAttribute(.underlineColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3249. }
  3250. cell.annotationContentLabel.attributedStringValue = attributeStr
  3251. if let data = model?.foldType, data == .unfold {
  3252. cell.isFold = false
  3253. } else if let data = model?.foldType, data == .fold {
  3254. cell.isFold = true
  3255. } else {
  3256. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3257. cell.isFold = false
  3258. } else {
  3259. cell.isFold = true
  3260. }
  3261. }
  3262. // noteString.isEmpty == false &&
  3263. if (contentString.isEmpty == false) {
  3264. cell.contentViewHidden(false)
  3265. } else {
  3266. cell.contentViewHidden(true)
  3267. }
  3268. } else if note.isKind(of: CPDFLineAnnotation.self) || noteType == SKNSquareString || noteType == SKNCircleString || noteType == SKNInkString {
  3269. cell.annotationContentLabel.stringValue = noteString
  3270. if (noteString.isEmpty == false) {
  3271. cell.contentViewHidden(false)
  3272. } else {
  3273. cell.contentViewHidden(true)
  3274. }
  3275. } else if note.isKind(of: CPDFStampAnnotation.self) {
  3276. if note.isKind(of: KMSelfSignAnnotation.self) {
  3277. let newAnnotation = note as! KMSelfSignAnnotation
  3278. let type = newAnnotation.annotationType
  3279. var returnString = ""
  3280. if (type == .signFalse) {
  3281. returnString = KMLocalizedString("X", nil)
  3282. } else if (type == .signature) {
  3283. returnString = KMLocalizedString("Check mark", nil)
  3284. } else if (type == .signCircle) {
  3285. returnString = KMLocalizedString("Circle", nil)
  3286. } else if (type == .signLine) {
  3287. returnString = KMLocalizedString("Line", nil)
  3288. } else if (type == .signDot) {
  3289. returnString = KMLocalizedString("Dot", nil)
  3290. } else if (type == .signText) {
  3291. returnString = KMLocalizedString("Text", nil)
  3292. }
  3293. cell.annotationContentLabel.stringValue = returnString
  3294. } else {
  3295. cell.annotationContentLabel.isHidden = true
  3296. cell.noteImageView.isHidden = false
  3297. let anno = note as! CPDFStampAnnotation
  3298. cell.noteImageView.image = anno.stampImage()
  3299. }
  3300. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3301. cell.foldButton.isHidden = false
  3302. if noteString.isEmpty {
  3303. cell.annotationContentLabel.stringValue = noteTextString
  3304. }else{
  3305. cell.annotationContentLabel.stringValue = noteString
  3306. cell.noteContentLabel.stringValue = noteTextString
  3307. }
  3308. if (self.foldType == .unfold) {
  3309. cell.isFold = false
  3310. } else if (self.foldType == .fold) {
  3311. cell.isFold = true
  3312. } else {
  3313. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3314. cell.isFold = false
  3315. } else {
  3316. cell.isFold = true
  3317. }
  3318. }
  3319. if (noteString.isEmpty == false || noteTextString.isEmpty == false) {
  3320. cell.contentView.isHidden = false
  3321. } else {
  3322. cell.contentView.isHidden = true
  3323. cell.contentViewHidden(true)
  3324. }
  3325. // noteString.isEmpty == false &&
  3326. if (noteTextString.isEmpty == false) {
  3327. cell.foldButton.isHidden = false
  3328. }else{
  3329. cell.foldButton.isHidden = true
  3330. }
  3331. } else {
  3332. cell.annotationContentLabel.stringValue = noteString
  3333. cell.imageViewHeightConstraint.constant = cell.contentView.frame.size.height
  3334. if (noteString.isEmpty == false) {
  3335. cell.contentViewHidden(false)
  3336. } else {
  3337. cell.contentViewHidden(true)
  3338. }
  3339. }
  3340. cell.autherLayoutConstraint.constant = cell.autherLabel.isHidden ? -(cell.autherLabel.bounds.size.width) + 10.0 : 10.0
  3341. cell.typeImageViewLayoutConstraint.constant = cell.typeImageView.isHidden ? -(cell.typeImageView.bounds.size.width) : 0.0
  3342. cell.contentBoxLayoutConstraint.constant = cell.noteContentBox.isHidden ? -(cell.noteContentBox.bounds.size.height+8.0) : 8.0
  3343. if note.isKind(of: CPDFStampAnnotation.self) && note.isKind(of: KMSelfSignAnnotation.self) == false {
  3344. } else {
  3345. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3346. if (!cell.isFold) {
  3347. self.allFoldNotes.append(note)
  3348. } else {
  3349. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3350. }
  3351. } else {
  3352. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3353. }
  3354. }
  3355. cell.isUnFoldNote = { [unowned self] cellNote, isUnfold in
  3356. model?.foldType = isUnfold ? .unfold : .fold
  3357. // let COLUMN_INDENTATION: CGFloat = 16
  3358. // if let _cell = tableColumn?.dataCell as? NSCell {
  3359. // _cell.objectValue = cell.annotationContentLabel.attributedStringValue
  3360. // let bound = NSMakeRect(0.0, 0.0, fmax(10.0, NSWidth(outlineView.frame) - COLUMN_INDENTATION - outlineView.indentationPerLevel-40), CGFLOAT_MAX)
  3361. // let height = _cell.cellSize(forBounds: bound).height
  3362. // KMPrint(height)
  3363. // }
  3364. if cellNote is CPDFMarkupAnnotation {
  3365. // let content = cell.annotationContentLabel.attributedStringValue
  3366. // let bound = content.string.boundingRect(with: NSMakeSize(150, CGFLOAT_MAX), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: nil)
  3367. // KMPrint(bound)
  3368. // 154 34 273
  3369. // 273 - 188 = 85 noteContentHeightConstraint maltlineLabelLayoutConstraint
  3370. model?.foldH = isUnfold ? 30 : (cell.noteContentHeightConstraint.constant + cell.maltlineLabelLayoutConstraint.constant + 85)
  3371. }
  3372. if (isUnfold) {
  3373. if (self.allFoldNotes.contains(note)) {
  3374. self.allFoldNotes.removeObject(note)
  3375. }
  3376. if (self.allFoldNotes.count == 0) {
  3377. self.foldType = .fold
  3378. } else {
  3379. self.foldType = .none
  3380. }
  3381. } else {
  3382. if self.allFoldNotes.contains(note) == false {
  3383. self.allFoldNotes.append(note)
  3384. }
  3385. // if (rightSideController.allFoldNotes.count == rightSideController.canFoldNotes.count) {
  3386. self.foldType = .unfold
  3387. // } else {
  3388. // self.foldType = KMFoldAllAnnotationType_None;
  3389. // }
  3390. }
  3391. }
  3392. return cell
  3393. }
  3394. return nil
  3395. }
  3396. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  3397. if outlineView.isEqual(self.noteOutlineView) {
  3398. if item is KMBOTAAnnotationItem {
  3399. let model = item as! KMBOTAAnnotationItem
  3400. if model.foldType == .fold {
  3401. return model.foldH
  3402. }
  3403. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  3404. }
  3405. return 30
  3406. } else if outlineView.isEqual(self.tocOutlineView) {
  3407. if item is CPDFOutline {
  3408. let tempItem = item as! CPDFOutline
  3409. let string: NSString = tempItem.label as NSString
  3410. let paragraphStyle = NSMutableParagraphStyle()
  3411. paragraphStyle.lineHeightMultiple = 1.32
  3412. paragraphStyle.alignment = .left
  3413. let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
  3414. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  3415. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attributes)
  3416. return max(40, size.height + 16)
  3417. }
  3418. return 40
  3419. }
  3420. return outlineView.rowHeight
  3421. }
  3422. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  3423. if outlineView.isEqual(self.tocOutlineView) {
  3424. // var _item: CPDFOutline?
  3425. // if item == nil && self.listView.document.isLocked == false {
  3426. // _item = self.listView.document.outlineRoot()
  3427. // }
  3428. if let data = item as? String, data == "Bookmarks" {
  3429. return true
  3430. } else if item is CPDFOutline {
  3431. return ((item as! CPDFOutline).numberOfChildren ?? 0) != 0
  3432. } else if item is CPDFBookmark {
  3433. return false
  3434. }
  3435. if (self.isSearchOutlineMode) {
  3436. // return [self subOutLineContainString:self.leftSideController.outlineSearchField.stringValue rootOutline:(PDFOutline *)item];
  3437. } else {
  3438. // return ((_item?.numberOfChildren ?? 0) != 0)
  3439. }
  3440. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3441. // return [item hasNoteText];
  3442. return false
  3443. }
  3444. return false
  3445. }
  3446. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  3447. if outlineView.isEqual(self.tocOutlineView) {
  3448. let itemView = KMBotaTableRowView()
  3449. return itemView
  3450. } else if outlineView.isEqual(self.noteOutlineView) {
  3451. let itemView = KMBotaTableRowView()
  3452. return itemView;
  3453. }
  3454. return nil
  3455. }
  3456. func outlineViewSelectionDidChange(_ notification: Notification) {
  3457. if self.tocOutlineView.isEqual(to: notification.object) {
  3458. // if ([[notification object] isEqual:leftSideController.tocOutlineView] && (mwcFlags.updatingOutlineSelection == 0)){
  3459. // mwcFlags.updatingOutlineSelection = 1;
  3460. self.goToSelectedOutlineItem(nil)
  3461. // mwcFlags.updatingOutlineSelection = 0;
  3462. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  3463. // [self hideLeftSideWindow];
  3464. }
  3465. }
  3466. func outlineViewItemDidExpand(_ notification: Notification) {
  3467. if self.tocOutlineView.isEqual(to: notification.object) {
  3468. self.updateOutlineSelection()
  3469. }
  3470. }
  3471. func outlineViewItemDidCollapse(_ notification: Notification) {
  3472. if self.tocOutlineView.isEqual(to: notification.object) {
  3473. self.updateOutlineSelection()
  3474. }
  3475. }
  3476. /*
  3477. #pragma mark NSOutlineView datasource protocol
  3478. - (void)outlineView:(NSOutlineView *)ov setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item{
  3479. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3480. PDFAnnotation *note = item;
  3481. if ([note type]) {
  3482. if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  3483. if ([(object ?: @"") isEqualToString:([note string] ?: @"")] == NO)
  3484. [note setString:object];
  3485. } else if ([[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3486. if ([(object ?: @"") isEqualToString:([note userName] ?: @"")] == NO)
  3487. [note setUserName:object];
  3488. }
  3489. }
  3490. }
  3491. }
  3492. #pragma mark Drag
  3493. - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard{
  3494. if ([outlineView isEqual:leftSideController.tocOutlineView]) {
  3495. if (leftSideController.tocOutlineView.selectedRowIndexes.count > 1) {
  3496. return NO;
  3497. }
  3498. NSIndexSet *tIndex = [[[NSIndexSet alloc] initWithIndex:leftSideController.tocOutlineView.clickedRow] autorelease];
  3499. [leftSideController.tocOutlineView deselectRow:tIndex.firstIndex];
  3500. self.dragPDFOutline = items.firstObject;
  3501. NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
  3502. NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:set];
  3503. [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  3504. [pasteboard setData:zNSIndexSetData forType:kKMPDFViewOutlineDragDataType];
  3505. return YES;
  3506. }
  3507. return NO;
  3508. }
  3509. - (NSDragOperation)outlineView:(NSOutlineView *)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)anIndex {
  3510. NSDragOperation dragOp = NSDragOperationNone;
  3511. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3512. NSPasteboard *pboard = [info draggingPasteboard];
  3513. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]] &&
  3514. anIndex == NSOutlineViewDropOnItemIndex && [(PDFAnnotation *)item type] != nil)
  3515. dragOp = NSDragOperationEvery;
  3516. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3517. if (anIndex == -1) {
  3518. dragOp = NSDragOperationNone;
  3519. } else {
  3520. dragOp = NSDragOperationMove;
  3521. }
  3522. }
  3523. return dragOp;
  3524. }
  3525. - (BOOL)outlineView:(NSOutlineView *)ov acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)anIndex {
  3526. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3527. NSPasteboard *pboard = [info draggingPasteboard];
  3528. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]]) {
  3529. BOOL isShift = ([NSEvent standardModifierFlags] & NSEventModifierFlagShift) != 0;
  3530. BOOL isAlt = ([NSEvent standardModifierFlags] & NSEventModifierFlagOption) != 0;
  3531. [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  3532. return YES;
  3533. }
  3534. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3535. if (anIndex < 0) {
  3536. return NO;
  3537. }
  3538. PDFOutline *outline = item;
  3539. //root,drag item to root
  3540. if (!outline.parent) {
  3541. //fetch root
  3542. PDFOutline *root = self.dragPDFOutline;
  3543. while (root.parent) {
  3544. root = root.parent;
  3545. }
  3546. if ([self.dragPDFOutline.parent isEqual:root]) {
  3547. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3548. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3549. } else {
  3550. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:root];
  3551. }
  3552. } else {
  3553. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3554. }
  3555. } else {
  3556. //在同一个层级内移动
  3557. if ([self.dragPDFOutline.parent isEqual:item]) {
  3558. if (self.dragPDFOutline.index) {
  3559. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3560. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3561. }else{
  3562. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:outline];
  3563. }
  3564. } else {
  3565. return NO;
  3566. }
  3567. } else {
  3568. PDFOutline *tOutlline = outline;
  3569. BOOL isContains = NO;
  3570. while (tOutlline) {
  3571. if ([tOutlline isEqual:self.dragPDFOutline]) {
  3572. isContains = YES;
  3573. break;
  3574. }
  3575. tOutlline = tOutlline.parent;
  3576. }
  3577. if (!isContains) {
  3578. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3579. }
  3580. }
  3581. }
  3582. return YES;
  3583. }
  3584. return NO;
  3585. }
  3586. #pragma mark NSOutlineView delegate protocol
  3587. - (NSCell *)outlineView:(NSOutlineView *)ov dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3588. if ([ov isEqual:rightSideController.noteOutlineView] && tableColumn == nil && [(PDFAnnotation *)item type] == nil) {
  3589. return [[ov tableColumnWithIdentifier:NOTE_COLUMNID] dataCellForRow:[ov rowForItem:item]];
  3590. }
  3591. return [tableColumn dataCellForRow:[ov rowForItem:item]];
  3592. }
  3593. - (void)outlineView:(NSOutlineView *)ov willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3594. if ([ov isEqual:leftSideController.tocOutlineView] &&
  3595. [ov selectionHighlightStyle] == NSTableViewSelectionHighlightStyleRegular &&
  3596. [ov isRowSelected:[ov rowForItem:item]]) {
  3597. [cell setBackgroundStyle:NSBackgroundStyleLowered];
  3598. }
  3599. }
  3600. - (BOOL)outlineView:(NSOutlineView *)ov shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item{
  3601. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3602. if (tableColumn == nil) {
  3603. if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  3604. PDFAnnotation *annotation = [(SKNoteText *)item note];
  3605. [pdfView scrollAnnotationToVisible:annotation];
  3606. [pdfView setActiveAnnotation:annotation];
  3607. [self showNote:annotation];
  3608. SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  3609. [[noteController window] makeFirstResponder:[noteController textView]];
  3610. [[noteController textView] selectAll:nil];
  3611. }
  3612. return NO;
  3613. } else if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID] || [[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3614. return YES;
  3615. }
  3616. }
  3617. return NO;
  3618. }
  3619. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  3620. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3621. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  3622. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  3623. NSMutableArray *sortDescriptors = nil;
  3624. BOOL ascending = YES;
  3625. if ([oldTableColumn isEqual:newTableColumn]) {
  3626. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  3627. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  3628. ascending = [[sortDescriptors firstObject] ascending];
  3629. } else {
  3630. NSString *tcID = [newTableColumn identifier];
  3631. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  3632. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  3633. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  3634. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  3635. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  3636. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  3637. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  3638. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  3639. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3640. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  3641. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3642. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  3643. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  3644. }
  3645. if (oldTableColumn)
  3646. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  3647. [ov setHighlightedTableColumn:newTableColumn];
  3648. }
  3649. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  3650. if (newTableColumn)
  3651. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  3652. inTableColumn:newTableColumn];
  3653. [ov reloadData];
  3654. }
  3655. }
  3656. - (NSString *)outlineView:(NSOutlineView *)ov toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tableColumn item:(id)item mouseLocation:(NSPoint)mouseLocation {
  3657. if ([ov isEqual:rightSideController.noteOutlineView] &&
  3658. (tableColumn == nil || [[tableColumn identifier] isEqualToString:NOTE_COLUMNID])) {
  3659. return [item string];
  3660. }
  3661. return @"";
  3662. }
  3663. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  3664. if (mwcFlags.autoResizeNoteRows &&
  3665. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  3666. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  3667. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  3668. [rowHeights removeAllFloats];
  3669. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  3670. }
  3671. }
  3672. - (void)updateSelectRowHeight{
  3673. CGFloat rowHeight = 0;
  3674. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:leftSideController.tocOutlineView.selectedRow];
  3675. if (!outline){
  3676. return;
  3677. }
  3678. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3679. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3680. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3681. [attributedString appendAttributedString:attr1];
  3682. NSInteger *row = [leftSideController.tocOutlineView selectedRow];
  3683. NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:row makeIfNecessary:YES];
  3684. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3685. // id cell = [tableColumn dataCell];
  3686. id cell = [tableColumn dataCellForRow:row];
  3687. [cell setObjectValue:attributedString];
  3688. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3689. NSInteger num = [self getNum:outline];
  3690. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3691. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3692. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3693. [rowHeights setFloat:rowHeight forKey:outline];
  3694. if (@available(macOS 10.13, *)) {
  3695. } else {
  3696. rowHeight = 40.0;
  3697. }
  3698. CGRect fram = viewS.frame;
  3699. viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3700. [leftSideController.tocOutlineView reloadData];
  3701. }
  3702. - (NSInteger)getNum:(PDFOutline *)ol{
  3703. NSInteger num = 0;
  3704. PDFOutline *outLine = [ol parent];
  3705. do {
  3706. outLine = [outLine parent];
  3707. if (outLine){
  3708. num ++;
  3709. }
  3710. } while (outLine);
  3711. return num;
  3712. }
  3713. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  3714. {
  3715. NSInteger rowCount = [outlineView numberOfRows];
  3716. for (NSInteger i = 0; i < rowCount; i++){
  3717. CGFloat rowHeight = 0;
  3718. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  3719. if (!outline){
  3720. continue;
  3721. }
  3722. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3723. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3724. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3725. [attributedString appendAttributedString:attr1];
  3726. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  3727. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3728. // id cell = [tableColumn dataCell];
  3729. id cell = [tableColumn dataCellForRow:i];
  3730. [cell setObjectValue:attributedString];
  3731. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3732. NSInteger num = [self getNum:outline];
  3733. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3734. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3735. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3736. [rowHeights setFloat:rowHeight forKey:outline];
  3737. if (@available(macOS 10.13, *)) {
  3738. } else {
  3739. rowHeight = 40.0;
  3740. }
  3741. // CGRect fram = viewS.frame;
  3742. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3743. }
  3744. [leftSideController.tocOutlineView reloadData];
  3745. }
  3746. */
  3747. func noteItems(_ items: NSArray) -> NSArray {
  3748. var noteItems = NSMutableArray()
  3749. for item in items {
  3750. guard let anno = (item as? KMBOTAAnnotationItem)?.annotation else {
  3751. continue
  3752. }
  3753. if anno.type == nil {
  3754. // item = [(SKNoteText *)item note];
  3755. }
  3756. if noteItems.contains(anno) == false {
  3757. noteItems.add(anno)
  3758. }
  3759. }
  3760. return noteItems
  3761. }
  3762. /*
  3763. - (NSArray *)outlineView:(NSOutlineView *)ov typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  3764. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3765. NSInteger i, count = [rightSideController.noteOutlineView numberOfRows];
  3766. NSMutableArray *texts = [NSMutableArray arrayWithCapacity:count];
  3767. for (i = 0; i < count; i++) {
  3768. id item = [rightSideController.noteOutlineView itemAtRow:i];
  3769. NSString *string = [item string];
  3770. [texts addObject:string ?: @""];
  3771. }
  3772. return texts;
  3773. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3774. NSInteger i, count = [leftSideController.tocOutlineView numberOfRows];
  3775. NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
  3776. for (i = 0; i < count; i++)
  3777. [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  3778. return array;
  3779. }
  3780. return nil;
  3781. }
  3782. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  3783. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3784. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  3785. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3786. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  3787. }
  3788. }
  3789. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  3790. if ([typeSelectHelper isEqual:[leftSideController.thumbnailTableView typeSelectHelper]] || [typeSelectHelper isEqual:[pdfView typeSelectHelper]]) {
  3791. if (searchString)
  3792. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  3793. else
  3794. [self updateLeftStatus];
  3795. } else if ([typeSelectHelper isEqual:[rightSideController.noteOutlineView typeSelectHelper]]) {
  3796. if (searchString)
  3797. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding note: \"%@\"", @"Status message"), searchString]];
  3798. else
  3799. [self updateRightStatus];
  3800. } else if ([typeSelectHelper isEqual:[leftSideController.tocOutlineView typeSelectHelper]]) {
  3801. if (searchString)
  3802. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding: \"%@\"", @"Status message"), searchString]];
  3803. else
  3804. [self updateLeftStatus];
  3805. }
  3806. }
  3807. */
  3808. }
  3809. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  3810. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  3811. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  3812. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3813. return self.listView.hideNotes == false && items.count > 0
  3814. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  3815. return items.count > 0
  3816. }
  3817. return false
  3818. }
  3819. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  3820. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3821. if (items.isEmpty) {
  3822. return
  3823. }
  3824. for item in self.noteItems(items as NSArray) {
  3825. guard let anno = item as? CPDFAnnotation else {
  3826. continue
  3827. }
  3828. self.listView.remove(anno)
  3829. }
  3830. self.listView.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  3831. self.reloadAnnotation()
  3832. self.noteOutlineView.reloadData()
  3833. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  3834. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  3835. }
  3836. }
  3837. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  3838. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3839. if (items.count == 1) {
  3840. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  3841. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  3842. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  3843. // return NO;
  3844. // }
  3845. }
  3846. return items.count > 0
  3847. }
  3848. return false
  3849. }
  3850. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  3851. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  3852. let pboard = NSPasteboard.general
  3853. var copiedItems: [Any] = []
  3854. var attrString = NSMutableAttributedString()
  3855. var isAttributed = false
  3856. var item: AnyObject?
  3857. // for (item in [self noteItems:items]) {
  3858. // if ([item isMovable])
  3859. // [copiedItems addObject:item];
  3860. // }
  3861. // for (item in items) {
  3862. // if ([attrString length])
  3863. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  3864. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  3865. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  3866. // isAttributed = YES;
  3867. // } else {
  3868. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  3869. // }
  3870. // }
  3871. //
  3872. // [pboard clearContents];
  3873. // if (isAttributed)
  3874. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  3875. // else
  3876. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  3877. // if ([copiedItems count] > 0)
  3878. // [pboard writeObjects:copiedItems];
  3879. }
  3880. }
  3881. }
  3882. // MARK: - KMTocOutlineViewDelegate
  3883. extension KMLeftSideViewController: KMTocOutlineViewDelegate {
  3884. // func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  3885. // if ([ov isEqual:leftSideController.tocOutlineView]) {
  3886. // NSInteger numRows = [ov numberOfRows];
  3887. // NSUInteger firstPage = [[[ov itemAtRow:row] page] pageIndex];
  3888. // NSUInteger lastPage = row + 1 < numRows ? [[[ov itemAtRow:row + 1] page] pageIndex] : [[self pdfDocument] pageCount];
  3889. // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  3890. // NSUInteger i, iMax = [lastViewedPages count];
  3891. // for (i = 0; i < iMax; i++) {
  3892. // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  3893. // return i;
  3894. // }
  3895. // }
  3896. // return NSNotFound;
  3897. // }
  3898. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  3899. if anOutlineView.isEqual(to: self.tocOutlineView) {
  3900. if item == nil {
  3901. return true as AnyObject
  3902. }
  3903. if item is CPDFOutline {
  3904. return (item as! CPDFOutline).destination
  3905. }
  3906. }
  3907. return nil
  3908. }
  3909. }
  3910. extension KMLeftSideViewController: KMNoteOutlineViewDelegate {
  3911. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  3912. if anOutlineView.isEqual(to: self.noteOutlineView) {
  3913. return true
  3914. }
  3915. return false
  3916. }
  3917. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  3918. // [rowHeights setFloat:newHeight forKey:item];
  3919. }
  3920. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  3921. // if (mwcFlags.autoResizeNoteRows &&
  3922. // [ov isEqual:rightSideController.noteOutlineView] &&
  3923. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  3924. // [rowHeights removeAllFloats];
  3925. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  3926. // }
  3927. }
  3928. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  3929. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  3930. // if (annotation) {
  3931. // [pdfView scrollAnnotationToVisible:annotation];
  3932. // [pdfView setActiveAnnotation:annotation];
  3933. // }
  3934. }
  3935. }
  3936. // MARK: - Menu Item Actions
  3937. extension KMLeftSideViewController {
  3938. @objc func cutPage(_ sender: AnyObject?) {
  3939. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  3940. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  3941. // return;
  3942. // }
  3943. self._tableView(self.thumbnailTableView, cutRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  3944. }
  3945. @objc func copyPage(_ sender: AnyObject?) {
  3946. self.tableView(self.thumbnailTableView, copyRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  3947. }
  3948. @objc func pastePage(_ sender: AnyObject?) {
  3949. self.tableView(self.thumbnailTableView, pasteFromPasteboard: nil)
  3950. }
  3951. @objc func deletePage(_ sender: AnyObject?) {
  3952. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  3953. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  3954. // return;
  3955. // }
  3956. self.tableView(self.thumbnailTableView, deleteRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  3957. }
  3958. @objc func rotatePageMenuAction(_ sender: AnyObject?) {
  3959. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  3960. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  3961. // return;
  3962. // }
  3963. //
  3964. self.tableView(self.thumbnailTableView, rotateRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes as NSIndexSet)
  3965. }
  3966. @objc func quickInsert(_ sender: AnyObject?) {
  3967. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  3968. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  3969. // return;
  3970. // }
  3971. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  3972. if idx == NSNotFound || idx >= self.listView.document.pageCount {
  3973. return
  3974. }
  3975. let result = self.listView.insertPage(KMNormalBlankSize, at: idx+1)
  3976. if result == false {
  3977. return
  3978. }
  3979. var selectedIndexSet = IndexSet()
  3980. selectedIndexSet.insert(idx+1)
  3981. self.insertPages(selectedIndexSet, pageAt: idx)
  3982. }
  3983. @objc func insert(_ sender: AnyObject?) {
  3984. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  3985. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  3986. // return;
  3987. // }
  3988. guard let document = self.listView.document else {
  3989. return
  3990. }
  3991. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  3992. if idx == NSNotFound || idx >= document.pageCount {
  3993. return
  3994. }
  3995. if document.allowsCopying == false || document.allowsPrinting == false {
  3996. Task {
  3997. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  3998. }
  3999. return
  4000. }
  4001. let insertVC = KMPDFEditInsertBlankPageWindow(document: document)
  4002. insertVC.insertLocation = 3
  4003. insertVC.currentPage = idx + 1
  4004. insertVC.callback = { [weak self] pdfDoc, _, pages, insertI in
  4005. if let _pages = pages {
  4006. // mm 单位的大小
  4007. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  4008. self?.km_endSheet()
  4009. return
  4010. }
  4011. var pageSize = _winC.pageSize
  4012. let direction = _winC.pageRotation == 0 ? 0 : 1
  4013. if (direction == 0) { // 纵向
  4014. if (pageSize.width > pageSize.height) { // 需要交换
  4015. let tmp = pageSize.width
  4016. pageSize.width = pageSize.height
  4017. pageSize.height = tmp
  4018. } else {
  4019. // no things.
  4020. }
  4021. } else { // 横向
  4022. if (pageSize.width > pageSize.height) {
  4023. // no things.
  4024. } else { // 需要交换
  4025. let tmp = pageSize.width
  4026. pageSize.width = pageSize.height
  4027. pageSize.height = tmp
  4028. }
  4029. }
  4030. /// 插入位置
  4031. let document = CPDFDocument()
  4032. document?.insertPage(pageSize, at: 0)
  4033. if let page: CPDFPage = (document?.page(at: 0)) {
  4034. self?.insertPage(page, pageAt: insertI)
  4035. }
  4036. }
  4037. self?.km_quick_endSheet()
  4038. }
  4039. self.km_beginSheet(windowC: insertVC)
  4040. }
  4041. @objc func insertPDF(_ sender: AnyObject?) {
  4042. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4043. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4044. // return;
  4045. // }
  4046. guard let document = self.listView.document else {
  4047. return
  4048. }
  4049. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4050. if idx == NSNotFound || idx >= document.pageCount {
  4051. return
  4052. }
  4053. if document.allowsCopying == false || document.allowsPrinting == false {
  4054. Task {
  4055. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4056. }
  4057. return
  4058. }
  4059. let panel = NSOpenPanel()
  4060. panel.allowedFileTypes = ["pdf"]
  4061. panel.beginSheetModal(for: self.view.window!) { response in
  4062. if response == .cancel {
  4063. return
  4064. }
  4065. for fileURL in panel.urls {
  4066. let pdfDoc = CPDFDocument(url: fileURL)
  4067. if let data = pdfDoc?.isLocked, data {
  4068. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4069. let com = PasswordWindowController(windowNibName: "PasswordWindowController")
  4070. com.fileURL = fileURL
  4071. self.km_beginSheet(windowC: com)
  4072. com.closeCallBack = { [unowned self] password in
  4073. self.km_quick_endSheet()
  4074. // }
  4075. if (password.isEmpty == false) {
  4076. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL, password: password)
  4077. insertVC.insertLocation = 3
  4078. insertVC.currentPage = idx + 1
  4079. self.km_beginSheet(windowC: insertVC)
  4080. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4081. var indexs = IndexSet()
  4082. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4083. self?.km_quick_endSheet()
  4084. return
  4085. }
  4086. let doc = _winC.insertDocument!
  4087. let fileAttribute = _winC.fileAttribute
  4088. var insertIndex = insertIdx
  4089. var insertPages: [CPDFPage] = []
  4090. for number in fileAttribute.fetchSelectPages() {
  4091. if let page = doc.page(at: UInt(number.intValue-1)) {
  4092. insertPages.append(page)
  4093. indexs.insert(insertIndex)
  4094. insertIndex += 1
  4095. }
  4096. }
  4097. for (i, page) in insertPages.enumerated() {
  4098. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4099. }
  4100. self?.insertPages(indexs, pageAt: insertIdx)
  4101. self?.km_quick_endSheet()
  4102. }
  4103. }
  4104. }
  4105. }
  4106. } else {
  4107. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL)
  4108. insertVC.insertLocation = 3
  4109. insertVC.currentPage = idx + 1
  4110. self.km_beginSheet(windowC: insertVC)
  4111. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4112. var indexs = IndexSet()
  4113. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4114. self?.km_quick_endSheet()
  4115. return
  4116. }
  4117. let doc = _winC.insertDocument!
  4118. let fileAttribute = _winC.fileAttribute
  4119. var insertIndex = insertIdx
  4120. var insertPages: [CPDFPage] = []
  4121. for number in fileAttribute.fetchSelectPages() {
  4122. if let page = doc.page(at: UInt(number.intValue-1)) {
  4123. insertPages.append(page)
  4124. indexs.insert(insertIndex)
  4125. insertIndex += 1
  4126. }
  4127. }
  4128. for (i, page) in insertPages.enumerated() {
  4129. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4130. }
  4131. self?.insertPages(indexs, pageAt: insertIdx)
  4132. self?.km_quick_endSheet()
  4133. }
  4134. }
  4135. }
  4136. }
  4137. }
  4138. @objc func extractPage(_ sender: AnyObject?) {
  4139. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4140. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4141. // return;
  4142. // }
  4143. self.tableView(self.thumbnailTableView, extractRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4144. }
  4145. @objc func pageEdit(_ sender: AnyObject?) {
  4146. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .pageEdit, params: nil)
  4147. }
  4148. @objc func displayPageSize(_ sender: AnyObject?) {
  4149. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4150. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4151. // return;
  4152. // }
  4153. self.isDisplayPageSize = !self.isDisplayPageSize;
  4154. UserDefaults.standard.setValue(self.isDisplayPageSize, forKey: "kKMThumbnailDisplayPageSizeKey")
  4155. UserDefaults.standard.synchronize()
  4156. Task { @MainActor in
  4157. self.thumbnailTableView.reloadData()
  4158. }
  4159. }
  4160. @objc func sharePage(_ sender: AnyObject?) {
  4161. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4162. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4163. // return;
  4164. // }
  4165. guard let document = self.listView.document else {
  4166. return
  4167. }
  4168. var pages = NSMutableArray()
  4169. for idx in self.thumbnailTableView.selectedRowIndexes {
  4170. if (idx < document.pageCount) {
  4171. if let page = self.listView.document.page(at: UInt(idx)) {
  4172. pages.add(page)
  4173. }
  4174. }
  4175. }
  4176. let pdf = CPDFDocument()
  4177. for page in pages {
  4178. // PDFPage *copyPage = [[page copy] autorelease];
  4179. if let _page = page as? CPDFPage {
  4180. pdf?.insertPageObject(_page, at: pdf?.pageCount ?? 0)
  4181. }
  4182. }
  4183. // NSString * = nil;
  4184. var fileName = ""
  4185. // NSString * = [self.pdfDocument.documentURL.lastPathComponent stringByDeletingPathExtension];
  4186. var documentFileName = document.documentURL?.deletingPathExtension().lastPathComponent ?? ""
  4187. var tName = self.fileNameWithSelectedPages(self.thumbnailTableView.selectedRowIndexes)
  4188. if (tName.count > 50) {
  4189. tName = tName.substring(to: 50)
  4190. }
  4191. if (pages.count > 1) {
  4192. fileName = String(format: "%@ pages %@", documentFileName, tName)
  4193. } else {
  4194. fileName = String(format: "%@ page %@", documentFileName, tName)
  4195. }
  4196. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  4197. var cachesDir = paths.first ?? ""
  4198. cachesDir = "\(cachesDir)/\(fileName).pdf"
  4199. var array = NSMutableArray()
  4200. let url = URL(fileURLWithPath: cachesDir)
  4201. array.add(url)
  4202. let vc = KMProgressWindowController()
  4203. // // [NSApp beginSheet:[vc window]
  4204. // // modalForWindow:self.window
  4205. // // modalDelegate:nil
  4206. // // didEndSelector:nil
  4207. // // contextInfo:NULL];
  4208. self.view.window?.beginSheet(vc.window!, completionHandler: { [unowned self] returnCode in
  4209. NSApp.endSheet(self.view.window!, returnCode: returnCode.rawValue)
  4210. })
  4211. DispatchQueue.global().async {
  4212. let sucess = pdf?.write(toFile: cachesDir) ?? false
  4213. if (sucess) {
  4214. DispatchQueue.main.async {
  4215. // [[sender representedObject] performWithItems:array];
  4216. let represent : NSSharingService = (sender as! NSMenuItem).representedObject as! NSSharingService
  4217. represent.perform(withItems: [url])
  4218. NSApp.endSheet(vc.window!)
  4219. vc.close()
  4220. }
  4221. } else {
  4222. NSApp.endSheet(vc.window!)
  4223. vc.close()
  4224. }
  4225. }
  4226. // [vc release];
  4227. }
  4228. @objc func toggleCaseInsensitiveSearch(_ sender: AnyObject?) {
  4229. KMPrint("KMLeftSideViewController-toggleCaseInsensitiveSearch...")
  4230. }
  4231. @objc func toggleCaseInsensitiveNoteSearch(_ sender: AnyObject?) {
  4232. KMPrint("KMLeftSideViewController-toggleCaseInsensitiveNoteSearch...")
  4233. }
  4234. @objc func searchNotes(_ sender: AnyObject?) {
  4235. self.noteSearchMode = false
  4236. if self.findState == .note {
  4237. if self.noteSearchField.isEqual(to: sender) {
  4238. self.noteSearchMode = true
  4239. }
  4240. self.updateNoteFilterPredicate()
  4241. } else {
  4242. self.updateSnapshotFilterPredicate()
  4243. }
  4244. let textfield = sender as? NSSearchField
  4245. if let data = textfield?.stringValue.isEmpty, data == false {
  4246. let findPboard = NSPasteboard(name: .find)
  4247. findPboard.clearContents()
  4248. // findPboard.writeObjects([textfield!.stringValue])
  4249. }
  4250. }
  4251. @objc func toggleSelectedSnapshots(_ sender: AnyObject?) {
  4252. let indexs = self.snapshotTableView.selectedRowIndexes
  4253. if indexs.isEmpty {
  4254. return
  4255. }
  4256. let model = self.snapshots[indexs.last!]
  4257. let windowC = model.windowC
  4258. if let data = windowC?.window?.isVisible, data {
  4259. windowC?.miniaturize()
  4260. } else {
  4261. windowC?.deminiaturize()
  4262. }
  4263. var rowIndexSet = IndexSet()
  4264. let row = self.snapshotTableView.selectedRow
  4265. if row >= 0 && row < self.snapshots.count {
  4266. rowIndexSet.insert(row)
  4267. }
  4268. var columnIndexSet = IndexSet()
  4269. columnIndexSet.insert(0)
  4270. self.snapshotTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  4271. }
  4272. @objc func toggleOutlineCaseInsensitiveSearch(_ sender: AnyObject?) {
  4273. KMPrint("KMLeftSideViewController-toggleOutlineCaseInsensitiveSearch...")
  4274. }
  4275. private func _tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  4276. if tv.isEqual(to: self.thumbnailTableView) {
  4277. self._copysPages.removeAll()
  4278. for idx in rowIndexes {
  4279. if (idx != NSNotFound) {
  4280. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  4281. self._copysPages.append(page)
  4282. }
  4283. }
  4284. }
  4285. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  4286. }
  4287. }
  4288. // MARK: - Snapshot
  4289. @objc func menuItemClick_ExportPNG(_ sender: AnyObject?) {
  4290. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4291. return
  4292. }
  4293. let image = snapshot.thumbnailWithSize(0)
  4294. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.pngData(), allowedTypes: ["png"]) { url in
  4295. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4296. }
  4297. }
  4298. @objc func menuItemClick_ExportJPG(_ sender: AnyObject?) {
  4299. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4300. return
  4301. }
  4302. let image = snapshot.thumbnailWithSize(0)
  4303. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.jpgData(), allowedTypes: ["jpg"]) { url in
  4304. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4305. }
  4306. }
  4307. @objc func menuItemClick_ExportPDF(_ sender: AnyObject?) {
  4308. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4309. return
  4310. }
  4311. if let image = snapshot.thumbnailWithSize(0) {
  4312. let document = CPDFDocument()
  4313. _ = document?.km_insert(image: image, at: 0)
  4314. NSPanel.savePanel_pdf_success(self.view.window!, document: document) { url in
  4315. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4316. }
  4317. }
  4318. }
  4319. @objc func menuItemClick_Print(_ sender: AnyObject?) {
  4320. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4321. return
  4322. }
  4323. if let image = snapshot.thumbnailWithSize(0) {
  4324. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .print, params: image)
  4325. }
  4326. }
  4327. @objc func menuItemClick_SelectAll(_ sender: AnyObject?) {
  4328. let selected = self.snapshotListIsAllSelected()
  4329. for model in self.snapshots {
  4330. model.isSelected = !selected
  4331. }
  4332. Task { @MainActor in
  4333. self.snapshotTableView.reloadData()
  4334. }
  4335. }
  4336. @objc func deleteAllSnapshot(_ sender: AnyObject?) {
  4337. for model in self.snapshots {
  4338. model.windowC?.close()
  4339. }
  4340. }
  4341. @objc func hideSnapshot(_ sender: AnyObject?) {
  4342. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4343. return
  4344. }
  4345. if let data = snapshot.window?.isVisible, data {
  4346. snapshot.miniaturize()
  4347. }
  4348. }
  4349. @objc func showSnapshot(_ sender: AnyObject?) {
  4350. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4351. return
  4352. }
  4353. if let data = snapshot.window?.isVisible, data {
  4354. snapshot.window?.orderFront(nil)
  4355. } else {
  4356. snapshot.deminiaturize()
  4357. }
  4358. }
  4359. @objc func deleteSnapshot(_ sender: AnyObject?) {
  4360. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4361. return
  4362. }
  4363. snapshot.close()
  4364. }
  4365. @objc func menuItemClick_Copy(_ sender: AnyObject?) {
  4366. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4367. return
  4368. }
  4369. let image = snapshot.thumbnailWithSize(0)
  4370. if let tiffData = image?.tiffRepresentation {
  4371. let pasteboardItem = NSPasteboardItem()
  4372. pasteboardItem.setData(tiffData, forType: .tiff)
  4373. let pboard = NSPasteboard.general
  4374. pboard.clearContents()
  4375. pboard.writeObjects([pasteboardItem])
  4376. }
  4377. }
  4378. func updateSnapshotFilterPredicate() {
  4379. let searchString = self.snapshotSearchField.stringValue
  4380. self.searchSnapshots.removeAll()
  4381. if self.findState == .snapshot && searchString.isEmpty == false {
  4382. self.searchSnapshots = self.snapshots.filter({ model in
  4383. let data = model.windowC?.string.contains(searchString) ?? false
  4384. return data
  4385. })
  4386. }
  4387. Task { @MainActor in
  4388. self.updataLeftSideSnapView()
  4389. self.snapshotTableView.reloadData()
  4390. }
  4391. }
  4392. func snapshotListIsAllSelected() -> Bool {
  4393. if self.snapshots.isEmpty {
  4394. return false
  4395. }
  4396. for model in self.snapshots {
  4397. if model.isSelected == false {
  4398. return false
  4399. }
  4400. }
  4401. return true
  4402. }
  4403. }
  4404. // MARK: - Undo & Redo
  4405. extension KMLeftSideViewController {
  4406. @objc dynamic func tableView(_ tv: NSTableView, rotateRowsWithIndexes rowIndexes: NSIndexSet) {
  4407. if tv.isEqual(to: self.thumbnailTableView) {
  4408. for idx in rowIndexes {
  4409. if (idx != NSNotFound) {
  4410. let page = self.listView.document.page(at: UInt(idx))
  4411. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).rotatePage(page, pageAt: idx)
  4412. page?.rightRotate()
  4413. self.listView.layoutDocumentView()
  4414. self.resetThumbnails()
  4415. // NSInteger pageIndex = MIN(idx, [[pdfView document] pageCount]-1);
  4416. // [pdfView goToPage:[[pdfView document] pageAtIndex:pageIndex]];
  4417. }
  4418. self.thumbnailTableView.selectRowIndexes(rowIndexes as IndexSet, byExtendingSelection: true)
  4419. }
  4420. }
  4421. }
  4422. @objc dynamic func rotatePage(_ page: CPDFPage?, pageAt index: Int) {
  4423. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, rotateRowsWithIndexes: NSIndexSet(index: index))
  4424. page?.leftRotate()
  4425. self.listView.layoutDocumentView()
  4426. self.resetThumbnails()
  4427. }
  4428. @objc dynamic func insertPage(_ page: CPDFPage, pageAt index: Int) {
  4429. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: index))
  4430. self.listView.document.insertPageObject(page, at: UInt(index))
  4431. self.listView.layoutDocumentView()
  4432. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4433. self.resetThumbnails()
  4434. let pageIndex = min(index, Int((self.listView.document?.pageCount ?? 0))-1)
  4435. self.listView.go(toPageIndex: pageIndex, animated: false)
  4436. }
  4437. @objc dynamic func insertPages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  4438. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).deletePages(selectedIndexSet, pageAt: index)
  4439. self.listView.layoutDocumentView()
  4440. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4441. self.resetThumbnails()
  4442. if let pageIndex = selectedIndexSet.first {
  4443. self.listView.go(toPageIndex: pageIndex, animated: false)
  4444. }
  4445. }
  4446. @objc dynamic func deletePages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  4447. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPages(selectedIndexSet, pageAt: index)
  4448. for idx in selectedIndexSet {
  4449. if idx < self.listView.document.pageCount {
  4450. self.listView.document.removePage(at: UInt(idx))
  4451. }
  4452. }
  4453. self.listView.layoutDocumentView()
  4454. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4455. self.resetThumbnails()
  4456. let pageIndex = min(index, Int(self.listView.document.pageCount)-1)
  4457. self.listView.go(toPageIndex: pageIndex, animated: false)
  4458. }
  4459. }
  4460. // MARK: - Other
  4461. extension KMLeftSideViewController {
  4462. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  4463. let outlineItem = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow)
  4464. let outline = self.tocOutlineView
  4465. if let cnt = outline?.selectedRowIndexes.count, cnt == 1 {
  4466. if outlineItem is CPDFOutline {
  4467. let outline = (outlineItem as! CPDFOutline)
  4468. if let des = outline.destination {
  4469. self.listView.go(to: des)
  4470. } else if let action = outline.action {
  4471. self.listView.perform(action)
  4472. }
  4473. } else if outlineItem is CPDFBookmark {
  4474. let bookmark = outlineItem as! CPDFBookmark
  4475. self.listView.go(toPageIndex: bookmark.pageIndex, animated: true)
  4476. }
  4477. }
  4478. }
  4479. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  4480. KMPrint("KMLeftSideViewController-goToSelectedFindResults...")
  4481. }
  4482. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  4483. if tv.isEqual(to: self.thumbnailTableView) {
  4484. guard let document = self.listView.document else {
  4485. return
  4486. }
  4487. var pages = NSMutableArray()
  4488. for idx in self.thumbnailTableView.selectedRowIndexes {
  4489. if (idx < document.pageCount) {
  4490. if let page = self.listView.document.page(at: UInt(idx)) {
  4491. pages.add(page)
  4492. }
  4493. }
  4494. }
  4495. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  4496. let saveAccessCtr = KMSavePanelAccessoryController()
  4497. let outputSavePanel = NSSavePanel()
  4498. outputSavePanel.allowedFileTypes = ["pdf"]
  4499. outputSavePanel.accessoryView = saveAccessCtr.view
  4500. outputSavePanel.nameFieldStringValue = fileName
  4501. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  4502. if (result == .OK) {
  4503. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  4504. let vc = KMProgressWindowController()
  4505. self.view.window?.beginSheet(vc.window!)
  4506. let saveFilePath = outputSavePanel.url?.path
  4507. DispatchQueue.global().async {
  4508. let pdf = CPDFDocument()
  4509. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  4510. DispatchQueue.main.async {
  4511. if (success) {
  4512. if (saveAccessCtr.openAutomaticButton.state == .on) {
  4513. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  4514. }
  4515. } else {
  4516. KMTools.viewFile(at: saveFilePath!)
  4517. }
  4518. }
  4519. NSApp.endSheet(vc.window!)
  4520. vc.close()
  4521. }
  4522. }
  4523. }
  4524. }
  4525. }
  4526. }
  4527. }
  4528. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  4529. var pagesName = ""
  4530. if (itemIndexes.count > 1) {
  4531. pagesName.append(" pages")
  4532. } else {
  4533. pagesName.append("page")
  4534. }
  4535. let docmentName = self.listView.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  4536. var fileName = ""
  4537. if (itemIndexes.count > 0) {
  4538. if (itemIndexes.count == 1) {
  4539. let idx = itemIndexes.first! + 1
  4540. let tFileName = String(format: "%@ %@", pagesName, "\(idx)")
  4541. return String(format: "%@%@", docmentName, tFileName)
  4542. }
  4543. var sortIndex = IndexSet()
  4544. for idx in itemIndexes {
  4545. let _idx = idx + 1
  4546. sortIndex.insert(_idx)
  4547. }
  4548. // NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
  4549. // NSArray *sortDesc = @[sort];
  4550. // NSArray *sortArray = [sortIndex sortedArrayUsingDescriptors:sortDesc];
  4551. let sortArray = sortIndex.sorted()
  4552. var a = 0
  4553. var b = 0
  4554. for num in sortArray {
  4555. // for (NSNumber *num in sortArray) {
  4556. if (fileName.isEmpty == false) {
  4557. if (num == b+1) {
  4558. b = num
  4559. if (num == sortArray.last) {
  4560. fileName = "\(fileName)\(a)-\(b)"
  4561. }
  4562. } else {
  4563. if (a == b) {
  4564. fileName = "\(fileName)\(a),"
  4565. } else {
  4566. fileName = "\(fileName)\(a)-\(b),"
  4567. }
  4568. b = num
  4569. a = b
  4570. if (num == sortArray.last) {
  4571. fileName = "\(fileName)\(a)"
  4572. }
  4573. }
  4574. } else {
  4575. fileName = ""
  4576. b = num
  4577. a = b
  4578. }
  4579. }
  4580. let tFileName = String(format: "%@ %@", pagesName,fileName)
  4581. return String(format: "%@%@", docmentName,tFileName)
  4582. }
  4583. return ""
  4584. }
  4585. }