KMLeftSideViewController.swift 246 KB

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