KMLeftSideViewController.swift 253 KB

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