Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 37 additions & 9 deletions internal/book/chapters.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package book

import (
"encoding/xml"
"os"
"path/filepath"
"sort"
"strings"
Expand All @@ -10,7 +11,8 @@ import (
// Chapter marks the first page of a chapter.
type Chapter struct {
Title string
Page int
Page int // zero-based
Depth int // zero-based outline level
}

type comicInfo struct {
Expand All @@ -22,23 +24,49 @@ type comicInfo struct {
} `xml:"Pages"`
}

// Chapters returns EPUB headings/document titles, ComicInfo.xml bookmarks,
// or top-level archive folder markers. Metadata errors do not fall back to folders.
// Chapters returns document outlines, headings, comic bookmarks or folder markers.
// PDF and DJVU extraction runs once and stops when the book closes.
func (b *Book) Chapters() ([]Chapter, error) {
b.chapOnce.Do(func() {
b.chaps, b.chapErr = b.comicInfoChapters()
b.mu.Lock()
if b.closed {
b.mu.Unlock()
b.chapErr = os.ErrClosed
return
}
ctx, arc := b.contextLocked(), b.arc
b.mu.Unlock()
if len(b.pages) > 0 {
if p, ok := b.pages[0].(toolPage); ok {
b.chaps, b.chapErr = p.chapters(ctx, b.Len())
return
}
}
b.chaps, b.chapErr = b.comicInfoChapters(arc)
if b.chaps == nil && b.chapErr == nil {
b.chaps = b.folderChapters()
}
})
return b.chaps, b.chapErr
}

func (b *Book) comicInfoChapters() ([]Chapter, error) {
if b.arc == nil {
// CurrentChapter returns the nearest preceding destination, regardless of outline order.
// Later entries win ties, so a subsection takes precedence over its parent.
func CurrentChapter(chapters []Chapter, page int) int {
current := -1
for i, c := range chapters {
if c.Page <= page && (current < 0 || c.Page >= chapters[current].Page) {
current = i
}
}
return current
}

func (b *Book) comicInfoChapters(arc archive) ([]Chapter, error) {
if arc == nil {
return nil, nil
}
for _, f := range b.arc.Entries() {
for _, f := range arc.Entries() {
if !strings.EqualFold(filepath.Base(f.Name()), "comicinfo.xml") {
continue
}
Expand All @@ -58,12 +86,12 @@ func (b *Book) comicInfoChapters() ([]Chapter, error) {
}
var chs []Chapter
for _, p := range ci.Pages.Page {
if p.Bookmark == "" || p.Image < 0 || p.Image >= len(b.pages) {
if strings.TrimSpace(p.Bookmark) == "" || p.Image < 0 || p.Image >= len(b.pages) {
continue
}
chs = append(chs, Chapter{Title: p.Bookmark, Page: p.Image})
}
sort.Slice(chs, func(i, j int) bool { return chs[i].Page < chs[j].Page })
sort.SliceStable(chs, func(i, j int) bool { return chs[i].Page < chs[j].Page })
return chs, nil
}
return nil, nil
Expand Down
Loading
Loading