~emersion/drmdb

ref: b5a982126750955c2a46092dca16144ce61639c5 drmdb/cmd/drmdump/main.go -rw-r--r-- 18.5 KiB
b5a98212Simon Ser cmd/drmdump: fix typo 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"syscall"

	"git.sr.ht/~emersion/drmdb/treefmt"
	"git.sr.ht/~emersion/go-drm"
)

type DriverVersion struct {
	Major int32  `json:"major"`
	Minor int32  `json:"minor"`
	Patch int32  `json:"patch"`
	Date  string `json:"date"`
}

func (ver *DriverVersion) String() string {
	return fmt.Sprintf("%v.%v.%v (%v)", ver.Major, ver.Minor, ver.Patch, ver.Date)
}

type Driver struct {
	Name       string             `json:"name"`
	Desc       string             `json:"desc"`
	Version    DriverVersion      `json:"version"`
	Caps       map[string]*uint64 `json:"caps"`
	ClientCaps map[string]bool    `json:"client_caps"`
}

var capNames = map[drm.Cap]string{
	drm.CapDumbBuffer:          "DUMB_BUFFER",
	drm.CapVblankHighCRTC:      "VBLANK_HIGH_CRTC",
	drm.CapDumbPreferredDepth:  "DUMB_PREFERRED_DEPTH",
	drm.CapDumbPreferredShadow: "DUMB_PREFER_SHADOW",
	drm.CapPrime:               "PRIME",
	drm.CapTimestampMonotonic:  "TIMESTAMP_MONOTONIC",
	drm.CapAsyncPageFlip:       "ASYNC_PAGE_FLIP",
	drm.CapCursorWidth:         "CURSOR_WIDTH",
	drm.CapCursorHeight:        "CURSOR_HEIGHT",
	drm.CapAddFB2Modifiers:     "ADDFB2_MODIFIERS",
	drm.CapPageFlipTarget:      "PAGE_FLIP_TARGET",
	drm.CapCRTCInVBlankEvent:   "CRTC_IN_VBLANK_EVENT",
	drm.CapSyncObj:             "SYNCOBJ",
}

var clientCapNames = map[drm.ClientCap]string{
	drm.ClientCapStereo3D:            "STEREO_3D",
	drm.ClientCapUniversalPlanes:     "UNIVERSAL_PLANES",
	drm.ClientCapAtomic:              "ATOMIC",
	drm.ClientCapAspectRatio:         "APSECT_RATIO",
	drm.ClientCapWritebackConnectors: "WRITEBACK_CONNECTORS",
}

func driver(n *drm.Node) (*Driver, error) {
	v, err := n.Version()
	if err != nil {
		return nil, fmt.Errorf("cannot get version: %v", err)
	}

	caps := make(map[string]*uint64)
	for c, s := range capNames {
		var ptr *uint64
		val, err := n.GetCap(c)
		if err == nil {
			ptr = &val
		} else if err != syscall.EINVAL {
			return nil, fmt.Errorf("failed to get cap: %v", err)
		}
		caps[s] = ptr
	}

	clientCaps := make(map[string]bool)
	for c, s := range clientCapNames {
		ok := false
		if err := n.SetClientCap(c, 1); err == nil {
			ok = true
		} else if err != syscall.EINVAL {
			return nil, fmt.Errorf("failed to set client cap: %v", err)
		}
		clientCaps[s] = ok
	}

	return &Driver{
		Name: v.Name,
		Desc: v.Desc,
		Version: DriverVersion{
			Major: v.Major,
			Minor: v.Minor,
			Patch: v.Patch,
			Date:  v.Date,
		},
		Caps:       caps,
		ClientCaps: clientCaps,
	}, nil
}

