From 0117c97a5556404b5f6602fd73d9c5ed579afe0c Mon Sep 17 00:00:00 2001 From: Graham Clark Date: Sun, 5 Jun 2022 18:55:10 -0400 Subject: [PATCH] Rearrange the config file handling code There is a new package called profiles and the config handling code is now there. Instead of using the viper default APIs, I'll now explicitly use a viper struct, and then I'll be able to use the same APIs to switch struct to "load" another profile. --- cmd/termshark/termshark.go | 58 ++++----- configs/profiles/profiles.go | 169 +++++++++++++++++++++++++++ shark/columnformat.go | 3 +- ui/convsui.go | 13 ++- ui/lastline.go | 27 ++--- ui/logsui.go | 3 +- ui/prochandlers.go | 7 +- ui/psmlcols.go | 10 +- ui/searchbyfilter.go | 5 +- ui/streamui.go | 7 +- ui/switchterm.go | 5 +- ui/ui.go | 39 ++++--- ui/wormhole.go | 8 +- utils.go | 135 +++++---------------- widgets/search/search.go | 19 +-- widgets/streamwidget/streamwidget.go | 7 +- 16 files changed, 306 insertions(+), 209 deletions(-) create mode 100644 configs/profiles/profiles.go diff --git a/cmd/termshark/termshark.go b/cmd/termshark/termshark.go index bd01ce23..1fd9ef75 100644 --- a/cmd/termshark/termshark.go +++ b/cmd/termshark/termshark.go @@ -21,6 +21,7 @@ import ( "github.com/gcla/termshark/v2" "github.com/gcla/termshark/v2/capinfo" "github.com/gcla/termshark/v2/cli" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/convs" "github.com/gcla/termshark/v2/pcap" "github.com/gcla/termshark/v2/shark" @@ -133,8 +134,6 @@ func cmain() int { // processes start running, they use the same tty line discipline. system.RegisterForSignals(sigChan) - viper.SetConfigName("termshark") // no need to include file extension - looks for file called termshark.ini for example - stdConf := configdir.New("", "termshark") dirs := stdConf.QueryFolders(configdir.Cache) if err := dirs[0].CreateParentDir("dummy"); err != nil { @@ -144,17 +143,10 @@ func cmain() int { if err := dirs[0].CreateParentDir("dummy"); err != nil { fmt.Fprintf(os.Stderr, "Warning: could not create config dir: %v\n", err) } - viper.AddConfigPath(dirs[0].Path) - - if f, err := os.OpenFile(filepath.Join(dirs[0].Path, "termshark.toml"), os.O_RDONLY|os.O_CREATE, 0666); err != nil { - fmt.Fprintf(os.Stderr, "Warning: could not create initial config file: %v\n", err) - } else { - f.Close() - } - err := viper.ReadInConfig() + err := profiles.ReadDefaultConfig(dirs[0].Path) if err != nil { - fmt.Println("Config file not found...") + fmt.Fprintf(os.Stderr, fmt.Sprintf("%s\n", err.Error())) } if os.Getenv("TERMSHARK_CAPTURE_MODE") == "1" { @@ -312,7 +304,7 @@ func cmain() int { // Allow the user to override the shell's TERM variable this way. Perhaps the user runs // under screen/tmux, and the TERM variable doesn't reflect the fact their preferred // terminal emumlator supports 256 colors. - termVar := termshark.ConfString("main.term", "") + termVar := profiles.ConfString("main.term", "") if termVar != "" { fmt.Fprintf(os.Stderr, "Configuration file overrides TERM setting, using TERM=%s\n", termVar) os.Setenv("TERM", termVar) @@ -533,7 +525,7 @@ func cmain() int { } debug := false - if (opts.Debug.Set && opts.Debug.Val == true) || (!opts.Debug.Set && termshark.ConfBool("main.debug", false)) { + if (opts.Debug.Set && opts.Debug.Val == true) || (!opts.Debug.Set && profiles.ConfBool("main.debug", false)) { debug = true } @@ -575,7 +567,7 @@ func cmain() int { // Here, tsharkBin is a fully-qualified tshark binary that exists on the fs (absent race // conditions...) - valids := termshark.ConfStrings("main.validated-tsharks") + valids := profiles.ConfStrings("main.validated-tsharks") if !termshark.StringInSlice(tsharkBin, valids) { tver, err := termshark.TSharkVersion(tsharkBin) @@ -592,24 +584,24 @@ func cmain() int { } valids = append(valids, tsharkBin) - termshark.SetConf("main.validated-tsharks", valids) + profiles.SetConf("main.validated-tsharks", valids) } // If the last tshark we used isn't the same as the current one, then remove the cached fields // data structure so it can be regenerated. - if tsharkBin != termshark.ConfString("main.last-used-tshark", "") { + if tsharkBin != profiles.ConfString("main.last-used-tshark", "") { termshark.DeleteCachedFields() } // Write out the last-used tshark path. We do this to make the above fields cache be consistent // with the tshark binary we're using. - termshark.SetConf("main.last-used-tshark", tsharkBin) + profiles.SetConf("main.last-used-tshark", tsharkBin) // Determine if the current binary supports color. Tshark will fail with an error if it's too old // and you supply the --color flag. Assume true, and check if our current binary is not in the // validate list. ui.PacketColorsSupported = true - colorTsharks := termshark.ConfStrings("main.color-tsharks") + colorTsharks := profiles.ConfStrings("main.color-tsharks") if !termshark.StringInSlice(tsharkBin, colorTsharks) { ui.PacketColorsSupported, err = termshark.TSharkSupportsColor(tsharkBin) @@ -617,7 +609,7 @@ func cmain() int { ui.PacketColorsSupported = false } else { colorTsharks = append(colorTsharks, tsharkBin) - termshark.SetConf("main.color-tsharks", colorTsharks) + profiles.SetConf("main.color-tsharks", colorTsharks) } } @@ -732,24 +724,24 @@ func cmain() int { }() // Initialize application state for dark mode and auto-scroll - ui.DarkMode = termshark.ConfBool("main.dark-mode", true) - ui.AutoScroll = termshark.ConfBool("main.auto-scroll", true) - ui.PacketColors = termshark.ConfBool("main.packet-colors", true) + ui.DarkMode = profiles.ConfBool("main.dark-mode", true) + ui.AutoScroll = profiles.ConfBool("main.auto-scroll", true) + ui.PacketColors = profiles.ConfBool("main.packet-colors", true) // Set them up here so they have access to any command-line flags that // need to be passed to the tshark commands used - pdmlArgs := termshark.ConfStringSlice("main.pdml-args", []string{}) - psmlArgs := termshark.ConfStringSlice("main.psml-args", []string{}) + pdmlArgs := profiles.ConfStringSlice("main.pdml-args", []string{}) + psmlArgs := profiles.ConfStringSlice("main.psml-args", []string{}) if opts.TimestampFormat != "" { psmlArgs = append(psmlArgs, "-t", opts.TimestampFormat) } - tsharkArgs := termshark.ConfStringSlice("main.tshark-args", []string{}) + tsharkArgs := profiles.ConfStringSlice("main.tshark-args", []string{}) if ui.PacketColors && !ui.PacketColorsSupported { log.Warnf("Packet coloring is enabled, but %s does not support --color", tsharkBin) ui.PacketColors = false } - cacheSize := termshark.ConfInt("main.pcap-cache-size", 64) - bundleSize := termshark.ConfInt("main.pcap-bundle-size", 1000) + cacheSize := profiles.ConfInt("main.pcap-cache-size", 64) + bundleSize := profiles.ConfInt("main.pcap-bundle-size", 1000) if bundleSize <= 0 { maxBundleSize := 100000 log.Infof("Config specifies pcap-bundle-size as %d - setting to max (%d)", bundleSize, maxBundleSize) @@ -795,8 +787,8 @@ func cmain() int { // 0-21 are set up normally, and not remapped. If the closest match is one of those // colors, then the theme won't look as expected. A workaround is to tell // gowid not to use colors 0-21 when finding the closest match. - if termshark.ConfKeyExists("main.ignore-base16-colors") { - gowid.IgnoreBase16 = termshark.ConfBool("main.ignore-base16-colors", false) + if profiles.ConfKeyExists("main.ignore-base16-colors") { + gowid.IgnoreBase16 = profiles.ConfBool("main.ignore-base16-colors", false) } else { // Try to auto-detect whether or not base16-shell is installed and in-use gowid.IgnoreBase16 = (os.Getenv("BASE16_SHELL") != "") @@ -810,7 +802,7 @@ func cmain() int { // just an implementation snafu, or if something else is going on... In any case, // termshark will fall back to 256-colors if base16 is detected because I can // programmatically avoid choosing colors 0-21 for anything termshark needs. - if os.Getenv("COLORTERM") != "" && !termshark.ConfBool("main.respect-colorterm", false) { + if os.Getenv("COLORTERM") != "" && !profiles.ConfBool("main.respect-colorterm", false) { log.Infof("Pessimistically disabling 24-bit color to avoid conflicts with base16") os.Unsetenv("COLORTERM") } @@ -1129,7 +1121,7 @@ Loop: case <-checkPcapCacheChan: // Only check the cache dir if we own it; don't want to delete pcap files // that might be shared with wireshark - if termshark.ConfBool("main.use-tshark-temp-for-pcap-cache", false) { + if profiles.ConfBool("main.use-tshark-temp-for-pcap-cache", false) { log.Infof("Termshark does not own the pcap temp dir %s; skipping size check", termshark.PcapDir()) } else { termshark.PrunePcapCache() @@ -1160,7 +1152,7 @@ Loop: // activated. mode := app.GetColorMode() modeStr := theme.Mode(mode) // more concise - themeName := termshark.ConfString(fmt.Sprintf("main.theme-%s", modeStr), "default") + themeName := profiles.ConfString(fmt.Sprintf("main.theme-%s", modeStr), "default") loaded := false if themeName != "" { err = theme.Load(themeName, app) @@ -1198,7 +1190,7 @@ Loop: // If exists is true, it means we already tried and then reverted back, so // just load up termshark normally with no further interruption. if _, exists := os.LookupEnv("TERMSHARK_ORIGINAL_TERM"); !exists { - if !termshark.ConfBool("main.disable-term-helper", false) { + if !profiles.ConfBool("main.disable-term-helper", false) { err = termshark.Does256ColorTermExist() if err != nil { log.Infof("Must use 8-color mode because 256-color version of TERM=%s unavailable - %v.", os.Getenv("TERM"), err) diff --git a/configs/profiles/profiles.go b/configs/profiles/profiles.go new file mode 100644 index 00000000..231e3f9e --- /dev/null +++ b/configs/profiles/profiles.go @@ -0,0 +1,169 @@ +// Copyright 2019-2022 Graham Clark. All rights reserved. Use of this source +// code is governed by the MIT license that can be found in the LICENSE +// file. + +package profiles + +import ( + "fmt" + "os" + "path/filepath" + "sync" + + "github.com/spf13/viper" +) + +//====================================================================== + +// The config is accessed by the main goroutine and pcap loading goroutines. So this +// is an attempt to prevent warnings with the -race flag (though they are very likely +// harmless) +var confMutex sync.Mutex + +// If this is non-nil, then the user has a profile loaded +var vProfile *viper.Viper +var vDefault *viper.Viper + +//====================================================================== + +func init() { + vDefault = viper.New() + vProfile = viper.New() +} + +//====================================================================== + +// First is error, second is warning +func ReadDefaultConfig(dir string) error { + return readConfig(vDefault, dir, "termshark") +} + +func readConfig(v *viper.Viper, dir string, base string) error { + confMutex.Lock() + defer confMutex.Unlock() + + var err error + + v.SetConfigName(base) // no need to include file extension - looks for file called termshark.ini for example + v.AddConfigPath(dir) + + fp := filepath.Join(dir, fmt.Sprintf("%s.toml", base)) + if f, err2 := os.OpenFile(fp, os.O_RDONLY|os.O_CREATE, 0666); err2 != nil { + err = fmt.Errorf("Warning: could not create initial config file: %w", err2) + } else { + f.Close() + } + + err = v.ReadInConfig() + if err != nil { + err = fmt.Errorf("Warning: config file %s not found...", fp) + } + + return err +} + +func ConfKeyExists(name string) bool { + return confKeyExists(vDefault, name) +} + +func confKeyExists(v *viper.Viper, name string) bool { + return v.Get(name) != nil +} + +func ConfString(name string, def string) string { + return confString(vDefault, name, def) +} + +func confString(v *viper.Viper, name string, def string) string { + confMutex.Lock() + defer confMutex.Unlock() + if v.Get(name) != nil { + return v.GetString(name) + } else { + return def + } +} + +func SetConf(name string, val interface{}) { + setConf(vDefault, name, val) +} + +func setConf(v *viper.Viper, name string, val interface{}) { + confMutex.Lock() + defer confMutex.Unlock() + v.Set(name, val) + v.WriteConfig() +} + +func ConfStrings(name string) []string { + return confStrings(vDefault, name) +} + +func confStrings(v *viper.Viper, name string) []string { + confMutex.Lock() + defer confMutex.Unlock() + return v.GetStringSlice(name) +} + +func DeleteConf(name string) { + deleteConf(vDefault, name) +} + +func deleteConf(v *viper.Viper, name string) { + confMutex.Lock() + defer confMutex.Unlock() + v.Set(name, "") + v.WriteConfig() +} + +func ConfInt(name string, def int) int { + return confInt(vDefault, name, def) +} + +func confInt(v *viper.Viper, name string, def int) int { + confMutex.Lock() + defer confMutex.Unlock() + if v.Get(name) != nil { + return v.GetInt(name) + } else { + return def + } +} + +func ConfBool(name string, def ...bool) bool { + return confBool(vDefault, name, def...) +} + +func confBool(v *viper.Viper, name string, def ...bool) bool { + confMutex.Lock() + defer confMutex.Unlock() + if v.Get(name) != nil { + return v.GetBool(name) + } else { + if len(def) > 0 { + return def[0] + } else { + return false + } + } +} + +func ConfStringSlice(name string, def []string) []string { + return confStringSlice(vDefault, name, def) +} + +func confStringSlice(v *viper.Viper, name string, def []string) []string { + confMutex.Lock() + defer confMutex.Unlock() + res := v.GetStringSlice(name) + if res == nil { + res = def + } + return res +} + +//====================================================================== +// Local Variables: +// mode: Go +// fill-column: 78 +// End: diff --git a/shark/columnformat.go b/shark/columnformat.go index 5fc772ab..0ea68a15 100644 --- a/shark/columnformat.go +++ b/shark/columnformat.go @@ -15,6 +15,7 @@ import ( "github.com/gcla/gowid/widgets/table" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" ) @@ -295,7 +296,7 @@ func GetPsmlColumnFormatFrom(colKey string) []PsmlColumnSpec { func getPsmlColumnFormatWithoutLock(colKey string) []PsmlColumnSpec { res := make([]PsmlColumnSpec, 0) - widths := termshark.ConfStringSlice(colKey, []string{}) + widths := profiles.ConfStringSlice(colKey, []string{}) if len(widths) == 0 || (len(widths)/3)*3 != len(widths) { logrus.Warnf("Unexpected %s structure - using defaults", colKey) res = DefaultPsmlColumnSpec diff --git a/ui/convsui.go b/ui/convsui.go index 1ea943d0..3f7f62e3 100644 --- a/ui/convsui.go +++ b/ui/convsui.go @@ -31,6 +31,7 @@ import ( "github.com/gcla/gowid/widgets/text" "github.com/gcla/gowid/widgets/vpadding" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/convs" "github.com/gcla/termshark/v2/pcap" "github.com/gcla/termshark/v2/psmlmodel" @@ -326,19 +327,19 @@ type ConvsUiWidget struct { } func (w *ConvsUiWidget) AbsoluteTime() bool { - return termshark.ConfBool("main.conv-absolute-time", false) + return profiles.ConfBool("main.conv-absolute-time", false) } func (w *ConvsUiWidget) SetAbsoluteTime(val bool) { - termshark.SetConf("main.conv-absolute-time", val) + profiles.SetConf("main.conv-absolute-time", val) } func (w *ConvsUiWidget) ResolveNames() bool { - return termshark.ConfBool("main.conv-resolve-names", false) + return profiles.ConfBool("main.conv-resolve-names", false) } func (w *ConvsUiWidget) SetResolveNames(val bool) { - termshark.SetConf("main.conv-resolve-names", val) + profiles.SetConf("main.conv-resolve-names", val) } func (w *ConvsUiWidget) Context() context.Context { @@ -350,11 +351,11 @@ func (w *ConvsUiWidget) FilterValue() string { } func (w *ConvsUiWidget) UseFilter() bool { - return termshark.ConfBool("main.conv-use-filter", false) + return profiles.ConfBool("main.conv-use-filter", false) } func (w *ConvsUiWidget) SetUseFilter(val bool) { - termshark.SetConf("main.conv-use-filter", val) + profiles.SetConf("main.conv-use-filter", val) } func (w *ConvsUiWidget) construct() { diff --git a/ui/lastline.go b/ui/lastline.go index 86b8af1d..3e584c95 100644 --- a/ui/lastline.go +++ b/ui/lastline.go @@ -16,6 +16,7 @@ import ( "github.com/gcla/gowid/gwutil" "github.com/gcla/gowid/vim" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/theme" "github.com/gcla/termshark/v2/widgets/mapkeys" "github.com/gcla/termshark/v2/widgets/minibuffer" @@ -184,7 +185,7 @@ func (s recentsArg) OfferCompletion() bool { func (s recentsArg) Completions() []string { matches := make([]string, 0) - cfiles := termshark.ConfStringSlice("main.recent-files", []string{}) + cfiles := profiles.ConfStringSlice("main.recent-files", []string{}) if cfiles != nil { for _, sc := range cfiles { scopy := sc @@ -212,7 +213,7 @@ func (s filterArg) OfferCompletion() bool { func (s filterArg) Completions() []string { matches := make([]string, 0) - cfiles := termshark.ConfStringSlice(s.field, []string{}) + cfiles := profiles.ConfStringSlice(s.field, []string{}) if cfiles != nil { for _, sc := range cfiles { scopy := sc @@ -325,33 +326,33 @@ func (d setCommand) Run(app gowid.IApp, args ...string) error { case "auto-scroll": if b, err = parseOnOff(args[2]); err == nil { AutoScroll = b - termshark.SetConf("main.auto-scroll", AutoScroll) + profiles.SetConf("main.auto-scroll", AutoScroll) OpenMessage(fmt.Sprintf("Packet auto-scroll is now %s", gwutil.If(b, "on", "off").(string)), appView, app) } case "copy-timeout": if i, err = strconv.ParseUint(args[2], 10, 32); err == nil { - termshark.SetConf("main.copy-command-timeout", i) + profiles.SetConf("main.copy-command-timeout", i) OpenMessage(fmt.Sprintf("Copy timeout is now %ds", i), appView, app) } case "dark-mode": if b, err = parseOnOff(args[2]); err == nil { DarkMode = b - termshark.SetConf("main.dark-mode", DarkMode) + profiles.SetConf("main.dark-mode", DarkMode) } case "disable-shark-fin": if b, err = strconv.ParseBool(args[2]); err == nil { - termshark.SetConf("main.disable-shark-fin", DarkMode) + profiles.SetConf("main.disable-shark-fin", DarkMode) OpenMessage(fmt.Sprintf("Shark-saver is now %s", gwutil.If(b, "off", "on").(string)), appView, app) } case "packet-colors": if b, err = parseOnOff(args[2]); err == nil { PacketColors = b - termshark.SetConf("main.packet-colors", PacketColors) + profiles.SetConf("main.packet-colors", PacketColors) OpenMessage(fmt.Sprintf("Packet colors are now %s", gwutil.If(b, "on", "off").(string)), appView, app) } case "suppress-tshark-errors": if b, err = parseOnOff(args[2]); err == nil { - termshark.SetConf("main.suppress-tshark-errors", b) + profiles.SetConf("main.suppress-tshark-errors", b) if b { OpenMessage("tshark errors will be suppressed.", appView, app) } else { @@ -360,11 +361,11 @@ func (d setCommand) Run(app gowid.IApp, args ...string) error { } case "term": if err = termshark.ValidateTerm(args[2]); err == nil { - termshark.SetConf("main.term", args[2]) + profiles.SetConf("main.term", args[2]) OpenMessage(fmt.Sprintf("Terminal type is now %s\n(Requires restart)", args[2]), appView, app) } case "pager": - termshark.SetConf("main.pager", args[2]) + profiles.SetConf("main.pager", args[2]) OpenMessage(fmt.Sprintf("Pager is now %s", args[2]), appView, app) default: err = invalidSetCommandErr @@ -372,10 +373,10 @@ func (d setCommand) Run(app gowid.IApp, args ...string) error { case 2: switch args[1] { case "noterm": - termshark.DeleteConf("main.term") + profiles.DeleteConf("main.term") OpenMessage("Terminal type is now unset\n(Requires restart)", appView, app) case "nopager": - termshark.DeleteConf("main.pager") + profiles.DeleteConf("main.pager") OpenMessage("Pager is now unset", appView, app) default: err = invalidSetCommandErr @@ -546,7 +547,7 @@ func (d themeCommand) Run(app gowid.IApp, args ...string) error { err = invalidThemeCommandErr } else { mode := theme.Mode(app.GetColorMode()).String() // more concise - termshark.SetConf(fmt.Sprintf("main.theme-%s", mode), args[1]) + profiles.SetConf(fmt.Sprintf("main.theme-%s", mode), args[1]) theme.Load(args[1], app) SetupColors() OpenMessage(fmt.Sprintf("Set %s theme for terminal mode %v.", args[1], app.GetColorMode()), appView, app) diff --git a/ui/logsui.go b/ui/logsui.go index 120c8763..f2ec5e0e 100644 --- a/ui/logsui.go +++ b/ui/logsui.go @@ -16,6 +16,7 @@ import ( "github.com/gcla/gowid/widgets/holder" "github.com/gcla/gowid/widgets/terminal" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/widgets/fileviewer" log "github.com/sirupsen/logrus" "github.com/spf13/viper" @@ -24,7 +25,7 @@ import ( //====================================================================== func pager() string { - res := termshark.ConfString("main.pager", "") + res := profiles.ConfString("main.pager", "") if res == "" { res = os.Getenv("PAGER") } diff --git a/ui/prochandlers.go b/ui/prochandlers.go index a861b394..4dc53a5c 100644 --- a/ui/prochandlers.go +++ b/ui/prochandlers.go @@ -14,6 +14,7 @@ import ( "github.com/gcla/gowid" "github.com/gcla/gowid/widgets/table" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/pcap" log "github.com/sirupsen/logrus" ) @@ -120,7 +121,7 @@ func (t updatePacketViews) OnError(code pcap.HandlerCode, app gowid.IApp, err er fmt.Fprintf(os.Stderr, "%v\n", err) RequestQuit() } else { - if !termshark.ConfBool("main.suppress-tshark-errors", false) { + if !profiles.ConfBool("main.suppress-tshark-errors", false) { var errstr string if kverr, ok := err.(gowid.KeyValueError); ok { errstr = fmt.Sprintf("%v\n\n", kverr.Cause()) @@ -153,7 +154,7 @@ func (t SimpleErrors) OnError(code pcap.HandlerCode, app gowid.IApp, err error) log.Error(err) // Hack to avoid picking up errors at other parts of the load // cycle. There should be specific handlers for specific errors. - if !termshark.ConfBool("main.suppress-tshark-errors", false) { + if !profiles.ConfBool("main.suppress-tshark-errors", false) { app.Run(gowid.RunFunction(func(app gowid.IApp) { OpenError(fmt.Sprintf("%v", err), app) })) @@ -372,7 +373,7 @@ func (s SetStructWidgets) OnError(code pcap.HandlerCode, app gowid.IApp, err err // Hack to avoid picking up errors at other parts of the load // cycle. There should be specific handlers for specific errors. if s.Ld.PdmlLoader.IsLoading() { - if !termshark.ConfBool("main.suppress-tshark-errors", false) { + if !profiles.ConfBool("main.suppress-tshark-errors", false) { app.Run(gowid.RunFunction(func(app gowid.IApp) { OpenLongError(fmt.Sprintf("%v", err), app) })) diff --git a/ui/psmlcols.go b/ui/psmlcols.go index fce49c68..3b4de195 100644 --- a/ui/psmlcols.go +++ b/ui/psmlcols.go @@ -25,7 +25,7 @@ import ( "github.com/gcla/gowid/widgets/styled" "github.com/gcla/gowid/widgets/table" "github.com/gcla/gowid/widgets/text" - "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/shark" "github.com/gcla/termshark/v2/shark/wiresharkcfg" "github.com/gcla/termshark/v2/ui/menuutil" @@ -224,7 +224,7 @@ func openEditColumns(app gowid.IApp) { } } - bakCols := termshark.ConfStringSlice("main.column-format-bak", []string{}) + bakCols := profiles.ConfStringSlice("main.column-format-bak", []string{}) if len(bakCols) != 0 { btn := button.New(text.New("Restore")) btn.OnClick(gowid.MakeWidgetCallback("cb", func(app gowid.IApp, widget gowid.IWidget) { @@ -299,12 +299,12 @@ func openEditColumns(app gowid.IApp) { } newcols := pcols.ToConfigList() - curcols := termshark.ConfStringSlice("main.column-format", []string{}) + curcols := profiles.ConfStringSlice("main.column-format", []string{}) updated := false if !reflect.DeepEqual(newcols, curcols) { - termshark.SetConf("main.column-format-bak", curcols) - termshark.SetConf("main.column-format", newcols) + profiles.SetConf("main.column-format-bak", curcols) + profiles.SetConf("main.column-format", newcols) updated = true } diff --git a/ui/searchbyfilter.go b/ui/searchbyfilter.go index 0364496a..f6a1567c 100644 --- a/ui/searchbyfilter.go +++ b/ui/searchbyfilter.go @@ -18,6 +18,7 @@ import ( "github.com/gcla/gowid" "github.com/gcla/gowid/widgets/table" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/format" "github.com/gcla/termshark/v2/pcap" "github.com/gcla/termshark/v2/widgets/search" @@ -384,8 +385,8 @@ func makePsmlCommand(filename string, displayFilter string) pcap.IPcapCommand { args = append(args, "-Y", displayFilter) } - psmlArgs := termshark.ConfStringSlice("main.psml-args", []string{}) - tsharkArgs := termshark.ConfStringSlice("main.tshark-args", []string{}) + psmlArgs := profiles.ConfStringSlice("main.psml-args", []string{}) + tsharkArgs := profiles.ConfStringSlice("main.tshark-args", []string{}) args = append(args, psmlArgs...) args = append(args, tsharkArgs...) diff --git a/ui/streamui.go b/ui/streamui.go index 55264766..f4516b66 100644 --- a/ui/streamui.go +++ b/ui/streamui.go @@ -19,6 +19,7 @@ import ( "github.com/gcla/gowid/widgets/null" "github.com/gcla/gowid/widgets/table" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/pcap" "github.com/gcla/termshark/v2/pdmltree" "github.com/gcla/termshark/v2/streams" @@ -339,7 +340,7 @@ func (t *streamParseHandler) OnError(code pcap.HandlerCode, app gowid.IApp, err if !Running { fmt.Fprintf(os.Stderr, "%v\n", err) RequestQuit() - } else if !termshark.ConfBool("main.suppress-tshark-errors", false) { + } else if !profiles.ConfBool("main.suppress-tshark-errors", false) { var errstr string if kverr, ok := err.(gowid.KeyValueError); ok { errstr = fmt.Sprintf("%v\n\n", kverr.Cause()) @@ -359,7 +360,7 @@ func (t *streamParseHandler) OnError(code pcap.HandlerCode, app gowid.IApp, err } func initStreamWidgetCache() { - widgetCacheSize := termshark.ConfInt("main.stream-cache-size", 100) + widgetCacheSize := profiles.ConfInt("main.stream-cache-size", 100) var err error streamWidgets, err = lru.New(widgetCacheSize) @@ -441,7 +442,7 @@ func makeStreamWidget(previousFilter string, filter string, cap string, proto st MenuOpener: &multiMenu1Opener, DefaultDisplay: func() streamwidget.DisplayFormat { view := streamwidget.Hex - choice := termshark.ConfString("main.stream-view", "hex") + choice := profiles.ConfString("main.stream-view", "hex") switch choice { case "raw": view = streamwidget.Raw diff --git a/ui/switchterm.go b/ui/switchterm.go index 5dacd2e9..ea5b223c 100644 --- a/ui/switchterm.go +++ b/ui/switchterm.go @@ -16,6 +16,7 @@ import ( "github.com/gcla/gowid/widgets/holder" "github.com/gcla/gowid/widgets/paragraph" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" ) //====================================================================== @@ -39,7 +40,7 @@ func SuggestSwitchingTerm(app gowid.IApp) { NoAsk := dialog.Button{ Msg: "No, don't ask", Action: gowid.MakeWidgetCallback("exec", gowid.WidgetChangedFunction(func(app gowid.IApp, w gowid.IWidget) { - termshark.SetConf("main.disable-term-helper", true) + profiles.SetConf("main.disable-term-helper", true) switchTerm.Close(app) })), } @@ -75,7 +76,7 @@ func IsTerminalLegible(app gowid.IApp) { YesSave := dialog.Button{ Msg: "Yes", Action: gowid.MakeWidgetCallback("exec", gowid.WidgetChangedFunction(func(app gowid.IApp, w gowid.IWidget) { - termshark.SetConf("main.term", os.Getenv("TERM")) + profiles.SetConf("main.term", os.Getenv("TERM")) saveTerm.Close(app) })), } diff --git a/ui/ui.go b/ui/ui.go index 187a01a2..0547e335 100644 --- a/ui/ui.go +++ b/ui/ui.go @@ -46,6 +46,7 @@ import ( "github.com/gcla/gowid/widgets/tree" "github.com/gcla/gowid/widgets/vpadding" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/pcap" "github.com/gcla/termshark/v2/pdmltree" "github.com/gcla/termshark/v2/psmlmodel" @@ -328,7 +329,7 @@ func columnNameFromShowname(showname string) string { } func useAsColumn(filter string, name string, app gowid.IApp) { - newCols := termshark.ConfStringSlice("main.column-format", []string{}) + newCols := profiles.ConfStringSlice("main.column-format", []string{}) colsBak := make([]string, len(newCols)) for i, col := range newCols { colsBak[i] = col @@ -340,8 +341,8 @@ func useAsColumn(filter string, name string, app gowid.IApp) { "true", ) - termshark.SetConf("main.column-format-bak", colsBak) - termshark.SetConf("main.column-format", newCols) + profiles.SetConf("main.column-format-bak", colsBak) + profiles.SetConf("main.column-format", newCols) RequestReload(app) } @@ -1222,7 +1223,7 @@ func openResultsAfterCopy(tmplName string, tocopy string, app gowid.IApp) { func processCopyChoices(copyLen int, app gowid.IApp) { var cc *dialog.Widget - copyCmd := termshark.ConfStringSlice( + copyCmd := profiles.ConfStringSlice( "main.copy-command", system.CopyToClipboard, ) @@ -1377,7 +1378,7 @@ func reallyQuit(app gowid.IApp) { // (a) Loader is in interface mode (b) User did not set -w flag // (c) always-keep-pcap setting is unset (def false) or false if Loader.InterfaceFile() != "" && !WriteToSelected && - !termshark.ConfBool("main.always-keep-pcap", false) { + !profiles.ConfBool("main.always-keep-pcap", false) { askToSave(app, func(app gowid.IApp) { RequestQuit() }) @@ -1415,7 +1416,7 @@ func lastLineMode(app gowid.IApp) { MiniBuffer.Register("no-theme", minibufferFn(func(app gowid.IApp, s ...string) error { mode := theme.Mode(app.GetColorMode()).String() // more concise - termshark.DeleteConf(fmt.Sprintf("main.theme-%s", mode)) + profiles.DeleteConf(fmt.Sprintf("main.theme-%s", mode)) theme.Load("default", app) SetupColors() OpenMessage(fmt.Sprintf("Cleared theme for terminal mode %v.", app.GetColorMode()), appView, app) @@ -2076,19 +2077,19 @@ func mainKeyPress(evk *tcell.EventKey, app gowid.IApp) bool { } else if isrune && evk.Rune() == '|' { if mainViewNoKeys.SubWidget() == mainview { mainViewNoKeys.SetSubWidget(altview1, app) - termshark.SetConf("main.layout", "altview1") + profiles.SetConf("main.layout", "altview1") } else if mainViewNoKeys.SubWidget() == altview1 { mainViewNoKeys.SetSubWidget(altview2, app) - termshark.SetConf("main.layout", "altview2") + profiles.SetConf("main.layout", "altview2") } else { mainViewNoKeys.SetSubWidget(mainview, app) - termshark.SetConf("main.layout", "mainview") + profiles.SetConf("main.layout", "mainview") } } else if isrune && evk.Rune() == '\\' { w := mainViewNoKeys.SubWidget() fp := gowid.FocusPath(w) if w == viewOnlyPacketList || w == viewOnlyPacketStructure || w == viewOnlyPacketHex { - switch termshark.ConfString("main.layout", "mainview") { + switch profiles.ConfString("main.layout", "mainview") { case "altview1": mainViewNoKeys.SetSubWidget(altview1, app) case "altview2": @@ -2505,7 +2506,7 @@ func ApplyAutoScroll(ev *tcell.EventKey, app gowid.IApp) bool { doit = true } if doit { - if termshark.ConfBool("main.auto-scroll", true) { + if profiles.ConfBool("main.auto-scroll", true) { AutoScroll = true reenableAutoScroll = true // when packet updates come, helps // understand that AutoScroll should not be disabled again @@ -2960,7 +2961,7 @@ func RequestLoadInterfaces(psrcs []pcap.IPacketSource, captureFilter string, dis // MaybeKeepThenRequestLoadPcap loads a pcap after first checking to see whether // the current load is a live load and the packets need to be kept. func MaybeKeepThenRequestLoadPcap(pcapf string, displayFilter string, jump termshark.GlobalJumpPos, app gowid.IApp) { - if Loader.InterfaceFile() != "" && !WriteToSelected && !termshark.ConfBool("main.always-keep-pcap", false) { + if Loader.InterfaceFile() != "" && !WriteToSelected && !profiles.ConfBool("main.always-keep-pcap", false) { askToSave(app, func(app gowid.IApp) { RequestLoadPcap(pcapf, displayFilter, jump, app) }) @@ -3085,7 +3086,7 @@ func progMax(x, y Prog) Prog { func makeRecentMenuWidget() (gowid.IWidget, int) { savedItems := make([]menuutil.SimpleMenuItem, 0) - cfiles := termshark.ConfStringSlice("main.recent-files", []string{}) + cfiles := profiles.ConfStringSlice("main.recent-files", []string{}) if cfiles != nil { for i, s := range cfiles { scopy := s @@ -3121,7 +3122,7 @@ var _ termshark.IPrefixCompleterCallback = (*savedCompleterCallback)(nil) func (s *savedCompleterCallback) Call(orig []string) { if s.prefix == "" { - comps := termshark.ConfStrings("main.recent-filters") + comps := profiles.ConfStrings("main.recent-filters") if len(comps) == 0 { comps = orig } @@ -3220,7 +3221,7 @@ func Build() (*gowid.App, error) { var err error var app *gowid.App - widgetCacheSize := termshark.ConfInt("main.ui-cache-size", 1000) + widgetCacheSize := profiles.ConfInt("main.ui-cache-size", 1000) if widgetCacheSize < 64 { widgetCacheSize = 64 } @@ -3345,7 +3346,7 @@ func Build() (*gowid.App, error) { CB: func(app gowid.IApp, w gowid.IWidget) { multiMenu1Opener.CloseMenu(generalMenu, app) DarkMode = !DarkMode - termshark.SetConf("main.dark-mode", DarkMode) + profiles.SetConf("main.dark-mode", DarkMode) }, }, menuutil.MakeMenuDivider(), @@ -3480,7 +3481,7 @@ func Build() (*gowid.App, error) { CB: func(app gowid.IApp, w gowid.IWidget) { multiMenu1Opener.CloseMenu(generalMenu, app) PacketColors = !PacketColors - termshark.SetConf("main.packet-colors", PacketColors) + profiles.SetConf("main.packet-colors", PacketColors) }, }, }, @@ -4122,7 +4123,7 @@ func Build() (*gowid.App, error) { altview2 = altview2OuterRows mainViewNoKeys = holder.New(mainview) - defaultLayout := termshark.ConfString("main.layout", "") + defaultLayout := profiles.ConfString("main.layout", "") switch defaultLayout { case "altview1": mainViewNoKeys = holder.New(altview1) @@ -4175,7 +4176,7 @@ func Build() (*gowid.App, error) { // For minibuffer mbView = holder.New(appViewWithKeys) - if !termshark.ConfBool("main.disable-shark-fin", false) { + if !profiles.ConfBool("main.disable-shark-fin", false) { Fin = rossshark.New(mbView) steerableFin := appkeys.NewMouse( diff --git a/ui/wormhole.go b/ui/wormhole.go index ca400f35..16a7012d 100644 --- a/ui/wormhole.go +++ b/ui/wormhole.go @@ -11,7 +11,7 @@ import ( "github.com/gcla/gowid" "github.com/gcla/gowid/widgets/dialog" "github.com/gcla/gowid/widgets/framed" - "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/widgets/wormhole" log "github.com/sirupsen/logrus" ) @@ -24,7 +24,7 @@ func openWormhole(app gowid.IApp) { var numWords int if CurrentWormholeWidget == nil { - numWords = termshark.ConfInt("main.wormhole-length", 2) + numWords = profiles.ConfInt("main.wormhole-length", 2) } else { numWords = CurrentWormholeWidget.CodeLength() } @@ -38,8 +38,8 @@ func openWormhole(app gowid.IApp) { OpenError(msg, app) }, CodeLength: numWords, - TransitRelayAddress: termshark.ConfString("main.wormhole-transit-relay", ""), - RendezvousURL: termshark.ConfString("main.wormhole-rendezvous-url", ""), + TransitRelayAddress: profiles.ConfString("main.wormhole-transit-relay", ""), + RendezvousURL: profiles.ConfString("main.wormhole-rendezvous-url", ""), }) if err != nil { msg := fmt.Sprintf("%v", err) diff --git a/utils.go b/utils.go index 76571dd2..f07ffe01 100644 --- a/utils.go +++ b/utils.go @@ -37,6 +37,7 @@ import ( "github.com/gcla/gowid/gwutil" "github.com/gcla/gowid/vim" "github.com/gcla/gowid/widgets/table" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/system" "github.com/gcla/termshark/v2/widgets/resizable" "github.com/gdamore/tcell/v2" @@ -46,7 +47,6 @@ import ( "github.com/pkg/errors" "github.com/shibukawa/configdir" log "github.com/sirupsen/logrus" - "github.com/spf13/viper" "github.com/tevino/abool" ) @@ -140,81 +140,6 @@ func ReverseStringSlice(s []string) { //====================================================================== -// The config is accessed by the main goroutine and pcap loading goroutines. So this -// is an attempt to prevent warnings with the -race flag (though they are very likely -// harmless) -var confMutex sync.Mutex - -func ConfKeyExists(name string) bool { - return viper.Get(name) != nil -} - -func ConfString(name string, def string) string { - confMutex.Lock() - defer confMutex.Unlock() - if viper.Get(name) != nil { - return viper.GetString(name) - } else { - return def - } -} - -func SetConf(name string, val interface{}) { - confMutex.Lock() - defer confMutex.Unlock() - viper.Set(name, val) - viper.WriteConfig() -} - -func ConfStrings(name string) []string { - confMutex.Lock() - defer confMutex.Unlock() - return viper.GetStringSlice(name) -} - -func DeleteConf(name string) { - confMutex.Lock() - defer confMutex.Unlock() - viper.Set(name, "") - viper.WriteConfig() -} - -func ConfInt(name string, def int) int { - confMutex.Lock() - defer confMutex.Unlock() - if viper.Get(name) != nil { - return viper.GetInt(name) - } else { - return def - } -} - -func ConfBool(name string, def ...bool) bool { - confMutex.Lock() - defer confMutex.Unlock() - if viper.Get(name) != nil { - return viper.GetBool(name) - } else { - if len(def) > 0 { - return def[0] - } else { - return false - } - } -} - -func ConfStringSlice(name string, def []string) []string { - confMutex.Lock() - defer confMutex.Unlock() - res := viper.GetStringSlice(name) - if res == nil { - res = def - } - return res -} - -//====================================================================== - var TSharkVersionUnknown = fmt.Errorf("Could not determine version of tshark") func TSharkVersionFromOutput(output string) (semver.Version, error) { @@ -254,7 +179,7 @@ func TSharkSupportsColor(tshark string) (bool, error) { // TSharkPath will return the full path of the tshark binary, if it's found in the path, otherwise an error func TSharkPath() (string, *gowid.KeyValueError) { - tsharkBin := ConfString("main.tshark", "") + tsharkBin := profiles.ConfString("main.tshark", "") if tsharkBin != "" { confirmedTshark := false if _, err := os.Stat(tsharkBin); err == nil { @@ -343,7 +268,7 @@ func CacheDir() string { func PcapDir() string { var res string // If use-tshark-temp-for-cache is set, use that - if ConfBool("main.use-tshark-temp-for-pcap-cache", false) { + if profiles.ConfBool("main.use-tshark-temp-for-pcap-cache", false) { tmp, err := TsharkSetting("Temp") if err == nil { res = tmp @@ -351,7 +276,7 @@ func PcapDir() string { } // Otherwise try the user's preference if res == "" { - res = ConfString("main.pcap-cache-dir", "") + res = profiles.ConfString("main.pcap-cache-dir", "") } if res == "" { res = DefaultPcapDir() @@ -366,15 +291,15 @@ func DefaultPcapDir() string { } func TSharkBin() string { - return ConfString("main.tshark", "tshark") + return profiles.ConfString("main.tshark", "tshark") } func DumpcapBin() string { - return ConfString("main.dumpcap", "dumpcap") + return profiles.ConfString("main.dumpcap", "dumpcap") } func CapinfosBin() string { - return ConfString("main.capinfos", "capinfos") + return profiles.ConfString("main.capinfos", "capinfos") } // CaptureBin is the binary the user intends to use to capture @@ -391,9 +316,9 @@ func CapinfosBin() string { // it switches to capture mode. func CaptureBin() string { if runtime.GOOS == "windows" { - return ConfString("main.capture-command", DumpcapBin()) + return profiles.ConfString("main.capture-command", DumpcapBin()) } else { - return ConfString("main.capture-command", os.Args[0]) + return profiles.ConfString("main.capture-command", os.Args[0]) } } @@ -420,7 +345,7 @@ func TailCommand() []string { if runtime.GOOS == "windows" { def = []string{os.Args[0], "--tail"} } - return ConfStringSlice("main.tail-command", def) + return profiles.ConfStringSlice("main.tail-command", def) } func KeyPressIsPrintable(key gowid.IKey) bool { @@ -456,7 +381,7 @@ func RemoveKeyMapping(kp vim.KeyPress) { } func LoadKeyMappings() []KeyMapping { - mappings := ConfStringSlice("main.key-mappings", []string{}) + mappings := profiles.ConfStringSlice("main.key-mappings", []string{}) res := make([]KeyMapping, 0) for _, mapping := range mappings { pair := strings.Split(mapping, " ") @@ -484,7 +409,7 @@ func SaveKeyMappings(mappings []KeyMapping) { for _, mapping := range mappings { ser = append(ser, fmt.Sprintf("%v %v", mapping.From, vim.KeySequence(mapping.To))) } - SetConf("main.key-mappings", ser) + profiles.SetConf("main.key-mappings", ser) } func RemoveFromStringSlice(pcap string, comps []string) []string { @@ -664,12 +589,12 @@ func SafePid(p IProcess) int { } func SetConvTypes(convs []string) { - SetConf("main.conv-types", convs) + profiles.SetConf("main.conv-types", convs) } func ConvTypes() []string { defs := []string{"eth", "ip", "ipv6", "tcp", "udp"} - ctypes := ConfStrings("main.conv-types") + ctypes := profiles.ConfStrings("main.conv-types") if len(ctypes) > 0 { z, ok := arrayOperations.Intersect(defs, ctypes) if ok { @@ -683,13 +608,13 @@ func ConvTypes() []string { } func AddToRecentFiles(pcap string) { - comps := ConfStrings("main.recent-files") + comps := profiles.ConfStrings("main.recent-files") if len(comps) == 0 || comps[0] != pcap { comps = RemoveFromStringSlice(pcap, comps) if len(comps) > 16 { comps = comps[0 : 16-1] } - SetConf("main.recent-files", comps) + profiles.SetConf("main.recent-files", comps) } } @@ -698,18 +623,18 @@ func AddToRecentFilters(val string) { } func addToRecent(field string, val string) { - comps := ConfStrings(field) + comps := profiles.ConfStrings(field) if (len(comps) == 0 || comps[0] != val) && strings.TrimSpace(val) != "" { comps = RemoveFromStringSlice(val, comps) if len(comps) > 64 { comps = comps[0 : 64-1] } - SetConf(field, comps) + profiles.SetConf(field, comps) } } func LoadOffsetFromConfig(name string) ([]resizable.Offset, error) { - offsStr := ConfString("main."+name, "") + offsStr := profiles.ConfString("main."+name, "") if offsStr == "" { return nil, errors.WithStack(gowid.WithKVs(ConfigErr, map[string]interface{}{ "name": name, @@ -735,16 +660,16 @@ func SaveOffsetToConfig(name string, offsets2 []resizable.Offset) { } } if len(offsets) == 0 { - DeleteConf("main." + name) + profiles.DeleteConf("main." + name) } else { offs, err := json.Marshal(offsets) if err != nil { log.Fatal(err) } - SetConf("main."+name, string(offs)) + profiles.SetConf("main."+name, string(offs)) } // Hack to make viper save if I only deleted from the map - SetConf("main.lastupdate", time.Now().String()) + profiles.SetConf("main.lastupdate", time.Now().String()) } //====================================================================== @@ -771,7 +696,7 @@ type globalJumpPosMapping struct { } func LoadGlobalMarks(m map[rune]GlobalJumpPos) error { - marksStr := ConfString("main.marks", "") + marksStr := profiles.ConfString("main.marks", "") if marksStr == "" { return nil } @@ -798,16 +723,16 @@ func SaveGlobalMarks(m map[rune]GlobalJumpPos) { marks = append(marks, globalJumpPosMapping{Key: k, GlobalJumpPos: v}) } if len(marks) == 0 { - DeleteConf("main.marks") + profiles.DeleteConf("main.marks") } else { marksJ, err := json.Marshal(marks) if err != nil { log.Fatal(err) } - SetConf("main.marks", string(marksJ)) + profiles.SetConf("main.marks", string(marksJ)) } // Hack to make viper save if I only deleted from the map - SetConf("main.lastupdate", time.Now().String()) + profiles.SetConf("main.lastupdate", time.Now().String()) } //====================================================================== @@ -922,7 +847,7 @@ func PrunePcapCache() error { // assume the cache can grow indefinitely - in case users are now relying on this // to keep old pcaps around. I don't want to delete any files without the user's // explicit permission. - var diskCacheSize int64 = int64(ConfInt("main.disk-cache-size-mb", -1)) + var diskCacheSize int64 = int64(profiles.ConfInt("main.disk-cache-size-mb", -1)) if diskCacheSize == -1 { log.Infof("No pcap disk cache size set. Skipping cache pruning.") @@ -1245,7 +1170,7 @@ func ApplyArguments(cmd []string, args []string) ([]string, int) { } func BrowseUrl(url string) error { - urlCmd := ConfStringSlice( + urlCmd := profiles.ConfStringSlice( "main.browse-command", system.OpenURL, ) @@ -1304,7 +1229,7 @@ type ICommandWaitTicker interface { func CopyCommand(input io.Reader, cb interface{}) error { var err error - copyCmd := ConfStringSlice( + copyCmd := profiles.ConfStringSlice( "main.copy-command", system.CopyToClipboard, ) @@ -1318,7 +1243,7 @@ func CopyCommand(input io.Reader, cb interface{}) error { outBuf := bytes.Buffer{} cmd.Stdout = &outBuf - cmdTimeout := ConfInt("main.copy-command-timeout", 5) + cmdTimeout := profiles.ConfInt("main.copy-command-timeout", 5) if err := cmd.Start(); err != nil { return errors.WithStack(gowid.WithKVs(BadCommand, map[string]interface{}{"err": err})) } diff --git a/widgets/search/search.go b/widgets/search/search.go index 512eeef2..b9096138 100644 --- a/widgets/search/search.go +++ b/widgets/search/search.go @@ -27,6 +27,7 @@ import ( "github.com/gcla/gowid/widgets/styled" "github.com/gcla/gowid/widgets/text" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/ui/menuutil" "github.com/gcla/termshark/v2/widgets/filter" "github.com/gcla/termshark/v2/widgets/ifwidget" @@ -298,7 +299,7 @@ func units(n int) gowid.RenderWithUnits { } func getSearchType() string { - res := termshark.ConfString("main.search-type", "filter") + res := profiles.ConfString("main.search-type", "filter") if _, ok := searchTypeMap[res]; !ok { res = "filter" } @@ -306,7 +307,7 @@ func getSearchType() string { } func getSearchTarget() string { - res := termshark.ConfString("main.search-target", "list") + res := profiles.ConfString("main.search-target", "list") if _, ok := searchTargetMap[res]; !ok { res = "list" } @@ -583,11 +584,11 @@ func (w *Widget) Value() string { } func (w *Widget) CaseSensitive() bool { - return termshark.ConfBool("main.search-case-sensitive", false) + return profiles.ConfBool("main.search-case-sensitive", false) } func (w *Widget) SetCaseSensitive(val bool) { - termshark.SetConf("main.search-case-sensitive", val) + profiles.SetConf("main.search-case-sensitive", val) } func (w *Widget) Open(app gowid.IApp) { @@ -686,7 +687,7 @@ func buildSearchTypeMenu(btn *button.Widget, men menu.IOpener, res *Widget) *men btn.SetSubWidget(text.New(searchTypeMap[stype]), app) // Save the default search type - termshark.SetConf("main.search-type", stype) + profiles.SetConf("main.search-type", stype) res.validator = getValidator() @@ -703,7 +704,7 @@ func buildSearchTypeMenu(btn *button.Widget, men menu.IOpener, res *Widget) *men switch stype { case "hex": - termshark.SetConf("main.search-target", "bytes") + profiles.SetConf("main.search-target", "bytes") } // read main.search-type and adjust which search algorithm to use @@ -729,9 +730,9 @@ func buildSearchTypeMenu(btn *button.Widget, men menu.IOpener, res *Widget) *men func (w *Widget) updateSearchTargetFromConf(app gowid.IApp) { - sAlg := termshark.ConfString("main.search-type", "filter") + sAlg := profiles.ConfString("main.search-type", "filter") if sAlg != "filter" && sAlg != "hex" { - sAlg = termshark.ConfString("main.search-target", "list") + sAlg = profiles.ConfString("main.search-target", "list") } switch sAlg { @@ -780,7 +781,7 @@ func buildSearchTargetMenu(btn *button.Widget, men menu.IOpener, res *Widget) *m Key: gowid.MakeKey('1' + rune(i)), CB: func(app gowid.IApp, _ gowid.IWidget) { - termshark.SetConf("main.search-target", target) + profiles.SetConf("main.search-target", target) btn.SetSubWidget(text.New(searchTargetMap[target]), app) diff --git a/widgets/streamwidget/streamwidget.go b/widgets/streamwidget/streamwidget.go index 85552694..8bead612 100644 --- a/widgets/streamwidget/streamwidget.go +++ b/widgets/streamwidget/streamwidget.go @@ -36,6 +36,7 @@ import ( "github.com/gcla/gowid/widgets/table" "github.com/gcla/gowid/widgets/text" "github.com/gcla/termshark/v2" + "github.com/gcla/termshark/v2/configs/profiles" "github.com/gcla/termshark/v2/format" "github.com/gcla/termshark/v2/streams" "github.com/gcla/termshark/v2/ui/menuutil" @@ -416,7 +417,7 @@ func (w *Widget) construct() { for i := 0; i < len(w.tblWidgets); i++ { w.updateChunkModel(i, w.displayAs, app) } - termshark.SetConf("main.stream-view", "hex") + profiles.SetConf("main.stream-view", "hex") } }}) rb2.OnClick(gowid.WidgetCallback{"cb", func(app gowid.IApp, w2 gowid.IWidget) { @@ -425,7 +426,7 @@ func (w *Widget) construct() { for i := 0; i < len(w.tblWidgets); i++ { w.updateChunkModel(i, w.displayAs, app) } - termshark.SetConf("main.stream-view", "ascii") + profiles.SetConf("main.stream-view", "ascii") } }}) rb3.OnClick(gowid.WidgetCallback{"cb", func(app gowid.IApp, w2 gowid.IWidget) { @@ -434,7 +435,7 @@ func (w *Widget) construct() { for i := 0; i < len(w.tblWidgets); i++ { w.updateChunkModel(i, w.displayAs, app) } - termshark.SetConf("main.stream-view", "raw") + profiles.SetConf("main.stream-view", "raw") } }})