-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
file.go
2054 lines (1825 loc) · 53 KB
/
file.go
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
// SiYuan - Refactor your thinking
// Copyright (c) 2020-present, b3log.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package model
import (
"bytes"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/88250/go-humanize"
"github.com/88250/gulu"
"github.com/88250/lute"
"github.com/88250/lute/ast"
"github.com/88250/lute/html"
"github.com/88250/lute/parse"
util2 "github.com/88250/lute/util"
"github.com/facette/natsort"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/riff"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/search"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
type File struct {
Path string `json:"path"`
Name string `json:"name"` // 标题,即 ial["title"]
Icon string `json:"icon"`
Name1 string `json:"name1"` // 命名,即 ial["name"]
Alias string `json:"alias"`
Memo string `json:"memo"`
Bookmark string `json:"bookmark"`
ID string `json:"id"`
Count int `json:"count"`
Size uint64 `json:"size"`
HSize string `json:"hSize"`
Mtime int64 `json:"mtime"`
CTime int64 `json:"ctime"`
HMtime string `json:"hMtime"`
HCtime string `json:"hCtime"`
Sort int `json:"sort"`
SubFileCount int `json:"subFileCount"`
Hidden bool `json:"hidden"`
NewFlashcardCount int `json:"newFlashcardCount"`
DueFlashcardCount int `json:"dueFlashcardCount"`
FlashcardCount int `json:"flashcardCount"`
}
func (box *Box) docFromFileInfo(fileInfo *FileInfo, ial map[string]string) (ret *File) {
ret = &File{}
ret.Path = fileInfo.path
ret.Size = uint64(fileInfo.size)
ret.Name = ial["title"] + ".sy"
ret.Icon = ial["icon"]
ret.ID = ial["id"]
ret.Name1 = ial["name"]
ret.Alias = ial["alias"]
ret.Memo = ial["memo"]
ret.Bookmark = ial["bookmark"]
t, _ := time.ParseInLocation("20060102150405", ret.ID[:14], time.Local)
ret.CTime = t.Unix()
ret.HCtime = t.Format("2006-01-02 15:04:05") + ", " + util.HumanizeTime(t, Conf.Lang)
ret.HSize = humanize.BytesCustomCeil(ret.Size, 2)
mTime := t
if updated := ial["updated"]; "" != updated {
if updatedTime, err := time.ParseInLocation("20060102150405", updated, time.Local); nil == err {
mTime = updatedTime
}
}
ret.Mtime = mTime.Unix()
ret.HMtime = mTime.Format("2006-01-02 15:04:05") + ", " + util.HumanizeTime(mTime, Conf.Lang)
return
}
func (box *Box) docIAL(p string) (ret map[string]string) {
name := strings.ToLower(filepath.Base(p))
if !strings.HasSuffix(name, ".sy") {
return nil
}
ret = cache.GetDocIAL(p)
if nil != ret {
return ret
}
filePath := filepath.Join(util.DataDir, box.ID, p)
data, err := filelock.ReadFile(filePath)
if util.IsCorruptedSYData(data) {
box.moveCorruptedData(filePath)
return nil
}
if nil != err {
logging.LogErrorf("read file [%s] failed: %s", p, err)
return nil
}
ret = filesys.ReadDocIAL(data)
if 1 > len(ret) {
logging.LogWarnf("tree [%s] is corrupted", filePath)
box.moveCorruptedData(filePath)
return nil
}
cache.PutDocIAL(p, ret)
return ret
}
func (box *Box) moveCorruptedData(filePath string) {
base := filepath.Base(filePath)
to := filepath.Join(util.WorkspaceDir, "corrupted", time.Now().Format("2006-01-02-150405"), box.ID, base)
if copyErr := filelock.Copy(filePath, to); nil != copyErr {
logging.LogErrorf("copy corrupted data file [%s] failed: %s", filePath, copyErr)
return
}
if removeErr := filelock.Remove(filePath); nil != removeErr {
logging.LogErrorf("remove corrupted data file [%s] failed: %s", filePath, removeErr)
return
}
logging.LogWarnf("moved corrupted data file [%s] to [%s]", filePath, to)
}
func SearchDocsByKeyword(keyword string, flashcard bool) (ret []map[string]string) {
ret = []map[string]string{}
var deck *riff.Deck
var deckBlockIDs []string
if flashcard {
deck = Decks[builtinDeckID]
if nil == deck {
return
}
deckBlockIDs = deck.GetBlockIDs()
}
openedBoxes := Conf.GetOpenedBoxes()
boxes := map[string]*Box{}
for _, box := range openedBoxes {
boxes[box.ID] = box
}
var rootBlocks []*sql.Block
if "" != keyword {
for _, box := range boxes {
if strings.Contains(box.Name, keyword) {
if flashcard {
newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)
if 0 < flashcardCount {
ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon, "newFlashcardCount": strconv.Itoa(newFlashcardCount), "dueFlashcardCount": strconv.Itoa(dueFlashcardCount), "flashcardCount": strconv.Itoa(flashcardCount)})
}
} else {
ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon})
}
}
}
condition := "hpath LIKE '%" + keyword + "%'"
if "" != keyword {
namCondition := Conf.Search.NAMFilter(keyword)
if "" != namCondition {
condition += " " + namCondition
}
}
rootBlocks = sql.QueryRootBlockByCondition(condition)
} else {
for _, box := range boxes {
if flashcard {
newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)
if 0 < flashcardCount {
ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon, "newFlashcardCount": strconv.Itoa(newFlashcardCount), "dueFlashcardCount": strconv.Itoa(dueFlashcardCount), "flashcardCount": strconv.Itoa(flashcardCount)})
}
} else {
ret = append(ret, map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon})
}
}
}
for _, rootBlock := range rootBlocks {
b := boxes[rootBlock.Box]
if nil == b {
continue
}
hPath := b.Name + rootBlock.HPath
if flashcard {
newFlashcardCount, dueFlashcardCount, flashcardCount := countTreeFlashcard(rootBlock.ID, deck, deckBlockIDs)
if 0 < flashcardCount {
ret = append(ret, map[string]string{"path": rootBlock.Path, "hPath": hPath, "box": rootBlock.Box, "boxIcon": b.Icon, "newFlashcardCount": strconv.Itoa(newFlashcardCount), "dueFlashcardCount": strconv.Itoa(dueFlashcardCount), "flashcardCount": strconv.Itoa(flashcardCount)})
}
} else {
ret = append(ret, map[string]string{"path": rootBlock.Path, "hPath": hPath, "box": rootBlock.Box, "boxIcon": b.Icon})
}
}
sort.Slice(ret, func(i, j int) bool {
return ret[i]["hPath"] < ret[j]["hPath"]
})
return
}
type FileInfo struct {
path string
name string
size int64
isdir bool
}
func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden bool, maxListCount int) (ret []*File, totals int, err error) {
//os.MkdirAll("pprof", 0755)
//cpuProfile, _ := os.Create("pprof/cpu_profile_list_doc_tree")
//pprof.StartCPUProfile(cpuProfile)
//defer pprof.StopCPUProfile()
ret = []*File{}
var deck *riff.Deck
var deckBlockIDs []string
if flashcard {
deck = Decks[builtinDeckID]
if nil == deck {
return
}
deckBlockIDs = deck.GetBlockIDs()
}
box := Conf.Box(boxID)
if nil == box {
return nil, 0, errors.New(Conf.Language(0))
}
boxConf := box.GetConf()
if util.SortModeUnassigned == sortMode {
sortMode = Conf.FileTree.Sort
if util.SortModeFileTree != boxConf.SortMode {
sortMode = boxConf.SortMode
}
}
var files []*FileInfo
start := time.Now()
files, totals, err = box.Ls(listPath)
if nil != err {
return
}
elapsed := time.Now().Sub(start).Milliseconds()
if 100 < elapsed {
logging.LogWarnf("ls elapsed [%dms]", elapsed)
}
start = time.Now()
boxLocalPath := filepath.Join(util.DataDir, box.ID)
var docs []*File
for _, file := range files {
if file.isdir {
if !ast.IsNodeIDPattern(file.name) {
continue
}
parentDocPath := strings.TrimSuffix(file.path, "/") + ".sy"
parentDocFile := box.Stat(parentDocPath)
if nil == parentDocFile {
continue
}
if ial := box.docIAL(parentDocPath); nil != ial {
if !showHidden && "true" == ial["custom-hidden"] {
continue
}
doc := box.docFromFileInfo(parentDocFile, ial)
subFiles, err := os.ReadDir(filepath.Join(boxLocalPath, file.path))
if nil == err {
for _, subFile := range subFiles {
subDocFilePath := path.Join(file.path, subFile.Name())
if subIAL := box.docIAL(subDocFilePath); "true" == subIAL["custom-hidden"] {
continue
}
if strings.HasSuffix(subFile.Name(), ".sy") {
doc.SubFileCount++
}
}
}
if flashcard {
rootID := strings.TrimSuffix(filepath.Base(parentDocPath), ".sy")
newFlashcardCount, dueFlashcardCount, flashcardCount := countTreeFlashcard(rootID, deck, deckBlockIDs)
if 0 < flashcardCount {
doc.NewFlashcardCount = newFlashcardCount
doc.DueFlashcardCount = dueFlashcardCount
doc.FlashcardCount = flashcardCount
docs = append(docs, doc)
}
} else {
docs = append(docs, doc)
}
}
continue
}
subFolder := filepath.Join(boxLocalPath, strings.TrimSuffix(file.path, ".sy"))
if gulu.File.IsDir(subFolder) {
continue
}
if ial := box.docIAL(file.path); nil != ial {
if !showHidden && "true" == ial["custom-hidden"] {
continue
}
doc := box.docFromFileInfo(file, ial)
if flashcard {
rootID := strings.TrimSuffix(filepath.Base(file.path), ".sy")
newFlashcardCount, dueFlashcardCount, flashcardCount := countTreeFlashcard(rootID, deck, deckBlockIDs)
if 0 < flashcardCount {
doc.NewFlashcardCount = newFlashcardCount
doc.DueFlashcardCount = dueFlashcardCount
doc.FlashcardCount = flashcardCount
docs = append(docs, doc)
}
} else {
docs = append(docs, doc)
}
}
}
elapsed = time.Now().Sub(start).Milliseconds()
if 500 < elapsed {
logging.LogWarnf("build docs [%d] elapsed [%dms]", len(docs), elapsed)
}
start = time.Now()
refCount := sql.QueryRootBlockRefCount()
for _, doc := range docs {
if count := refCount[doc.ID]; 0 < count {
doc.Count = count
}
}
elapsed = time.Now().Sub(start).Milliseconds()
if 500 < elapsed {
logging.LogWarnf("query root block ref count elapsed [%dms]", elapsed)
}
start = time.Now()
switch sortMode {
case util.SortModeNameASC:
sort.Slice(docs, func(i, j int) bool {
return util.PinYinCompare(util.RemoveEmojiInvisible(docs[i].Name), util.RemoveEmojiInvisible(docs[j].Name))
})
case util.SortModeNameDESC:
sort.Slice(docs, func(i, j int) bool {
return util.PinYinCompare(util.RemoveEmojiInvisible(docs[j].Name), util.RemoveEmojiInvisible(docs[i].Name))
})
case util.SortModeUpdatedASC:
sort.Slice(docs, func(i, j int) bool { return docs[i].Mtime < docs[j].Mtime })
case util.SortModeUpdatedDESC:
sort.Slice(docs, func(i, j int) bool { return docs[i].Mtime > docs[j].Mtime })
case util.SortModeAlphanumASC:
sort.Slice(docs, func(i, j int) bool {
return natsort.Compare(util.RemoveEmojiInvisible(docs[i].Name), util.RemoveEmojiInvisible(docs[j].Name))
})
case util.SortModeAlphanumDESC:
sort.Slice(docs, func(i, j int) bool {
return natsort.Compare(util.RemoveEmojiInvisible(docs[j].Name), util.RemoveEmojiInvisible(docs[i].Name))
})
case util.SortModeCustom:
fileTreeFiles := docs
box.fillSort(&fileTreeFiles)
sort.Slice(fileTreeFiles, func(i, j int) bool {
if fileTreeFiles[i].Sort == fileTreeFiles[j].Sort {
return util.TimeFromID(fileTreeFiles[i].ID) > util.TimeFromID(fileTreeFiles[j].ID)
}
return fileTreeFiles[i].Sort < fileTreeFiles[j].Sort
})
ret = append(ret, fileTreeFiles...)
totals = len(ret)
if maxListCount < len(ret) {
ret = ret[:maxListCount]
}
ret = ret[:]
return
case util.SortModeRefCountASC:
sort.Slice(docs, func(i, j int) bool { return docs[i].Count < docs[j].Count })
case util.SortModeRefCountDESC:
sort.Slice(docs, func(i, j int) bool { return docs[i].Count > docs[j].Count })
case util.SortModeCreatedASC:
sort.Slice(docs, func(i, j int) bool { return docs[i].CTime < docs[j].CTime })
case util.SortModeCreatedDESC:
sort.Slice(docs, func(i, j int) bool { return docs[i].CTime > docs[j].CTime })
case util.SortModeSizeASC:
sort.Slice(docs, func(i, j int) bool { return docs[i].Size < docs[j].Size })
case util.SortModeSizeDESC:
sort.Slice(docs, func(i, j int) bool { return docs[i].Size > docs[j].Size })
case util.SortModeSubDocCountASC:
sort.Slice(docs, func(i, j int) bool { return docs[i].SubFileCount < docs[j].SubFileCount })
case util.SortModeSubDocCountDESC:
sort.Slice(docs, func(i, j int) bool { return docs[i].SubFileCount > docs[j].SubFileCount })
}
if util.SortModeCustom != sortMode {
ret = append(ret, docs...)
}
totals = len(ret)
if maxListCount < len(ret) {
ret = ret[:maxListCount]
}
ret = ret[:]
elapsed = time.Now().Sub(start).Milliseconds()
if 200 < elapsed {
logging.LogInfof("sort docs elapsed [%dms]", elapsed)
}
return
}
func ContentStat(content string) (ret *util.BlockStatResult) {
luteEngine := util.NewLute()
return contentStat(content, luteEngine)
}
func contentStat(content string, luteEngine *lute.Lute) (ret *util.BlockStatResult) {
tree := luteEngine.BlockDOM2Tree(content)
runeCnt, wordCnt, linkCnt, imgCnt, refCnt := tree.Root.Stat()
return &util.BlockStatResult{
RuneCount: runeCnt,
WordCount: wordCnt,
LinkCount: linkCnt,
ImageCount: imgCnt,
RefCount: refCnt,
}
}
func BlocksWordCount(ids []string) (ret *util.BlockStatResult) {
ret = &util.BlockStatResult{}
trees := map[string]*parse.Tree{} // 缓存
luteEngine := util.NewLute()
for _, id := range ids {
bt := treenode.GetBlockTree(id)
if nil == bt {
continue
}
tree := trees[bt.RootID]
if nil == tree {
tree, _ = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
if nil == tree {
continue
}
trees[bt.RootID] = tree
}
node := treenode.GetNodeInTree(tree, id)
if nil == node {
continue
}
runeCnt, wordCnt, linkCnt, imgCnt, refCnt := node.Stat()
ret.RuneCount += runeCnt
ret.WordCount += wordCnt
ret.LinkCount += linkCnt
ret.ImageCount += imgCnt
ret.RefCount += refCnt
}
return
}
func StatTree(id string) (ret *util.BlockStatResult) {
WaitForWritingFiles()
tree, _ := LoadTreeByBlockID(id)
if nil == tree {
return
}
var databaseBlockNodes []*ast.Node
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || ast.NodeAttributeView != n.Type {
return ast.WalkContinue
}
databaseBlockNodes = append(databaseBlockNodes, n)
return ast.WalkContinue
})
luteEngine := util.NewLute()
var dbRuneCnt, dbWordCnt, dbLinkCnt, dbImgCnt, dbRefCnt int
for _, n := range databaseBlockNodes {
if "" == n.AttributeViewID {
continue
}
attrView, _ := av.ParseAttributeView(n.AttributeViewID)
if nil == attrView {
continue
}
content := bytes.Buffer{}
for _, kValues := range attrView.KeyValues {
for _, v := range kValues.Values {
switch kValues.Key.Type {
case av.KeyTypeURL:
if v.IsEmpty() {
continue
}
dbLinkCnt++
content.WriteString(v.URL.Content)
case av.KeyTypeMAsset:
if v.IsEmpty() {
continue
}
for _, asset := range v.MAsset {
if av.AssetTypeImage == asset.Type {
dbImgCnt++
}
}
case av.KeyTypeBlock:
if v.IsEmpty() {
continue
}
if !v.IsDetached {
dbRefCnt++
}
content.WriteString(v.Block.Content)
case av.KeyTypeText:
if v.IsEmpty() {
continue
}
content.WriteString(v.Text.Content)
case av.KeyTypeNumber:
if v.IsEmpty() {
continue
}
v.Number.FormatNumber()
content.WriteString(v.Number.FormattedContent)
case av.KeyTypeEmail:
if v.IsEmpty() {
continue
}
content.WriteString(v.Email.Content)
case av.KeyTypePhone:
if v.IsEmpty() {
continue
}
content.WriteString(v.Phone.Content)
}
}
}
dbStat := contentStat(content.String(), luteEngine)
dbRuneCnt += dbStat.RuneCount
dbWordCnt += dbStat.WordCount
}
runeCnt, wordCnt, linkCnt, imgCnt, refCnt := tree.Root.Stat()
runeCnt += dbRuneCnt
wordCnt += dbWordCnt
linkCnt += dbLinkCnt
imgCnt += dbImgCnt
refCnt += dbRefCnt
return &util.BlockStatResult{
RuneCount: runeCnt,
WordCount: wordCnt,
LinkCount: linkCnt,
ImageCount: imgCnt,
RefCount: refCnt,
}
}
func GetDoc(startID, endID, id string, index int, query string, queryTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool) (blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxID, docPath string, isBacklinkExpand bool, err error) {
//os.MkdirAll("pprof", 0755)
//cpuProfile, _ := os.Create("pprof/GetDoc")
//pprof.StartCPUProfile(cpuProfile)
//defer pprof.StopCPUProfile()
WaitForWritingFiles() // 写入数据时阻塞,避免获取到的数据不一致
inputIndex := index
tree, err := LoadTreeByBlockID(id)
if nil != err {
if ErrBlockNotFound == err {
if 0 == mode {
err = ErrTreeNotFound // 初始化打开文档时如果找不到则关闭编辑器
}
}
return
}
if nil == tree {
err = ErrBlockNotFound
return
}
luteEngine := NewLute()
node := treenode.GetNodeInTree(tree, id)
if nil == node {
// Unable to open the doc when the block pointed by the scroll position does not exist https://github.com/siyuan-note/siyuan/issues/9030
node = treenode.GetNodeInTree(tree, tree.Root.ID)
if nil == node {
err = ErrBlockNotFound
return
}
}
if isBacklink { // 引用计数浮窗请求,需要按照反链逻辑组装 https://github.com/siyuan-note/siyuan/issues/6853
if ast.NodeParagraph == node.Type {
if nil != node.Parent && ast.NodeListItem == node.Parent.Type {
node = node.Parent
}
}
}
located := false
isDoc := ast.NodeDocument == node.Type
isHeading := ast.NodeHeading == node.Type
boxID = node.Box
docPath = node.Path
if isDoc {
if 4 == mode { // 加载文档末尾
node = node.LastChild
located = true
// 重新计算 index
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
index++
return ast.WalkContinue
})
} else {
node = node.FirstChild
}
typ = ast.NodeDocument.String()
idx := 0
if 0 < index {
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || !n.IsChildBlockOf(tree.Root, 1) {
return ast.WalkContinue
}
idx++
if index == idx {
node = n.DocChild()
if "1" == node.IALAttr("heading-fold") {
// 加载到折叠标题下方块的话需要回溯到上方标题块
for h := node.Previous; nil != h; h = h.Previous {
if "1" == h.IALAttr("fold") {
node = h
break
}
}
}
located = true
return ast.WalkStop
}
return ast.WalkContinue
})
}
} else {
if 0 == index && 0 != mode {
// 非文档且没有指定 index 时需要计算 index
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
index++
if id == n.ID {
node = n.DocChild()
located = true
return ast.WalkStop
}
return ast.WalkContinue
})
}
}
if 1 < index && !located {
count := 0
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
count++
if index == count {
node = n.DocChild()
return ast.WalkStop
}
return ast.WalkContinue
})
}
blockCount = tree.DocBlockCount()
if ast.NodeDocument == node.Type {
parentID = node.ID
parent2ID = parentID
} else {
parentID = node.Parent.ID
parent2ID = parentID
tmp := node
if ast.NodeListItem == node.Type {
// 列表项聚焦返回和面包屑保持一致 https://github.com/siyuan-note/siyuan/issues/4914
tmp = node.Parent
}
if headingParent := treenode.HeadingParent(tmp); nil != headingParent {
parent2ID = headingParent.ID
}
}
rootID = tree.Root.ID
if !isDoc {
typ = node.Type.String()
}
// 判断是否需要显示动态加载滚动条 https://github.com/siyuan-note/siyuan/issues/7693
childCount := 0
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if 1 > childCount {
childCount = 1
} else {
childCount += treenode.CountBlockNodes(n)
}
if childCount > Conf.Editor.DynamicLoadBlocks {
scroll = true
return ast.WalkStop
}
return ast.WalkContinue
})
var nodes []*ast.Node
if isBacklink {
// 引用计数浮窗请求,需要按照反链逻辑组装 https://github.com/siyuan-note/siyuan/issues/6853
nodes, isBacklinkExpand = getBacklinkRenderNodes(node)
} else {
// 如果同时存在 startID 和 endID,并且是动态加载的情况,则只加载 startID 和 endID 之间的块 [startID, endID]
if "" != startID && "" != endID && scroll {
nodes, eof = loadNodesByStartEnd(tree, startID, endID)
if 1 > len(nodes) {
// 按 mode 加载兜底
nodes, eof = loadNodesByMode(node, inputIndex, mode, size, isDoc, isHeading)
} else {
// 文档块没有指定 index 时需要计算 index,否则初次打开文档时 node-index 会为 0,导致首次 Ctrl+Home 无法回到顶部
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
index++
if nodes[0].ID == n.ID {
return ast.WalkStop
}
return ast.WalkContinue
})
}
} else {
nodes, eof = loadNodesByMode(node, inputIndex, mode, size, isDoc, isHeading)
}
}
refCount := sql.QueryRootChildrenRefCount(rootID)
virtualBlockRefKeywords := getBlockVirtualRefKeywords(tree.Root)
subTree := &parse.Tree{ID: rootID, Root: &ast.Node{Type: ast.NodeDocument}, Marks: tree.Marks}
var keywords []string
if "" != query && (0 == queryMethod || 1 == queryMethod) { // 只有关键字搜索和查询语法搜索才支持高亮
if 0 == queryMethod {
query = stringQuery(query)
}
typeFilter := buildTypeFilter(queryTypes)
keywords = highlightByQuery(query, typeFilter, rootID)
}
for _, n := range nodes {
var unlinks []*ast.Node
ast.Walk(n, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if "1" == n.IALAttr("heading-fold") {
// 折叠标题下被引用的块无法悬浮查看
// The referenced block under the folded heading cannot be hovered to view https://github.com/siyuan-note/siyuan/issues/9582
if (0 != mode && id != n.ID) || isDoc {
unlinks = append(unlinks, n)
return ast.WalkContinue
}
}
if avs := n.IALAttr(av.NodeAttrNameAvs); "" != avs {
// 填充属性视图角标 Display the database title on the block superscript https://github.com/siyuan-note/siyuan/issues/10545
avNames := getAvNames(n.IALAttr(av.NodeAttrNameAvs))
if "" != avNames {
n.SetIALAttr(av.NodeAttrViewNames, avNames)
}
}
if "" != n.ID {
// 填充块引计数
if cnt := refCount[n.ID]; 0 < cnt {
n.SetIALAttr("refcount", strconv.Itoa(cnt))
}
}
if 0 < len(keywords) {
hitBlock := false
for p := n.Parent; nil != p; p = p.Parent {
if p.ID == id {
hitBlock = true
break
}
}
if hitBlock {
if ast.NodeCodeBlockCode == n.Type && !treenode.IsChartCodeBlockCode(n) {
// 支持代码块搜索定位 https://github.com/siyuan-note/siyuan/issues/5520
code := string(n.Tokens)
markedCode := search.EncloseHighlighting(code, keywords, search.SearchMarkLeft, search.SearchMarkRight, Conf.Search.CaseSensitive, false)
if code != markedCode {
n.Tokens = gulu.Str.ToBytes(markedCode)
return ast.WalkContinue
}
} else if markReplaceSpan(n, &unlinks, keywords, search.MarkDataType, luteEngine) {
return ast.WalkContinue
}
}
}
if processVirtualRef(n, &unlinks, virtualBlockRefKeywords, refCount, luteEngine) {
return ast.WalkContinue
}
return ast.WalkContinue
})
for _, unlink := range unlinks {
unlink.Unlink()
}
subTree.Root.AppendChild(n)
}
luteEngine.RenderOptions.NodeIndexStart = index
dom = luteEngine.Tree2BlockDOM(subTree, luteEngine.RenderOptions)
SetRecentDocByTree(tree)
return
}
func loadNodesByStartEnd(tree *parse.Tree, startID, endID string) (nodes []*ast.Node, eof bool) {
node := treenode.GetNodeInTree(tree, startID)
if nil == node {
return
}
nodes = append(nodes, node)
for n := node.Next; nil != n; n = n.Next {
if treenode.IsInFoldedHeading(n, nil) {
continue
}
nodes = append(nodes, n)
if n.ID == endID {
if next := n.Next; nil == next {
eof = true
} else {
eof = util2.IsDocIAL(n.Tokens) || util2.IsDocIAL(next.Tokens)
}
break
}
}
return
}
func loadNodesByMode(node *ast.Node, inputIndex, mode, size int, isDoc, isHeading bool) (nodes []*ast.Node, eof bool) {
if 2 == mode /* 向下 */ {
next := node.Next
if ast.NodeHeading == node.Type && "1" == node.IALAttr("fold") {
// 标题展开时进行动态加载导致重复内容 https://github.com/siyuan-note/siyuan/issues/4671
// 这里要考虑折叠标题是最后一个块的情况
if children := treenode.HeadingChildren(node); 0 < len(children) {
next = children[len(children)-1].Next
}
}
if nil == next {
eof = true
} else {
eof = util2.IsDocIAL(node.Tokens) || util2.IsDocIAL(next.Tokens)
}
}
count := 0
switch mode {
case 0: // 仅加载当前 ID
nodes = append(nodes, node)
if isDoc {
for n := node.Next; nil != n; n = n.Next {
if treenode.IsInFoldedHeading(n, nil) {
continue
}
nodes = append(nodes, n)
if 1 > count {
count++
} else {
count += treenode.CountBlockNodes(n)
}
if size < count {
break
}
}
} else if isHeading {
level := node.HeadingLevel
for n := node.Next; nil != n; n = n.Next {
if treenode.IsInFoldedHeading(n, node) {
// 大纲点击折叠标题跳转聚焦 https://github.com/siyuan-note/siyuan/issues/4920
// 多级标题折叠后上级块引浮窗中未折叠 https://github.com/siyuan-note/siyuan/issues/4997
continue
}
if ast.NodeHeading == n.Type {
if n.HeadingLevel <= level {
break
}
}
nodes = append(nodes, n)
count++
if size < count {
break
}
}
}
case 4: // Ctrl+End 跳转到末尾后向上加载
for n := node; nil != n; n = n.Previous {
if treenode.IsInFoldedHeading(n, nil) {
continue
}
nodes = append([]*ast.Node{n}, nodes...)
if 1 > count {
count++
} else {
count += treenode.CountBlockNodes(n)
}
if size < count {
break
}
}
eof = true
case 1: // 向上加载
for n := node.Previous; /* 从上一个节点开始加载 */ nil != n; n = n.Previous {
if treenode.IsInFoldedHeading(n, nil) {
continue
}
nodes = append([]*ast.Node{n}, nodes...)
if 1 > count {
count++
} else {
count += treenode.CountBlockNodes(n)
}
if size < count {
break
}
}
eof = nil == node.Previous