func printDriver(tf treefmt.Formatter, drv *Driver) {
	tf.Printf("Driver: %v (%v) version %v", drv.Name, drv.Desc, &drv.Version)
	tfc := tf.NewChild()

	for c, v := range drv.Caps {
		if v != nil {
			if c == "PRIME" {
				tfc.Printf("DRM_CAP_PRIME supported")
				tfcc := tfc.NewChild()
				tfcc.Printf("DRM_CAP_PRIME_IMPORT = %v", *v&drm.CapPrimeImport != 0)
				tfcc.Printf("DRM_CAP_PRIME_EXPORT = %v", *v&drm.CapPrimeExport != 0)
			} else {
				tfc.Printf("DRM_CAP_%v = %v", c, *v)
			}
		} else {
			tfc.Printf("DRM_CAP_%v unsupported", c)
		}
	}

	for c, ok := range drv.ClientCaps {
		if ok {
			tfc.Printf("DRM_CLIENT_CAP_%v supported", c)
		} else {
			tfc.Printf("DRM_CLIENT_CAP_%v unsupported", c)
		}
	}
}

type DevicePCI struct {
	Vendor    uint32 `json:"vendor"`
	Device    uint32 `json:"device"`
	SubVendor uint32 `json:"subsystem_vendor"`
	SubDevice uint32 `json:"subsystem_device"`
}

type Device struct {
	BusType    drm.BusType `json:"bus_type"`
	DeviceData interface{} `json:"device_data,omitempty"`
}

func device(n *drm.Node) (*Device, error) {
	dev, err := n.GetDevice()
	if err != nil {
		return nil, fmt.Errorf("failed to get device: %v", err)
	}

	switch dev := dev.(type) {
	case *drm.PCIDevice:
		return &Device{
			BusType: dev.BusType(),
			DeviceData: &DevicePCI{
				Vendor:    dev.Vendor,
				Device:    dev.Device,
				SubVendor: dev.SubVendor,
				SubDevice: dev.SubDevice,
			},
		}, nil
	default:
		return &Device{BusType: dev.BusType()}, nil
	}
}

func printDevice(tf treefmt.Formatter, dev *Device) {
	switch dev.BusType {
	case drm.BusPCI:
		pci := dev.DeviceData.(*DevicePCI)
		tf.Printf("Device: %v %04X:%04X", dev.BusType, pci.Vendor, pci.Device)
	default:
		tf.Printf("Device: %v", dev.BusType)
	}
}

func bitfieldString(v uint32) string {
	s := "{"
	first := true
	for i := 0; i < 32; i++ {
		if v&(1<<uint(i)) != 0 {
			if !first {
				s += ", "
			}
			s += fmt.Sprintf("%v", i)
			first = false
		}
	}
	s += "}"
	return s
}

type Mode struct {
	Clock      uint32 `json:"clock"`
	HDisplay   uint16 `json:"hdisplay"`
	HSyncStart uint16 `json:"hsync_start"`
	HSyncEnd   uint16 `json:"hsync_end"`
	HTotal     uint16 `json:"htotal"`
	HSkew      uint16 `json:"hskew"`
	VDisplay   uint16 `json:"vdisplay"`
	VSyncStart uint16 `json:"vsync_total"`
	VSyncEnd   uint16 `json:"vsync_end"`
	VTotal     uint16 `json:"vtotal"`
	VScan      uint16 `json:"vscan"`
	VRefresh   uint32 `json:"vrefresh"`
	Flags      uint32 `json:"flags"`
	Type       uint32 `json:"type"`
	Name       string `json:"name"`
}

func (mode *Mode) String() string {
	// TODO: refresh and flags
	return mode.Name
}

func modeList(modes []drm.ModeModeInfo) []Mode {
	l := make([]Mode, len(modes))
	for i, m := range modes {
		l[i] = Mode(m)
	}
	return l
}

func parseFixedPoint16(v interface{}) (interface{}, error) {
	return v.(uint64) >> 16, nil
}

type PlaneInFormatsModifier struct {
	Modifier drm.Modifier `json:"modifier"`
	Formats  []drm.Format `json:"formats"`
}

