Adopt common v0.8.0 and preserve canceled hardware settings
This commit is contained in:
1 parent
b21fceb311
commit
5dfa038706
410 files changed
+5353
-4803
No files matched your search
@@ -53,7 +53,7 @@ func (request CaptureRequest) Validate() error {
|
||||
}
|
||||
switch request.Kind {
|
||||
case ObjectSource:
|
||||
if !valid_screen_rectangle(request.Bounds) {
|
||||
if !validScreenRectangle(request.Bounds) {
|
||||
return ErrSource
|
||||
}
|
||||
case WindowSource, DesktopSource, ClipboardSource:
|
||||
@@ -120,14 +120,14 @@ func (capturer *Capturer) Capture(ctx context.Context, request CaptureRequest) (
|
||||
if err != nil {
|
||||
return Capture{}, ErrSource
|
||||
}
|
||||
output, _, err := run_process(ctx, capturer.command, input, maxImageBytes+maxCaptureHeader, "--ocr-capture")
|
||||
output, _, err := runProcess(ctx, capturer.command, input, maxImageBytes+maxCaptureHeader, "--ocr-capture")
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrUnavailable) || errors.Is(err, ErrRecognition) {
|
||||
return Capture{}, ErrCapture
|
||||
}
|
||||
return Capture{}, err
|
||||
}
|
||||
capture, err := decode_capture(output, request)
|
||||
capture, err := decodeCapture(output, request)
|
||||
if ctx.Err() != nil {
|
||||
return Capture{}, ctx.Err()
|
||||
}
|
||||
@@ -157,10 +157,10 @@ func WriteCaptureResponse(output io.Writer, header CaptureHeader, pixels image.I
|
||||
if err != nil || len(data)+1 > maxCaptureHeader {
|
||||
return ErrLimit
|
||||
}
|
||||
buffer := &bounded_buffer{ctx: context.Background(), limit: maxImageBytes + maxCaptureHeader}
|
||||
buffer := &boundedBuffer{ctx: context.Background(), limit: maxImageBytes + maxCaptureHeader}
|
||||
_, _ = buffer.Write(append(data, '\n'))
|
||||
if header.Status == "" {
|
||||
if pixels == nil || !valid_dimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) {
|
||||
if pixels == nil || !validDimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
if err := png.Encode(buffer, pixels); err != nil {
|
||||
@@ -171,7 +171,7 @@ func WriteCaptureResponse(output io.Writer, header CaptureHeader, pixels image.I
|
||||
return err
|
||||
}
|
||||
|
||||
func decode_capture(data []byte, request CaptureRequest) (Capture, error) {
|
||||
func decodeCapture(data []byte, request CaptureRequest) (Capture, error) {
|
||||
separator := bytes.IndexByte(data, '\n')
|
||||
if separator < 0 || separator >= maxCaptureHeader || len(data) > maxImageBytes+maxCaptureHeader {
|
||||
return Capture{}, ErrCapture
|
||||
@@ -204,7 +204,7 @@ func decode_capture(data []byte, request CaptureRequest) (Capture, error) {
|
||||
if err != nil {
|
||||
return Capture{}, ErrCapture
|
||||
}
|
||||
if !valid_dimensions(config.Width, config.Height) {
|
||||
if !validDimensions(config.Width, config.Height) {
|
||||
return Capture{}, ErrLimit
|
||||
}
|
||||
transform := Transform{ImageContent: image.Rect(0, 0, config.Width, config.Height)}
|
||||
@@ -213,8 +213,8 @@ func decode_capture(data []byte, request CaptureRequest) (Capture, error) {
|
||||
return Capture{}, ErrCapture
|
||||
}
|
||||
} else {
|
||||
if !valid_screen_rectangle(header.RootBounds) || !valid_screen_rectangle(header.SourceBounds) ||
|
||||
!valid_screen_rectangle(header.ScreenBounds) || !header.ScreenBounds.In(header.RootBounds) || !header.ScreenBounds.In(header.SourceBounds) ||
|
||||
if !validScreenRectangle(header.RootBounds) || !validScreenRectangle(header.SourceBounds) ||
|
||||
!validScreenRectangle(header.ScreenBounds) || !header.ScreenBounds.In(header.RootBounds) || !header.ScreenBounds.In(header.SourceBounds) ||
|
||||
header.ScreenBounds.Dx() != config.Width || header.ScreenBounds.Dy() != config.Height {
|
||||
return Capture{}, ErrCapture
|
||||
}
|
||||
|
||||
@@ -24,11 +24,11 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func capture_request() CaptureRequest {
|
||||
func captureRequest() CaptureRequest {
|
||||
return CaptureRequest{Kind: ObjectSource, Bounds: image.Rect(-20, 10, 30, 50), Foreground: 123, Generation: 7}
|
||||
}
|
||||
|
||||
func capture_frame(t *testing.T, header CaptureHeader, pixels image.Image) []byte {
|
||||
func captureFrame(t *testing.T, header CaptureHeader, pixels image.Image) []byte {
|
||||
t.Helper()
|
||||
var output bytes.Buffer
|
||||
if err := WriteCaptureResponse(&output, header, pixels); err != nil {
|
||||
@@ -38,7 +38,7 @@ func capture_frame(t *testing.T, header CaptureHeader, pixels image.Image) []byt
|
||||
}
|
||||
|
||||
func TestCaptureRequestRejectsUnownedOrInvalidSources(t *testing.T) {
|
||||
base := capture_request()
|
||||
base := captureRequest()
|
||||
if err := base.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -80,20 +80,20 @@ func TestCaptureRequestRejectsUnownedOrInvalidSources(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCaptureFrameClippingAndGeneration(t *testing.T) {
|
||||
request := capture_request()
|
||||
request := captureRequest()
|
||||
header := CaptureHeader{Request: request, SourceWindow: request.Foreground,
|
||||
RootBounds: image.Rect(0, 0, 100, 100), SourceBounds: image.Rect(-10, 0, 80, 80), ScreenBounds: image.Rect(0, 10, 30, 50)}
|
||||
pixels := image.NewRGBA(image.Rect(0, 0, 30, 40))
|
||||
pixels.Set(1, 2, color.RGBA{12, 34, 56, 255})
|
||||
frame := capture_frame(t, header, pixels)
|
||||
result, err := decode_capture(frame, request)
|
||||
frame := captureFrame(t, header, pixels)
|
||||
result, err := decodeCapture(frame, request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if color.RGBAModel.Convert(result.Pixels.At(1, 2)) != pixels.At(1, 2) {
|
||||
t.Fatal("pixels changed")
|
||||
}
|
||||
if _, err := decode_capture(append(append([]byte(nil), frame...), 'x'), request); !errors.Is(err, ErrCapture) {
|
||||
if _, err := decodeCapture(append(append([]byte(nil), frame...), 'x'), request); !errors.Is(err, ErrCapture) {
|
||||
t.Fatalf("trailing payload accepted: %v", err)
|
||||
}
|
||||
mapped, ok := result.Transform.ScreenRectangle(image.Rect(1, 2, 3, 4))
|
||||
@@ -101,7 +101,7 @@ func TestCaptureFrameClippingAndGeneration(t *testing.T) {
|
||||
t.Fatalf("mapping: %v, %v", mapped, ok)
|
||||
}
|
||||
request.Generation++
|
||||
if _, err := decode_capture(frame, request); !errors.Is(err, ErrCapture) {
|
||||
if _, err := decodeCapture(frame, request); !errors.Is(err, ErrCapture) {
|
||||
t.Fatalf("old generation accepted: %v", err)
|
||||
}
|
||||
request.Generation--
|
||||
@@ -113,7 +113,7 @@ func TestCaptureFrameClippingAndGeneration(t *testing.T) {
|
||||
} {
|
||||
bad := header
|
||||
change(&bad)
|
||||
if _, err := decode_capture(capture_frame(t, bad, pixels), request); err == nil {
|
||||
if _, err := decodeCapture(captureFrame(t, bad, pixels), request); err == nil {
|
||||
t.Fatalf("invalid mapping accepted: %+v", bad)
|
||||
}
|
||||
}
|
||||
@@ -123,47 +123,47 @@ func TestCaptureClipboardDoesNotMapToScreen(t *testing.T) {
|
||||
request := CaptureRequest{Kind: ClipboardSource, Foreground: 123, Generation: 1}
|
||||
header := CaptureHeader{Request: request}
|
||||
pixels := image.NewRGBA(image.Rect(0, 0, 10, 10))
|
||||
result, err := decode_capture(capture_frame(t, header, pixels), request)
|
||||
result, err := decodeCapture(captureFrame(t, header, pixels), request)
|
||||
if err != nil || result.Transform.HasScreenMapping {
|
||||
t.Fatalf("clipboard: %+v, %v", result, err)
|
||||
}
|
||||
header.ScreenBounds = image.Rect(0, 0, 10, 10)
|
||||
if _, err := decode_capture(capture_frame(t, header, pixels), request); err == nil {
|
||||
if _, err := decodeCapture(captureFrame(t, header, pixels), request); err == nil {
|
||||
t.Fatal("clipboard gained coordinates")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureProtocolErrorsAndPixelLimit(t *testing.T) {
|
||||
request := capture_request()
|
||||
request := captureRequest()
|
||||
for status, want := range map[string]error{"unavailable": ErrCapture, "source": ErrSource, "changed": ErrSourceChanged, "limit": ErrLimit, "Private diagnostics": ErrCapture} {
|
||||
frame := capture_frame(t, CaptureHeader{Request: request, Status: status}, nil)
|
||||
_, err := decode_capture(frame, request)
|
||||
frame := captureFrame(t, CaptureHeader{Request: request, Status: status}, nil)
|
||||
_, err := decodeCapture(frame, request)
|
||||
if !errors.Is(err, want) || strings.Contains(err.Error(), "Private") {
|
||||
t.Fatalf("status %q: %v", status, err)
|
||||
}
|
||||
if _, err := decode_capture(append(frame, 'x'), request); !errors.Is(err, ErrCapture) {
|
||||
if _, err := decodeCapture(append(frame, 'x'), request); !errors.Is(err, ErrCapture) {
|
||||
t.Fatal("failure with payload accepted")
|
||||
}
|
||||
}
|
||||
clipboard := CaptureRequest{Kind: ClipboardSource, Foreground: 123, Generation: 1}
|
||||
frame := capture_frame(t, CaptureHeader{Request: clipboard}, image.NewRGBA(image.Rect(0, 0, 1, 1)))
|
||||
frame := captureFrame(t, CaptureHeader{Request: clipboard}, image.NewRGBA(image.Rect(0, 0, 1, 1)))
|
||||
start := bytes.IndexByte(frame, '\n') + 1
|
||||
// A valid CRC and malicious IHDR are rejected before allocating pixel data.
|
||||
binary.BigEndian.PutUint32(frame[start+16:start+20], 10000)
|
||||
binary.BigEndian.PutUint32(frame[start+20:start+24], 10000)
|
||||
binary.BigEndian.PutUint32(frame[start+29:start+33], crc32.ChecksumIEEE(frame[start+12:start+29]))
|
||||
if _, err := decode_capture(frame, clipboard); !errors.Is(err, ErrLimit) {
|
||||
if _, err := decodeCapture(frame, clipboard); !errors.Is(err, ErrLimit) {
|
||||
t.Fatalf("oversize PNG: %v", err)
|
||||
}
|
||||
for _, invalid := range [][]byte{nil, []byte("{}\nnot a png"), bytes.Repeat([]byte{'x'}, maxCaptureHeader+1)} {
|
||||
if _, err := decode_capture(invalid, request); !errors.Is(err, ErrCapture) {
|
||||
if _, err := decodeCapture(invalid, request); !errors.Is(err, ErrCapture) {
|
||||
t.Fatalf("invalid response: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapturerMissingHelperAndCancellation(t *testing.T) {
|
||||
request := capture_request()
|
||||
request := captureRequest()
|
||||
if _, err := NewCapturer("/nonexistent-ocr-capture-helper").Capture(context.Background(), request); !errors.Is(err, ErrCapture) {
|
||||
t.Fatalf("missing helper: %v", err)
|
||||
}
|
||||
|
||||
@@ -59,12 +59,12 @@ func NewCursor(result Result) *Cursor {
|
||||
return cursor
|
||||
}
|
||||
|
||||
func (cursor *Cursor) line_index() int {
|
||||
func (cursor *Cursor) lineIndex() int {
|
||||
return sort.Search(len(cursor.lines), func(index int) bool { return cursor.lines[index].End >= cursor.offset })
|
||||
}
|
||||
|
||||
func (cursor *Cursor) Current(unit Unit) Position {
|
||||
lineIndex := cursor.line_index()
|
||||
lineIndex := cursor.lineIndex()
|
||||
line := cursor.lines[lineIndex]
|
||||
position := Position{Offset: cursor.offset, Line: cursor.lineTexts[lineIndex], LineStart: line.Start, Cursor: cursor.offset - line.Start}
|
||||
switch unit {
|
||||
@@ -84,7 +84,7 @@ func (cursor *Cursor) Current(unit Unit) Position {
|
||||
|
||||
func (cursor *Cursor) Move(unit Unit, step int) Position {
|
||||
previous := cursor.offset
|
||||
lineIndex := cursor.line_index()
|
||||
lineIndex := cursor.lineIndex()
|
||||
line := cursor.lines[lineIndex]
|
||||
switch unit {
|
||||
case Character:
|
||||
@@ -119,7 +119,7 @@ func (cursor *Cursor) Move(unit Unit, step int) Position {
|
||||
cursor.offset = len(cursor.text)
|
||||
}
|
||||
if unit != LineUnit && unit != PageUnit {
|
||||
cursor.column = cursor.offset - cursor.lines[cursor.line_index()].Start
|
||||
cursor.column = cursor.offset - cursor.lines[cursor.lineIndex()].Start
|
||||
}
|
||||
position := cursor.Current(unit)
|
||||
position.Moved = previous != cursor.offset
|
||||
@@ -133,7 +133,7 @@ func (cursor *Cursor) Set(offset int) (Position, bool) {
|
||||
return Position{}, false
|
||||
}
|
||||
cursor.offset = offset
|
||||
cursor.column = offset - cursor.lines[cursor.line_index()].Start
|
||||
cursor.column = offset - cursor.lines[cursor.lineIndex()].Start
|
||||
return cursor.Current(Character), true
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ func (cursor *Cursor) Slice(start, end int) (string, bool) {
|
||||
// LinesFrom returns whole lines after the virtual cursor. The first line
|
||||
// begins at the cursor position; following lines retain recognition order.
|
||||
func (cursor *Cursor) LinesFrom() []ReadLine {
|
||||
index := cursor.line_index()
|
||||
index := cursor.lineIndex()
|
||||
first := index
|
||||
parts := make([]ReadLine, 0, len(cursor.lines)-index)
|
||||
for ; index < len(cursor.lines); index++ {
|
||||
|
||||
+10
-10
@@ -103,10 +103,10 @@ func (engine *Engine) discover(ctx context.Context) (Catalog, error) {
|
||||
}
|
||||
return Catalog{}, err
|
||||
}
|
||||
return parse_catalog(string(output))
|
||||
return parseCatalog(string(output))
|
||||
}
|
||||
|
||||
func parse_catalog(output string) (Catalog, error) {
|
||||
func parseCatalog(output string) (Catalog, error) {
|
||||
lines := strings.Split(strings.TrimSpace(output), "\n")
|
||||
header := strings.TrimSuffix(lines[0], "\r")
|
||||
countStart := strings.LastIndex(header, "(")
|
||||
@@ -121,7 +121,7 @@ func parse_catalog(output string) (Catalog, error) {
|
||||
seen := make(map[string]bool)
|
||||
for _, line := range lines[1:] {
|
||||
language := strings.TrimSuffix(line, "\r")
|
||||
if !valid_language(language) || seen[language] {
|
||||
if !validLanguage(language) || seen[language] {
|
||||
return Catalog{}, fmt.Errorf("%w: invalid language catalog", ErrUnavailable)
|
||||
}
|
||||
seen[language] = true
|
||||
@@ -140,9 +140,9 @@ func parse_catalog(output string) (Catalog, error) {
|
||||
return catalog, nil
|
||||
}
|
||||
|
||||
// valid_language permits upstream script/Latin-style identifiers, without
|
||||
// validLanguage permits upstream script/Latin-style identifiers, without
|
||||
// accepting path traversal, options, whitespace or expression delimiters.
|
||||
func valid_language(language string) bool {
|
||||
func validLanguage(language string) bool {
|
||||
if language == "" || len(language) > 128 {
|
||||
return false
|
||||
}
|
||||
@@ -163,7 +163,7 @@ func valid_language(language string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (catalog Catalog) resolve_language(expression string) (string, error) {
|
||||
func (catalog Catalog) resolveLanguage(expression string) (string, error) {
|
||||
if expression == "" {
|
||||
return catalog.DefaultLanguage, nil
|
||||
}
|
||||
@@ -172,7 +172,7 @@ func (catalog Catalog) resolve_language(expression string) (string, error) {
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
for _, language := range strings.Split(expression, "+") {
|
||||
if !valid_language(language) || language == "osd" || seen[language] {
|
||||
if !validLanguage(language) || language == "osd" || seen[language] {
|
||||
return "", fmt.Errorf("%w: invalid language selection", ErrUnavailable)
|
||||
}
|
||||
seen[language] = true
|
||||
@@ -190,7 +190,7 @@ func (catalog Catalog) resolve_language(expression string) (string, error) {
|
||||
func (engine *Engine) Recognize(ctx context.Context, pixels image.Image, options Options) (Result, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, recognitionTimeout)
|
||||
defer cancel()
|
||||
if pixels == nil || !valid_dimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) {
|
||||
if pixels == nil || !validDimensions(pixels.Bounds().Dx(), pixels.Bounds().Dy()) {
|
||||
return Result{}, ErrInvalidImage
|
||||
}
|
||||
if options.Layout == 0 {
|
||||
@@ -212,11 +212,11 @@ func (engine *Engine) Recognize(ctx context.Context, pixels image.Image, options
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
language, err := catalog.resolve_language(options.Language)
|
||||
language, err := catalog.resolveLanguage(options.Language)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
encoded := &bounded_buffer{limit: maxImageBytes, ctx: ctx}
|
||||
encoded := &boundedBuffer{limit: maxImageBytes, ctx: ctx}
|
||||
if err := png.Encode(encoded, pixels); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return Result{}, ctx.Err()
|
||||
|
||||
+18
-18
@@ -24,13 +24,13 @@ import (
|
||||
)
|
||||
|
||||
func TestCatalogAndOrderedLanguages(t *testing.T) {
|
||||
catalog, err := parse_catalog("List of available languages in \"/data\" (4):\nfra\nosd\nscript/Latin\neng\n")
|
||||
catalog, err := parseCatalog("List of available languages in \"/data\" (4):\nfra\nosd\nscript/Latin\neng\n")
|
||||
if err != nil || catalog.DefaultLanguage != "eng" ||
|
||||
!reflect.DeepEqual(catalog.Languages, []string{"eng", "fra", "script/Latin"}) {
|
||||
t.Fatalf("catalog: %+v, %v", catalog, err)
|
||||
}
|
||||
for _, expression := range []string{"", "fra+eng", "script/Latin"} {
|
||||
got, err := catalog.resolve_language(expression)
|
||||
got, err := catalog.resolveLanguage(expression)
|
||||
want := expression
|
||||
if want == "" {
|
||||
want = "eng"
|
||||
@@ -40,11 +40,11 @@ func TestCatalogAndOrderedLanguages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
for _, expression := range []string{"osd", "deu", "fra+missing", "eng+eng", "eng+", "+eng", "../eng", "-l eng", "eng;command", "fra\neng"} {
|
||||
if _, err := catalog.resolve_language(expression); !errors.Is(err, ErrUnavailable) {
|
||||
if _, err := catalog.resolveLanguage(expression); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("invalid/uninstalled expression %q accepted: %v", expression, err)
|
||||
}
|
||||
}
|
||||
other, err := parse_catalog("List of available languages in \"/data\" (2):\nfra\ndeu\n")
|
||||
other, err := parseCatalog("List of available languages in \"/data\" (2):\nfra\ndeu\n")
|
||||
if err != nil || other.DefaultLanguage != "deu" {
|
||||
t.Fatalf("default without English: %+v, %v", other, err)
|
||||
}
|
||||
@@ -59,14 +59,14 @@ func TestMissingAndMalformedCatalogs(t *testing.T) {
|
||||
"List of available languages in \"/data\" (1):\neng\nfra\n",
|
||||
"List of available languages in \"/data\" (1):\n../eng\n",
|
||||
} {
|
||||
_, err := parse_catalog(output)
|
||||
_, err := parseCatalog(output)
|
||||
if !errors.Is(err, ErrUnavailable) || !strings.HasPrefix(err.Error(), "OCR not available") || strings.Contains(err.Error(), "Private") {
|
||||
t.Fatalf("unavailable message: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_engine(t *testing.T, mode string) *Engine {
|
||||
func testEngine(t *testing.T, mode string) *Engine {
|
||||
t.Helper()
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
@@ -82,7 +82,7 @@ func test_engine(t *testing.T, mode string) *Engine {
|
||||
}
|
||||
|
||||
func TestEngineRecognizesOneTSVInvocation(t *testing.T) {
|
||||
engine := test_engine(t, "success")
|
||||
engine := testEngine(t, "success")
|
||||
original := engine.command
|
||||
var invocations [][]string
|
||||
engine.command = func(ctx context.Context, args ...string) *exec.Cmd {
|
||||
@@ -118,7 +118,7 @@ func TestEngineMissingExecutableAndUnavailableLanguage(t *testing.T) {
|
||||
if _, err := engine.Recognize(context.Background(), image.NewGray(image.Rect(0, 0, 100, 100)), Options{}); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("missing executable recognition: %v", err)
|
||||
}
|
||||
engine = test_engine(t, "success")
|
||||
engine = testEngine(t, "success")
|
||||
original := engine.command
|
||||
var invocations int
|
||||
engine.command = func(ctx context.Context, args ...string) *exec.Cmd {
|
||||
@@ -158,7 +158,7 @@ func TestEngineFailuresAndOutputBounds(t *testing.T) {
|
||||
{"catalog-limit", ErrLimit},
|
||||
} {
|
||||
t.Run(test.mode, func(t *testing.T) {
|
||||
engine := test_engine(t, test.mode)
|
||||
engine := testEngine(t, test.mode)
|
||||
result, err := engine.Recognize(context.Background(), image.NewGray(image.Rect(0, 0, 100, 100)), Options{})
|
||||
if !errors.Is(err, test.want) || result.Text != "" || len(result.Words) != 0 {
|
||||
t.Fatalf("result: %+v, error: %v; want %v", result, err, test.want)
|
||||
@@ -176,7 +176,7 @@ func TestEngineRejectsInvalidImageAndLayoutBeforeStartingChild(t *testing.T) {
|
||||
t.Fatal("child invoked for invalid request")
|
||||
return nil
|
||||
}
|
||||
for _, pixels := range []image.Image{nil, image.NewGray(image.Rectangle{}), oversized_image{}} {
|
||||
for _, pixels := range []image.Image{nil, image.NewGray(image.Rectangle{}), oversizedImage{}} {
|
||||
if _, err := engine.Recognize(context.Background(), pixels, Options{}); !errors.Is(err, ErrInvalidImage) {
|
||||
t.Fatalf("invalid image: %v", err)
|
||||
}
|
||||
@@ -186,18 +186,18 @@ func TestEngineRejectsInvalidImageAndLayoutBeforeStartingChild(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type oversized_image struct{ image.Image }
|
||||
type oversizedImage struct{ image.Image }
|
||||
|
||||
func (oversized_image) Bounds() image.Rectangle { return image.Rect(0, 0, MaxPixels, 2) }
|
||||
func (oversizedImage) Bounds() image.Rectangle { return image.Rect(0, 0, MaxPixels, 2) }
|
||||
|
||||
func TestEngineCancellationReapsChildAndUnblocksWaitingRequest(t *testing.T) {
|
||||
t.Run("cancel", func(t *testing.T) { check_child_cancellation(t, false) })
|
||||
t.Run("deadline", func(t *testing.T) { check_child_cancellation(t, true) })
|
||||
t.Run("cancel", func(t *testing.T) { checkChildCancellation(t, false) })
|
||||
t.Run("deadline", func(t *testing.T) { checkChildCancellation(t, true) })
|
||||
}
|
||||
|
||||
func check_child_cancellation(t *testing.T, deadline bool) {
|
||||
func checkChildCancellation(t *testing.T, deadline bool) {
|
||||
t.Helper()
|
||||
engine := test_engine(t, "wait")
|
||||
engine := testEngine(t, "wait")
|
||||
original := engine.command
|
||||
readyRead, readyWrite, err := os.Pipe()
|
||||
if err != nil {
|
||||
@@ -264,7 +264,7 @@ func check_child_cancellation(t *testing.T, deadline bool) {
|
||||
}
|
||||
|
||||
func TestEngineRetiresDescendantsHoldingPipes(t *testing.T) {
|
||||
engine := test_engine(t, "orphan")
|
||||
engine := testEngine(t, "orphan")
|
||||
original := engine.command
|
||||
readyRead, readyWrite, err := os.Pipe()
|
||||
if err != nil {
|
||||
@@ -346,7 +346,7 @@ func TestEngineExpiredDeadlineStartsNoChild(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBoundedBufferCannotBypassWriteLimit(t *testing.T) {
|
||||
buffer := &bounded_buffer{limit: 5, ctx: context.Background()}
|
||||
buffer := &boundedBuffer{limit: 5, ctx: context.Background()}
|
||||
if _, err := io.Copy(buffer, strings.NewReader("0123456789")); !errors.Is(err, ErrLimit) || buffer.Len() > 5 {
|
||||
t.Fatalf("writer limit bypassed: %d bytes, %v", buffer.Len(), err)
|
||||
}
|
||||
|
||||
@@ -116,9 +116,9 @@ type Transform struct {
|
||||
// Invalid, empty and entirely padded rectangles have no screen mapping.
|
||||
func (transform Transform) ScreenRectangle(bounds image.Rectangle) (image.Rectangle, bool) {
|
||||
content, screen := transform.ImageContent, transform.ScreenBounds
|
||||
if !transform.HasScreenMapping || !valid_dimensions(content.Dx(), content.Dy()) ||
|
||||
if !transform.HasScreenMapping || !validDimensions(content.Dx(), content.Dy()) ||
|
||||
content.Min.X < 0 || content.Min.Y < 0 || content.Max.X > MaxPixels || content.Max.Y > MaxPixels ||
|
||||
!valid_screen_rectangle(screen) {
|
||||
!validScreenRectangle(screen) {
|
||||
return image.Rectangle{}, false
|
||||
}
|
||||
bounds = bounds.Intersect(content)
|
||||
@@ -137,7 +137,7 @@ func (transform Transform) ScreenRectangle(bounds image.Rectangle) (image.Rectan
|
||||
return mapped, !mapped.Empty()
|
||||
}
|
||||
|
||||
func valid_screen_rectangle(bounds image.Rectangle) bool {
|
||||
func validScreenRectangle(bounds image.Rectangle) bool {
|
||||
return bounds.Min.X > math.MinInt32 && bounds.Min.Y > math.MinInt32 &&
|
||||
bounds.Max.X <= math.MaxInt32 && bounds.Max.Y <= math.MaxInt32 &&
|
||||
bounds.Max.X > bounds.Min.X && bounds.Max.Y > bounds.Min.Y &&
|
||||
@@ -145,13 +145,13 @@ func valid_screen_rectangle(bounds image.Rectangle) bool {
|
||||
int64(bounds.Max.Y)-int64(bounds.Min.Y) <= MaxPixels
|
||||
}
|
||||
|
||||
func valid_dimensions(width, height int) bool {
|
||||
func validDimensions(width, height int) bool {
|
||||
return width > 0 && height > 0 && height <= MaxPixels && width <= MaxPixels/height
|
||||
}
|
||||
|
||||
func valid_word_bounds(bounds image.Rectangle, width, height int) bool {
|
||||
func validWordBounds(bounds image.Rectangle, width, height int) bool {
|
||||
return bounds.Min.X >= 0 && bounds.Min.Y >= 0 && !bounds.Empty() &&
|
||||
bounds.Max.X <= width && bounds.Max.Y <= height
|
||||
}
|
||||
|
||||
func rune_length(text string) int { return utf8.RuneCountInString(text) }
|
||||
func runeLength(text string) int { return utf8.RuneCountInString(text) }
|
||||
@@ -24,7 +24,7 @@ func TestNativeTesseract(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if language, err := catalog.resolve_language("eng"); err != nil || language != "eng" {
|
||||
if language, err := catalog.resolveLanguage("eng"); err != nil || language != "eng" {
|
||||
t.Fatal("the native painted-text fixture requires installed English data")
|
||||
}
|
||||
file, err := os.Open("testdata/painted-text.png")
|
||||
@@ -52,7 +52,7 @@ func TestNativeTesseract(t *testing.T) {
|
||||
t.Fatalf("PSM %d lost line/word structure: %+v", layout, result)
|
||||
}
|
||||
for _, word := range result.Words {
|
||||
if !valid_word_bounds(word.Bounds, result.Width, result.Height) ||
|
||||
if !validWordBounds(word.Bounds, result.Width, result.Height) ||
|
||||
word.Bounds.Min.X < 20 || word.Bounds.Min.Y < 15 || word.Bounds.Max.Y > 185 {
|
||||
t.Fatalf("PSM %d word outside painted area: %+v", layout, word)
|
||||
}
|
||||
@@ -67,7 +67,7 @@ func TestNativeTesseract(t *testing.T) {
|
||||
t.Fatalf("scaled recognition did not retain image coordinates: %dx%d, %d words", scaled.Width, scaled.Height, len(scaled.Words))
|
||||
}
|
||||
for _, word := range scaled.Words {
|
||||
if !valid_word_bounds(word.Bounds, scaled.Width, scaled.Height) {
|
||||
if !validWordBounds(word.Bounds, scaled.Width, scaled.Height) {
|
||||
t.Fatalf("invalid scaled word: %+v", word)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
// Preprocess returns owned pixels in recognition coordinates. Scale uses nearest
|
||||
// neighbor sampling so recognized word boxes map back through the capture transform.
|
||||
func Preprocess(ctx context.Context, source image.Image, options Options) (image.Image, error) {
|
||||
if source == nil || !valid_dimensions(source.Bounds().Dx(), source.Bounds().Dy()) {
|
||||
if source == nil || !validDimensions(source.Bounds().Dx(), source.Bounds().Dy()) {
|
||||
return nil, ErrInvalidImage
|
||||
}
|
||||
scale := options.Scale
|
||||
@@ -21,7 +21,7 @@ func Preprocess(ctx context.Context, source image.Image, options Options) (image
|
||||
scale = 1
|
||||
}
|
||||
width, height := source.Bounds().Dx(), source.Bounds().Dy()
|
||||
if scale < 1 || scale > 4 || height > MaxPixels/scale || !valid_dimensions(width*scale, height*scale) ||
|
||||
if scale < 1 || scale > 4 || height > MaxPixels/scale || !validDimensions(width*scale, height*scale) ||
|
||||
options.Threshold < 0 || options.Threshold > 255 {
|
||||
return nil, ErrLimit
|
||||
}
|
||||
|
||||
+11
-11
@@ -15,9 +15,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// bounded_buffer never retains more than limit bytes. Child-output overflow
|
||||
// boundedBuffer never retains more than limit bytes. Child-output overflow
|
||||
// cancels its process immediately instead of leaving a stopped pipe reader.
|
||||
type bounded_buffer struct {
|
||||
type boundedBuffer struct {
|
||||
data bytes.Buffer
|
||||
limit int
|
||||
ctx context.Context
|
||||
@@ -25,7 +25,7 @@ type bounded_buffer struct {
|
||||
overflow bool
|
||||
}
|
||||
|
||||
func (buffer *bounded_buffer) Write(data []byte) (int, error) {
|
||||
func (buffer *boundedBuffer) Write(data []byte) (int, error) {
|
||||
if err := buffer.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -39,14 +39,14 @@ func (buffer *bounded_buffer) Write(data []byte) (int, error) {
|
||||
return buffer.data.Write(data)
|
||||
}
|
||||
|
||||
func (buffer *bounded_buffer) Bytes() []byte { return buffer.data.Bytes() }
|
||||
func (buffer *bounded_buffer) Len() int { return buffer.data.Len() }
|
||||
func (buffer *boundedBuffer) Bytes() []byte { return buffer.data.Bytes() }
|
||||
func (buffer *boundedBuffer) Len() int { return buffer.data.Len() }
|
||||
|
||||
func (engine *Engine) run(parent context.Context, input []byte, limit int, args ...string) ([]byte, []byte, error) {
|
||||
return run_process(parent, engine.command, input, limit, args...)
|
||||
return runProcess(parent, engine.command, input, limit, args...)
|
||||
}
|
||||
|
||||
func run_process(parent context.Context, factory func(context.Context, ...string) *exec.Cmd, input []byte, limit int, args ...string) ([]byte, []byte, error) {
|
||||
func runProcess(parent context.Context, factory func(context.Context, ...string) *exec.Cmd, input []byte, limit int, args ...string) ([]byte, []byte, error) {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
command := factory(ctx, args...)
|
||||
@@ -65,10 +65,10 @@ func run_process(parent context.Context, factory func(context.Context, ...string
|
||||
}
|
||||
command.Cancel = kill
|
||||
command.WaitDelay = time.Second
|
||||
command.Env = process_environment(command.Env)
|
||||
command.Env = processEnvironment(command.Env)
|
||||
command.Stdin = bytes.NewReader(input)
|
||||
output := &bounded_buffer{limit: limit, ctx: ctx, cancel: cancel}
|
||||
diagnostics := &bounded_buffer{limit: maxStderrBytes, ctx: ctx, cancel: cancel}
|
||||
output := &boundedBuffer{limit: limit, ctx: ctx, cancel: cancel}
|
||||
diagnostics := &boundedBuffer{limit: maxStderrBytes, ctx: ctx, cancel: cancel}
|
||||
command.Stdout, command.Stderr = output, diagnostics
|
||||
err := command.Run()
|
||||
// WaitDelay closes inherited pipes after a bound, but os/exec only kills the
|
||||
@@ -92,7 +92,7 @@ func run_process(parent context.Context, factory func(context.Context, ...string
|
||||
return output.Bytes(), diagnostics.Bytes(), nil
|
||||
}
|
||||
|
||||
func process_environment(environment []string) []string {
|
||||
func processEnvironment(environment []string) []string {
|
||||
if environment == nil {
|
||||
environment = os.Environ()
|
||||
}
|
||||
|
||||
+14
-14
@@ -23,7 +23,7 @@ const tsvHeader = "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft
|
||||
// Malformed output is rejected atomically, with no recognized text in errors.
|
||||
// The supplied dimensions must describe the actual recognition image.
|
||||
func ParseTSV(input io.Reader, width, height int) (Result, error) {
|
||||
if !valid_dimensions(width, height) {
|
||||
if !validDimensions(width, height) {
|
||||
return Result{}, ErrInvalidImage
|
||||
}
|
||||
limited := &io.LimitedReader{R: input, N: maxTSVBytes + 1}
|
||||
@@ -46,41 +46,41 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) {
|
||||
}
|
||||
fields := strings.SplitN(scanner.Text(), "\t", 12)
|
||||
if len(fields) != 12 {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
var numbers [10]int
|
||||
for index := range numbers {
|
||||
number, err := strconv.ParseInt(fields[index], 10, 32)
|
||||
if err != nil || number < 0 {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
numbers[index] = int(number)
|
||||
}
|
||||
level := numbers[0]
|
||||
if level < 1 || level > 5 || numbers[1] < 1 {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
for index := 2; index <= 5; index++ {
|
||||
if (index <= level && numbers[index] < 1) || (index > level && numbers[index] != 0) {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
}
|
||||
confidence, err := strconv.ParseFloat(fields[10], 64)
|
||||
if err != nil || math.IsNaN(confidence) || math.IsInf(confidence, 0) || confidence < -1 || confidence > 100 {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
// Subtraction avoids overflowing 32-bit additions on ARM builds.
|
||||
left, top, boxWidth, boxHeight := numbers[6], numbers[7], numbers[8], numbers[9]
|
||||
if left > width || top > height || boxWidth > width-left || boxHeight > height-top {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
wordText := fields[11]
|
||||
if !utf8.ValidString(wordText) || strings.ContainsFunc(wordText, unicode.IsControl) {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
if level != 5 {
|
||||
if wordText != "" || confidence != -1 {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -88,8 +88,8 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) {
|
||||
continue
|
||||
}
|
||||
bounds := image.Rect(left, top, left+boxWidth, top+boxHeight)
|
||||
if !valid_word_bounds(bounds, width, height) || strings.TrimSpace(wordText) != wordText {
|
||||
return Result{}, invalid_row(rows)
|
||||
if !validWordBounds(bounds, width, height) || strings.TrimSpace(wordText) != wordText {
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
separatorBytes := 0
|
||||
if len(result.Words) != 0 {
|
||||
@@ -101,7 +101,7 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) {
|
||||
id := LineID{numbers[1], numbers[2], numbers[3], numbers[4]}
|
||||
if len(result.Lines) == 0 || result.Lines[len(result.Lines)-1].ID != id {
|
||||
if closedLines[id] {
|
||||
return Result{}, invalid_row(rows)
|
||||
return Result{}, invalidRow(rows)
|
||||
}
|
||||
if len(result.Lines) != 0 {
|
||||
closedLines[result.Lines[len(result.Lines)-1].ID] = true
|
||||
@@ -115,7 +115,7 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) {
|
||||
}
|
||||
start := offset
|
||||
text.WriteString(wordText)
|
||||
offset += rune_length(wordText)
|
||||
offset += runeLength(wordText)
|
||||
result.Words = append(result.Words, Word{wordText, confidence, bounds, Span{start, offset}})
|
||||
line := &result.Lines[len(result.Lines)-1]
|
||||
line.End, line.WordEnd = offset, len(result.Words)
|
||||
@@ -133,6 +133,6 @@ func ParseTSV(input io.Reader, width, height int) (Result, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func invalid_row(row int) error {
|
||||
func invalidRow(row int) error {
|
||||
return fmt.Errorf("%w: TSV row %d", ErrInvalidOutput, row)
|
||||
}
|
||||
@@ -126,7 +126,7 @@ func FuzzParseTSV(f *testing.F) {
|
||||
start, startOK := result.ByteOffset(word.Start)
|
||||
end, endOK := result.ByteOffset(word.End)
|
||||
if !startOK || !endOK || word.Start < lastEnd || word.End <= word.Start ||
|
||||
result.Text[start:end] != word.Text || !valid_word_bounds(word.Bounds, result.Width, result.Height) {
|
||||
result.Text[start:end] != word.Text || !validWordBounds(word.Bounds, result.Width, result.Height) {
|
||||
t.Fatal("invalid word map")
|
||||
}
|
||||
lastEnd = word.End
|
||||
|
||||
Reference in new issue
Block a user