Skip to content

Commit

Permalink
fix: NPE when delete item and clear search;
Browse files Browse the repository at this point in the history
  • Loading branch information
MapoMagpie committed May 21, 2024
1 parent af8e93a commit 3ab4842
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 52 deletions.
72 changes: 43 additions & 29 deletions core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,27 +41,29 @@ func Start(opts *Options) {

// 添加菜单
menuNameAdd := tui.Menu{Name: "Add", Cb: func(m *tui.Model) (cmd tea.Cmd) {
if len(m.Inputs) > 0 {
file, err := m.CurrFile()
if err != nil {
log.Fatalf("add to dict error: %v", err)
return
}
raw := strings.TrimSpace(strings.Join(m.Inputs, ""))
if raw == "" {
return
}
pair := dict.ParseInput(raw)
if pair[1] != "" {
filePath := file.String()
dc.ResetMatcher()
dc.Add(dict.NewEntryAdd([]byte(strings.Join(pair[:], "\t")), filePath))
log.Printf("add item: %s\n", pair)
m.Inputs = []string{}
m.InputCursor = 0
FlushAndSync(opts, dc, opts.SyncOnChange)
}
if len(m.Inputs) == 0 {
return tui.ExitMenuCmd
}
file, err := m.CurrFile()
if err != nil {
log.Fatalf("add to dict error: %v", err)
return
}
raw := strings.TrimSpace(strings.Join(m.Inputs, ""))
if raw == "" {
return
}
pair := dict.ParseInput(raw)
if pair[1] == "" {
return tui.ExitMenuCmd
}
filePath := file.String()
dc.Add(dict.NewEntryAdd([]byte(strings.Join(pair[:], "\t")), filePath))
log.Printf("add item: %s\n", pair)
m.Inputs = strings.Split(pair[1], "")
m.InputCursor = len(m.Inputs)
dc.ResetMatcher()
FlushAndSync(opts, dc, opts.SyncOnChange)
return tui.ExitMenuCmd
}}

Expand All @@ -75,9 +77,9 @@ func Start(opts *Options) {
}
switch item := item.(type) {
case *dict.MatchResult:
dc.ResetMatcher()
dc.Delete(item.Entry)
log.Printf("delete item: %s\n", item)
dc.ResetMatcher()
FlushAndSync(opts, dc, opts.SyncOnChange)
}
return tui.ExitMenuCmd
Expand All @@ -103,12 +105,17 @@ func Start(opts *Options) {
// 确认修改菜单
menuNameConfirm := tui.Menu{Name: "Confirm", Cb: func(m *tui.Model) tea.Cmd {
m.Modifying = false
str := strings.Join(m.Inputs, "")
raw := strings.Join(m.Inputs, "")
switch item := modifyingItem.(type) {
case *dict.MatchResult:
log.Printf("modify confirm item: %s\n", item)
pair := dict.ParseInput(raw)
if pair[1] != "" {
item.Entry.ReRaw([]byte(strings.Join(pair[:], "\t")))
m.Inputs = strings.Split(pair[1], "")
m.InputCursor = len(m.Inputs)
}
dc.ResetMatcher()
item.Entry.ReRaw([]byte(str))
FlushAndSync(opts, dc, opts.SyncOnChange)
}
return tui.ExitMenuCmd
Expand Down Expand Up @@ -153,13 +160,20 @@ func Start(opts *Options) {
searchChan := make(chan string, 20)
listManager := tui.NewListManager(searchChan)
listManager.SetFiles(fileNames)
model := tui.NewModel(listManager, menuFetcher, tui.MoveEvent, tui.EnterEvent, tui.ClearInputEvent, exitEvent, exportDictEvent)
events := []*tui.Event{
tui.MoveEvent,
tui.EnterEvent,
tui.ClearInputEvent,
exitEvent,
exportDictEvent,
}
model := tui.NewModel(listManager, menuFetcher, events...)
teaProgram := tea.NewProgram(model)

go func() {
var cancelFunc context.CancelFunc
ch := make(chan []*dict.MatchResult)
timer := time.NewTicker(time.Millisecond * 100)
resultChan := make(chan []*dict.MatchResult)
timer := time.NewTicker(time.Millisecond * 100) // debounce
hasAppend := false
for {
select {
Expand All @@ -177,8 +191,8 @@ func Start(opts *Options) {
rs = []rune(pair[1])
}
}
go dc.Search(rs, ch, ctx)
case ret := <-ch:
go dc.Search(rs, resultChan, ctx)
case ret := <-resultChan:
if len(ret) > 0 {
list := make([]tui.ItemRender, len(ret))
for i, entry := range ret {
Expand All @@ -187,7 +201,7 @@ func Start(opts *Options) {
listManager.AppendList(list)
hasAppend = true
}
case <-timer.C:
case <-timer.C: // debounce, if appended then flush
if hasAppend {
hasAppend = false
teaProgram.Send(tui.FreshListMsg(0))
Expand Down
2 changes: 1 addition & 1 deletion core/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
"github.com/goccy/go-yaml"
)

var version = "1.0.5"
var version = "1.0.6"

type Options struct {
RestartRimeCmd string `yaml:"restart_rime_cmd"`
Expand Down
53 changes: 38 additions & 15 deletions dict/dictionary.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"log"
"strconv"
"strings"
"time"

Expand All @@ -12,25 +13,27 @@ import (

type Dictionary struct {
matcher Matcher
entries []*Entry
fileEntries []*FileEntries
}

func NewDictionary(fes []*FileEntries, matcher Matcher) *Dictionary {
if matcher == nil {
matcher = &CacheMatcher{}
}
entries := make([]*Entry, 0)
for _, fe := range fes {
entries = append(entries, fe.Entries...)
}
return &Dictionary{
fileEntries: fes,
matcher: matcher,
entries: entries,
fileEntries: fes,
}
}

func (d *Dictionary) Entries() []*Entry {
entries := make([]*Entry, 0)
for _, fe := range d.fileEntries {
entries = append(entries, fe.Entries...)
}
return entries
return d.entries
}

func (d *Dictionary) Search(key []rune, resultChan chan<- []*MatchResult, ctx context.Context) {
Expand All @@ -41,14 +44,19 @@ func (d *Dictionary) Search(key []rune, resultChan chan<- []*MatchResult, ctx co
done = true
}()
list := d.Entries()
deleteCount := 0
ret := make([]*MatchResult, len(list))
for i, entry := range list {
if done {
return
}
ret[i] = &MatchResult{Entry: entry}
if entry.IsDelete() {
deleteCount += 1
continue
}
ret[i-deleteCount] = &MatchResult{Entry: entry}
}
resultChan <- ret
resultChan <- ret[0 : len(ret)-deleteCount]
} else {
d.matcher.Search(key, d.Entries(), resultChan, ctx)
}
Expand All @@ -60,6 +68,7 @@ func (d *Dictionary) Add(entry *Entry) {
fe.Entries = append(fe.Entries, entry)
}
}
d.entries = append(d.entries, entry)
}

func (d *Dictionary) Delete(entry *Entry) {
Expand All @@ -71,11 +80,7 @@ func (d *Dictionary) ResetMatcher() {
}

func (d *Dictionary) Len() int {
le := 0
for _, fe := range d.fileEntries {
le = le + len(fe.Entries)
}
return le
return len(d.entries)
}

func (d *Dictionary) Flush() {
Expand Down Expand Up @@ -110,6 +115,7 @@ type Entry struct {
rawSize int64
modType ModifyType
log bool
Weight int
}

func (e *Entry) ReRaw(raw []byte) {
Expand All @@ -119,6 +125,10 @@ func (e *Entry) ReRaw(raw []byte) {
e.modType = MODIFY
}
e.log = true
e.Weight = 1
if len(e.Pair) >= 3 {
e.Weight, _ = strconv.Atoi(string(e.Pair[2]))
}
}

func (e *Entry) Delete() {
Expand Down Expand Up @@ -172,6 +182,7 @@ func ParseInput(raw string) (pair [3]string) {
if isAscii(item) {
pair[1] = item
} else {
// 表(汉字)的输入可能包含空格,类似 "富强 强国",因此在splited后重新拼接起来。
space := " "
if pair[0] == "" {
space = ""
Expand Down Expand Up @@ -224,21 +235,33 @@ func ParsePair(raw []byte) [][]byte {
}

func NewEntry(raw []byte, refFile string, seek int64, size int64) *Entry {
pair := ParsePair(raw)
weight := 1
if len(pair) >= 3 {
weight, _ = strconv.Atoi(string(pair[2]))
}
return &Entry{
text: util.ToChars(raw),
Pair: ParsePair(raw),
Pair: pair,
refFile: refFile,
seek: seek,
rawSize: size,
Weight: weight,
}
}

func NewEntryAdd(raw []byte, refFile string) *Entry {
pair := ParsePair(raw)
weight := 1
if len(pair) >= 3 {
weight, _ = strconv.Atoi(string(pair[2]))
}
return &Entry{
text: util.ToChars(raw),
Pair: ParsePair(raw),
Pair: pair,
refFile: refFile,
modType: ADD,
log: true,
Weight: weight,
}
}
8 changes: 4 additions & 4 deletions dict/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func (m *MatchResult) String() string {

func (m *MatchResult) Order() int {
score := m.result.Score
score = score * (200 - m.Entry.text.Length())
score = score * (200 * m.Entry.Weight) * (1000 - m.Entry.text.Length())
return score
}

Expand Down Expand Up @@ -73,13 +73,13 @@ func (m *CacheMatcher) Search(key []rune, list []*Entry, resultChan chan<- []*Ma
listLen := len(list)
chunkSize := 50000 // chunkSize = listLen means no async search
for idx, entry := range list {
if done {
return
}
if entry.modType == DELETE {
continue
}
result, _ := algo.FuzzyMatchV2(false, true, true, &entry.text, key, false, slab)
if done {
return
}
if result.Score > 0 {
matched = append(matched, &MatchResult{entry, result})
}
Expand Down
5 changes: 2 additions & 3 deletions tui/tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package tui
import (
"errors"
"fmt"
"log"
"os"
"sort"
"strings"
Expand Down Expand Up @@ -79,9 +78,9 @@ func (l *ListManager) NewList() {
}

func (l *ListManager) newSearch(inputs []string) {
log.Printf("send search key: %v", strings.Join(inputs, ""))
// log.Printf("send search key: %v", strings.Join(inputs, ""))
l.SearchChan <- strings.Join(inputs, "")
log.Printf("send search key finshed")
// log.Printf("send search key finshed")
}

func (l *ListManager) AppendList(rs []ItemRender) {
Expand Down

0 comments on commit 3ab4842

Please sign in to comment.