func parseInFormats(v interface{}) (interface{}, error) {
	b := v.([]byte)
	set, err := drm.ParseFormatModifierSet(b)
	if err != nil {
		return nil, err
	}
	m := set.Map()
	l := make([]PlaneInFormatsModifier, 0, len(m))
	for mod, fmts := range m {
		l = append(l, PlaneInFormatsModifier{
			Modifier: mod,
			Formats:  fmts,
		})
	}
	return l, nil
}

func parseModeID(v interface{}) (interface{}, error) {
	b := v.([]byte)
	mode, err := drm.ParseModeModeInfo(b)
	if err != nil {
		return nil, err
	}
	return (*Mode)(mode), nil
}

func parseWritebackPixelFormats(v interface{}) (interface{}, error) {
	b := v.([]byte)
	formats, err := drm.ParseFormats(b)
	if err != nil {
		return nil, err
	}
	return formats, nil
}

func parsePath(v interface{}) (interface{}, error) {
	b := v.([]byte)
	return drm.ParsePath(b)
}

var propertyParsers = map[string]struct {
	objectType   drm.ObjectType
	propertyType drm.PropertyType
	f            func(v interface{}) (interface{}, error)
}{
	"SRC_X":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"SRC_Y":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"SRC_W":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"SRC_H":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"IN_FORMATS":              {drm.ObjectPlane, drm.PropertyBlob, parseInFormats},
	"MODE_ID":                 {drm.ObjectCRTC, drm.PropertyBlob, parseModeID},
	"WRITEBACK_PIXEL_FORMATS": {drm.ObjectConnector, drm.PropertyBlob, parseWritebackPixelFormats},
	"PATH":                    {drm.ObjectConnector, drm.PropertyBlob, parsePath},
}

type PropertySpecEnum struct {
	Name  string `json:"name"`
	Value uint64 `json:"value"`
}

type PropertySpecRange struct {
	Min uint64 `json:"min"`
	Max uint64 `json:"max`
}

type PropertySpecSignedRange struct {
	Min int64 `json:"min"`
	Max int64 `json:"max`
}

type Property struct {
	ID        drm.PropertyID   `json:"id"`
	Type      drm.PropertyType `json:"type"`
	Immutable bool             `json:"immutable"`
	Atomic    bool             `json:"atomic"`
	Spec      interface{}      `json:"spec"`
	RawValue  uint64           `json:"raw_value"`
	// Value interpreted with the property type
	Value interface{} `json:"value"`
	// Value interpreted with the property name, optional
	Data interface{} `json:"data"`
}

func properties(n *drm.Node, id drm.AnyID) (map[string]Property, error) {
	props, err := n.ModeObjectGetProperties(id)
	if err != nil {
		return nil, fmt.Errorf("failed to get properties for object %v: %v", id, err)
	}

	m := make(map[string]Property, len(props))
	for propID, propValue := range props {
		prop, err := n.ModeGetProperty(propID)
		if err != nil {
			return nil, fmt.Errorf("failed to get property %v: %v", propID, err)
		}

		var spec interface{}
		switch prop.Type() {
		case drm.PropertyRange:
			min, max, _ := prop.Range()
			spec = &PropertySpecRange{Min: min, Max: max}
		case drm.PropertyEnum, drm.PropertyBitmask:
			enums, _ := prop.Enums()
			l := make([]PropertySpecEnum, len(enums))
			for i, e := range enums {
				l[i] = PropertySpecEnum(e)
			}
			spec = l
		case drm.PropertyObject:
			spec, _ = prop.ObjectType()
		case drm.PropertySignedRange:
			min, max, _ := prop.SignedRange()
			spec = &PropertySpecSignedRange{Min: min, Max: max}
		}

		var val interface{}
		switch prop.Type() {
		case drm.PropertyBlob:
			blobID := drm.BlobID(propValue)
			if blobID == 0 {
				// NULL blob
				val = []byte(nil)
				break
			}
			b, err := n.ModeGetBlob(blobID)
			if err != nil {
				return nil, fmt.Errorf("failed to get blob %v: %v", blobID, err)
			}
			val = b
		case drm.PropertyObject:
			val = drm.ObjectID(propValue)
		case drm.PropertySignedRange:
			val = int64(propValue)
		default:
			val = propValue
		}

		var data interface{}
		if parser, ok := propertyParsers[prop.Name]; ok {
			if parser.objectType != id.Type() {
				log.Printf("Cannot parse property %v: expected object type %v, got %v", prop.Name, parser.objectType, id.Type())
			}
			if parser.propertyType != prop.Type() {
				log.Printf("Cannot parse property %v: expected property type %v, got %v", prop.Name, parser.propertyType, prop.Type())
			}
			data, err = parser.f(val)
			if err != nil {
				log.Printf("Cannot parse property %v: %v", prop.Name, err)
			}
		}

		m[prop.Name] = Property{
			ID:        prop.ID,
			Type:      prop.Type(),
			Immutable: prop.Immutable(),
			Atomic:    prop.Atomic(),
			Spec:      spec,
			RawValue:  propValue,
			Value:     val,
			Data:      data,
		}
	}

	return m, nil
}

