-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodeplug.go
More file actions
2373 lines (2013 loc) · 48.3 KB
/
codeplug.go
File metadata and controls
2373 lines (2013 loc) · 48.3 KB
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017-2019 Dale Farnsworth. All rights reserved.
// Dale Farnsworth
// 1007 W Mendoza Ave
// Mesa, AZ 85210
// USA
//
// dale@farnsworth.org
// This file is part of Codeplug.
//
// Codeplug is free software: you can redistribute it and/or modify
// it under the terms of version 3 of the GNU Lesser General Public
// License as published by the Free Software Foundation.
//
// Codeplug is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Codeplug. If not, see <http://www.gnu.org/licenses/>.
// Package codeplug implements access to MD380-style codeplug files.
// It can read/update/write both .rdt files and .bin files.
package codeplug
import (
"archive/tar"
"bufio"
"bytes"
"compress/bzip2"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"unicode"
l "github.com/dalefarnsworth-dmr/debug"
"github.com/dalefarnsworth-dmr/dfu"
"github.com/tealeg/xlsx/v3"
)
// FileType tells whether the codeplug is an rdt file or a bin file.
type FileType int
const (
FileTypeNone FileType = iota
FileTypeRdt
FileTypeBin
FileTypeNew
FileTypeText
FileTypeJSON
FileTypeXLSX
)
const (
MinProgress = dfu.MinProgress
MaxProgress = dfu.MaxProgress
)
// A Codeplug represents a codeplug file.
type Codeplug struct {
filename string
importFilename string
fileType FileType
rdtSize int
fileSize int
fileOffset int
id string
bytes []byte
hash [sha256.Size]byte
rDesc map[RecordType]*rDesc
changed bool
lowFrequency float64
highFrequency float64
lowFrequencyB float64
highFrequencyB float64
connectChange func(*Change)
codeplugInfo *CodeplugInfo
loaded bool
cachedNameToRt map[string]RecordType
cachedNameToFt map[RecordType]map[string]FieldType
gpsEnabled bool
uniqueContactNames bool
warnings []string
}
type CodeplugInfo struct {
Type string
Models []string
Ext string
RdtSize int
HeaderSize int
TrailerOffset int
TrailerSize int
RecordInfos []*recordInfo
}
// NewCodeplug returns a Codeplug, given a filename and codeplug type.
func NewCodeplug(fType FileType, filename string) (*Codeplug, error) {
cp := new(Codeplug)
cp.fileType = fType
switch fType {
case FileTypeNone:
err := cp.findFileType(filename)
if err != nil {
return nil, err
}
if cp.fileType == FileTypeRdt {
err = cp.read(filename)
if err != nil {
cp.fileType = FileTypeNone
return nil, err
}
}
case FileTypeText, FileTypeJSON, FileTypeXLSX:
cp.importFilename = filename
fallthrough
case FileTypeNew:
baseName := "codeplug"
for i := 1; ; i++ {
filename = fmt.Sprintf("%s%d", baseName, i)
found := false
for _, cp := range codeplugs {
if strings.HasPrefix(cp.filename, filename) {
found = true
break
}
}
if !found {
matches, err := filepath.Glob(filename + "*")
if err != nil {
l.Fatal(err.Error())
}
if len(matches) != 0 {
found = true
break
}
}
if !found {
break
}
}
default:
l.Fatal("unknown file type")
}
cp.filename = filename
cp.rDesc = make(map[RecordType]*rDesc)
cp.id = RandomString(64)
return cp, nil
}
type Warning struct {
error
}
func (cp *Codeplug) Load(typ string, freqRange string) error {
cp.codeplugInfo = nil
for _, cpi := range codeplugInfos {
if typ == cpi.Type {
cp.codeplugInfo = cpi
}
}
if cp.codeplugInfo == nil {
return fmt.Errorf("codeplug type not found: %s", typ)
}
switch cp.fileType {
case FileTypeNew, FileTypeBin, FileTypeText, FileTypeJSON, FileTypeXLSX:
freqRange = strings.Replace(freqRange, " ", "_", -1)
filename := cp.Type() + "_" + freqRange + "." + cp.Ext()
err := cp.readNew(filename)
if err != nil {
return err
}
}
switch cp.fileType {
case FileTypeRdt, FileTypeBin:
err := cp.read(cp.filename)
if err != nil {
return err
}
}
err := cp.Revert()
if err != nil {
return err
}
switch cp.fileType {
case FileTypeText, FileTypeJSON, FileTypeXLSX:
cp.RemoveAllRecords()
var err error
switch cp.fileType {
case FileTypeText:
file, err := os.Open(cp.importFilename)
if err == nil {
defer file.Close()
err = cp.importText(file)
}
case FileTypeJSON:
err = cp.importJSON(cp.importFilename)
case FileTypeXLSX:
err = cp.importXLSX(cp.importFilename)
}
cp.AddMissingFields()
if err != nil {
return err
}
}
codeplugs = append(codeplugs, cp)
cp.loaded = true
return nil
}
func (cp *Codeplug) Loaded() bool {
return cp.loaded
}
func (cp *Codeplug) AllExts() []string {
extMap := make(map[string]bool)
for _, cpi := range codeplugInfos {
extMap[cpi.Ext] = true
}
exts := make([]string, 0, len(extMap))
for ext := range extMap {
exts = append(exts, ext)
}
return exts
}
func (cp *Codeplug) Ext() string {
return cp.codeplugInfo.Ext
}
func (cp *Codeplug) CodeplugInfo() *CodeplugInfo {
return cp.codeplugInfo
}
func ModelTypes(model string) string {
types := make([]string, 0)
for _, cpi := range codeplugInfos {
for _, cpModel := range cpi.Models {
if cpModel == model {
types = append(types, cpi.Type)
break
}
}
}
if len(types) > 0 && (len(types) != 1 || types[0] != model) {
model += " (" + strings.Join(types, ", ") + ")"
}
return model
}
func (cp *Codeplug) SetGPSEnabled(b bool) {
cp.gpsEnabled = b
}
func (cp *Codeplug) SetUniqueContactNames(b bool) {
cp.uniqueContactNames = b
}
func (cp *Codeplug) HasRecordType(rType RecordType) bool {
return cp.rDesc[rType] != nil
}
func (cp *Codeplug) RecordTypeName(rType RecordType) string {
var str string
rDesc := cp.rDesc[rType]
if rDesc != nil {
str = rDesc.typeName
}
return str
}
func (cp *Codeplug) AllFields() []*Field {
fields := make([]*Field, 0)
for _, rType := range cp.RecordTypes() {
for _, r := range cp.records(rType) {
for _, fType := range r.FieldTypes() {
for _, f := range r.Fields(fType) {
fields = append(fields, f)
}
}
}
}
return fields
}
func (cp *Codeplug) fields(rType RecordType, fType FieldType) []*Field {
fields := make([]*Field, 0)
for _, r := range cp.records(rType) {
for _, f := range r.Fields(fType) {
fields = append(fields, f)
}
}
return fields
}
func (cp *Codeplug) TextLines() []string {
lines := make([]string, 0)
for _, rType := range cp.RecordTypes() {
for _, r := range cp.records(rType) {
var w bytes.Buffer
PrintOneLineRecord(&w, r)
lines = append(lines, w.String())
}
}
return lines
}
func AllFrequencyRanges() map[string][]string {
freqRanges := make(map[string][]string)
for _, cpi := range codeplugInfos {
model := cpi.Type
for _, rInfo := range cpi.RecordInfos {
if rInfo.rType == RtBasicInformation_md380 {
for _, fInfo := range rInfo.fieldInfos {
if fInfo.fType == FtBiFrequencyRange_md380 {
freqRanges[model] = *fInfo.strings
}
if fInfo.fType == FtBiFrequencyRangeA {
freqRanges[model] = *fInfo.strings
}
}
}
}
}
for _, cpi := range codeplugInfos {
model := cpi.Type
for _, rInfo := range cpi.RecordInfos {
if rInfo.rType == RtBasicInformation_md380 {
for _, fInfo := range rInfo.fieldInfos {
if fInfo.fType == FtBiFrequencyRangeB {
aRanges := freqRanges[model]
freqRanges[model] = make([]string, 0)
for _, ra := range aRanges {
for _, rb := range *fInfo.strings {
freqRanges[model] = append(freqRanges[model], ra+"_"+rb)
}
}
}
}
}
}
}
return freqRanges
}
// TypesFrequencyRanges returns the potential codeplug model and
// freqRange
func (cp *Codeplug) TypesFrequencyRanges() (types []string, freqRanges map[string][]string) {
types = make([]string, 0)
freqRanges = make(map[string][]string)
var model string
var freqRange string
switch cp.fileType {
case FileTypeRdt:
case FileTypeText, FileTypeJSON, FileTypeXLSX:
model, freqRange = cp.parseModelFrequencyRange()
fallthrough
default:
cp.bytes = make([]byte, codeplugInfos[0].RdtSize)
}
for _, cpi := range codeplugInfos {
cp.codeplugInfo = cpi
cp.loadHeader()
typ := cp.Type()
freqRanges[typ] = cp.freqRanges()
if cp.fileType == FileTypeRdt {
if cpi.RdtSize != cp.rdtSize {
types = append(types, typ)
continue
}
model = cp.Model()
freqRange = cp.FrequencyRange()
}
for _, cpiModel := range cpi.Models {
if cpiModel != model {
continue
}
for _, r := range freqRanges[typ] {
if r != freqRange {
continue
}
types = []string{typ}
freqRanges = make(map[string][]string)
freqRanges[typ] = []string{r}
return types, freqRanges
}
}
types = append(types, typ)
}
if cp.fileType != FileTypeRdt {
cp.bytes = nil
}
cp.codeplugInfo = nil
sort.Strings(types)
return types, freqRanges
}
func (cp *Codeplug) Model() string {
fDescs := cp.rDesc[RtBasicInformation_md380].records[0].fDesc
return (*fDescs)[FtBiModel].fields[0].String()
}
func (cp *Codeplug) FrequencyRange() string {
freqRange := ""
fDescs := cp.rDesc[RtBasicInformation_md380].records[0].fDesc
r := (*fDescs)[FtBiFrequencyRange_md380]
if r != nil {
freqRange = r.fields[0].String()
}
r = (*fDescs)[FtBiFrequencyRangeA]
if r != nil {
freqRange = r.fields[0].String()
}
r = (*fDescs)[FtBiFrequencyRangeB]
if r != nil {
freqRange += "_" + r.fields[0].String()
}
return freqRange
}
func (cp *Codeplug) freqRanges() []string {
cpi := cp.codeplugInfo
var rangesA []string
var rangesB []string
for _, rInfo := range cpi.RecordInfos {
if rInfo.rType == RtBasicInformation_uv380 {
for _, fInfo := range rInfo.fieldInfos {
switch fInfo.fType {
case FtBiFrequencyRange_md380:
rangesA = *fInfo.strings
case FtBiFrequencyRangeA:
rangesA = *fInfo.strings
}
}
for _, fInfo := range rInfo.fieldInfos {
switch fInfo.fType {
case FtBiFrequencyRangeB:
rangesB = *fInfo.strings
}
}
}
}
ranges := rangesA
if len(rangesB) > 1 {
ranges = make([]string, 0)
for i := range rangesA {
for j := range rangesB {
ranges = append(ranges, rangesA[i]+"_"+rangesB[j])
}
}
}
return ranges
}
func (cp *Codeplug) Type() string {
return cp.codeplugInfo.Type
}
func (cp *Codeplug) Models() []string {
return cp.codeplugInfo.Models
}
func (cp *Codeplug) Warnings() []string {
return cp.warnings
}
// Codeplugs returns a slice containing all currently open codeplugs.
func Codeplugs() []*Codeplug {
return codeplugs
}
// Free frees a codeplug
func (cp *Codeplug) Free() {
for i, codeplug := range codeplugs {
if cp == codeplug {
codeplugs = append(codeplugs[:i], codeplugs[i+1:]...)
for _, rd := range cp.rDesc {
rd.codeplug = nil
}
break
}
}
}
func (cp *Codeplug) readNew(filename string) error {
archive := bzip2.NewReader(bytes.NewReader(new_tar_bz2))
tarfile := tar.NewReader(archive)
var bytes []byte
for {
hdr, err := tarfile.Next()
if err != nil {
if err == io.EOF {
break
}
l.Fatal(err)
}
if hdr.Name != filename {
continue
}
bytes, err = ioutil.ReadAll(tarfile)
if err != nil {
l.Fatal(err)
}
break
}
if len(bytes) == 0 {
return fmt.Errorf("file %s not found", filename)
}
cp.bytes = bytes
return nil
}
// read opens a file and reads its contents into cp.bytes.
func (cp *Codeplug) read(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
if cp.bytes == nil {
cp.bytes = make([]byte, cp.fileOffset+cp.fileSize)
}
bytes := make([]byte, cp.fileSize)
bytesRead, err := file.Read(bytes)
if err != nil {
return err
}
if bytesRead != cp.fileSize {
err = fmt.Errorf("Failed to read all of %s", filename)
return err
}
if cp.fileType != FileTypeBin {
copy(cp.bytes, bytes)
return nil
}
cpi := cp.codeplugInfo
srcBegin := 0
srcEnd := cpi.TrailerOffset - cpi.HeaderSize
dstBegin := cpi.HeaderSize
dstEnd := cpi.TrailerOffset
copy(cp.bytes[dstBegin:dstEnd], bytes[srcBegin:srcEnd])
srcBegin = cpi.TrailerOffset - cpi.HeaderSize
srcEnd = len(bytes)
dstBegin = cpi.TrailerOffset + cpi.TrailerSize
dstEnd = len(cp.bytes)
copy(cp.bytes[dstBegin:dstEnd], bytes[srcBegin:srcEnd])
return nil
}
// Revert reverts the codeplug to its state after the most recent open or
// save operation. An error is returned if the new codeplug state is
// invalid.
func (cp *Codeplug) Revert() error {
cp.clearCachedListNames()
cp.load()
cp.ResolveDeferredValueFields(nil)
// Turn off talkaround toggle in the radio (for all channels)
for _, r := range cp.records(RtChannels_md380) {
r.Field(FtCiTalkaround).SetString("Off")
}
cp.store()
cp.Valid()
cp.changed = false
cp.hash = sha256.Sum256(cp.bytes)
return nil
}
// Save stores the state of the Codeplug into its file
// An error may be returned if the codeplug state is invalid.
func (cp *Codeplug) Save() error {
return cp.SaveAs(cp.filename)
}
// SaveAs saves the state of the Codeplug into a named file.
// An error will be returned if the codeplug state is invalid.
// The named file becomes the current file associated with the codeplug.
func (cp *Codeplug) SaveAs(filename string) error {
err := cp.SaveToFile(filename)
if err != nil {
return err
}
cp.filename = filename
cp.changed = false
cp.hash = sha256.Sum256(cp.bytes)
return nil
}
// SaveToFile saves the state of the Codeplug into a named file.
// An error will be returned if the codeplug state is invalid.
// The state of the codeplug is not changed, so this
// is useful for use by an autosave function.
func (cp *Codeplug) SaveToFile(filename string) (err error) {
cp.Valid()
cp.setLastProgrammedTime(time.Now())
cp.store()
dir, base := filepath.Split(filename)
if dir == "" {
var err error
dir, err = os.Getwd()
if err != nil {
return err
}
}
tmpFile, err := ioutil.TempFile(dir, base)
if err != nil {
return err
}
tmpFilename := tmpFile.Name()
defer func() {
closeErr := tmpFile.Close()
if err == nil {
err = closeErr
}
if err != nil {
os.Remove(tmpFilename)
return
}
err = os.Rename(tmpFilename, filename)
}()
cpi := cp.codeplugInfo
fileSize := cpi.RdtSize
fileOffset := 0
bytes := cp.bytes[fileOffset : fileOffset+fileSize]
bytesWritten, err := tmpFile.Write(bytes)
if err != nil {
return err
}
if bytesWritten != fileSize {
return fmt.Errorf("write to %s failed", cp.filename)
}
return err
}
func (cp *Codeplug) setLastProgrammedTime(t time.Time) {
r := cp.rDesc[RtBasicInformation_md380].records[0]
f := r.Field(FtBiLastProgrammedTime)
f.setString(t.Format("02-Jan-2006 15:04:05"))
}
func (cp *Codeplug) getLastProgrammedTime() (time.Time, error) {
r := cp.rDesc[RtBasicInformation_md380].records[0]
f := r.Field(FtBiLastProgrammedTime)
return time.Parse("02-Jan-2006 15:04:05", f.String())
}
// Filename returns the path name of the file associated with the codeplug.
// This is the file named in the most recent Open or SaveAs function.
func (cp *Codeplug) Filename() string {
return cp.filename
}
// CurrentHash returns a cryptographic hash of the current (modified) codeplug
func (cp *Codeplug) CurrentHash() [sha256.Size]byte {
if !cp.changed {
return cp.hash
}
bytes := make([]byte, len(cp.bytes))
copy(bytes, cp.bytes)
saveBytes := cp.bytes
cp.bytes = bytes
cp.store()
cp.bytes = saveBytes
return sha256.Sum256(bytes)
}
// Changed returns false if the codeplug state is the same as that at
// the most recent Open or Save/SaveAs operation.
func (cp *Codeplug) Changed() bool {
if cp.changed && cp.CurrentHash() != cp.hash {
return true
}
return false
}
func (cp *Codeplug) SetChanged() {
cp.changed = true
for i := range cp.hash {
cp.hash[i] = 0
}
}
// FileType returns the type of codeplug file (rdt or bin).
func (cp *Codeplug) FileType() FileType {
return cp.fileType
}
// Records returns all of a codeplug's records of the given RecordType.
func (cp *Codeplug) Records(rType RecordType) []*Record {
records := cp.rDesc[rType].records
if len(records) == 0 {
rIndex := 0
r := cp.newRecord(rType, rIndex)
cp.InsertRecord(r)
r.load()
nameField := r.NameField()
if nameField != nil {
nameField.setString(string(rType) + "1")
}
records = cp.rDesc[rType].records
}
return records
}
func (cp *Codeplug) records(rType RecordType) []*Record {
return cp.rDesc[rType].records
}
// Record returns the first record of a codeplug's given RecordType.
func (cp *Codeplug) Record(rType RecordType) *Record {
return cp.Records(rType)[0]
}
// record returns the first record of a codeplug's given RecordType.
func (cp *Codeplug) record(rType RecordType) *Record {
return cp.records(rType)[0]
}
// MaxRecords returns a codeplug's maximum number of records of the given
// Recordtype.
func (cp *Codeplug) MaxRecords(rType RecordType) int {
return cp.rDesc[rType].max
}
// RecordTypes returns all of the record types of the codeplug except
// BasicInformation. The BasicInformation record is omitted.
func (cp *Codeplug) RecordTypes() []RecordType {
indexedStrs := make(map[int]string)
indexes := make([]int, 0, len(cp.rDesc))
for rType, rDesc := range cp.rDesc {
index := rDesc.recordInfo.index
indexes = append(indexes, index)
indexedStrs[index] = string(rType)
}
sort.Ints(indexes)
rTypes := make([]RecordType, len(indexes))
for i, index := range indexes {
rTypes[i] = RecordType(indexedStrs[index])
}
return rTypes
}
func (cp *Codeplug) SetRecordsField(recs []*Record, fType FieldType, str string, progFunc func(int)) error {
change := cp.RecordsFieldChange(recs)
for i, r := range recs {
f := r.Field(fType)
pValue := f.String()
change.changes = append(change.changes, fieldChange(f, pValue))
err := f.setString(str)
if err != nil {
return err
}
progFunc(i)
}
change.Complete()
return nil
}
// ID returns a string unique to the codeplug.
func (cp *Codeplug) ID() string {
return cp.id
}
// MoveRecord moves a record from its current slice index to the given index.
func (cp *Codeplug) MoveRecord(dIndex int, r *Record) {
sIndex := r.rIndex
cp.RemoveRecord(r)
if sIndex < dIndex {
dIndex--
}
r.rIndex = dIndex
cp.InsertRecord(r)
}
// InsertRecord inserts the given record into the codeplug.
// The record's index determines the slice index at which it will be inserted.
// If the name of the record matches that of an existing record,
// the name is modified to make it unique. An error will be returned if
// the codeplug's maximum records of that type would be exceeded.
func (cp *Codeplug) InsertRecord(r *Record) error {
rType := r.rType
records := cp.records(rType)
if len(records) >= cp.MaxRecords(rType) {
return fmt.Errorf("too many records")
}
err := r.makeNameUnique()
if err != nil {
return err
}
i := r.rIndex
if i > len(records) {
i = len(records)
}
records = append(records[:i], append([]*Record{r}, records[i:]...)...)
for i, r := range records {
r.rIndex = i
}
cp.rDesc[rType].records = records
records[0].cachedListNames = nil
return nil
}
func (cp *Codeplug) AppendRecord(r *Record) error {
r.rIndex = len(cp.records(r.rType))
return cp.InsertRecord(r)
}
// RemoveRecord removes the given record from the codeplug.
func (cp *Codeplug) RemoveRecord(r *Record) {
rType := r.rType
index := -1
records := cp.records(rType)
for i, record := range records {
if record == r {
index = i
break
}
}
if index < 0 || index >= len(records) {
l.Fatal("removeRecord: bad record")
}
deleteRecord(&records, index)
for i, r := range records {
r.rIndex = i
}
cp.rDesc[rType].records = records
cp.rDesc[rType].cachedListNames = nil
}
func (cp *Codeplug) RemoveAllRecords() {
for _, rType := range cp.RecordTypes() {
if cp.MaxRecords(rType) == 1 {
continue
}
records := cp.records(rType)
for i := len(records) - 1; i >= 0; i-- {
cp.RemoveRecord(records[i])
}
}
}
func (cp *Codeplug) AddMissingFields() {
for _, rType := range cp.RecordTypes() {
for _, r := range cp.Records(rType) {
for _, fType := range r.AllFieldTypes() {
nf := r.NewField(fType)
if nf.MaxFields() > 1 {
continue
}
f := r.Field(fType)
if f != nil {
continue
}
r.addField(nf)
}
}
}
}
// ConnectChange will cause the given function to be called passing
// the given change.
func (cp *Codeplug) ConnectChange(fn func(*Change)) {
cp.connectChange = fn
}
// loadHeader loads the rdt header into the codeplug from its file.
func (cp *Codeplug) loadHeader() {
cp.clearCachedListNames()
ri := cp.codeplugInfo.RecordInfos[0]
ri.max = 1
rd := &rDesc{recordInfo: ri}
cp.rDesc[ri.rType] = rd
rd.codeplug = cp
rd.loadRecords()
}
// load loads all the records into the codeplug from its file.
func (cp *Codeplug) load() {
cp.clearCachedListNames()
for i, ri := range cp.codeplugInfo.RecordInfos {
ri.index = i
if ri.max == 0 {
ri.max = 1
}
rd := &rDesc{recordInfo: ri}
cp.rDesc[ri.rType] = rd
rd.codeplug = cp
rd.loadRecords()
}
}
// newRecord creates and returns the address of a new record of the given type.
func (cp *Codeplug) newRecord(rType RecordType, rIndex int) *Record {
r := new(Record)
r.rDesc = cp.rDesc[rType]
r.rIndex = rIndex
m := make(map[FieldType]*fDesc)