func printProperties(tf treefmt.Formatter, props map[string]Property) {
	for name, prop := range props {
		// TODO: immutable, atomic
		// TODO: type-specific property data
		val := prop.Data
		if val == nil {
			val = prop.Value
		}
		tf.Printf("%q: %v = %v", name, prop.Type, val)
	}
}

type Connector struct {
	ID         drm.ConnectorID     `json:"id"`
	Type       drm.ConnectorType   `json:"type"`
	Status     drm.ConnectorStatus `json:"status"`
	PhyWidth   uint32              `json:"phy_width"`
	PhyHeight  uint32              `json:"phy_height"`
	Subpixel   drm.Subpixel        `json:"subpixel"`
	Encoders   []drm.EncoderID     `json:"encoders"`
	Modes      []Mode              `json:"modes"`
	Properties map[string]Property `json:"properties"`
}

func connectors(n *drm.Node, card *drm.ModeCard) ([]Connector, error) {
	l := make([]Connector, len(card.Connectors))
	for i, id := range card.Connectors {
		conn, err := n.ModeGetConnector(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get connector: %v", err)
		}

		props, err := properties(n, conn.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to get connector properties: %v", err)
		}

		l[i] = Connector{
			ID:         conn.ID,
			Type:       conn.Type,
			Status:     conn.Status,
			PhyWidth:   conn.PhyWidth,
			PhyHeight:  conn.PhyHeight,
			Subpixel:   conn.Subpixel,
			Encoders:   conn.PossibleEncoders,
			Modes:      modeList(conn.Modes),
			Properties: props,
		}
	}
	return l, nil
}

func encoderIDsString(encs []drm.EncoderID) string {
	s := "{"
	for i, id := range encs {
		if i != 0 {
			s += ", "
		}
		s += fmt.Sprintf("%v", id)
	}
	s += "}"
	return s
}

func printModes(tf treefmt.Formatter, modes []Mode) {
	for _, mode := range modes {
		tf.Printf("%v", &mode)
	}
}

func printConnectors(tf treefmt.Formatter, conns []Connector) {
	for i, conn := range conns {
		tf.Printf("Connector %v", i)
		tfc := tf.NewChild()

		tfc.Printf("Object ID: %v", conn.ID)
		tfc.Printf("Type: %v", conn.Type)
		tfc.Printf("Status: %v", conn.Status)
		tfc.Printf("Physical size: %vx%v mm", conn.PhyWidth, conn.PhyHeight)
		tfc.Printf("Subpixel: %v", conn.Subpixel)
		tfc.Printf("Encoders: %v", encoderIDsString(conn.Encoders))
		if len(conn.Modes) > 0 {
			tfc.Printf("Modes")
			printModes(tfc.NewChild(), conn.Modes)
		}
		if len(conn.Properties) > 0 {
			tfc.Printf("Properties")
			printProperties(tfc.NewChild(), conn.Properties)
		}
	}
}

type Encoder struct {
	ID             drm.EncoderID   `json:"id"`
	Type           drm.EncoderType `json:"type"`
	CRTC           drm.CRTCID      `json:"crtc"`
	PossibleCRTCs  uint32          `json:"possible_crtcs"`
	PossibleClones uint32          `json:"possible_clones"`
}

func encoders(n *drm.Node, card *drm.ModeCard) ([]Encoder, error) {
	l := make([]Encoder, len(card.Encoders))
	for i, id := range card.Encoders {
		enc, err := n.ModeGetEncoder(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get encoder: %v", err)
		}

		l[i] = Encoder(*enc)
	}
	return l, nil
}

func printEncoders(tf treefmt.Formatter, encs []Encoder) {
	for i, enc := range encs {
		tf.Printf("Encoder %v", i)
		tfc := tf.NewChild()

		tfc.Printf("Object ID: %v", enc.ID)
		tfc.Printf("Type: %v", enc.Type)
		tfc.Printf("CRTCs: %v", bitfieldString(enc.PossibleCRTCs))
		tfc.Printf("Clones: %v", bitfieldString(enc.PossibleClones))
	}
}

type CRTC struct {
	ID         drm.CRTCID          `json:"id"`
	FB         drm.FBID            `json:"fb"`
	X          uint32              `json:"x"`
	Y          uint32              `json:"y"`
	GammaSize  uint32              `json:"gamma_size"`
	Mode       *Mode               `json:"mode"`
	Properties map[string]Property `json:"properties"`
}

func crtcs(n *drm.Node, card *drm.ModeCard) ([]CRTC, error) {
	l := make([]CRTC, len(card.CRTCs))
	for i, id := range card.CRTCs {
		crtc, err := n.ModeGetCRTC(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get CRTC: %v", err)
		}

		props, err := properties(n, crtc.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to get CRTC properties: %v", err)
		}

		l[i] = CRTC{
			ID:         crtc.ID,
			FB:         crtc.FB,
			X:          crtc.X,
			Y:          crtc.Y,
			GammaSize:  crtc.GammaSize,
			Mode:       (*Mode)(crtc.Mode),
			Properties: props,
		}
	}
	return l, nil
}

func printCRTCs(tf treefmt.Formatter, crtcs []CRTC) {
	for i, crtc := range crtcs {
		tf.Printf("CRTC %v", i)
		tfc := tf.NewChild()

		tfc.Printf("Object ID: %v", crtc.ID)
		tfc.Printf("FB: %v", crtc.FB)
		tfc.Printf("Position: %v, %v", crtc.X, crtc.Y)
		tfc.Printf("Gamma size: %v", crtc.GammaSize)
		if crtc.Mode != nil {
			tfc.Printf("Mode: %v", crtc.Mode)
		}
		if len(crtc.Properties) > 0 {
			tfc.Printf("Properties")
			printProperties(tfc.NewChild(), crtc.Properties)
		}
	}
}

type Plane struct {
	ID            drm.PlaneID         `json:"id"`
	CRTC          drm.CRTCID          `json:"crtc"`
	FB            drm.FBID            `json:"fb"`
	PossibleCRTCs uint32              `json:"possible_crtcs"`
	GammaSize     uint32              `json:"gamma_size"`
	Formats       []drm.Format        `json:"formats"`
	Properties    map[string]Property `json:"properties"`
}

func planes(n *drm.Node) ([]Plane, error) {
	planes, err := n.ModeGetPlaneResources()
	if err != nil {
		log.Fatal(err)
	}

	l := make([]Plane, len(planes))
	for i, id := range planes {
		plane, err := n.ModeGetPlane(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get CRTC: %v", err)
		}

		props, err := properties(n, plane.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to get plane properties: %v", err)
		}

		l[i] = Plane{
			ID:            plane.ID,
			CRTC:          plane.CRTC,
			FB:            plane.FB,
			PossibleCRTCs: plane.PossibleCRTCs,
			GammaSize:     plane.GammaSize,
			Formats:       plane.Formats,
			Properties:    props,
		}
	}

	return l, nil
}

func printFormats(tf treefmt.Formatter, formats []drm.Format) {
	for _, fmt := range formats {
		tf.Printf("%v", fmt)
	}
}

func printPlanes(tf treefmt.Formatter, planes []Plane) {
	for i, plane := range planes {
		tf.Printf("Plane %v", i)
		tfc := tf.NewChild()

		tfc.Printf("Object ID: %v", plane.ID)
		tfc.Printf("CRTC: %v", plane.CRTC)
		tfc.Printf("FB: %v", plane.FB)
		tfc.Printf("CRTCs: %v", bitfieldString(plane.PossibleCRTCs))
		tfc.Printf("Gamma size: %v", plane.GammaSize)
		if len(plane.Formats) > 0 {
			tfc.Printf("Formats")
			printFormats(tfc.NewChild(), plane.Formats)
		}
		if len(plane.Properties) > 0 {
			tfc.Printf("Properties")
			printProperties(tfc.NewChild(), plane.Properties)
		}
	}
}

type Node struct {
	Driver     *Driver     `json:"driver"`
	Device     *Device     `json:"device"`
	Connectors []Connector `json:"connectors"`
	Encoders   []Encoder   `json:"encoders"`
	CRTCs      []CRTC      `json:"crtcs"`
	Planes     []Plane     `json:"planes"`
}

func node(nodePath string) (*Node, error) {
	f, err := os.Open(nodePath)
	if err != nil {
		return nil, fmt.Errorf("failed to open DRM node: %v", err)
	}
	defer f.Close()

	n := drm.NewNode(f.Fd())

	drv, err := driver(n)
	if err != nil {
		return nil, err
	}

	dev, err := device(n)
	if err != nil {
		return nil, err
	}

	r, err := n.ModeGetResources()
	if err != nil {
		return nil, fmt.Errorf("failed to get DRM resources: %v", err)
	}

	conns, err := connectors(n, r)
	if err != nil {
		return nil, err
	}

	encs, err := encoders(n, r)
	if err != nil {
		return nil, err
	}

	crtcs, err := crtcs(n, r)
	if err != nil {
		return nil, err
	}

	planes, err := planes(n)
	if err != nil {
		return nil, err
	}

	return &Node{
		Driver:     drv,
		Device:     dev,
		Connectors: conns,
		Encoders:   encs,
		CRTCs:      crtcs,
		Planes:     planes,
	}, nil
}

func printNode(tf treefmt.Formatter, path string, n *Node) {
	tf.Printf("Node: %s", path)
	tfc := tf.NewChild()

	printDriver(tfc, n.Driver)
	printDevice(tfc, n.Device)

	tfc.Printf("Connectors")
	printConnectors(tfc.NewChild(), n.Connectors)

	tfc.Printf("Encoders")
	printEncoders(tfc.NewChild(), n.Encoders)

	tfc.Printf("CRTCs")
	printCRTCs(tfc.NewChild(), n.CRTCs)

	tfc.Printf("Planes")
	printPlanes(tfc.NewChild(), n.Planes)
}

func main() {
	var (
		outputJSON bool
	)
	flag.BoolVar(&outputJSON, "j", false, "Enable JSON output")
	flag.Parse()

	paths, err := filepath.Glob(drm.NodePatternPrimary)
	if err != nil {
		log.Fatalf("Failed to list DRM nodes: %v", err)
	}

	nodes := make(map[string]*Node)
	for _, p := range paths {
		n, err := node(p)
		if err != nil {
			log.Fatal(err)
		}
		nodes[p] = n
	}

	if outputJSON {
		err = json.NewEncoder(os.Stdout).Encode(nodes)
		if err != nil {
			log.Fatalf("Failed to write JSON: %v", err)
		}
	} else {
		tf := treefmt.NewTextFormatter(os.Stdout)
		for path, n := range nodes {
			printNode(tf, path, n)
		}
	}
}