Browse Source

Add advance filtering and search to Photo

Toby Chui 2 days ago
parent
commit
46ac505469

+ 14 - 0
src/mod/agi/README.md

@@ -446,6 +446,20 @@ Returns JSON string. JPEG, TIFF based RAW and HEIC / HEIF photos.
 var exif = JSON.parse(imagelib.getExif("user:/img.jpg"));
 ```
 
+### `imagelib.renderPreview(src, dest, maxWidth, maxHeight)`
+Draws a photo upright and scaled down to fit `maxWidth` x `maxHeight`, keeping
+its shape (0 leaves a side free; smaller photos are not enlarged). Reads JPEG,
+PNG, WebP, GIF, HEIC / HEIF and RAW (its embedded JPEG) and applies the EXIF
+orientation. `dest` is a `.jpg` or `.png` path (folders are created); pass `""`
+to get a JPEG data URL instead of writing a file. Returns
+`{width, height}` (plus `dataURL` when `dest` is `""`). Pictures over 120 MP
+are refused.
+
+```javascript
+var p = imagelib.renderPreview("user:/Photo/a.heic", "user:/.appdata/photo/previews/a.jpg", 720, 1440);
+var inline = imagelib.renderPreview("user:/Photo/b.jpg", "", 480, 480).dataURL;
+```
+
 ## http API
 
 Load:

+ 4 - 0
src/mod/agi/agi.image.go

@@ -666,6 +666,9 @@ func (g *Gateway) injectImageLibFunctions(payload *static.AgiLibInjectionPayload
 		return otto.TrueValue()
 	})
 
+	//Photo previews that keep their shape (agi.image.preview.go)
+	g.injectImagePreviewFunction(payload)
+
 	//Wrap all the native code function into an imagelib class
 	vm.Run(`
 		var imagelib = {};
@@ -677,6 +680,7 @@ func (g *Gateway) injectImageLibFunctions(payload *static.AgiLibInjectionPayload
 		imagelib.hasExif = _imagelib_hasExif;
 		imagelib.getExif = _imagelib_getExif;
 		imagelib.rawToJPEG = _imagelib_rawToJPEG;
+		imagelib.renderPreview = _imagelib_renderPreview;
 	`)
 }
 

+ 235 - 0
src/mod/agi/agi.image.preview.go

@@ -0,0 +1,235 @@
+package agi
+
+import (
+	"bytes"
+	"encoding/base64"
+	"errors"
+	"image"
+	"image/color"
+	"image/draw"
+	"image/jpeg"
+	"image/png"
+	"path/filepath"
+	"strings"
+
+	"github.com/disintegration/imaging"
+	"github.com/gen2brain/h265/heic"
+	"github.com/robertkrimen/otto"
+
+	"imuslab.com/arozos/mod/agi/static"
+	"imuslab.com/arozos/mod/filesystem"
+	metadata "imuslab.com/arozos/mod/filesystem/metadata"
+)
+
+/*
+	imagelib.renderPreview
+
+	Draws a photo upright and scaled down to fit a box, keeping its shape.
+	The file manager thumbnails are square crops, so a gallery that shows
+	photos in their own shape (the Photo app's waterfall layout) needs this
+	instead. Unlike resizeImage it also reads RAW photos (their embedded
+	JPEG) and HEIC / HEIF, applies the EXIF orientation (and the HEIC
+	rotation), never enlarges, and refuses pictures too large to decode.
+*/
+
+const (
+	//Largest non RAW source read into memory (RAW files are limited by
+	//metadata.RenderRAWImage, which only keeps their embedded JPEG)
+	previewMaxFileSize = 80 << 20
+	//Largest picture decoded, in pixels (a 108 MP phone photo still fits)
+	previewMaxPixels   = 120_000_000
+	previewJPEGQuality = 82
+)
+
+// previewSourceConfig reports the size of an encoded picture without
+// decoding it, so oversized ones are refused before they are decoded
+func previewSourceConfig(data []byte) (image.Config, error) {
+	cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
+	return cfg, err
+}
+
+// decodePreviewSource decodes the bytes of a picture upright. ext is the
+// extension of the source file (with the dot), which picks the decoder.
+func decodePreviewSource(data []byte, ext string) (image.Image, error) {
+	cfg, err := previewSourceConfig(data)
+	if err != nil {
+		return nil, err
+	}
+	if cfg.Width <= 0 || cfg.Height <= 0 {
+		return nil, errors.New("picture has no size")
+	}
+	if int64(cfg.Width)*int64(cfg.Height) > previewMaxPixels {
+		return nil, errors.New("picture too large to preview")
+	}
+	if metadata.IsHEICImageFile("preview" + strings.ToLower(ext)) {
+		//irot / imir / clap of the container, like the media server applies
+		return heic.Decode(bytes.NewReader(data), heic.Options{AutoRotate: true})
+	}
+	return imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
+}
+
+// fitPreview scales img down to fit maxWidth x maxHeight, keeping its shape.
+// A limit of 0 or less leaves that side free; smaller pictures are kept.
+func fitPreview(img image.Image, maxWidth int, maxHeight int) image.Image {
+	b := img.Bounds()
+	if maxWidth <= 0 {
+		maxWidth = b.Dx()
+	}
+	if maxHeight <= 0 {
+		maxHeight = b.Dy()
+	}
+	if b.Dx() <= maxWidth && b.Dy() <= maxHeight {
+		return img
+	}
+	return imaging.Fit(img, maxWidth, maxHeight, imaging.Linear)
+}
+
+// encodePreview encodes img as "jpeg" (transparent parts turn white) or "png"
+func encodePreview(img image.Image, format string) ([]byte, error) {
+	var buf bytes.Buffer
+	switch format {
+	case "png":
+		if err := png.Encode(&buf, img); err != nil {
+			return nil, err
+		}
+	case "jpeg":
+		b := img.Bounds()
+		flat := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
+		draw.Draw(flat, flat.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
+		draw.Draw(flat, flat.Bounds(), img, b.Min, draw.Over)
+		if err := jpeg.Encode(&buf, flat, &jpeg.Options{Quality: previewJPEGQuality}); err != nil {
+			return nil, err
+		}
+	default:
+		return nil, errors.New("unsupported preview format " + format)
+	}
+	return buf.Bytes(), nil
+}
+
+// previewFormatOf names the encoding a preview written to dest gets
+func previewFormatOf(dest string) (string, error) {
+	switch strings.ToLower(filepath.Ext(dest)) {
+	case ".jpg", ".jpeg":
+		return "jpeg", nil
+	case ".png":
+		return "png", nil
+	}
+	return "", errors.New("preview must be saved as .jpg or .png")
+}
+
+// renderPreview reads the photo at rpath and returns it upright, scaled to
+// fit maxWidth x maxHeight and encoded in format, with its new size
+func renderPreview(fsh *filesystem.FileSystemHandler, rpath string, maxWidth int, maxHeight int, format string) ([]byte, int, int, error) {
+	fshAbs := fsh.FileSystemAbstraction
+	if !fshAbs.FileExists(rpath) || fshAbs.IsDir(rpath) {
+		return nil, 0, 0, errors.New("source not exists")
+	}
+
+	var data []byte
+	ext := strings.ToLower(filepath.Ext(rpath))
+	if metadata.IsRawImageFile(rpath) {
+		//The embedded full size JPEG, as the viewer shows it
+		jpegData, err := metadata.RenderRAWImage(fsh, rpath)
+		if err != nil {
+			return nil, 0, 0, err
+		}
+		data = jpegData
+		ext = ".jpg"
+	} else {
+		if fshAbs.GetFileSize(rpath) > previewMaxFileSize {
+			return nil, 0, 0, errors.New("image file too large to preview")
+		}
+		fileData, err := fshAbs.ReadFile(rpath)
+		if err != nil {
+			return nil, 0, 0, err
+		}
+		data = fileData
+	}
+
+	img, err := decodePreviewSource(data, ext)
+	if err != nil {
+		return nil, 0, 0, err
+	}
+	img = fitPreview(img, maxWidth, maxHeight)
+	encoded, err := encodePreview(img, format)
+	if err != nil {
+		return nil, 0, 0, err
+	}
+	b := img.Bounds()
+	return encoded, b.Dx(), b.Dy(), nil
+}
+
+// injectImagePreviewFunction adds imagelib.renderPreview to the VM; it is
+// called from injectImageLibFunctions before the imagelib object is built
+func (g *Gateway) injectImagePreviewFunction(payload *static.AgiLibInjectionPayload) {
+	vm := payload.VM
+	u := payload.User
+
+	//Render a photo upright and fitted, require (src, dest, maxWidth, maxHeight).
+	//dest "" returns the preview as a JPEG data URL instead of writing it.
+	vm.Set("_imagelib_renderPreview", func(call otto.FunctionCall) otto.Value {
+		vsrc, err := call.Argument(0).ToString()
+		if err != nil {
+			g.RaiseError(err)
+			return otto.FalseValue()
+		}
+		vdest := ""
+		if !call.Argument(1).IsUndefined() && !call.Argument(1).IsNull() {
+			vdest, _ = call.Argument(1).ToString()
+		}
+		maxWidth, _ := call.Argument(2).ToInteger()
+		maxHeight, _ := call.Argument(3).ToInteger()
+
+		if !u.CanRead(vsrc) {
+			g.RaiseError(errors.New("Permission Denied"))
+			return otto.FalseValue()
+		}
+		srcfsh, rsrc, err := static.VirtualPathToRealPath(vsrc, u)
+		if err != nil {
+			g.RaiseError(err)
+			return otto.FalseValue()
+		}
+
+		format := "jpeg"
+		var destfsh *filesystem.FileSystemHandler
+		rdest := ""
+		if vdest != "" {
+			format, err = previewFormatOf(vdest)
+			if err != nil {
+				g.RaiseError(err)
+				return otto.FalseValue()
+			}
+			if !u.CanWrite(vdest) {
+				g.RaiseError(errors.New("Permission Denied"))
+				return otto.FalseValue()
+			}
+			destfsh, rdest, err = static.VirtualPathToRealPath(vdest, u)
+			if err != nil {
+				g.RaiseError(err)
+				return otto.FalseValue()
+			}
+		}
+
+		encoded, width, height, err := renderPreview(srcfsh, rsrc, int(maxWidth), int(maxHeight), format)
+		if err != nil {
+			g.RaiseError(err)
+			return otto.FalseValue()
+		}
+
+		result := map[string]interface{}{
+			"width":  width,
+			"height": height,
+		}
+		if destfsh == nil {
+			result["dataURL"] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(encoded)
+		} else {
+			destfsh.FileSystemAbstraction.MkdirAll(filepath.Dir(rdest), 0755)
+			if err := destfsh.FileSystemAbstraction.WriteFile(rdest, encoded, 0775); err != nil {
+				g.RaiseError(err)
+				return otto.FalseValue()
+			}
+		}
+		value, _ := vm.ToValue(result)
+		return value
+	})
+}

+ 264 - 0
src/mod/agi/agi.image_preview_test.go

@@ -0,0 +1,264 @@
+package agi
+
+import (
+	"bytes"
+	"encoding/binary"
+	"hash/crc32"
+	"image"
+	"image/color"
+	"image/jpeg"
+	"image/png"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// jpegOfSize encodes a w x h picture whose left half is red and right half blue
+func jpegOfSize(t *testing.T, w, h int) []byte {
+	t.Helper()
+	img := image.NewRGBA(image.Rect(0, 0, w, h))
+	for y := 0; y < h; y++ {
+		for x := 0; x < w; x++ {
+			c := color.RGBA{R: 220, A: 255}
+			if x >= w/2 {
+				c = color.RGBA{B: 220, A: 255}
+			}
+			img.Set(x, y, c)
+		}
+	}
+	var buf bytes.Buffer
+	if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 95}); err != nil {
+		t.Fatalf("jpeg encode: %v", err)
+	}
+	return buf.Bytes()
+}
+
+// withExifOrientation puts an APP1 Exif segment holding only the Orientation
+// tag right after the SOI marker of a JPEG
+func withExifOrientation(jpg []byte, orientation uint16) []byte {
+	tiff := []byte{'I', 'I', 42, 0, 8, 0, 0, 0} //little endian, IFD0 at 8
+	ifd := make([]byte, 2+12+4)
+	binary.LittleEndian.PutUint16(ifd[0:], 1)      //one entry
+	binary.LittleEndian.PutUint16(ifd[2:], 0x0112) //Orientation
+	binary.LittleEndian.PutUint16(ifd[4:], 3)      //SHORT
+	binary.LittleEndian.PutUint32(ifd[6:], 1)      //count
+	binary.LittleEndian.PutUint16(ifd[10:], orientation)
+	payload := append([]byte("Exif\x00\x00"), append(tiff, ifd...)...)
+
+	seg := []byte{0xFF, 0xE1, 0, 0}
+	binary.BigEndian.PutUint16(seg[2:], uint16(len(payload)+2))
+	seg = append(seg, payload...)
+
+	out := append([]byte{}, jpg[:2]...)
+	out = append(out, seg...)
+	return append(out, jpg[2:]...)
+}
+
+// pngClaimingSize returns a PNG whose header says w x h (the pixel data is
+// that of a 1 x 1 picture, so only DecodeConfig can read it)
+func pngClaimingSize(t *testing.T, w, h uint32) []byte {
+	t.Helper()
+	var buf bytes.Buffer
+	if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 1, 1))); err != nil {
+		t.Fatalf("png encode: %v", err)
+	}
+	data := buf.Bytes()
+	//IHDR data starts after the 8 byte signature, 4 byte length and "IHDR"
+	binary.BigEndian.PutUint32(data[16:], w)
+	binary.BigEndian.PutUint32(data[20:], h)
+	binary.BigEndian.PutUint32(data[29:], crc32.ChecksumIEEE(data[12:29]))
+	return data
+}
+
+func TestFitPreview(t *testing.T) {
+	tests := []struct {
+		name         string
+		w, h         int
+		maxW, maxH   int
+		wantW, wantH int
+	}{
+		{"landscape fits the width", 1200, 800, 600, 1200, 600, 400},
+		{"portrait fits the width", 800, 1200, 400, 1200, 400, 600},
+		{"tall picture fits the height", 200, 2000, 600, 1000, 100, 1000},
+		{"small picture is kept", 300, 200, 600, 1200, 300, 200},
+		{"no height limit", 1200, 2400, 600, 0, 600, 1200},
+		{"no limits", 640, 480, 0, 0, 640, 480},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			got := fitPreview(image.NewRGBA(image.Rect(0, 0, tc.w, tc.h)), tc.maxW, tc.maxH)
+			if b := got.Bounds(); b.Dx() != tc.wantW || b.Dy() != tc.wantH {
+				t.Errorf("got %dx%d, want %dx%d", b.Dx(), b.Dy(), tc.wantW, tc.wantH)
+			}
+		})
+	}
+}
+
+func TestDecodePreviewSourceOrientation(t *testing.T) {
+	src := jpegOfSize(t, 40, 20)
+	tests := []struct {
+		name         string
+		orientation  uint16
+		wantW, wantH int
+	}{
+		{"no exif", 0, 40, 20},
+		{"upright", 1, 40, 20},
+		{"rotated 180", 3, 40, 20},
+		{"rotated 90 clockwise", 6, 20, 40},
+		{"rotated 90 counter clockwise", 8, 20, 40},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			data := src
+			if tc.orientation > 0 {
+				data = withExifOrientation(src, tc.orientation)
+			}
+			img, err := decodePreviewSource(data, ".jpg")
+			if err != nil {
+				t.Fatalf("decode: %v", err)
+			}
+			if b := img.Bounds(); b.Dx() != tc.wantW || b.Dy() != tc.wantH {
+				t.Errorf("got %dx%d, want %dx%d", b.Dx(), b.Dy(), tc.wantW, tc.wantH)
+			}
+		})
+	}
+
+	t.Run("rotated 90 clockwise puts the left edge on top", func(t *testing.T) {
+		img, err := decodePreviewSource(withExifOrientation(src, 6), ".jpg")
+		if err != nil {
+			t.Fatalf("decode: %v", err)
+		}
+		r, _, b, _ := img.At(10, 2).RGBA()
+		if r < b {
+			t.Errorf("top of the upright picture should be red (the old left half), got r=%d b=%d", r>>8, b>>8)
+		}
+	})
+}
+
+func TestDecodePreviewSourceRefuses(t *testing.T) {
+	tests := []struct {
+		name string
+		data []byte
+	}{
+		{"not a picture", []byte("hello world, not an image")},
+		{"empty", []byte{}},
+		{"too many pixels", pngClaimingSize(t, 20000, 20000)},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			if _, err := decodePreviewSource(tc.data, ".png"); err == nil {
+				t.Errorf("expected an error")
+			}
+		})
+	}
+}
+
+func TestEncodePreview(t *testing.T) {
+	clear := image.NewNRGBA(image.Rect(0, 0, 8, 8)) //fully transparent
+
+	t.Run("jpeg turns transparency white", func(t *testing.T) {
+		data, err := encodePreview(clear, "jpeg")
+		if err != nil {
+			t.Fatalf("encode: %v", err)
+		}
+		img, format, err := image.Decode(bytes.NewReader(data))
+		if err != nil || format != "jpeg" {
+			t.Fatalf("decode: %v (%s)", err, format)
+		}
+		r, g, b, _ := img.At(4, 4).RGBA()
+		if r>>8 < 245 || g>>8 < 245 || b>>8 < 245 {
+			t.Errorf("expected white, got %d,%d,%d", r>>8, g>>8, b>>8)
+		}
+	})
+
+	t.Run("png keeps transparency", func(t *testing.T) {
+		data, err := encodePreview(clear, "png")
+		if err != nil {
+			t.Fatalf("encode: %v", err)
+		}
+		img, format, err := image.Decode(bytes.NewReader(data))
+		if err != nil || format != "png" {
+			t.Fatalf("decode: %v (%s)", err, format)
+		}
+		if _, _, _, a := img.At(4, 4).RGBA(); a != 0 {
+			t.Errorf("expected a transparent pixel, alpha %d", a)
+		}
+	})
+
+	t.Run("unknown format", func(t *testing.T) {
+		if _, err := encodePreview(clear, "gif"); err == nil {
+			t.Errorf("expected an error")
+		}
+	})
+}
+
+func TestPreviewFormatOf(t *testing.T) {
+	tests := []struct {
+		dest    string
+		want    string
+		wantErr bool
+	}{
+		{"user:/a/b.jpg", "jpeg", false},
+		{"user:/a/b.JPEG", "jpeg", false},
+		{"user:/a/b.png", "png", false},
+		{"user:/a/b.webp", "", true},
+		{"user:/a/b", "", true},
+	}
+	for _, tc := range tests {
+		t.Run(tc.dest, func(t *testing.T) {
+			got, err := previewFormatOf(tc.dest)
+			if (err != nil) != tc.wantErr || got != tc.want {
+				t.Errorf("got %q, %v; want %q, error %v", got, err, tc.want, tc.wantErr)
+			}
+		})
+	}
+}
+
+func TestRenderPreview(t *testing.T) {
+	fsh, dir := newImageTestFSH(t)
+
+	photo := filepath.Join(dir, "photo.jpg")
+	if err := os.WriteFile(photo, withExifOrientation(jpegOfSize(t, 300, 200), 6), 0644); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+	raw := filepath.Join(dir, "photo.arw")
+	if err := os.WriteFile(raw, jpegOfSize(t, 300, 200), 0644); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+
+	tests := []struct {
+		name         string
+		path         string
+		wantW, wantH int
+		wantErr      bool
+	}{
+		{"jpeg is upright and fitted", photo, 100, 150, false},
+		{"raw uses its embedded jpeg", raw, 100, 66, false},
+		{"missing file", filepath.Join(dir, "none.jpg"), 0, 0, true},
+		{"folder", dir, 0, 0, true},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			data, w, h, err := renderPreview(fsh, tc.path, 100, 400, "jpeg")
+			if tc.wantErr {
+				if err == nil {
+					t.Errorf("expected an error")
+				}
+				return
+			}
+			if err != nil {
+				t.Fatalf("renderPreview: %v", err)
+			}
+			if w != tc.wantW || h != tc.wantH {
+				t.Errorf("reported %dx%d, want %dx%d", w, h, tc.wantW, tc.wantH)
+			}
+			cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
+			if err != nil {
+				t.Fatalf("output is not a jpeg: %v", err)
+			}
+			if cfg.Width != w || cfg.Height != h {
+				t.Errorf("encoded %dx%d, reported %dx%d", cfg.Width, cfg.Height, w, h)
+			}
+		})
+	}
+}

+ 71 - 0
src/web/Photo/README.md

@@ -0,0 +1,71 @@
+# Photo
+
+The gallery (`index.html`) and the photo viewer / editor (`embedded.html`,
+see `embedded/README.md`).
+
+## Gallery front end
+
+| File | What it holds |
+|------|---------------|
+| `photo.js` | `photoListObject()`, the Alpine component: folders, search, the top right menus, settings dialog, indexing; also the old full screen viewer and Arozcast |
+| `layout.js` | Zoom steps, timeline sections (Day / Month / Year), waterfall column dealing, `PhotoPreviews` (loads waterfall previews for cards near the viewport) |
+| `filters.js` | The Sort & filter panel: each control owns a *slot* and writes one search chip |
+| `search.js` | Chip parsing and labels, suggestion icons, `aoPhotoBackend()` |
+| `i18n.js`, `locale/photo.json` | `T()` and the six languages |
+
+The top right of the gallery has three buttons: **Sort & filter** (sort order,
+"Look in" this folder or all photos, rating, date range, camera, lens, file
+type, orientation, and under *Camera settings & file details* ISO, aperture,
+focal length, megapixels, shutter speed, time of day, file size), **View**
+(timeline Off / Day / Month / Year, layout Grid / Waterfall, a 5 step zoom;
+Ctrl / ⌘ + wheel zooms too) and **Settings**. View choices are kept in
+`localStorage` (`ao-photo-view`).
+
+- The search chips are the single description of a search. A panel control
+  writes a chip with a `slot`; removing that chip clears the control. Typed
+  chips have no slot. Everything goes to `backend/searchPhotos.js`, whose
+  header lists the query syntax (including `-token` exclusions).
+- The timeline orders by the date taken. EXIF times are the camera clock,
+  stored by the index as if UTC, so they are read back in UTC; file times are
+  real instants and read in local time (`photoImageDate`).
+- Section keys must stay unique: a list that is not in date order would bring
+  a month back, and duplicate `x-for` keys break Alpine. `setTimeline` sorts
+  before grouping and `groupedImages` suffixes repeats.
+
+## Waterfall previews
+
+System thumbnails are 480 px square crops, so the waterfall cannot use them.
+`backend/previews.js` (with `previewlib.js`) draws upright, uncropped previews
+(720 x 2160 at most) with the AGI `imagelib.renderPreview`, which reads JPEG,
+PNG, WebP, GIF, HEIC and RAW and applies the EXIF orientation. The core
+thumbnail code is not involved.
+
+Where they are kept is a per user setting (Settings dialog, stored in
+`index_meta` of the index database, which survives an index rebuild):
+
+- **appdata** (default): `user:/.appdata/photo/previews/<hh>/<hash>.jpg`
+- **custom**: the same layout inside a folder the user picks; it must be
+  writable and outside the Photo library roots, and only files named like
+  previews are ever deleted from it
+- **realtime**: drawn on every request and sent as a data URL; nothing stored
+
+A preview is drawn again when the photo is newer than it. The front end asks
+`previews.js` for cached ones first (`generate: false`, up to 200 at a time),
+then has the missing ones drawn a few per request, two requests at a time,
+showing the square thumbnail until each arrives. The card shape comes from
+the index (`width` / `height`, which follow the EXIF orientation since index
+schema 2) and is corrected when a preview reports its real size.
+
+## Backend scripts (`backend/`)
+
+| Script | Purpose |
+|--------|---------|
+| `imagedb.js` | Shared: index schema, metadata extraction, query parser + SQL builder, exclude list |
+| `indexPhotos.js` / `indexStatus.js` | Incremental indexing (also drops excluded and deleted photos) |
+| `listFolder.js` | Folder listing with dates and upright sizes from the index |
+| `searchPhotos.js` / `searchSuggest.js` / `searchFacets.js` | Search, autocomplete, the choices of the filter panel |
+| `previewlib.js` / `previews.js` | Waterfall previews |
+| `photoSettings.js` | Settings dialog: preview storage, cache size / clear, excluded folders |
+| `getRating.js` / `setRating.js` | Star ratings (kept in their own table) |
+
+All backend scripts are ES5 (Otto VM).

+ 191 - 39
src/web/Photo/backend/imagedb.js

@@ -32,7 +32,8 @@ requirelib("imagelib");
 var INDEX_DB_PATH = "user:/.appdata/photo/photoindex.db";
 
 // Bump when the schema below changes; openIndexDB() will rebuild the cache.
-var SCHEMA_VERSION = 1;
+// 2: width / height follow the EXIF orientation (phone photos stored sideways).
+var SCHEMA_VERSION = 2;
 
 // Image / RAW extension sets (kept in sync with constants.js + listFolder.js).
 var IMAGE_EXTENSIONS = ["jpg", "jpeg", "png", "webp", "gif", "heic", "heif", "arw", "cr2", "dng", "nef", "raf", "orf"];
@@ -428,6 +429,15 @@ function extractPhotoMeta(filepath, modifiedUnix, filesize) {
             meta.shutter_label = shutterLabel(expTime);
         }
         meta.iso = exifInt(exif, "ISOSpeedRatings");
+
+        // Orientations 5-8 turn the picture a quarter: the stored pixels (and
+        // the size read above) are sideways, the photo as shown is not.
+        var orient = exifInt(exif, "Orientation");
+        if (orient >= 5 && orient <= 8 && meta.width && meta.height) {
+            var tw = meta.width;
+            meta.width = meta.height;
+            meta.height = tw;
+        }
     }
 
     // Derived geometry fields.
@@ -560,23 +570,57 @@ function isExcluded(filepath, excludeList) {
  *  Query parsing (iOS-style free text) + SQL builder
  * ------------------------------------------------------------------ */
 
+// A number that may be written as a fraction ("1/250", for shutter speeds)
+// and may carry a trailing "s" (seconds).
+function parseNum(s) {
+    s = ("" + s).trim().replace(/s$/i, "");
+    var m = s.match(/^([0-9.]+)\s*\/\s*([0-9.]+)$/);
+    if (m) {
+        var den = parseFloat(m[2]);
+        return den ? parseFloat(m[1]) / den : NaN;
+    }
+    return parseFloat(s);
+}
+
+// File size with an optional unit (b, kb, mb, gb; none means MB) => bytes.
+function parseBytes(s) {
+    var m = ("" + s).trim().toLowerCase().match(/^([0-9.]+)\s*(b|k|kb|m|mb|g|gb)?$/);
+    if (!m) {
+        return NaN;
+    }
+    var n = parseFloat(m[1]);
+    var unit = m[2] || "mb";
+    if (unit === "b") {
+        return n;
+    }
+    if (unit.charAt(0) === "k") {
+        return n * 1024;
+    }
+    if (unit.charAt(0) === "g") {
+        return n * 1073741824;
+    }
+    return n * 1048576;
+}
+
 // Numeric range token: ">800", "<1600", "800-3200", "800..3200", "100".
-function parseRange(s) {
+// toNum reads one bound (parseNum unless given).
+function parseRange(s, toNum) {
+    toNum = toNum || parseNum;
     s = ("" + s).trim();
     var m;
     if ((m = s.match(/^>=?\s*(.+)$/))) {
-        return { min: parseFloat(m[1]), max: null };
+        return { min: toNum(m[1]), max: null };
     }
     if ((m = s.match(/^<=?\s*(.+)$/))) {
-        return { min: null, max: parseFloat(m[1]) };
+        return { min: null, max: toNum(m[1]) };
     }
     if ((m = s.match(/^(.+?)\.\.(.+)$/))) {
-        return { min: parseFloat(m[1]), max: parseFloat(m[2]) };
+        return { min: toNum(m[1]), max: toNum(m[2]) };
     }
-    if ((m = s.match(/^([0-9.]+)-([0-9.]+)$/))) {
-        return { min: parseFloat(m[1]), max: parseFloat(m[2]) };
+    if ((m = s.match(/^([^\-]+)-([^\-]+)$/))) {
+        return { min: toNum(m[1]), max: toNum(m[2]) };
     }
-    var v = parseFloat(s);
+    var v = toNum(s);
     if (isNaN(v)) {
         return null;
     }
@@ -710,35 +754,47 @@ function pushMonth(filter, mnum) {
 }
 
 // Every category is a list. Within a category the values are OR-ed; across
-// categories they are AND-ed (see buildWhere). `raw` is the single boolean
-// exception (a shorthand that expands into the RAW extensions).
+// categories they are AND-ed (see buildWhere). Free-text terms are the one
+// exception: each term must match (they narrow the search like the chips do).
+// `raw` is a boolean shorthand that expands into the RAW extensions, and
+// `nots` holds one filter per "-token", each of which must NOT match.
 function newFilter() {
     return {
-        text: [], filename: [], ext: [], raw: false,
+        text: [], filename: [], folder: [], ext: [], raw: false,
         model: [], make: [], lens: [], orientation: [], month: [],
-        iso: [], aperture: [], focal: [], mp: [], width: [], height: [],
-        taken: [], modified: [], rating: []
+        iso: [], aperture: [], focal: [], shutter: [], mp: [], width: [], height: [],
+        size: [], hour: [], taken: [], modified: [], rating: [],
+        nots: []
     };
 }
 
-// Split a query string into tokens, honouring `key:"quoted value"` and "quoted".
+// Split a query string into tokens, honouring `key:"quoted value"`, "quoted"
+// and a leading "-" (exclusion) on either form.
 function tokenizeQuery(q) {
     var tokens = [];
-    var re = /(\w+):"([^"]*)"|"([^"]*)"|(\S+)/g;
+    var re = /(-?)(\w+):"([^"]*)"|(-?)"([^"]*)"|(\S+)/g;
     var m;
     while ((m = re.exec(q)) !== null) {
-        if (m[1] !== undefined) {
-            tokens.push(m[1] + ":" + m[2]);
-        } else if (m[3] !== undefined) {
-            tokens.push(m[3]);
-        } else {
-            tokens.push(m[4]);
+        if (m[6]) {
+            tokens.push(m[6]);
+        } else if (m[2]) {
+            tokens.push((m[1] || "") + m[2] + ":" + (m[3] || ""));
+        } else if (m[5]) {
+            tokens.push((m[4] || "") + m[5]);
         }
     }
     return tokens;
 }
 
 function classifyToken(filter, token) {
+    // "-word" / "-key:value": photos matching the rest are left out
+    if (token.length > 1 && token.charAt(0) === "-") {
+        var neg = newFilter();
+        classifyToken(neg, token.substring(1));
+        filter.nots.push(neg);
+        return;
+    }
+
     var lower = token.toLowerCase();
     var colon = token.indexOf(":");
     var key = "";
@@ -804,7 +860,12 @@ function classifyToken(filter, token) {
                 return;
             case "focal":
             case "fl":
-                pushRange(filter, "focal", parseRange(val.replace(/mm$/i, "")));
+                pushRange(filter, "focal", parseRange(val.replace(/mm/ig, "")));
+                return;
+            case "shutter":
+            case "exposure":
+            case "ss":
+                pushRange(filter, "shutter", parseRange(val));
                 return;
             case "mp":
             case "megapixels":
@@ -818,6 +879,14 @@ function classifyToken(filter, token) {
             case "h":
                 pushRange(filter, "height", parseRange(val));
                 return;
+            case "size":
+            case "filesize":
+                pushRange(filter, "size", parseRange(val, parseBytes));
+                return;
+            case "hour":
+            case "time":
+                pushRange(filter, "hour", parseRange(val));
+                return;
             case "model":
             case "camera":
                 filter.model.push(val);
@@ -831,12 +900,24 @@ function classifyToken(filter, token) {
                 return;
             case "ext":
             case "type":
-                filter.ext.push(val.toLowerCase().replace(/^\./, ""));
+                var exts = val.split(",");
+                for (var ei = 0; ei < exts.length; ei++) {
+                    var e = exts[ei].toLowerCase().replace(/^\./, "").trim();
+                    if (e === "raw") {
+                        filter.raw = true;
+                    } else if (e.length) {
+                        filter.ext.push(e);
+                    }
+                }
                 return;
             case "name":
             case "filename":
                 filter.filename.push(val);
                 return;
+            case "folder":
+            case "in":
+                filter.folder.push(val);
+                return;
             case "orientation":
                 filter.orientation.push(val.toLowerCase());
                 return;
@@ -896,10 +977,13 @@ function applyExplicitFilters(filter, f) {
         }
         var list = Array.isArray(v) ? v : [v];
         for (var k = 0; k < list.length; k++) {
-            filter[field].push("" + list[k]);
+            if (("" + list[k]).length) {
+                filter[field].push("" + list[k]);
+            }
         }
     }
     pushStrings("filename", f.filename);
+    pushStrings("folder", f.folder);
     pushStrings("model", f.model);
     pushStrings("make", f.make);
     pushStrings("lens", f.lens);
@@ -917,7 +1001,7 @@ function applyExplicitFilters(filter, f) {
             filter.ext.push(("" + f.ext[i]).toLowerCase().replace(/^\./, ""));
         }
     }
-    var ranges = ["iso", "aperture", "focal", "mp", "width", "height", "rating"];
+    var ranges = ["iso", "aperture", "focal", "shutter", "mp", "width", "height", "size", "hour", "rating"];
     for (var r = 0; r < ranges.length; r++) {
         var rv = f[ranges[r]];
         if (rv) {
@@ -1023,26 +1107,69 @@ function addRangeGroup(clauses, args, col, list) {
     pushOrGroup(clauses, ors);
 }
 
-// Build the parameterised WHERE clause + args for a structured filter.
-// Within a category multiple values are OR-ed; categories are AND-ed together.
-function buildWhere(filter) {
-    var clauses = [];
-    var args = [];
+// The part of a folder path after its drive ("user:/Photo/Trip" => "Photo/Trip").
+var FOLDER_PATH_SQL = "LOWER(substr(IFNULL(photos.folder,''), instr(IFNULL(photos.folder,''), ':/') + 2))";
+
+// Folder scope. A virtual path ("user:/Photo/Trip") matches that folder and
+// every folder below it; any other text matches folder paths containing it.
+function addFolderGroup(clauses, args, list) {
+    if (!list || !list.length) {
+        return;
+    }
+    var ors = [];
+    for (var i = 0; i < list.length; i++) {
+        var f = ("" + list[i]).trim().replace(/\/+$/, "");
+        if (f.length === 0) {
+            continue;
+        }
+        if (/^[^\/]+:(\/.*)?$/.test(f)) {
+            ors.push("(photos.folder = ? OR substr(photos.folder, 1, length(?)) = ?)");
+            args.push(f, f + "/", f + "/");
+        } else {
+            ors.push(FOLDER_PATH_SQL + " LIKE ?");
+            args.push("%" + f.toLowerCase() + "%");
+        }
+    }
+    pushOrGroup(clauses, ors);
+}
+
+// Hour of the day the photo was taken (0-23). The EXIF time is stored as the
+// camera's own clock, so the hour is the local time it showed. A range whose
+// start is after its end wraps over midnight ("hour:22..4").
+var HOUR_SQL = "CAST(strftime('%H', taken_date, 'unixepoch') AS INTEGER)";
+function addHourGroup(clauses, args, list) {
+    if (!list || !list.length) {
+        return;
+    }
+    var ors = [];
+    for (var i = 0; i < list.length; i++) {
+        var r = list[i];
+        var lo = (r.min === null || r.min === undefined) ? 0 : r.min;
+        var hi = (r.max === null || r.max === undefined) ? 23 : r.max;
+        ors.push("(" + HOUR_SQL + " >= ? " + (lo <= hi ? "AND " : "OR ") + HOUR_SQL + " <= ?)");
+        args.push(lo, hi);
+    }
+    // Only photos whose time came from the camera know their hour.
+    clauses.push("(has_exif = 1 AND " + (ors.length > 1 ? "(" + ors.join(" OR ") + ")" : ors[0]) + ")");
+}
+
+// Add the AND-ed clauses of one structured filter (its "-tokens" included).
+function addFilterClauses(clauses, args, filter) {
     var i;
 
-    // Free text: OR across terms, each term matching any of several columns.
+    // Free text: every term must match one of the descriptive columns.
     if (filter.text && filter.text.length) {
-        var textOrs = [];
         for (i = 0; i < filter.text.length; i++) {
             var term = "%" + filter.text[i].toLowerCase() + "%";
-            textOrs.push("(filename_lc LIKE ? OR LOWER(IFNULL(camera_model,'')) LIKE ?" +
-                " OR LOWER(IFNULL(lens_model,'')) LIKE ? OR LOWER(IFNULL(camera_make,'')) LIKE ?)");
-            args.push(term, term, term, term);
+            clauses.push("(filename_lc LIKE ? OR LOWER(IFNULL(camera_model,'')) LIKE ?" +
+                " OR LOWER(IFNULL(lens_model,'')) LIKE ? OR LOWER(IFNULL(camera_make,'')) LIKE ?" +
+                " OR " + FOLDER_PATH_SQL + " LIKE ?)");
+            args.push(term, term, term, term, term);
         }
-        pushOrGroup(clauses, textOrs);
     }
 
     addLikeGroup(clauses, args, "filename_lc", filter.filename);
+    addFolderGroup(clauses, args, filter.folder);
     addNullableLikeGroup(clauses, args, "camera_model", filter.model);
     addNullableLikeGroup(clauses, args, "camera_make", filter.make);
     addNullableLikeGroup(clauses, args, "lens_model", filter.lens);
@@ -1072,23 +1199,44 @@ function buildWhere(filter) {
     addRangeGroup(clauses, args, "iso", filter.iso);
     addRangeGroup(clauses, args, "aperture", filter.aperture);
     addRangeGroup(clauses, args, "focal_length", filter.focal);
+    addRangeGroup(clauses, args, "shutter", filter.shutter);
     addRangeGroup(clauses, args, "megapixels", filter.mp);
     addRangeGroup(clauses, args, "width", filter.width);
     addRangeGroup(clauses, args, "height", filter.height);
+    addRangeGroup(clauses, args, "filesize", filter.size);
     addRangeGroup(clauses, args, "taken_date", filter.taken);
     addRangeGroup(clauses, args, "modified_date", filter.modified);
+    addHourGroup(clauses, args, filter.hour);
     // Rating lives in the joined photo_ratings table; unrated photos count as 0.
     addRangeGroup(clauses, args, "IFNULL(photo_ratings.rating, 0)", filter.rating);
 
+    // Exclusions: each "-token" leaves out what it alone would match. A NULL
+    // comparison (photo without that data) counts as "does not match".
+    if (filter.nots) {
+        for (i = 0; i < filter.nots.length; i++) {
+            var sub = [];
+            addFilterClauses(sub, args, filter.nots[i]);
+            if (sub.length) {
+                clauses.push("NOT IFNULL((" + sub.join(" AND ") + "), 0)");
+            }
+        }
+    }
+}
+
+// Build the parameterised WHERE clause + args for a structured filter.
+function buildWhere(filter) {
+    var clauses = [];
+    var args = [];
+    addFilterClauses(clauses, args, filter);
     return { clause: clauses.length ? clauses.join(" AND ") : "1=1", args: args };
 }
 
 function buildOrderBy(sort) {
     switch (sort) {
         case "taken_asc":
-            return "taken_date ASC";
+            return "taken_date ASC, filename_lc ASC";
         case "taken_desc":
-            return "taken_date DESC";
+            return "taken_date DESC, filename_lc ASC";
         case "modified_asc":
             return "modified_date ASC";
         case "modified_desc":
@@ -1101,11 +1249,15 @@ function buildOrderBy(sort) {
             return "filesize ASC";
         case "size_desc":
             return "filesize DESC";
+        case "ext_asc":
+            return "ext ASC, filename_lc ASC";
+        case "ext_desc":
+            return "ext DESC, filename_lc ASC";
         case "mp_desc":
             return "megapixels DESC";
         case "mp_asc":
             return "megapixels ASC";
         default:
-            return "taken_date DESC";
+            return "taken_date DESC, filename_lc ASC";
     }
 }

+ 11 - 3
src/web/Photo/backend/listFolder.js

@@ -129,18 +129,23 @@ function main(){
     // taken_date = EXIF DateTimeOriginal for every indexed photo, so resolve it
     // with one folder-scoped query instead of decoding EXIF per file per request.
     // The index only refines the dates: if it cannot be read (busy, damaged),
-    // list the folder anyway and let mtime stand in.
+    // list the folder anyway and let mtime stand in. The index also knows the
+    // upright size of each photo, which the waterfall layout needs up front.
     var takenMap = {};
+    var sizeMap = {};
     try {
         var db = openIndexDB();
         if (db != null) {
             // `folder` is the request wildcard ("user:/Photo/*"); its dirname is
             // the folder being listed, which is exactly how the index keys its rows.
-            var rows = db.query("SELECT filepath, taken_date FROM photos WHERE folder = ?", [dirname(folder)]);
+            var rows = db.query("SELECT filepath, taken_date, width, height FROM photos WHERE folder = ?", [dirname(folder)]);
             for (var ri = 0; ri < rows.length; ri++) {
                 if (rows[ri].taken_date) {
                     takenMap[rows[ri].filepath] = rows[ri].taken_date;
                 }
+                if (rows[ri].width && rows[ri].height) {
+                    sizeMap[rows[ri].filepath] = [rows[ri].width, rows[ri].height];
+                }
             }
             db.close();
         }
@@ -159,11 +164,14 @@ function main(){
         if (mtime === false){
             mtime = 0;
         }
+        var dim = sizeMap[filepath];
         filesWithSize.push({
             filepath: filepath,
             filesize: filesize,
             mtime: mtime,
-            taken_date: takenMap[filepath] || null
+            taken_date: takenMap[filepath] || null,
+            width: dim ? dim[0] : null,
+            height: dim ? dim[1] : null
         });
     }
 

+ 129 - 0
src/web/Photo/backend/photoSettings.js

@@ -0,0 +1,129 @@
+/*
+    photoSettings.js
+
+    Backend of the Photo settings dialog. Settings live in the per-user index
+    database (index_meta), which an index rebuild keeps.
+
+    Request body (JSON) by action:
+      { action: "get" }
+          => { preview: {mode, path, dir, defaultDir}, index: {total, lastIndexed},
+               exclude: [...] }
+      { action: "set", previewMode: "appdata|custom|realtime", previewPath }
+          => same as get, or { error } when the custom folder cannot be used
+      { action: "cacheStats", dir? }   => { files, bytes } of the cache folder
+      { action: "clearCache", dir? }   => { removed }
+          dir defaults to the cache folder in use; another folder is only
+          accepted when it is the default or the saved custom folder.
+      { action: "setExclude", folders: ["Screenshots", ...] }  => same as get
+*/
+
+includes("previewlib.js");
+
+function settingsReply(db) {
+    var st = previewSettings(db);
+    var totalRow = db.queryRow("SELECT COUNT(*) AS c FROM photos");
+    return {
+        preview: { mode: st.mode, path: st.path, dir: st.dir, defaultDir: PREVIEW_DEFAULT_DIR },
+        index: {
+            total: totalRow ? totalRow.c : 0,
+            lastIndexed: parseInt(metaGet(db, "last_indexed", "0")) || 0
+        },
+        exclude: parseExcludeList(metaGet(db, "exclude_folders", "[]"))
+    };
+}
+
+// Whether a folder is one of the photo library roots or inside one
+function insidePhotoLibrary(path) {
+    var roots = getPhotoRoots();
+    for (var i = 0; i < roots.length; i++) {
+        var r = roots[i].replace(/\/+$/, "");
+        if (path === r || path.indexOf(r + "/") === 0) {
+            return true;
+        }
+    }
+    return false;
+}
+
+// A cache folder this request may look into or clear
+function knownCacheDir(db, dir) {
+    var st = previewSettings(db);
+    if (!dir) {
+        return st.dir;
+    }
+    dir = previewCleanFolder(dir);
+    if (dir === PREVIEW_DEFAULT_DIR || (dir !== "" && dir === previewCleanFolder(st.path))) {
+        return dir;
+    }
+    return null;
+}
+
+function main() {
+    var payload = {};
+    try {
+        payload = JSON.parse((typeof POST_data !== "undefined") ? POST_data : "{}") || {};
+    } catch (e) {
+        payload = {};
+    }
+
+    var db = openIndexDB();
+    if (db == null) {
+        sendJSONResp(JSON.stringify({ error: "index unavailable" }));
+        return;
+    }
+
+    var action = payload.action || "get";
+    var reply;
+    if (action === "set") {
+        var mode = "" + (payload.previewMode || "appdata");
+        if (PREVIEW_MODES.indexOf(mode) < 0) {
+            reply = { error: "unknown preview mode" };
+        } else if (mode === "custom") {
+            var path = previewCleanFolder(payload.previewPath);
+            if (path === "") {
+                reply = { error: "not a folder path" };
+            } else if (!filelib.fileExists(path) || !filelib.isDir(path)) {
+                reply = { error: "folder not found" };
+            } else if (!pathCanWrite(path)) {
+                reply = { error: "folder is read only" };
+            } else if (insidePhotoLibrary(path)) {
+                // Previews there would be indexed and listed as photos
+                reply = { error: "folder is inside the photo library" };
+            } else {
+                metaSet(db, "preview_mode", mode);
+                metaSet(db, "preview_path", path);
+            }
+        } else {
+            metaSet(db, "preview_mode", mode);
+        }
+        if (!reply) {
+            reply = settingsReply(db);
+        }
+    } else if (action === "cacheStats" || action === "clearCache") {
+        var dir = knownCacheDir(db, payload.dir);
+        if (dir === null) {
+            reply = action === "cacheStats" ? { files: 0, bytes: 0 } : { removed: 0 };
+        } else if (action === "cacheStats") {
+            reply = previewCacheStats(dir);
+        } else {
+            reply = { removed: previewCacheClear(dir) };
+        }
+    } else if (action === "setExclude") {
+        var list = Array.isArray(payload.folders) ? payload.folders : [];
+        var clean = [];
+        for (var i = 0; i < list.length; i++) {
+            var frag = ("" + list[i]).trim().replace(/^\/+|\/+$/g, "");
+            if (frag.length && clean.indexOf(frag) < 0) {
+                clean.push(frag);
+            }
+        }
+        metaSet(db, "exclude_folders", JSON.stringify(clean));
+        reply = settingsReply(db);
+    } else {
+        reply = settingsReply(db);
+    }
+
+    db.close();
+    sendJSONResp(JSON.stringify(reply));
+}
+
+main();

+ 223 - 0
src/web/Photo/backend/previewlib.js

@@ -0,0 +1,223 @@
+/*
+    previewlib.js
+
+    Previews for the waterfall layout: every photo drawn upright and fitted to
+    PREVIEW_MAX_WIDTH x PREVIEW_MAX_HEIGHT, keeping its shape. The system
+    thumbnails are square crops, so they cannot show a photo in its own shape.
+    The drawing is done by imagelib.renderPreview (RAW, HEIC and the EXIF
+    orientation included).
+
+    Where previews go is the user's choice (Photo > Settings). It is kept in
+    the index database's index_meta table, which survives an index rebuild:
+      preview_mode  "appdata"   cache in PREVIEW_DEFAULT_DIR (default)
+                    "custom"    cache in the folder in preview_path
+                    "realtime"  draw on every request and store nothing
+    A cached preview is <dir>/<hh>/<hash>.jpg, where hash is 14 hex digits of
+    the photo's virtual path and hh its first two. It is drawn again when the
+    photo is newer than it. Only files named like that are ever deleted from a
+    cache folder, so a custom folder may hold other files too.
+
+    ES5 only (Otto VM).
+*/
+
+includes("imagedb.js");
+
+var PREVIEW_DEFAULT_DIR = "user:/.appdata/photo/previews";
+var PREVIEW_MAX_WIDTH = 720;
+var PREVIEW_MAX_HEIGHT = 2160;
+var PREVIEW_MODES = ["appdata", "custom", "realtime"];
+var PREVIEW_SHARD_RE = /^[0-9a-f]{2}$/;
+var PREVIEW_FILE_RE = /^[0-9a-f]{14}\.jpg$/;
+
+// 32 bit integer multiply (Math.imul is not part of ES5)
+function pv_imul(a, b) {
+    var ah = (a >>> 16) & 0xffff;
+    var al = a & 0xffff;
+    var bh = (b >>> 16) & 0xffff;
+    var bl = b & 0xffff;
+    return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)) | 0;
+}
+
+// 53 bit hash (cyrb53) of a string as 14 hex digits. A collision among a
+// million photos is about a one in twenty thousand chance.
+function previewHash(str) {
+    str = "" + str;
+    var h1 = 0xdeadbeef ^ 0;
+    var h2 = 0x41c6ce57 ^ 0;
+    for (var i = 0; i < str.length; i++) {
+        var ch = str.charCodeAt(i);
+        h1 = pv_imul(h1 ^ ch, 2654435761);
+        h2 = pv_imul(h2 ^ ch, 1597334677);
+    }
+    h1 = pv_imul(h1 ^ (h1 >>> 16), 2246822507);
+    h1 ^= pv_imul(h2 ^ (h2 >>> 13), 3266489909);
+    h2 = pv_imul(h2 ^ (h2 >>> 16), 2246822507);
+    h2 ^= pv_imul(h1 ^ (h1 >>> 13), 3266489909);
+    var n = 4294967296 * (2097151 & h2) + (h1 >>> 0);
+    var hex = n.toString(16);
+    while (hex.length < 14) {
+        hex = "0" + hex;
+    }
+    return hex;
+}
+
+// A virtual folder path the user typed or picked, without trailing slashes,
+// or "" when it is not one ("disk1:/Cache", "user:/").
+function previewCleanFolder(path) {
+    path = ("" + (path || "")).trim().replace(/\\/g, "/");
+    if (!/^[^\/:]+:\//.test(path) && !/^[^\/:]+:$/.test(path)) {
+        return "";
+    }
+    var parts = path.split("/");
+    for (var i = 0; i < parts.length; i++) {
+        if (parts[i] === "..") {
+            return "";
+        }
+    }
+    path = path.replace(/\/+$/, "");
+    if (/^[^\/:]+:$/.test(path)) {
+        path = path + "/";
+    }
+    return path;
+}
+
+// The preview settings of this user: { mode, path, dir }. dir is the cache
+// folder, or null for realtime previews.
+function previewSettings(db) {
+    var mode = "appdata";
+    var path = "";
+    if (db != null) {
+        mode = metaGet(db, "preview_mode", "appdata");
+        path = metaGet(db, "preview_path", "");
+    }
+    if (PREVIEW_MODES.indexOf(mode) < 0) {
+        mode = "appdata";
+    }
+    var dir = PREVIEW_DEFAULT_DIR;
+    if (mode === "realtime") {
+        dir = null;
+    } else if (mode === "custom" && previewCleanFolder(path) !== "") {
+        dir = previewCleanFolder(path);
+    }
+    return { mode: mode, path: path, dir: dir };
+}
+
+function previewJoin(dir, name) {
+    return dir.charAt(dir.length - 1) === "/" ? dir + name : dir + "/" + name;
+}
+
+// Cache file of a photo inside a cache folder
+function previewCacheFile(dir, filepath) {
+    var h = previewHash(filepath);
+    return previewJoin(previewJoin(dir, h.substring(0, 2)), h + ".jpg");
+}
+
+// Whether the preview drawer reads this kind of file
+function previewSupported(filepath) {
+    return db_isImageFile(filepath);
+}
+
+// The cached preview of a photo as {src, w, h, v}, or null when there is none
+// or the photo changed after it was drawn. v (its time) busts browser caches.
+function previewLookup(dir, filepath) {
+    var file = previewCacheFile(dir, filepath);
+    if (!filelib.fileExists(file)) {
+        return null;
+    }
+    var cacheTime = filelib.mtime(file, true);
+    var photoTime = filelib.mtime(filepath, true);
+    if (cacheTime === false || (photoTime !== false && photoTime > cacheTime)) {
+        return null;
+    }
+    var dim = imagelib.getImageDimension(file);
+    if (!dim || !dim[0] || !dim[1]) {
+        return null;
+    }
+    return { src: file, w: dim[0], h: dim[1], v: cacheTime };
+}
+
+// Draw the preview of a photo into dir (or inline when dir is null)
+function previewRender(dir, filepath) {
+    var r;
+    if (dir === null) {
+        r = imagelib.renderPreview(filepath, "", PREVIEW_MAX_WIDTH, PREVIEW_MAX_HEIGHT);
+        if (!r || !r.dataURL) {
+            return { error: "failed" };
+        }
+        return { dataURL: r.dataURL, w: r.width, h: r.height };
+    }
+    var file = previewCacheFile(dir, filepath);
+    r = imagelib.renderPreview(filepath, file, PREVIEW_MAX_WIDTH, PREVIEW_MAX_HEIGHT);
+    if (!r || !r.width) {
+        return { error: "failed" };
+    }
+    var t = filelib.mtime(file, true);
+    return { src: file, w: r.width, h: r.height, v: t || Math.floor(Date.now() / 1000) };
+}
+
+// The entries of a folder as [{Filename, Filepath, Filesize, IsDir}]. readdir,
+// unlike glob, lists folders below a hidden one such as user:/.appdata.
+function previewReadDir(dir) {
+    try {
+        var list = filelib.readdir(dir, "default");
+        if (typeof list === "string") {
+            list = JSON.parse(list);
+        }
+        return Array.isArray(list) ? list : [];
+    } catch (e) {
+        return [];
+    }
+}
+
+// Calls fn(vpath, bytes) for every preview file in a cache folder. Only the
+// shard folders 00-ff are looked into, never the rest of a custom folder.
+function previewEachCacheFile(dir, fn) {
+    if (!dir || !filelib.fileExists(dir)) {
+        return;
+    }
+    var hex = "0123456789abcdef";
+    for (var a = 0; a < 16; a++) {
+        for (var b = 0; b < 16; b++) {
+            var shard = previewJoin(dir, hex.charAt(a) + hex.charAt(b));
+            if (!filelib.fileExists(shard)) {
+                continue;
+            }
+            var files = previewReadDir(shard);
+            for (var i = 0; i < files.length; i++) {
+                if (!files[i].IsDir && PREVIEW_FILE_RE.test(files[i].Filename)) {
+                    fn(previewJoin(shard, files[i].Filename), files[i].Filesize || 0);
+                }
+            }
+        }
+    }
+}
+
+// How many previews a cache folder holds and their size in bytes
+function previewCacheStats(dir) {
+    var stats = { files: 0, bytes: 0 };
+    previewEachCacheFile(dir, function (file, bytes) {
+        stats.files++;
+        stats.bytes += bytes;
+    });
+    return stats;
+}
+
+// Delete every preview of a cache folder, and the shard folders left empty
+function previewCacheClear(dir) {
+    var removed = 0;
+    var shards = {};
+    previewEachCacheFile(dir, function (file) {
+        if (filelib.deleteFile(file)) {
+            removed++;
+        }
+        var parts = ("" + file).split("/");
+        parts.pop();
+        shards[parts.join("/")] = true;
+    });
+    for (var shard in shards) {
+        if (PREVIEW_SHARD_RE.test(shard.split("/").pop()) && previewReadDir(shard).length === 0) {
+            filelib.deleteFile(shard);
+        }
+    }
+    return removed;
+}

+ 70 - 0
src/web/Photo/backend/previews.js

@@ -0,0 +1,70 @@
+/*
+    previews.js
+
+    Previews of photos for the waterfall layout (see previewlib.js).
+
+    Request body (JSON):
+      { "files": ["user:/Photo/a.jpg", ...], "generate": false }
+        generate false  report the previews already cached (quick, up to 200
+                        files); the others come back as {pending: true}
+        generate true   draw the missing ones (slow, up to 6 files)
+
+    Response (JSON):
+      { mode, items: { <vpath>: item } } where item is one of
+        { src, w, h, v }      cached preview: load ../media?file=<src>&v=<v>
+        { dataURL, w, h }     realtime preview, drawn for this request
+        { pending: true }     not drawn yet (ask again with generate)
+        { error }             cannot be previewed; show the thumbnail
+*/
+
+includes("previewlib.js");
+
+function main() {
+    var payload = {};
+    try {
+        payload = JSON.parse((typeof POST_data !== "undefined") ? POST_data : "{}") || {};
+    } catch (e) {
+        payload = {};
+    }
+    var files = Array.isArray(payload.files) ? payload.files : [];
+    var generate = payload.generate === true;
+    files = files.slice(0, generate ? 6 : 200);
+
+    var db = openIndexDB();
+    var settings = previewSettings(db);
+    if (db != null) {
+        db.close();
+    }
+
+    var items = {};
+    for (var i = 0; i < files.length; i++) {
+        var f = "" + files[i];
+        if (items[f]) {
+            continue;
+        }
+        if (!previewSupported(f)) {
+            items[f] = { error: "unsupported" };
+            continue;
+        }
+        if (!filelib.fileExists(f)) {
+            items[f] = { error: "missing" };
+            continue;
+        }
+        if (settings.dir !== null) {
+            var hit = previewLookup(settings.dir, f);
+            if (hit) {
+                items[f] = hit;
+                continue;
+            }
+        }
+        if (!generate) {
+            items[f] = { pending: true };
+            continue;
+        }
+        items[f] = previewRender(settings.dir, f);
+    }
+
+    sendJSONResp(JSON.stringify({ mode: settings.mode, items: items }));
+}
+
+main();

+ 84 - 0
src/web/Photo/backend/searchFacets.js

@@ -0,0 +1,84 @@
+/*
+    searchFacets.js
+
+    What the Photo filter panel can offer, read from the per-user index: the
+    cameras, lenses and file types present (with photo counts), how many
+    photos carry each star rating, and the ranges of the shooting values, so
+    the panel only lists choices that will match something.
+
+    Request body (JSON): { "folder": "user:/Photo/Trip" }   optional scope,
+        the same as searchPhotos.js (that folder and every folder below it)
+    Response (JSON):
+      { available, total, cameras: [{v, make, c}], lenses: [{v, c}],
+        exts: [{v, c}], ratings: {0: c, 1: c, ...},
+        ranges: { iso, aperture, focal, taken, megapixels, filesize } each {min, max} }
+*/
+
+includes("imagedb.js");
+
+function main() {
+    var payload = {};
+    try {
+        payload = JSON.parse((typeof POST_data !== "undefined") ? POST_data : "{}") || {};
+    } catch (e) {
+        payload = {};
+    }
+
+    var db = openIndexDB();
+    if (db == null) {
+        sendJSONResp(JSON.stringify({ available: false }));
+        return;
+    }
+
+    var filter = newFilter();
+    if (payload.folder) {
+        filter.folder.push("" + payload.folder);
+    }
+    var w = buildWhere(filter);
+    var from = " FROM photos LEFT JOIN photo_ratings ON photo_ratings.filepath = photos.filepath WHERE " + w.clause;
+
+    var cameras = db.query("SELECT camera_model AS v, MAX(camera_make) AS make, COUNT(*) AS c" + from +
+        " AND camera_model IS NOT NULL AND camera_model <> '' GROUP BY camera_model ORDER BY c DESC LIMIT 60", w.args);
+    var lenses = db.query("SELECT lens_model AS v, COUNT(*) AS c" + from +
+        " AND lens_model IS NOT NULL AND lens_model <> '' GROUP BY lens_model ORDER BY c DESC LIMIT 60", w.args);
+    var exts = db.query("SELECT ext AS v, COUNT(*) AS c" + from +
+        " AND ext IS NOT NULL AND ext <> '' GROUP BY ext ORDER BY c DESC", w.args);
+    var ratingRows = db.query("SELECT IFNULL(photo_ratings.rating, 0) AS r, COUNT(*) AS c" + from +
+        " GROUP BY r", w.args);
+    var agg = db.queryRow("SELECT COUNT(*) AS total," +
+        " MIN(iso) AS isoMin, MAX(iso) AS isoMax," +
+        " MIN(aperture) AS fMin, MAX(aperture) AS fMax," +
+        " MIN(focal_length) AS focalMin, MAX(focal_length) AS focalMax," +
+        " MIN(taken_date) AS takenMin, MAX(taken_date) AS takenMax," +
+        " MIN(megapixels) AS mpMin, MAX(megapixels) AS mpMax," +
+        " MIN(filesize) AS sizeMin, MAX(filesize) AS sizeMax" + from, w.args) || {};
+    db.close();
+
+    var ratings = {};
+    for (var i = 0; i < ratingRows.length; i++) {
+        ratings[ratingRows[i].r] = ratingRows[i].c;
+    }
+
+    function range(lo, hi) {
+        return { min: (lo === undefined ? null : lo), max: (hi === undefined ? null : hi) };
+    }
+
+    sendJSONResp(JSON.stringify({
+        available: true,
+        total: agg.total || 0,
+        cameras: cameras,
+        lenses: lenses,
+        exts: exts,
+        ratings: ratings,
+        ranges: {
+            iso: range(agg.isoMin, agg.isoMax),
+            aperture: range(agg.fMin, agg.fMax),
+            focal: range(agg.focalMin, agg.focalMax),
+            taken: range(agg.takenMin, agg.takenMax),
+            megapixels: range(agg.mpMin, agg.mpMax),
+            filesize: range(agg.sizeMin, agg.sizeMax)
+        }
+    }));
+}
+
+main();

+ 20 - 8
src/web/Photo/backend/searchPhotos.js

@@ -3,14 +3,15 @@
 
     Search the per-user photo index. Accepts an iOS-style free-text query and/or
     a structured filter object, and returns matching photos. Search covers — but
-    is not limited to — file name, resolution, shooting parameters (camera, lens,
-    ISO, aperture, shutter, focal length), the date a photo was taken (created)
-    and its file modification date.
+    is not limited to — file name, folder, resolution, shooting parameters
+    (camera, lens, ISO, aperture, shutter, focal length), the date and hour a
+    photo was taken, its file size and its file modification date.
 
     Request body (JSON, all optional):
       {
         "q": "canon iso:1600 f/2.8 2023 landscape",  // free-text query
         "filters": { ... },                          // structured overrides
+        "folder": "user:/Photo/Trip",                // only this folder + below
         "sort": "taken_desc",                        // see buildOrderBy()
         "limit": 1000,
         "offset": 0
@@ -22,8 +23,9 @@
     Each result carries `filepath` and `filesize`, so the existing Photo grid /
     viewer renders them with no further changes.
 
-    Free-text query tokens (combine freely, all AND-ed together):
-      canon              free text -> file name / camera / lens / make
+    Free-text query tokens (combine freely, all AND-ed together; several values
+    of one filter, like two cameras, are OR-ed):
+      canon              free text -> file name / camera / lens / make / folder
       name:beach         file name contains
       model:"EOS R5"     camera model
       make:sony          camera make
@@ -31,15 +33,21 @@
       iso:1600           ISO equals (or 800-3200, >800, <1600)
       f/2.8  aperture:2  aperture (or 1.4-2.8)
       focal:50  50mm     focal length mm (or 24-70)
+      shutter:<=1/1000   exposure time (1/250..1/30, >=1 for long exposures)
       mp:24  mp:>20      megapixels
       width:>4000        pixel width   (also w:)
       height:>3000       pixel height  (also h:)
+      size:>5mb          file size (kb / mb / gb; MB when no unit)
       landscape          orientation (portrait / square)
-      .jpg  raw          file type / RAW group
+      .jpg  raw          file type / RAW group (type:jpg,heic,raw)
+      in:trip            folder path contains; folder:"user:/Photo/Trip" is
+                         that folder and every folder below it
       2023  year:2023    taken in year
       taken:2023-01..2023-06   taken date range  (before:/after: also work)
+      hour:22..4         hour of the day taken (camera clock, wraps midnight)
       modified:>2024-01-01     file modified date
       rating:>=4  rating:5  rating:3-5   user star rating (0 = unrated)
+      -token             leave out what the token matches (-raw, -in:screenshots)
 */
 
 includes("imagedb.js");
@@ -61,8 +69,8 @@ function main() {
     if (isNaN(limit) || limit <= 0) {
         limit = 500;
     }
-    if (limit > 2000) {
-        limit = 2000;
+    if (limit > 5000) {
+        limit = 5000;
     }
     var offset = parseInt(payload.offset);
     if (isNaN(offset) || offset < 0) {
@@ -77,6 +85,10 @@ function main() {
 
     var filter = parseSearchQuery(q);
     applyExplicitFilters(filter, filters);
+    if (payload.folder) {
+        // "This folder" scope of the filter panel
+        filter.folder.push("" + payload.folder);
+    }
 
     var w = buildWhere(filter);
     var orderBy = buildOrderBy(sort);

+ 76 - 6
src/web/Photo/backend/searchSuggest.js

@@ -8,12 +8,16 @@
       - When the box is empty: popular facets (top cameras, recent years,
         orientation, common file types) so there is always something to tap.
       - While typing: completions for the active (last) token — matching camera
-        models, lenses, file names, years, file types, plus smart filter tokens
-        (iso:..., f/...) when the user starts typing a known filter keyword.
+        models, lenses, folders, file names, years, file types, plus smart filter
+        tokens (iso:..., f/..., shutter / size / time of day presets) when the
+        user starts typing a known filter keyword. A leading "-" asks for the
+        same completions as exclusions.
 
     Each suggestion: { type, label, value, hint }
-      type  -> drives the icon on the front-end (camera/lens/date/type/file/filter)
-      label -> what is shown to the user
+      type  -> drives the icon on the front-end
+               (camera/lens/date/type/file/folder/filter/rating/shutter/size/time)
+      label -> what is shown to the user (the front-end translates the
+               labels that are not data)
       value -> text inserted into the query box when picked
       hint  -> small right-aligned note (usually a photo count)
 
@@ -23,6 +27,27 @@
 
 includes("imagedb.js");
 
+// Presets offered for the filter keywords, as query tokens
+var SHUTTER_PRESETS = [
+    ["shutter:<=1/1000", "Faster than 1/1000 s"],
+    ["shutter:1/1000..1/250", "1/1000 - 1/250 s"],
+    ["shutter:1/250..1/30", "1/250 - 1/30 s"],
+    ["shutter:1/30..1", "1/30 - 1 s"],
+    ["shutter:>=1", "Long exposure (1 s or longer)"]
+];
+var SIZE_PRESETS = [
+    ["size:<1mb", "Under 1 MB"],
+    ["size:1mb..5mb", "1 - 5 MB"],
+    ["size:5mb..20mb", "5 - 20 MB"],
+    ["size:>20mb", "Over 20 MB"]
+];
+var TIME_PRESETS = [
+    ["hour:5..11", "Morning", ["morning", "sunrise"]],
+    ["hour:12..16", "Afternoon", ["afternoon", "noon"]],
+    ["hour:17..20", "Evening", ["evening", "sunset"]],
+    ["hour:21..4", "Night", ["night", "midnight"]]
+];
+
 function buildSuggestions(db, q) {
     var out = [];
     var lower = ("" + q).toLowerCase();
@@ -71,8 +96,15 @@ function buildSuggestions(db, q) {
     var lastToken = parts[parts.length - 1].toLowerCase();
     var prefix = parts.slice(0, parts.length - 1).join(" ");
 
+    // "-word": the same completions, inserted as exclusions
+    var neg = false;
+    if (lastToken.length > 1 && lastToken.charAt(0) === "-") {
+        neg = true;
+        lastToken = lastToken.substring(1);
+    }
+
     function withPrefix(tok) {
-        return (prefix ? prefix + " " : "") + tok;
+        return (prefix ? prefix + " " : "") + (neg ? "-" : "") + tok;
     }
 
     var like = "%" + lastToken + "%";
@@ -99,6 +131,30 @@ function buildSuggestions(db, q) {
             add("rating", rs + "★ & up", withPrefix("rating:>=" + rs), (rc && rc.c ? rc.c + " photos" : ""));
         }
     }
+    // Shutter speed presets: "shutter", "exposure", "long", "fast".
+    if (lastToken.length >= 2 && ("shutter".indexOf(lastToken) === 0 || "exposure".indexOf(lastToken) === 0 ||
+            lastToken.indexOf("shutter") === 0 || lastToken === "long" || lastToken === "fast")) {
+        for (a = 0; a < SHUTTER_PRESETS.length; a++) {
+            add("shutter", SHUTTER_PRESETS[a][1], withPrefix(SHUTTER_PRESETS[a][0]), "");
+        }
+    }
+    // File size presets.
+    if (lastToken.length >= 2 && ("size".indexOf(lastToken) === 0 || lastToken.indexOf("size") === 0)) {
+        for (a = 0; a < SIZE_PRESETS.length; a++) {
+            add("size", SIZE_PRESETS[a][1], withPrefix(SIZE_PRESETS[a][0]), "");
+        }
+    }
+    // Time of day presets ("night", "morning", "hour", "time").
+    for (a = 0; a < TIME_PRESETS.length; a++) {
+        var words = TIME_PRESETS[a][2];
+        var hit = lastToken.length >= 3 && ("hour".indexOf(lastToken) === 0 || "time".indexOf(lastToken) === 0);
+        for (var wi = 0; wi < words.length && !hit; wi++) {
+            hit = lastToken.length >= 3 && words[wi].indexOf(lastToken) === 0;
+        }
+        if (hit) {
+            add("time", TIME_PRESETS[a][1], withPrefix(TIME_PRESETS[a][0]), "");
+        }
+    }
 
     // Camera models.
     list = db.query("SELECT camera_model AS m, COUNT(*) AS c FROM photos" +
@@ -116,11 +172,25 @@ function buildSuggestions(db, q) {
         add("lens", list[a].l, withPrefix("lens:\"" + list[a].l + "\""), list[a].c + " photos");
     }
 
+    // Folders whose own name contains the token (with what is below them).
+    if (lastToken.length >= 2) {
+        list = db.query("SELECT folder AS f, COUNT(*) AS c FROM photos" +
+            " WHERE LOWER(folder) LIKE ? GROUP BY folder ORDER BY c DESC LIMIT 40", [like]);
+        var folderSeen = 0;
+        for (a = 0; a < list.length && folderSeen < 3; a++) {
+            var fname = ("" + list[a].f).split("/").pop();
+            if (fname.toLowerCase().indexOf(lastToken) >= 0) {
+                add("folder", fname, withPrefix("folder:\"" + list[a].f + "\""), list[a].c + " photos");
+                folderSeen++;
+            }
+        }
+    }
+
     // File names.
     list = db.query("SELECT filename FROM photos WHERE filename_lc LIKE ?" +
         " ORDER BY filename_lc LIMIT 6", [like]);
     for (a = 0; a < list.length; a++) {
-        add("file", list[a].filename, list[a].filename, "file name");
+        add("file", list[a].filename, withPrefix(list[a].filename), "file name");
     }
 
     // Years.

+ 213 - 0
src/web/Photo/filters.js

@@ -0,0 +1,213 @@
+/*
+    filters.js
+
+    The Sort & filter panel of the Photo gallery (the funnel button at the top
+    right). Each control of the panel owns a "slot" and writes its value as
+    one search chip carrying that slot, so the chips in the search box stay
+    the single description of the search: removing a chip clears its control,
+    and every chip is a token backend/imagedb.js parses (see searchPhotos.js
+    for the syntax). Chips typed by hand have no slot and are left alone.
+
+    The panel state lives in photoListObject().pf; this file holds the pure
+    helpers it uses.
+*/
+
+// Panel values with nothing chosen
+function photoEmptyPanel() {
+    return {
+        rating: 0,          // 1-5: that many stars or more, -1: unrated
+        from: '', to: '',   // taken between (yyyy-mm-dd)
+        camera: '', lens: '',
+        types: [],          // extensions
+        orient: [],         // landscape / portrait / square
+        isoMin: '', isoMax: '',
+        fMin: '', fMax: '',
+        focalMin: '', focalMax: '',
+        shutter: '',        // PHOTO_SHUTTER_PRESETS value
+        time: '',           // PHOTO_TIME_PRESETS value
+        mpMin: '',
+        sizeMin: '', sizeMax: ''   // MB
+    };
+}
+
+var PHOTO_SHUTTER_PRESETS = [
+    { v: 'fast', q: 'shutter:<=1/1000', key: 'shutter/fast', en: 'Faster than 1/1000 s' },
+    { v: 'action', q: 'shutter:1/1000..1/250', key: 'shutter/action', en: '1/1000 – 1/250 s' },
+    { v: 'normal', q: 'shutter:1/250..1/30', key: 'shutter/normal', en: '1/250 – 1/30 s' },
+    { v: 'slow', q: 'shutter:1/30..1', key: 'shutter/slow', en: '1/30 – 1 s' },
+    { v: 'long', q: 'shutter:>=1', key: 'shutter/long', en: 'Long exposure (1 s or longer)' }
+];
+
+var PHOTO_TIME_PRESETS = [
+    { v: 'morning', q: 'hour:5..11', key: 'time/morning', en: 'Morning' },
+    { v: 'afternoon', q: 'hour:12..16', key: 'time/afternoon', en: 'Afternoon' },
+    { v: 'evening', q: 'hour:17..20', key: 'time/evening', en: 'Evening' },
+    { v: 'night', q: 'hour:21..4', key: 'time/night', en: 'Night' }
+];
+
+var PHOTO_SORT_OPTIONS = [
+    { v: 'smart', key: 'sort/smart', en: 'Natural Order', date: false },
+    { v: 'mostRecent', key: 'sort/newest', en: 'Newest First', date: true },
+    { v: 'leastRecent', key: 'sort/oldest', en: 'Oldest First', date: true },
+    { v: 'default', key: 'sort/nameAsc', en: 'Filename A→Z', date: false },
+    { v: 'reverse', key: 'sort/nameDesc', en: 'Filename Z→A', date: false },
+    { v: 'smallToLarge', key: 'sort/sizeAsc', en: 'Size Small→Large', date: false },
+    { v: 'largeToSmall', key: 'sort/sizeDesc', en: 'Size Large→Small', date: false },
+    { v: 'fileTypeAsce', key: 'sort/extAsc', en: 'Extension A→Z', date: false },
+    { v: 'fileTypeDesc', key: 'sort/extDesc', en: 'Extension Z→A', date: false }
+];
+
+// The searchPhotos.js order of a folder sort mode
+function photoBackendSort(sortOrder) {
+    switch (sortOrder) {
+        case 'leastRecent': return 'taken_asc';
+        case 'default': case 'smart': return 'name_asc';
+        case 'reverse': return 'name_desc';
+        case 'smallToLarge': return 'size_asc';
+        case 'largeToSmall': return 'size_desc';
+        case 'fileTypeAsce': return 'ext_asc';
+        case 'fileTypeDesc': return 'ext_desc';
+        default: return 'taken_desc';
+    }
+}
+
+function photoPresetLabel(list, v) {
+    for (var i = 0; i < list.length; i++) {
+        if (list[i].v === v) return T(list[i].key, list[i].en);
+    }
+    return v;
+}
+
+function photoPresetQuery(list, v) {
+    for (var i = 0; i < list.length; i++) {
+        if (list[i].v === v) return list[i].q;
+    }
+    return '';
+}
+
+// A number typed in the panel, or null
+function photoNum(v) {
+    if (v === null || v === undefined || ('' + v).trim() === '') return null;
+    var n = parseFloat(v);
+    return isNaN(n) ? null : n;
+}
+
+// "key:min..max" / "key:>=min" / "key:<=max", or '' when both are empty
+function photoRangeToken(key, min, max, unit) {
+    var lo = photoNum(min);
+    var hi = photoNum(max);
+    unit = unit || '';
+    if (lo !== null && hi !== null && lo > hi) { var t = lo; lo = hi; hi = t; }
+    if (lo !== null && hi !== null) return key + ':' + lo + unit + '..' + hi + unit;
+    if (lo !== null) return key + ':>=' + lo + unit;
+    if (hi !== null) return key + ':<=' + hi + unit;
+    return '';
+}
+
+// "a – b", "≥ a" or "≤ b", each bound passed through fmt
+function photoRangeLabel(min, max, fmt) {
+    fmt = fmt || function (v) { return '' + v; };
+    var lo = photoNum(min);
+    var hi = photoNum(max);
+    if (lo !== null && hi !== null && lo > hi) { var t = lo; lo = hi; hi = t; }
+    if (lo !== null && hi !== null) return lo === hi ? fmt(lo) : fmt(lo) + ' – ' + fmt(hi);
+    if (lo !== null) return '≥ ' + fmt(lo);
+    if (hi !== null) return '≤ ' + fmt(hi);
+    return '';
+}
+
+// A yyyy-mm-dd day in the page's language
+function photoFormatDay(s) {
+    var m = /^(\d{4})-(\d{2})-(\d{2})$/.exec('' + s);
+    if (!m) return '' + s;
+    var d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], 12));
+    return d.toLocaleDateString(localeTag() || undefined, { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' });
+}
+
+// Name of a camera for lists: the model, with its make in front when the
+// model does not already say it ("SONY ILCE-7M4", "Canon EOS R5")
+function photoCameraName(model, make) {
+    model = '' + (model || '');
+    make = ('' + (make || '')).replace(/\s+(corporation|corp\.?|co\.,?\s*ltd\.?|imaging|company)$/i, '').trim();
+    if (!make || model.toLowerCase().indexOf(make.toLowerCase().split(' ')[0]) === 0) return model;
+    return make + ' ' + model;
+}
+
+function photoQuote(v) {
+    return '"' + ('' + v).replace(/"/g, '') + '"';
+}
+
+// The chips the panel values stand for, in panel order
+function photoPanelChips(pf) {
+    var chips = [];
+    function add(slot, type, label, value) {
+        if (value) chips.push({ slot: slot, type: type, label: label, value: value });
+    }
+    if (pf.rating > 0) {
+        add('rating', 'rating', '★ ≥ ' + pf.rating, 'rating:>=' + pf.rating);
+    } else if (pf.rating < 0) {
+        add('rating', 'rating', T('rating/unrated', 'Unrated'), 'rating:0');
+    }
+    if (pf.from || pf.to) {
+        var dv = pf.from && pf.to ? 'taken:' + (pf.from <= pf.to ? pf.from + '..' + pf.to : pf.to + '..' + pf.from) :
+            (pf.from ? 'taken:>=' + pf.from : 'taken:<=' + pf.to);
+        var dl = pf.from && pf.to ? photoFormatDay(pf.from <= pf.to ? pf.from : pf.to) + ' – ' + photoFormatDay(pf.from <= pf.to ? pf.to : pf.from) :
+            (pf.from ? T('tag/from', 'From {v}', { v: photoFormatDay(pf.from) }) : T('tag/until', 'Until {v}', { v: photoFormatDay(pf.to) }));
+        add('taken', 'date', dl, dv);
+    }
+    if (pf.camera) add('camera', 'camera', pf.camera, 'model:' + photoQuote(pf.camera));
+    if (pf.lens) add('lens', 'lens', pf.lens, 'lens:' + photoQuote(pf.lens));
+    for (var i = 0; i < pf.types.length; i++) {
+        add('type:' + pf.types[i], 'type', '.' + pf.types[i], '.' + pf.types[i]);
+    }
+    for (var o = 0; o < pf.orient.length; o++) {
+        add('orient:' + pf.orient[o], 'filter', photoOrientationLabel(pf.orient[o]), pf.orient[o]);
+    }
+    add('iso', 'filter', 'ISO ' + photoRangeLabel(pf.isoMin, pf.isoMax), photoRangeToken('iso', pf.isoMin, pf.isoMax));
+    add('aperture', 'filter', photoRangeLabel(pf.fMin, pf.fMax, function (v) { return 'f/' + v; }),
+        photoRangeToken('aperture', pf.fMin, pf.fMax));
+    add('focal', 'filter', photoRangeLabel(pf.focalMin, pf.focalMax) + ' mm', photoRangeToken('focal', pf.focalMin, pf.focalMax));
+    if (pf.shutter) add('shutter', 'shutter', photoPresetLabel(PHOTO_SHUTTER_PRESETS, pf.shutter), photoPresetQuery(PHOTO_SHUTTER_PRESETS, pf.shutter));
+    if (pf.time) add('time', 'time', photoPresetLabel(PHOTO_TIME_PRESETS, pf.time), photoPresetQuery(PHOTO_TIME_PRESETS, pf.time));
+    add('mp', 'filter', photoRangeLabel(pf.mpMin, null) + ' MP', photoRangeToken('mp', pf.mpMin, null));
+    add('size', 'size', T('tag/size', 'Size {v}', { v: photoRangeLabel(pf.sizeMin, pf.sizeMax, function (v) { return v + ' MB'; }) }),
+        photoRangeToken('size', pf.sizeMin, pf.sizeMax, 'mb'));
+    return chips;
+}
+
+// Clear the panel control that owns a slot (its chip was removed)
+function photoClearPanelSlot(pf, slot) {
+    var k = ('' + slot).split(':');
+    switch (k[0]) {
+        case 'rating': pf.rating = 0; break;
+        case 'taken': pf.from = ''; pf.to = ''; break;
+        case 'camera': pf.camera = ''; break;
+        case 'lens': pf.lens = ''; break;
+        case 'type': pf.types = pf.types.filter(function (t) { return t !== k[1]; }); break;
+        case 'orient': pf.orient = pf.orient.filter(function (t) { return t !== k[1]; }); break;
+        case 'iso': pf.isoMin = ''; pf.isoMax = ''; break;
+        case 'aperture': pf.fMin = ''; pf.fMax = ''; break;
+        case 'focal': pf.focalMin = ''; pf.focalMax = ''; break;
+        case 'shutter': pf.shutter = ''; break;
+        case 'time': pf.time = ''; break;
+        case 'mp': pf.mpMin = ''; break;
+        case 'size': pf.sizeMin = ''; pf.sizeMax = ''; break;
+    }
+}
+
+// How many panel controls are set (the badge on the funnel button)
+function photoPanelCount(pf) {
+    var groups = {};
+    var chips = photoPanelChips(pf);
+    for (var i = 0; i < chips.length; i++) groups[chips[i].slot.split(':')[0]] = true;
+    return Object.keys(groups).length;
+}
+
+// "1.2 MB" style size
+function photoFormatBytes(n) {
+    n = n || 0;
+    if (n < 1024) return n + ' B';
+    if (n < 1048576) return (n / 1024).toFixed(1) + ' KB';
+    if (n < 1073741824) return (n / 1048576).toFixed(1) + ' MB';
+    return (n / 1073741824).toFixed(2) + ' GB';
+}

+ 751 - 165
src/web/Photo/index.html

@@ -16,6 +16,8 @@
     <script src="i18n.js"></script>
     <script src="constants.js"></script>
     <script src="histogram.js"></script>
+    <script src="layout.js"></script>
+    <script src="filters.js"></script>
     <script src="search.js"></script>
     <script src="photo.js"></script>
     <style>
@@ -142,45 +144,6 @@
             margin: 0.3em 0.8em;
         }
 
-        .sidebar-select {
-            width: 100%;
-            background: #252525;
-            color: #bbb;
-            border: 1px solid #3a3a3a;
-            border-radius: 5px;
-            padding: 0.45em 2em 0.45em 0.7em;
-            font-size: 0.87em;
-            cursor: pointer;
-            outline: none;
-            appearance: none;
-            -webkit-appearance: none;
-            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath fill='%23777' d='M0 0l5 6 5-6z'/%3E%3C/svg%3E");
-            background-repeat: no-repeat;
-            background-position: right 0.7em center;
-            background-size: 0.65em;
-            box-sizing: border-box;
-            transition: border-color 0.15s, color 0.15s;
-        }
-
-        .sidebar-select:hover,
-        .sidebar-select:focus {
-            border-color: #f76c5d;
-            color: #fff;
-            outline: none;
-        }
-
-        .sidebar-select:disabled {
-            opacity: 0.45;
-            cursor: not-allowed;
-            border-color: #3a3a3a;
-            color: #777;
-        }
-
-        .sidebar-select option {
-            background: #252525;
-            color: #bbb;
-        }
-
         #sidebar-overlay {
             display: none;
         }
@@ -232,18 +195,6 @@
             color: #ffffff;
         }
 
-        .imagecard{
-            border: 1px solid #444;
-            overflow: hidden;
-        }
-
-        .imagecard img{
-            width: 100%;
-            height: 100%;
-            object-fit: cover;
-            object-position: center;
-        }
-
         #viewbox{
             margin-left: 0px !important;
             margin-top: 0px !important;
@@ -877,9 +828,6 @@
             padding: 0.75em 0.6em 0.5em 0.6em;
             border-bottom: 1px solid #2a2a2a;
         }
-        .photo-date-cards {
-            margin: 0 !important;
-        }
 
         /* ── Grid zoom hint snackbar (Ctrl/⌘ + wheel) ────────────────────── */
         #grid-zoom-snackbar {
@@ -904,52 +852,6 @@
             transform: translateX(-50%) translateY(0);
         }
 
-        /* ── Sidebar: view toggle + rating filter ────────────────────────── */
-        .sidebar-toggle {
-            display: flex;
-            align-items: center;
-            gap: 0.5em;
-            padding: 0.25em 0.5em;
-            color: #bbb;
-            font-size: 0.87em;
-            cursor: pointer;
-            user-select: none;
-        }
-        .sidebar-toggle:hover { color: #fff; }
-        .sidebar-toggle input { cursor: pointer; accent-color: #f76c5d; }
-        .sidebar-zoom-hint {
-            padding: 0.4em 0.5em 0;
-            color: #666;
-            font-size: 0.74em;
-            line-height: 1.4;
-        }
-        .sidebar-rating {
-            display: flex;
-            align-items: center;
-            gap: 0.05em;
-            padding: 0.1em 0.4em 0;
-        }
-        .sidebar-rating .star.icon {
-            cursor: pointer;
-            margin: 0;
-            color: #f6c350;
-            transition: transform 0.08s;
-        }
-        .sidebar-rating .star.outline.icon { color: #666; }
-        .sidebar-rating .star.icon:hover { transform: scale(1.18); }
-        .sidebar-rating-clear {
-            margin-left: 0.5em;
-            color: #f76c5d;
-            font-size: 0.78em;
-            cursor: pointer;
-        }
-        .sidebar-rating-clear:hover { text-decoration: underline; }
-        .sidebar-rating-hint {
-            padding: 0.35em 0.5em 0;
-            color: #888;
-            font-size: 0.78em;
-        }
-
         /* ── Viewer: download button + star rating ───────────────────────── */
         .download-photo-btn {
             position: absolute;
@@ -995,12 +897,430 @@
             color: #aaa;
             font-size: 0.85em;
         }
+
+        /* ── Gallery: grid (square tiles) and waterfall (own shapes) ─────── */
+        .photo-grid {
+            display: grid;
+            gap: 3px;
+            padding: 0 3px;
+        }
+        .photo-masonry {
+            display: flex;
+            align-items: flex-start;
+            gap: 3px;
+            padding: 0 3px;
+        }
+        .photo-masonry-col {
+            flex: 1 1 0;
+            min-width: 0;
+            display: flex;
+            flex-direction: column;
+            gap: 3px;
+        }
+        .imagecard {
+            position: relative;
+            overflow: hidden;
+            cursor: pointer;
+            background: #242424;
+            aspect-ratio: 1 / 1;
+        }
+        .imagecard img {
+            display: block;
+            width: 100%;
+            height: 100%;
+            object-fit: cover;
+            object-position: center;
+            transition: transform 0.25s ease, filter 0.2s ease;
+        }
+        .imagecard:hover img { filter: brightness(1.08); }
+        .imagecard::after {
+            content: "";
+            position: absolute;
+            inset: 0;
+            box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.06);
+            pointer-events: none;
+        }
+
+        /* ── Top right toolbar (filter / view / settings) ─────────────────── */
+        .search-row {
+            display: flex;
+            align-items: flex-start;
+            gap: 0.6em;
+        }
+        .search-row .search-input-wrap { flex: 1; min-width: 0; }
+        .photo-toolbar {
+            display: flex;
+            align-items: center;
+            gap: 0.45em;
+            flex-shrink: 0;
+        }
+        .tb-anchor { position: relative; }
+        .tb-btn {
+            position: relative;
+            width: 38px;
+            height: 38px;
+            border-radius: 50%;
+            border: 1px solid #3c3c3c;
+            background: #1c1c1c;
+            color: #e8e8e8;
+            cursor: pointer;
+            display: flex;
+            align-items: center;
+            justify-content: center;
+            padding: 0;
+            transition: background 0.15s, border-color 0.15s;
+        }
+        .tb-btn .tb-ico { width: 17px; height: 17px; display: block; }
+        .tb-btn:hover { background: #2c2c2c; }
+        .tb-btn.open { background: #333; border-color: #555; }
+        .tb-btn.has-filter { border-color: #f76c5d; color: #f7b3aa; }
+        .tb-btn:focus-visible { outline: 2px solid #f76c5d; outline-offset: 2px; }
+        .tb-badge {
+            position: absolute;
+            top: -4px;
+            right: -4px;
+            min-width: 17px;
+            height: 17px;
+            padding: 0 4px;
+            border-radius: 9px;
+            background: #f76c5d;
+            color: #fff;
+            font-size: 10.5px;
+            font-weight: 700;
+            line-height: 17px;
+            text-align: center;
+        }
+        .tb-pop {
+            position: absolute;
+            top: calc(100% + 10px);
+            right: 0;
+            z-index: 60;
+            background: #1e1e1e;
+            border: 1px solid #333;
+            border-radius: 16px;
+            box-shadow: 0 16px 40px rgba(0, 0, 0, 0.55);
+            color: #e8e8e8;
+            text-align: left;
+        }
+        .view-pop { width: 380px; padding: 0.7em 0.9em 0.6em 0.9em; }
+        .filter-pop {
+            width: 380px;
+            max-height: calc(100vh - 110px);
+            display: flex;
+            flex-direction: column;
+        }
+        .pop-head {
+            display: flex;
+            align-items: center;
+            padding: 0.85em 1em 0.55em 1em;
+            border-bottom: 1px solid #2c2c2c;
+        }
+        .pop-title { font-weight: 600; font-size: 1em; }
+        .pop-reset { margin-left: auto; color: #f76c5d; cursor: pointer; font-size: 0.88em; }
+        .pop-reset:hover { text-decoration: underline; }
+        .pop-body { overflow-y: auto; padding: 0.4em 1em 0.8em 1em; }
+        .pop-foot {
+            padding: 0.6em 1em;
+            border-top: 1px solid #2c2c2c;
+            color: #aaa;
+            font-size: 0.85em;
+        }
+        .pop-row {
+            display: flex;
+            align-items: center;
+            justify-content: space-between;
+            gap: 0.8em;
+            min-height: 44px;
+        }
+        .pop-label { color: #e3e3e3; font-size: 0.95em; white-space: nowrap; }
+        .pop-field { padding: 0.55em 0 0.2em 0; }
+        .pop-field > .pop-label { display: block; margin-bottom: 0.4em; font-size: 0.88em; color: #bbb; }
+        .pop-sep { height: 1px; background: #2c2c2c; margin: 0.35em 0; }
+        .pop-note, .pop-hint, .pf-hint {
+            color: #888;
+            font-size: 0.78em;
+            line-height: 1.4;
+        }
+        .pop-note { margin: -0.2em 0 0.3em 0; }
+        .pop-hint { padding-top: 0.35em; text-align: right; }
+        .pf-hint { margin-top: 0.25em; }
+
+        /* Segmented control */
+        .seg {
+            display: inline-flex;
+            background: #141414;
+            border: 1px solid #333;
+            border-radius: 999px;
+            padding: 3px;
+            gap: 2px;
+        }
+        .seg button {
+            border: none;
+            background: transparent;
+            color: #8d8d8d;
+            font-size: 0.88em;
+            padding: 0.38em 0.9em;
+            border-radius: 999px;
+            cursor: pointer;
+            white-space: nowrap;
+            transition: background 0.15s, color 0.15s;
+        }
+        .seg button:hover { color: #ddd; }
+        .seg button.on { background: #2f2f2f; color: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4); }
+        .seg button:focus-visible { outline: 2px solid #f76c5d; outline-offset: 1px; }
+
+        /* Zoom slider: five dots, a round thumb */
+        .zoom-slider {
+            width: 214px;
+            height: 32px;
+            border-radius: 999px;
+            background: #141414;
+            border: 1px solid #333;
+            padding: 0 15px;
+            cursor: pointer;
+            touch-action: none;
+            outline: none;
+        }
+        .zoom-slider:focus-visible { border-color: #f76c5d; }
+        .zs-track { position: relative; height: 100%; }
+        .zs-dot, .zs-thumb {
+            position: absolute;
+            top: 50%;
+            transform: translate(-50%, -50%);
+            border-radius: 50%;
+        }
+        .zs-dot { width: 5px; height: 5px; background: #555; }
+        .zs-thumb {
+            width: 24px;
+            height: 24px;
+            background: #2f2f2f;
+            border: 1px solid #555;
+            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
+            transition: left 0.12s ease;
+        }
+        .zs-thumb::after {
+            content: "";
+            position: absolute;
+            left: 50%;
+            top: 50%;
+            width: 7px;
+            height: 7px;
+            border-radius: 50%;
+            background: #f76c5d;
+            transform: translate(-50%, -50%);
+        }
+
+        /* Filter fields */
+        .pop-select, .pf-input {
+            background: #252525;
+            color: #ddd;
+            border: 1px solid #3a3a3a;
+            border-radius: 8px;
+            padding: 0.42em 0.6em;
+            font-size: 0.88em;
+            outline: none;
+            color-scheme: dark;
+            min-width: 0;
+        }
+        .pop-select { max-width: 200px; cursor: pointer; }
+        .pop-select.wide { width: 100%; max-width: none; }
+        .pop-select:focus, .pf-input:focus { border-color: #f76c5d; }
+        .pop-select option { background: #252525; color: #ddd; }
+        .pop-select option:disabled { color: #666; }
+        .pf-pair { display: flex; align-items: center; gap: 0.4em; }
+        .pf-pair .pf-input { flex: 1; width: 0; }
+        .pf-dash { color: #777; }
+        .pf-unit { color: #888; font-size: 0.85em; }
+        .pf-stars { display: flex; align-items: center; gap: 0.1em; flex-wrap: wrap; }
+        .pf-stars .star.icon {
+            cursor: pointer;
+            margin: 0;
+            font-size: 1.2em;
+            color: #f6c350;
+            transition: transform 0.08s;
+        }
+        .pf-stars .star.outline.icon { color: #5a5a5a; }
+        .pf-stars .star.icon:hover { transform: scale(1.15); }
+        .pf-stars .pf-chip { margin-left: 0.6em; }
+        .pf-chips { display: flex; flex-wrap: wrap; gap: 0.35em; }
+        .pf-chip {
+            border: 1px solid #3a3a3a;
+            background: #222;
+            color: #bbb;
+            border-radius: 999px;
+            padding: 0.28em 0.8em;
+            font-size: 0.82em;
+            cursor: pointer;
+        }
+        .pf-chip:hover { color: #fff; border-color: #555; }
+        .pf-chip.on { background: rgba(247, 108, 93, 0.18); border-color: rgba(247, 108, 93, 0.6); color: #f7b3aa; }
+        .pf-empty { color: #777; font-size: 0.82em; }
+        .pf-more {
+            display: flex;
+            align-items: center;
+            gap: 0.45em;
+            margin-top: 0.8em;
+            color: #bbb;
+            cursor: pointer;
+            font-size: 0.88em;
+            user-select: none;
+        }
+        .pf-more:hover { color: #fff; }
+        .pf-more .pf-chev { width: 12px; height: 12px; flex-shrink: 0; transition: transform 0.15s ease; }
+        .pf-more.open .pf-chev { transform: rotate(90deg); }
+        .pf-grid {
+            display: grid;
+            grid-template-columns: 1fr 1fr;
+            gap: 0 0.8em;
+        }
+
+        /* Extra chip colours of the search box */
+        .search-tag.tag-folder { background: rgba(160, 160, 160, 0.14); border-color: rgba(180, 180, 180, 0.35); color: #ddd; }
+        .search-tag.tag-folder > i.icon, .search-tag.tag-folder .tag-remove { color: #bbb; }
+        .search-tag.tag-shutter, .search-tag.tag-time { background: rgba(155, 120, 220, 0.16); border-color: rgba(155, 120, 220, 0.42); color: #c9b6f0; }
+        .search-tag.tag-shutter > i.icon, .search-tag.tag-shutter .tag-remove,
+        .search-tag.tag-time > i.icon, .search-tag.tag-time .tag-remove { color: #a98be0; }
+        .search-tag.tag-size { background: rgba(80, 180, 170, 0.15); border-color: rgba(80, 180, 170, 0.42); color: #9fdcd4; }
+        .search-tag.tag-size > i.icon, .search-tag.tag-size .tag-remove { color: #5fbfb3; }
+        .search-tag.neg { background: rgba(214, 72, 72, 0.16); border-color: rgba(214, 72, 72, 0.45); color: #f2a5a5; }
+        .search-tag.neg > i.icon, .search-tag.neg .tag-remove { color: #e06a6a; }
+
+        /* ── Settings dialog ─────────────────────────────────────────────── */
+        .photo-modal {
+            position: fixed;
+            inset: 0;
+            z-index: 1500;
+            background: rgba(0, 0, 0, 0.6);
+            display: flex;
+            align-items: center;
+            justify-content: center;
+            padding: 1em;
+        }
+        .photo-dialog {
+            width: 520px;
+            max-width: 100%;
+            max-height: calc(100vh - 2em);
+            display: flex;
+            flex-direction: column;
+            background: #1e1e1e;
+            border: 1px solid #333;
+            border-radius: 16px;
+            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.6);
+            color: #e8e8e8;
+        }
+        .pd-head {
+            display: flex;
+            align-items: center;
+            padding: 0.9em 1.1em;
+            border-bottom: 1px solid #2c2c2c;
+            font-weight: 600;
+            font-size: 1.05em;
+        }
+        .pd-close {
+            margin-left: auto;
+            background: none;
+            border: none;
+            color: #aaa;
+            cursor: pointer;
+            font-size: 1.05em;
+        }
+        .pd-close:hover { color: #fff; }
+        .pd-body { overflow-y: auto; padding: 0.4em 1.1em 1.1em 1.1em; }
+        .pd-section { padding: 0.8em 0; }
+        .pd-section + .pd-section { border-top: 1px solid #2c2c2c; }
+        .pd-title { font-weight: 600; margin-bottom: 0.3em; }
+        .pd-subtitle { font-weight: 600; font-size: 0.92em; margin: 1em 0 0.2em 0; }
+        .pd-desc { color: #999; font-size: 0.85em; line-height: 1.45; margin-bottom: 0.7em; }
+        .pd-option {
+            display: flex;
+            align-items: center;
+            gap: 0.75em;
+            padding: 0.65em 0.8em;
+            border: 1px solid #2f2f2f;
+            border-radius: 10px;
+            margin-bottom: 0.45em;
+            cursor: pointer;
+            outline: none;
+        }
+        .pd-option:hover { border-color: #444; background: #232323; }
+        .pd-option:focus-visible { border-color: #f76c5d; }
+        .pd-option.on { border-color: rgba(247, 108, 93, 0.65); background: rgba(247, 108, 93, 0.07); }
+        .pd-radio {
+            width: 16px;
+            height: 16px;
+            border-radius: 50%;
+            border: 2px solid #666;
+            flex-shrink: 0;
+            position: relative;
+        }
+        .pd-option.on .pd-radio { border-color: #f76c5d; }
+        .pd-option.on .pd-radio::after {
+            content: "";
+            position: absolute;
+            inset: 2px;
+            border-radius: 50%;
+            background: #f76c5d;
+        }
+        .pd-opt-main { flex: 1; min-width: 0; }
+        .pd-opt-title { font-size: 0.92em; }
+        .pd-opt-desc { color: #888; font-size: 0.8em; margin-top: 0.15em; word-break: break-all; }
+        .pd-btn {
+            border: 1px solid #444;
+            background: #2a2a2a;
+            color: #ddd;
+            border-radius: 8px;
+            padding: 0.4em 0.9em;
+            font-size: 0.85em;
+            cursor: pointer;
+            white-space: nowrap;
+            flex-shrink: 0;
+        }
+        .pd-btn:hover:not(:disabled) { background: #343434; color: #fff; }
+        .pd-btn:disabled { opacity: 0.45; cursor: default; }
+        .pd-row {
+            display: flex;
+            align-items: center;
+            gap: 0.8em;
+            margin-top: 0.5em;
+        }
+        .pd-row .pd-muted { flex: 1; }
+        .pd-muted { color: #999; font-size: 0.85em; }
+        .pd-error { color: #f0857a; font-size: 0.85em; margin: 0.3em 0; }
+        .pd-tags { display: flex; flex-wrap: wrap; gap: 0.35em; margin-bottom: 0.6em; }
+        .pd-tag {
+            display: inline-flex;
+            align-items: center;
+            gap: 0.3em;
+            background: #2a2a2a;
+            border: 1px solid #3a3a3a;
+            border-radius: 6px;
+            padding: 0.15em 0.3em 0.15em 0.55em;
+            font-size: 0.85em;
+        }
+        .pd-tag i.icon { margin: 0; cursor: pointer; color: #999; font-size: 0.85em; }
+        .pd-tag i.icon:hover { color: #f76c5d; }
+        .pd-add { display: flex; gap: 0.5em; }
+        .pd-add .pf-input { flex: 1; }
+
+        @media (max-width: 600px) {
+            /* Menus open full width under the search bar */
+            .tb-anchor { position: static; }
+            .tb-pop {
+                top: calc(100% + 4px);
+                left: 0.5em;
+                right: 0.5em;
+                width: auto;
+            }
+            .filter-pop { max-height: calc(100vh - 150px); }
+            .zoom-slider { width: 170px; }
+            .seg button { padding: 0.38em 0.65em; }
+        }
     </style>
 
 </head>
 <body>
     <!-- Alpine calls init() of the x-data object by itself: no x-init here -->
-    <div id="main" x-cloak x-data='photoListObject()'>
+    <div id="main" x-cloak x-data='photoListObject()' x-on:keydown.escape.window="onEscape()">
         <div class="ui inverted secondary small menu" id="menu">
             <!-- Mobile sidebar toggle (hidden on desktop via CSS) -->
             <a class="icon item" id="sidebar-toggle-btn" x-on:click="sidebarOpen = !sidebarOpen;" style="display:none;">
@@ -1015,54 +1335,6 @@
             <!-- Sidebar folder tree -->
             <div id="sidebar" :class="{ 'open': sidebarOpen }">
 
-                <div class="sidebar-section">
-                    <div class="sidebar-section-title" locale="sidebar/sortBy">Sort By</div>
-                    <div style="padding: 0 0.4em;">
-                        <select class="sidebar-select" x-model="sortOrder" x-on:change="getFolderInfo();"
-                                :disabled="groupByDate" :title="groupByDate ? T('sort/groupTip', 'Turn off Group by date to sort manually') : ''">
-                            <option value="smart" locale="sort/smart">Natural Order</option>
-                            <option value="mostRecent" locale="sort/newest">Newest First</option>
-                            <option value="leastRecent" locale="sort/oldest">Oldest First</option>
-                            <option value="default" locale="sort/nameAsc">Filename A→Z</option>
-                            <option value="reverse" locale="sort/nameDesc">Filename Z→A</option>
-                            <option value="smallToLarge" locale="sort/sizeAsc">Size Small→Large</option>
-                            <option value="largeToSmall" locale="sort/sizeDesc">Size Large→Small</option>
-                            <option value="fileTypeAsce" locale="sort/extAsc">Extension A→Z</option>
-                            <option value="fileTypeDesc" locale="sort/extDesc">Extension Z→A</option>
-                        </select>
-                    </div>
-                </div>
-
-                <div class="sidebar-divider"></div>
-
-                <div class="sidebar-section">
-                    <div class="sidebar-section-title" locale="sidebar/view">View</div>
-                    <label class="sidebar-toggle" title="Split the grid into Year / Month sections">
-                        <input type="checkbox" x-model="groupByDate" x-on:change="onGroupByDateChange();">
-                        <span locale="view/groupByDate">Group by date</span>
-                    </label>
-                    <div class="sidebar-zoom-hint" locale="view/zoomHint">Hold Ctrl / ⌘ and scroll to resize photos</div>
-                </div>
-
-                <div class="sidebar-divider"></div>
-
-                <div class="sidebar-section">
-                    <div class="sidebar-section-title" locale="sidebar/filterRating">Filter by Rating</div>
-                    <div class="sidebar-rating">
-                        <template x-for="n in [1,2,3,4,5]" :key="n">
-                            <i class="star icon" :class="{ 'outline': n > ratingFilter }"
-                               x-on:click="setRatingFilter(n)"
-                               :title="T('rating/andUp', 'Rating {n} and up', {n: n})"></i>
-                        </template>
-                        <span class="sidebar-rating-clear" x-show="ratingFilter > 0"
-                              x-on:click="setRatingFilter(0)" locale="rating/clear">Clear</span>
-                    </div>
-                    <div class="sidebar-rating-hint" x-show="ratingFilter > 0"
-                         x-text="T('rating/showing', 'Showing {n}★ & up', {n: ratingFilter})"></div>
-                </div>
-
-                <div class="sidebar-divider"></div>
-
                 <div class="sidebar-section">
                     <div class="sidebar-section-title" locale="sidebar/library">Library</div>
                     <template x-for="vroot in vroots">
@@ -1111,14 +1383,15 @@
             <div id="display">
                 <!-- Search bar (iOS-style tags input with autocomplete) -->
                 <div id="search-header">
+                    <div class="search-row">
                     <div class="search-input-wrap" x-on:click.outside="showSuggestions = false">
                         <div id="search-box" :class="{ 'focused': showSuggestions }"
                             x-on:click="$refs.searchInput.focus()">
                             <i class="search icon"></i>
                             <div class="search-tags">
                                 <template x-for="(tag, ti) in searchTags" :key="ti">
-                                    <span class="search-tag" :class="'tag-' + tag.type">
-                                        <i class="icon" :class="suggestIcon(tag.type)"></i>
+                                    <span class="search-tag" :class="['tag-' + tag.type, tag.neg ? 'neg' : '']">
+                                        <i class="icon" :class="tag.neg ? 'minus circle' : suggestIcon(tag.type)"></i>
                                         <span x-text="tag.label"></span>
                                         <i class="times icon tag-remove" x-on:click.stop="removeTag(ti)"></i>
                                     </span>
@@ -1150,10 +1423,234 @@
                         </div>
                     </div>
 
+                    <!-- Top right: sort & filter, view, settings -->
+                    <div class="photo-toolbar">
+                        <div class="tb-anchor" x-on:click.outside="closeMenu('filter')">
+                            <button type="button" class="tb-btn"
+                                :class="{ 'open': openMenu === 'filter', 'has-filter': activeFilterCount() > 0 }"
+                                x-on:click="toggleMenu('filter')" :aria-expanded="openMenu === 'filter'"
+                                :title="T('toolbar/filter', 'Sort & filter')" :aria-label="T('toolbar/filter', 'Sort & filter')">
+                                <svg class="tb-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16l-6.2 7.6V18l-3.6 1.6v-7L4 5z"/></svg>
+                                <span class="tb-badge" x-show="activeFilterCount() > 0" x-text="activeFilterCount()"></span>
+                            </button>
+                            <div class="tb-pop filter-pop" x-show="openMenu === 'filter'" x-transition.opacity.duration.120ms>
+                                <div class="pop-head">
+                                    <span class="pop-title" locale="filter/title">Sort &amp; filter</span>
+                                    <a class="pop-reset" x-show="activeFilterCount() > 0" x-on:click="resetPanel()" locale="filter/reset">Reset filters</a>
+                                </div>
+                                <div class="pop-body">
+                                    <div class="pop-row">
+                                        <span class="pop-label" locale="filter/sort">Sort by</span>
+                                        <select class="pop-select" x-on:change="setSort($event.target.value)">
+                                            <template x-for="opt in sortOptions()" :key="opt.v">
+                                                <option :value="opt.v" x-text="opt.label" :disabled="sortDisabled(opt)" :selected="opt.v === effectiveSort()"></option>
+                                            </template>
+                                        </select>
+                                    </div>
+                                    <div class="pop-note" x-show="timeline !== 'none'" locale="filter/sortNote">The timeline keeps photos in date order. Turn it off under View to sort by name, size or type.</div>
+                                    <div class="pop-sep"></div>
+
+                                    <div class="pop-row">
+                                        <span class="pop-label" locale="filter/searchIn">Look in</span>
+                                        <div class="seg">
+                                            <button type="button" :class="{ 'on': scope === 'folder' }" x-on:click="setScope('folder')" locale="filter/thisFolder">This folder</button>
+                                            <button type="button" :class="{ 'on': scope === 'all' }" x-on:click="setScope('all')" locale="filter/everywhere">All photos</button>
+                                        </div>
+                                    </div>
+                                    <div class="pop-note" x-show="scope === 'folder'"
+                                        x-text="T('filter/scopeNote', '{folder} and the folders inside it', { folder: scopeName() })"></div>
+
+                                    <div class="pop-field">
+                                        <span class="pop-label" locale="filter/rating">Rating</span>
+                                        <div class="pf-stars">
+                                            <template x-for="n in [1,2,3,4,5]" :key="n">
+                                                <i class="star icon" :class="{ 'outline': !(pf.rating >= n) }"
+                                                    x-on:click="setPanelRating(n)"
+                                                    :title="T('rating/andUp', 'Rating {n} and up', { n: n }) + (facets ? ' (' + ratingCount(n) + ')' : '')"></i>
+                                            </template>
+                                            <button type="button" class="pf-chip" :class="{ 'on': pf.rating === -1 }"
+                                                x-on:click="setPanelRating(-1)" locale="rating/unrated">Unrated</button>
+                                        </div>
+                                    </div>
+
+                                    <div class="pop-field">
+                                        <span class="pop-label" locale="filter/taken">Date taken</span>
+                                        <div class="pf-pair">
+                                            <input type="date" class="pf-input" x-model="pf.from" x-on:change="applyPanel()" :aria-label="T('filter/from', 'From')">
+                                            <span class="pf-dash">–</span>
+                                            <input type="date" class="pf-input" x-model="pf.to" x-on:change="applyPanel()" :aria-label="T('filter/to', 'To')">
+                                        </div>
+                                    </div>
+
+                                    <div class="pop-field">
+                                        <span class="pop-label" locale="filter/camera">Camera</span>
+                                        <select class="pop-select wide" x-model="pf.camera" x-on:change="applyPanel()">
+                                            <option value="" locale="filter/anyCamera">Any camera</option>
+                                            <template x-for="c in cameraOptions()" :key="c.v">
+                                                <option :value="c.v" x-text="c.label + (c.c ? '  (' + c.c + ')' : '')" :selected="c.v === pf.camera"></option>
+                                            </template>
+                                        </select>
+                                    </div>
+
+                                    <div class="pop-field">
+                                        <span class="pop-label" locale="filter/lens">Lens</span>
+                                        <select class="pop-select wide" x-model="pf.lens" x-on:change="applyPanel()">
+                                            <option value="" locale="filter/anyLens">Any lens</option>
+                                            <template x-for="l in lensOptions()" :key="l.v">
+                                                <option :value="l.v" x-text="l.label + (l.c ? '  (' + l.c + ')' : '')" :selected="l.v === pf.lens"></option>
+                                            </template>
+                                        </select>
+                                    </div>
+
+                                    <div class="pop-field">
+                                        <span class="pop-label" locale="filter/type">File type</span>
+                                        <div class="pf-chips">
+                                            <template x-for="t in typeOptions()" :key="t.v">
+                                                <button type="button" class="pf-chip" :class="{ 'on': pf.types.includes(t.v) }"
+                                                    x-on:click="togglePanelValue('types', t.v)" x-text="t.v.toUpperCase()"
+                                                    :title="t.c ? T('suggest/photos', '{n} photos', { n: t.c }) : ''"></button>
+                                            </template>
+                                            <span class="pf-empty" x-show="typeOptions().length === 0"
+                                                x-text="facetsLoading ? T('filter/loading', 'Loading…') : T('filter/notIndexed', 'Nothing indexed here yet')"></span>
+                                        </div>
+                                    </div>
+
+                                    <div class="pop-field">
+                                        <span class="pop-label" locale="filter/orientation">Orientation</span>
+                                        <div class="pf-chips">
+                                            <template x-for="o in ['landscape', 'portrait', 'square']" :key="o">
+                                                <button type="button" class="pf-chip" :class="{ 'on': pf.orient.includes(o) }"
+                                                    x-on:click="togglePanelValue('orient', o)" x-text="photoOrientationLabel(o)"></button>
+                                            </template>
+                                        </div>
+                                    </div>
+
+                                    <a class="pf-more" :class="{ 'open': showAdvanced }" x-on:click="showAdvanced = !showAdvanced">
+                                        <svg class="pf-chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg>
+                                        <span locale="filter/more">Camera settings &amp; file details</span>
+                                    </a>
+                                    <div x-show="showAdvanced">
+                                        <div class="pf-grid">
+                                            <div class="pop-field">
+                                                <span class="pop-label">ISO</span>
+                                                <div class="pf-pair">
+                                                    <input type="number" min="0" step="1" class="pf-input" x-model="pf.isoMin" x-on:change="applyPanel()" :placeholder="T('filter/min', 'Min')">
+                                                    <span class="pf-dash">–</span>
+                                                    <input type="number" min="0" step="1" class="pf-input" x-model="pf.isoMax" x-on:change="applyPanel()" :placeholder="T('filter/max', 'Max')">
+                                                </div>
+                                                <div class="pf-hint" x-text="rangeHint('iso', v => Math.round(v))"></div>
+                                            </div>
+                                            <div class="pop-field">
+                                                <span class="pop-label" locale="filter/aperture">Aperture (f/)</span>
+                                                <div class="pf-pair">
+                                                    <input type="number" min="0" step="0.1" class="pf-input" x-model="pf.fMin" x-on:change="applyPanel()" :placeholder="T('filter/min', 'Min')">
+                                                    <span class="pf-dash">–</span>
+                                                    <input type="number" min="0" step="0.1" class="pf-input" x-model="pf.fMax" x-on:change="applyPanel()" :placeholder="T('filter/max', 'Max')">
+                                                </div>
+                                                <div class="pf-hint" x-text="rangeHint('aperture', v => 'f/' + (Math.round(v * 10) / 10))"></div>
+                                            </div>
+                                            <div class="pop-field">
+                                                <span class="pop-label" locale="filter/focal">Focal length (mm)</span>
+                                                <div class="pf-pair">
+                                                    <input type="number" min="0" step="1" class="pf-input" x-model="pf.focalMin" x-on:change="applyPanel()" :placeholder="T('filter/min', 'Min')">
+                                                    <span class="pf-dash">–</span>
+                                                    <input type="number" min="0" step="1" class="pf-input" x-model="pf.focalMax" x-on:change="applyPanel()" :placeholder="T('filter/max', 'Max')">
+                                                </div>
+                                                <div class="pf-hint" x-text="rangeHint('focal', v => Math.round(v) + ' mm')"></div>
+                                            </div>
+                                            <div class="pop-field">
+                                                <span class="pop-label" locale="filter/megapixels">Megapixels</span>
+                                                <div class="pf-pair">
+                                                    <input type="number" min="0" step="1" class="pf-input" x-model="pf.mpMin" x-on:change="applyPanel()" :placeholder="T('filter/atLeast', 'At least')">
+                                                    <span class="pf-unit">MP</span>
+                                                </div>
+                                                <div class="pf-hint" x-text="rangeHint('megapixels', v => (Math.round(v * 10) / 10) + ' MP')"></div>
+                                            </div>
+                                        </div>
+                                        <div class="pop-field">
+                                            <span class="pop-label" locale="filter/shutter">Shutter speed</span>
+                                            <select class="pop-select wide" x-model="pf.shutter" x-on:change="applyPanel()">
+                                                <option value="" locale="filter/any">Any</option>
+                                                <template x-for="p in PHOTO_SHUTTER_PRESETS" :key="p.v">
+                                                    <option :value="p.v" x-text="T(p.key, p.en)" :selected="p.v === pf.shutter"></option>
+                                                </template>
+                                            </select>
+                                        </div>
+                                        <div class="pop-field">
+                                            <span class="pop-label" locale="filter/time">Time of day</span>
+                                            <select class="pop-select wide" x-model="pf.time" x-on:change="applyPanel()">
+                                                <option value="" locale="filter/any">Any</option>
+                                                <template x-for="p in PHOTO_TIME_PRESETS" :key="p.v">
+                                                    <option :value="p.v" x-text="T(p.key, p.en)" :selected="p.v === pf.time"></option>
+                                                </template>
+                                            </select>
+                                        </div>
+                                        <div class="pop-field">
+                                            <span class="pop-label" locale="filter/size">File size (MB)</span>
+                                            <div class="pf-pair">
+                                                <input type="number" min="0" step="0.5" class="pf-input" x-model="pf.sizeMin" x-on:change="applyPanel()" :placeholder="T('filter/min', 'Min')">
+                                                <span class="pf-dash">–</span>
+                                                <input type="number" min="0" step="0.5" class="pf-input" x-model="pf.sizeMax" x-on:change="applyPanel()" :placeholder="T('filter/max', 'Max')">
+                                            </div>
+                                        </div>
+                                        <div class="pop-note" style="margin-top: 0.7em;" locale="filter/syntaxTip">Tip: type -word in the search box to leave matching photos out, e.g. -raw or -in:screenshots.</div>
+                                    </div>
+                                </div>
+                                <div class="pop-foot" x-show="searchMode" x-text="searchSummary()"></div>
+                            </div>
+                        </div>
+
+                        <div class="tb-anchor" x-on:click.outside="closeMenu('view')">
+                            <button type="button" class="tb-btn" :class="{ 'open': openMenu === 'view' }"
+                                x-on:click="toggleMenu('view')" :aria-expanded="openMenu === 'view'"
+                                :title="T('toolbar/view', 'View')" :aria-label="T('toolbar/view', 'View')">
+                                <svg class="tb-ico" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="4.5" y="4.5" width="6.6" height="6.6" rx="1.8"/><rect x="12.9" y="4.5" width="6.6" height="6.6" rx="1.8"/><rect x="4.5" y="12.9" width="6.6" height="6.6" rx="1.8"/><rect x="12.9" y="12.9" width="6.6" height="6.6" rx="1.8"/></svg>
+                            </button>
+                            <div class="tb-pop view-pop" x-show="openMenu === 'view'" x-transition.opacity.duration.120ms>
+                                <div class="pop-row">
+                                    <span class="pop-label" locale="view/timeline">Timeline</span>
+                                    <div class="seg">
+                                        <template x-for="opt in timelineOptions()" :key="opt.v">
+                                            <button type="button" :class="{ 'on': timeline === opt.v }" x-on:click="setTimeline(opt.v)" x-text="opt.label"></button>
+                                        </template>
+                                    </div>
+                                </div>
+                                <div class="pop-sep"></div>
+                                <div class="pop-row">
+                                    <span class="pop-label" locale="view/layout">Layout</span>
+                                    <div class="seg">
+                                        <button type="button" :class="{ 'on': layout === 'grid' }" x-on:click="setLayout('grid')" locale="view/grid">Grid</button>
+                                        <button type="button" :class="{ 'on': layout === 'waterfall' }" x-on:click="setLayout('waterfall')" locale="view/waterfall">Waterfall</button>
+                                    </div>
+                                </div>
+                                <div class="pop-row">
+                                    <span class="pop-label" locale="view/zoom">Zoom</span>
+                                    <div class="zoom-slider" role="slider" tabindex="0" aria-valuemin="0" aria-valuemax="4"
+                                        :aria-valuenow="zoomLevel" :aria-label="T('view/zoom', 'Zoom')"
+                                        x-on:pointerdown.prevent="zoomPointer($event)" x-on:keydown="zoomKey($event)">
+                                        <div class="zs-track">
+                                            <template x-for="n in [0, 1, 2, 3, 4]" :key="n">
+                                                <span class="zs-dot" :style="{ left: (n * 25) + '%' }"></span>
+                                            </template>
+                                            <span class="zs-thumb" :style="{ left: (zoomLevel * 25) + '%' }"></span>
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="pop-hint" x-text="T('grid/perRow', '{n} per row', { n: columnCount() }) + ' · ' + T('view/zoomHint', 'Hold Ctrl / ⌘ and scroll to resize photos')"></div>
+                            </div>
+                        </div>
+
+                        <button type="button" class="tb-btn" x-on:click="openSettings()"
+                            :title="T('toolbar/settings', 'Settings')" :aria-label="T('toolbar/settings', 'Settings')">
+                            <svg class="tb-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.8"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
+                        </button>
+                    </div>
+                    </div>
+
                     <!-- Result count / indexing status -->
                     <div id="search-meta" x-show="searchMode || indexStatusText.length > 0">
-                        <span x-show="searchMode"
-                            x-text="searchTotal === 1 ? T('search/result', '{n} result', {n: searchTotal}) : T('search/results', '{n} results', {n: searchTotal})"></span>
+                        <span x-show="searchMode" x-text="searchSummary()"></span>
+                        <a class="search-clear-link" x-show="searchMode && scope === 'folder'" x-on:click="setScope('all')" locale="search/everywhere">Search all photos</a>
                         <a class="search-clear-link" x-show="searchMode" x-on:click="clearSearch()" locale="search/clear">Clear search</a>
                         <span id="index-chip" x-show="indexStatusText.length > 0">
                             <i class="loading spinner icon" x-show="indexing"></i>
@@ -1175,21 +1672,37 @@
                 </div>
                 <div id="viewboxContainer">
                     <div id="viewbox">
-                        <!-- Photos are split into Year / Month sections (Google-Photos style).
-                             When "Group by date" is off, groupedImages() returns one
-                             unlabelled group, so this renders as a single flat grid. -->
+                        <!-- Photos are split into Day / Month / Year sections by the
+                             timeline (one unlabelled section when it is off). Grid
+                             shows square tiles; waterfall keeps each photo's shape and
+                             deals it into the shortest column (layout.js). -->
                         <template x-for="group in groupedImages()" :key="group.key">
                             <div class="photo-date-group">
                                 <div class="photo-date-header" x-show="group.label !== ''" x-text="group.label"></div>
-                                <div class="ui six cards photo-date-cards">
-                                    <template x-for="image in group.images" :key="image.filepath">
-                                        <div class="imagecard" style="cursor: pointer;" x-on:click="showImage($el); ShowModal();" :style="{width: renderSize + 'px', height: renderSize + 'px'}" :filedata="encodeURIComponent(JSON.stringify({'filename':image.filepath.split('/').pop(),'filepath':image.filepath,'filesize':image.filesize}))">
-                                            <a class="image" x-init="updateImageSizes();">
-                                                <img :src="'../system/file_system/loadThumbnail?bytes=true&vpath=' + image.filepath">
-                                            </a>
-                                        </div>
-                                    </template>
-                                </div>
+                                <template x-if="layout === 'grid'">
+                                    <div class="photo-grid" :style="gridStyle()">
+                                        <template x-for="image in group.images" :key="image.filepath">
+                                            <div class="imagecard" x-on:click="showImage($el); ShowModal();" :filedata="cardFiledata(image)">
+                                                <img :src="thumbUrl(image)" loading="lazy" alt="">
+                                            </div>
+                                        </template>
+                                    </div>
+                                </template>
+                                <template x-if="layout === 'waterfall'">
+                                    <div class="photo-masonry">
+                                        <template x-for="col in group.columns" :key="col.key">
+                                            <div class="photo-masonry-col">
+                                                <template x-for="image in col.items" :key="image.filepath">
+                                                    <div class="imagecard" x-on:click="showImage($el); ShowModal();"
+                                                        :style="{ aspectRatio: cardRatio(image) }" :filedata="cardFiledata(image)">
+                                                        <img :src="PhotoPreviews.url(image.filepath) || thumbUrl(image)" :data-thumb="thumbUrl(image)"
+                                                            x-init="PhotoPreviews.observe($el, image.filepath)" alt="">
+                                                    </div>
+                                                </template>
+                                            </div>
+                                        </template>
+                                    </div>
+                                </template>
                             </div>
                         </template>
                     </div>
@@ -1203,6 +1716,79 @@
             </div>
 
         </div><!-- /#content-area -->
+
+        <!-- Settings (gear, top right) -->
+        <div class="photo-modal" x-show="settingsOpen" x-transition.opacity.duration.120ms x-on:click.self="settingsOpen = false">
+            <div class="photo-dialog" role="dialog" aria-modal="true" :aria-label="T('settings/title', 'Photo settings')">
+                <div class="pd-head">
+                    <span locale="settings/title">Photo settings</span>
+                    <button type="button" class="pd-close" x-on:click="settingsOpen = false" :aria-label="T('common/close', 'Close')"><i class="close icon"></i></button>
+                </div>
+                <div class="pd-body">
+                    <div class="pd-section">
+                        <div class="pd-title" locale="settings/previews">Waterfall previews</div>
+                        <div class="pd-desc" locale="settings/previewsDesc">The waterfall layout shows every photo in its own shape. Those previews are drawn on the server and can be kept, so they load quickly next time.</div>
+
+                        <div class="pd-option" role="radio" tabindex="0" :class="{ 'on': settings.mode === 'appdata' }" :aria-checked="settings.mode === 'appdata'"
+                            x-on:click="setPreviewMode('appdata')" x-on:keydown.enter.prevent="setPreviewMode('appdata')" x-on:keydown.space.prevent="setPreviewMode('appdata')">
+                            <span class="pd-radio"></span>
+                            <div class="pd-opt-main">
+                                <div class="pd-opt-title" locale="settings/modeAppdata">Keep them in my app data (recommended)</div>
+                                <div class="pd-opt-desc" x-text="settings.defaultDir"></div>
+                            </div>
+                        </div>
+                        <div class="pd-option" role="radio" tabindex="0" :class="{ 'on': settings.mode === 'custom' }" :aria-checked="settings.mode === 'custom'"
+                            x-on:click="setPreviewMode('custom')" x-on:keydown.enter.prevent="setPreviewMode('custom')" x-on:keydown.space.prevent="setPreviewMode('custom')">
+                            <span class="pd-radio"></span>
+                            <div class="pd-opt-main">
+                                <div class="pd-opt-title" locale="settings/modeCustom">Keep them in a folder I choose</div>
+                                <div class="pd-opt-desc" x-text="settings.path || T('settings/noFolder', 'No folder chosen yet')"></div>
+                            </div>
+                            <button type="button" class="pd-btn" x-on:click.stop="chooseCacheFolder()" :disabled="settings.busy" locale="settings/choose">Choose…</button>
+                        </div>
+                        <div class="pd-option" role="radio" tabindex="0" :class="{ 'on': settings.mode === 'realtime' }" :aria-checked="settings.mode === 'realtime'"
+                            x-on:click="setPreviewMode('realtime')" x-on:keydown.enter.prevent="setPreviewMode('realtime')" x-on:keydown.space.prevent="setPreviewMode('realtime')">
+                            <span class="pd-radio"></span>
+                            <div class="pd-opt-main">
+                                <div class="pd-opt-title" locale="settings/modeRealtime">Draw them every time</div>
+                                <div class="pd-opt-desc" locale="settings/modeRealtimeDesc">Uses no disk space, but every preview is drawn again each time it is shown.</div>
+                            </div>
+                        </div>
+
+                        <div class="pd-error" x-show="settings.error" x-text="settings.error"></div>
+                        <div class="pd-row" x-show="settings.loaded && settings.mode !== 'realtime'">
+                            <span class="pd-muted" x-text="cacheStatsText()"></span>
+                            <button type="button" class="pd-btn" x-on:click="clearPreviewCache()"
+                                :disabled="settings.busy || !settings.stats || settings.stats.files === 0" locale="settings/clearCache">Clear cache</button>
+                        </div>
+                        <div class="pd-desc" style="margin: 0.6em 0 0 0;" x-show="settings.mode === 'custom'" locale="settings/customNote">Previews are kept in sub folders named 00 to ff. Clearing the cache only removes those.</div>
+                    </div>
+
+                    <div class="pd-section">
+                        <div class="pd-title" locale="settings/index">Search index</div>
+                        <div class="pd-row">
+                            <span class="pd-muted" x-text="T('settings/indexStatus', '{n} photos indexed, last updated {time}', { n: settings.total, time: lastIndexedText() })"></span>
+                            <button type="button" class="pd-btn" x-on:click="rebuildIndex()" :disabled="indexing" locale="settings/rebuild">Rebuild index</button>
+                        </div>
+                        <div class="pd-muted" style="margin-top: 0.4em;" x-show="indexing" x-text="indexStatusText"></div>
+
+                        <div class="pd-subtitle" locale="settings/exclude">Excluded folders</div>
+                        <div class="pd-desc" locale="settings/excludeDesc">Photos in folders with these names are left out of the index, the search and the filters.</div>
+                        <div class="pd-tags">
+                            <template x-for="(f, i) in settings.exclude" :key="f">
+                                <span class="pd-tag"><span x-text="f"></span><i class="times icon" x-on:click="removeExclude(i)" :title="T('settings/remove', 'Remove')"></i></span>
+                            </template>
+                            <span class="pd-muted" x-show="settings.exclude.length === 0" locale="settings/noExclude">None</span>
+                        </div>
+                        <div class="pd-add">
+                            <input type="text" class="pf-input" x-model="settings.excludeInput" x-on:keydown.enter.prevent="addExclude()"
+                                :placeholder="T('settings/excludePlaceholder', 'Folder name, e.g. Screenshots')">
+                            <button type="button" class="pd-btn" x-on:click="addExclude()" locale="settings/add">Add</button>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
     </div><!-- /#main -->
     <!-- Photo Viewer -->
     <div id="photo-viewer" class="photo-viewer">

+ 318 - 0
src/web/Photo/layout.js

@@ -0,0 +1,318 @@
+/*
+    layout.js
+
+    Gallery layout helpers for the Photo grid, used by photoListObject()
+    (photo.js):
+
+      - zoom: five steps, each a target tile width; the column count follows
+        the width of the gallery
+      - timeline: Day / Month / Year sections keyed by the date a photo was
+        taken (EXIF times are the camera's clock, stored as UTC, so they are
+        read back in UTC; file times are real instants, read in local time)
+      - waterfall: photos keep their shape and are dealt into equal width
+        columns, each to the shortest column so far
+      - PhotoPreviews: loads the upright, uncropped previews the waterfall
+        shows (backend/previews.js) for the cards that scroll into view
+
+    Ratios learnt from previews live outside Alpine (photoRatioOf), so a
+    preview arriving does not re-render the gallery by itself; the component
+    batches a relayout instead.
+*/
+
+// Target tile width (CSS px) of each zoom step, small to large
+var PHOTO_ZOOM_STEPS = [96, 136, 190, 260, 360];
+var PHOTO_ZOOM_DEFAULT = 2;
+var PHOTO_MAX_COLUMNS = 20;
+var PHOTO_GAP = 3;
+
+// Columns for a gallery width at a zoom step
+function photoColumnCount(width, zoomLevel) {
+    var target = PHOTO_ZOOM_STEPS[Math.max(0, Math.min(PHOTO_ZOOM_STEPS.length - 1, zoomLevel))];
+    if (!width || width <= 0) {
+        width = Math.max(320, window.innerWidth - 210);
+    }
+    var cols = Math.round(width / target);
+    return Math.max(1, Math.min(PHOTO_MAX_COLUMNS, cols));
+}
+
+// ── Dates ─────────────────────────────────────────────────────────────────────
+
+// The date a grid item stands for: {t: unix seconds, utc: bool} or null.
+// taken_date comes from the index (EXIF clock time stored as UTC); mtime is a
+// real instant, used for photos the indexer has not reached yet.
+function photoImageDate(img) {
+    if (!img) return null;
+    if (img.taken_date) return { t: img.taken_date, utc: true };
+    if (img.mtime) return { t: img.mtime, utc: false };
+    if (img.modified_date) return { t: img.modified_date, utc: false };
+    return null;
+}
+
+// Kept for the code that only needs a number to sort by
+function photoImageDateUnix(img) {
+    var d = photoImageDate(img);
+    return d ? d.t : null;
+}
+
+// Sort key that orders UTC clock times and local instants together
+function photoDateSortKey(img) {
+    var d = photoImageDate(img);
+    if (!d) return 0;
+    return d.utc ? d.t : d.t - new Date(d.t * 1000).getTimezoneOffset() * 60;
+}
+
+function sortImagesByDate(arr, ascending) {
+    return arr.slice().sort(function (a, b) {
+        var ka = photoDateSortKey(a);
+        var kb = photoDateSortKey(b);
+        if (ka === kb) {
+            return a.filepath < b.filepath ? -1 : (a.filepath > b.filepath ? 1 : 0);
+        }
+        return ascending ? ka - kb : kb - ka;
+    });
+}
+
+// Newest first (kept for older callers)
+function sortImagesByDateDesc(arr) {
+    return sortImagesByDate(arr, false);
+}
+
+// Section {key, label} of an item for a timeline mode ('day' | 'month' | 'year')
+function photoTimelineSection(img, mode) {
+    var d = photoImageDate(img);
+    if (!d) {
+        return { key: 'undated', label: T('grid/undated', 'Undated') };
+    }
+    var dt = new Date(d.t * 1000);
+    if (isNaN(dt.getTime())) {
+        return { key: 'undated', label: T('grid/undated', 'Undated') };
+    }
+    var y = d.utc ? dt.getUTCFullYear() : dt.getFullYear();
+    var m = d.utc ? dt.getUTCMonth() : dt.getMonth();
+    var day = d.utc ? dt.getUTCDate() : dt.getDate();
+    var lang = localeTag() || undefined;
+    // Format the calendar date itself, whatever zone it was read in
+    var labelDate = new Date(Date.UTC(y, m, day, 12));
+    var opts = { timeZone: 'UTC' };
+    if (mode === 'year') {
+        opts.year = 'numeric';
+        return { key: '' + y, label: labelDate.toLocaleDateString(lang, opts) };
+    }
+    if (mode === 'day') {
+        opts.weekday = 'short';
+        opts.year = 'numeric';
+        opts.month = 'long';
+        opts.day = 'numeric';
+        return { key: y + '-' + (m + 1) + '-' + day, label: labelDate.toLocaleDateString(lang, opts) };
+    }
+    opts.year = 'numeric';
+    opts.month = 'long';
+    return { key: y + '-' + (m + 1), label: labelDate.toLocaleDateString(lang, opts) };
+}
+
+// ── Waterfall ─────────────────────────────────────────────────────────────────
+
+// Width / height ratios learnt from loaded previews, by file path
+var photoRatioOverrides = {};
+
+// Shape of a photo: the preview's when known, else the index's, else 4:3
+function photoRatioOf(img) {
+    var r = photoRatioOverrides[img.filepath];
+    if (r) return r;
+    if (img.width && img.height) return img.width / img.height;
+    return 4 / 3;
+}
+
+// Deal items into `cols` columns, each to the column that is shortest so far.
+// Heights are compared for equal column widths, so 1 / ratio is enough.
+function photoMasonry(items, cols) {
+    var columns = [];
+    var heights = [];
+    for (var c = 0; c < cols; c++) {
+        columns.push({ key: 'c' + c, items: [] });
+        heights.push(0);
+    }
+    for (var i = 0; i < items.length; i++) {
+        var best = 0;
+        for (var k = 1; k < cols; k++) {
+            if (heights[k] < heights[best] - 1e-6) best = k;
+        }
+        var ratio = photoRatioOf(items[i]);
+        // Keep extreme panoramas / strips readable
+        ratio = Math.max(0.25, Math.min(4, ratio));
+        columns[best].items.push(items[i]);
+        heights[best] += 1 / ratio;
+    }
+    return columns;
+}
+
+// ── Previews for the waterfall ────────────────────────────────────────────────
+
+var PhotoPreviews = {
+    ready: {},          // filepath -> {url, w, h} or {failed: true}
+    elements: {},       // filepath -> [img elements waiting for it]
+    lookupQueue: [],
+    lookupTimer: null,
+    generateQueue: [],
+    queued: {},         // filepath -> true while looked up / generating
+    active: 0,
+    maxActive: 2,
+    batchSize: 3,
+    mode: '',
+    observer: null,
+    generation: 0,      // bumps on reset, so late answers are dropped
+    onSize: null,       // function(filepath, w, h) set by the component
+
+    url: function (filepath) {
+        var r = this.ready[filepath];
+        return r && r.url ? r.url : null;
+    },
+
+    // Watch a card image: load its preview when it comes near the viewport
+    observe: function (el, filepath) {
+        var self = this;
+        el.setAttribute('data-preview', filepath);
+        if (this.ready[filepath]) {
+            this.apply(el, filepath);
+            return;
+        }
+        if (!this.observer) {
+            var root = document.getElementById('viewboxContainer');
+            this.observer = new IntersectionObserver(function (entries) {
+                for (var i = 0; i < entries.length; i++) {
+                    if (!entries[i].isIntersecting) continue;
+                    var target = entries[i].target;
+                    self.observer.unobserve(target);
+                    self.want(target, target.getAttribute('data-preview'));
+                }
+            }, { root: root, rootMargin: '800px 0px' });
+        }
+        this.observer.observe(el);
+    },
+
+    unobserve: function (el) {
+        if (this.observer) this.observer.unobserve(el);
+    },
+
+    apply: function (el, filepath) {
+        var r = this.ready[filepath];
+        if (!r || !r.url || el.getAttribute('data-preview') !== filepath) return;
+        if (el.getAttribute('src') !== r.url) {
+            el.setAttribute('src', r.url);
+        }
+        el.classList.add('is-preview');
+    },
+
+    want: function (el, filepath) {
+        if (!filepath) return;
+        if (this.ready[filepath]) {
+            this.apply(el, filepath);
+            return;
+        }
+        if (!this.elements[filepath]) this.elements[filepath] = [];
+        this.elements[filepath].push(el);
+        if (this.queued[filepath]) return;
+        this.queued[filepath] = true;
+        this.lookupQueue.push(filepath);
+        var self = this;
+        clearTimeout(this.lookupTimer);
+        this.lookupTimer = setTimeout(function () { self.flushLookups(); }, 60);
+    },
+
+    flushLookups: function () {
+        var self = this;
+        var gen = this.generation;
+        while (this.lookupQueue.length) {
+            var batch = this.lookupQueue.splice(0, 200);
+            aoPhotoBackend('Photo/backend/previews.js', { files: batch, generate: false }).then(function (data) {
+                if (gen !== self.generation) return;
+                self.mode = (data && data.mode) || self.mode;
+                var items = (data && data.items) || {};
+                for (var f in items) {
+                    if (items[f].pending) {
+                        self.generateQueue.push(f);
+                    } else {
+                        self.store(f, items[f]);
+                    }
+                }
+                self.pump();
+            }).catch(function () { /* keep the thumbnails */ });
+        }
+    },
+
+    pump: function () {
+        var self = this;
+        while (this.active < this.maxActive && this.generateQueue.length) {
+            var batch = this.generateQueue.splice(0, this.batchSize);
+            var gen = this.generation;
+            this.active++;
+            aoPhotoBackend('Photo/backend/previews.js', { files: batch, generate: true }).then(function (data) {
+                if (gen !== self.generation) return;
+                var items = (data && data.items) || {};
+                for (var f in items) self.store(f, items[f]);
+            }).catch(function () {
+                /* leave the thumbnails */
+            }).then(function () {
+                if (gen !== self.generation) return;
+                self.active--;
+                self.pump();
+            });
+        }
+    },
+
+    store: function (filepath, item) {
+        delete this.queued[filepath];
+        if (!item || item.error || item.pending) {
+            this.ready[filepath] = { failed: true };
+        } else {
+            var url = item.dataURL ? item.dataURL :
+                ao_root + 'media?file=' + encodeURIComponent(item.src) + '&v=' + (item.v || 0);
+            this.ready[filepath] = { url: url, w: item.w, h: item.h };
+            this.trim();
+            if (this.onSize && item.w && item.h) this.onSize(filepath, item.w, item.h);
+        }
+        var els = this.elements[filepath] || [];
+        delete this.elements[filepath];
+        for (var i = 0; i < els.length; i++) {
+            if (els[i].isConnected) this.apply(els[i], filepath);
+        }
+        // Cards rendered again since they asked
+        var again = document.querySelectorAll('#viewbox img[data-preview]');
+        for (var k = 0; k < again.length; k++) {
+            if (again[k].getAttribute('data-preview') === filepath) this.apply(again[k], filepath);
+        }
+    },
+
+    // Realtime previews are data URLs held in memory: keep the newest 400
+    trim: function () {
+        if (this.mode !== 'realtime') return;
+        var keys = Object.keys(this.ready);
+        var over = keys.length - 400;
+        for (var i = 0; i < keys.length && over > 0; i++) {
+            if (this.ready[keys[i]].url && this.ready[keys[i]].url.indexOf('data:') === 0) {
+                delete this.ready[keys[i]];
+                over--;
+            }
+        }
+    },
+
+    // Forget everything (settings changed or cache cleared) and ask again for
+    // the cards on the page
+    reset: function () {
+        this.generation++;
+        this.ready = {};
+        this.elements = {};
+        this.lookupQueue = [];
+        this.generateQueue = [];
+        this.queued = {};
+        this.active = 0;
+        clearTimeout(this.lookupTimer);
+        var imgs = document.querySelectorAll('#viewbox img[data-preview]');
+        for (var i = 0; i < imgs.length; i++) {
+            imgs[i].classList.remove('is-preview');
+            var thumb = imgs[i].getAttribute('data-thumb');
+            if (thumb) imgs[i].setAttribute('src', thumb);
+            this.observe(imgs[i], imgs[i].getAttribute('data-preview'));
+        }
+    }
+};

+ 540 - 48
src/web/Photo/locale/photo.json

@@ -11,8 +11,6 @@
                 "common/cancel": "取消",
                 "common/close": "關閉",
                 "common/download": "下載",
-                "sidebar/sortBy": "排序方式",
-                "sort/groupTip": "請關閉「依日期分組」以手動排序",
                 "sort/smart": "自然排序",
                 "sort/newest": "最新優先",
                 "sort/oldest": "最舊優先",
@@ -22,13 +20,8 @@
                 "sort/sizeDesc": "大小 大→小",
                 "sort/extAsc": "副檔名 A→Z",
                 "sort/extDesc": "副檔名 Z→A",
-                "sidebar/view": "檢視",
-                "view/groupByDate": "依日期分組",
                 "view/zoomHint": "按住 Ctrl / ⌘ 並捲動即可調整相片大小",
-                "sidebar/filterRating": "依評分篩選",
                 "rating/andUp": "評分 {n} 以上",
-                "rating/clear": "清除",
-                "rating/showing": "顯示 {n}★ 以上",
                 "sidebar/library": "媒體庫",
                 "sidebar/currentPath": "目前路徑",
                 "sidebar/subfolders": "子資料夾",
@@ -227,7 +220,96 @@
                 "editor/rotate": "旋轉",
                 "editor/aspect": "長寬比",
                 "editor/undo": "復原",
-                "editor/redo": "重做"
+                "editor/redo": "重做",
+                "toolbar/filter": "排序與篩選",
+                "toolbar/view": "檢視",
+                "toolbar/settings": "設定",
+                "filter/title": "排序與篩選",
+                "filter/reset": "重設篩選",
+                "filter/sort": "排序方式",
+                "filter/sortNote": "時間軸會依日期排列相片。如要依名稱、大小或類型排序,請在「檢視」中關閉時間軸。",
+                "filter/searchIn": "搜尋範圍",
+                "filter/thisFolder": "此資料夾",
+                "filter/everywhere": "所有相片",
+                "filter/scopeNote": "{folder} 及其中的資料夾",
+                "filter/rating": "評分",
+                "rating/unrated": "未評分",
+                "filter/taken": "拍攝日期",
+                "filter/from": "開始",
+                "filter/to": "結束",
+                "filter/camera": "相機",
+                "filter/anyCamera": "所有相機",
+                "filter/lens": "鏡頭",
+                "filter/anyLens": "所有鏡頭",
+                "filter/type": "檔案類型",
+                "filter/loading": "載入中…",
+                "filter/notIndexed": "這裡尚未建立索引",
+                "filter/orientation": "方向",
+                "filter/more": "相機設定與檔案詳細資料",
+                "filter/min": "最小",
+                "filter/max": "最大",
+                "filter/aperture": "光圈 (f/)",
+                "filter/focal": "焦距 (mm)",
+                "filter/megapixels": "像素",
+                "filter/atLeast": "至少",
+                "filter/shutter": "快門速度",
+                "filter/time": "拍攝時段",
+                "filter/any": "不限",
+                "filter/size": "檔案大小 (MB)",
+                "filter/syntaxTip": "提示:在搜尋框輸入 -字詞 可排除符合的相片,例如 -raw 或 -in:screenshots。",
+                "shutter/fast": "快於 1/1000 秒",
+                "shutter/action": "1/1000 – 1/250 秒",
+                "shutter/normal": "1/250 – 1/30 秒",
+                "shutter/slow": "1/30 – 1 秒",
+                "shutter/long": "長曝光(1 秒以上)",
+                "time/morning": "早上",
+                "time/afternoon": "下午",
+                "time/evening": "傍晚",
+                "time/night": "夜晚",
+                "tag/not": "排除 {v}",
+                "tag/from": "{v} 起",
+                "tag/until": "至 {v}",
+                "tag/size": "大小 {v}",
+                "view/timeline": "時間軸",
+                "view/timelineOff": "關閉",
+                "view/day": "日",
+                "view/month": "月",
+                "view/year": "年",
+                "view/layout": "版面",
+                "view/grid": "格狀",
+                "view/waterfall": "瀑布流",
+                "view/zoom": "縮放",
+                "search/everywhere": "搜尋所有相片",
+                "search/inFolder": "{folder} 中有 {results}",
+                "settings/title": "相片設定",
+                "settings/previews": "瀑布流預覽圖",
+                "settings/previewsDesc": "瀑布流版面會以原本的比例顯示每張相片。這些預覽圖由伺服器產生,可以保存起來,下次就能更快載入。",
+                "settings/modeAppdata": "保存在我的應用程式資料中(建議)",
+                "settings/modeCustom": "保存在我選擇的資料夾",
+                "settings/noFolder": "尚未選擇資料夾",
+                "settings/choose": "選擇…",
+                "settings/modeRealtime": "每次即時產生",
+                "settings/modeRealtimeDesc": "不佔用磁碟空間,但每次顯示時都要重新產生預覽圖。",
+                "settings/clearCache": "清除快取",
+                "settings/customNote": "預覽圖存放在名為 00 至 ff 的子資料夾中,清除快取只會刪除這些檔案。",
+                "settings/counting": "計算中…",
+                "settings/cacheSize": "{n} 張預覽圖,{size}",
+                "settings/index": "搜尋索引",
+                "settings/indexStatus": "已索引 {n} 張相片,上次更新:{time}",
+                "settings/neverIndexed": "尚未建立索引",
+                "settings/rebuild": "重建索引",
+                "settings/exclude": "排除的資料夾",
+                "settings/excludeDesc": "這些名稱的資料夾中的相片不會加入索引、搜尋與篩選。",
+                "settings/noExclude": "無",
+                "settings/excludePlaceholder": "資料夾名稱,例如 Screenshots",
+                "settings/add": "新增",
+                "settings/remove": "移除",
+                "settings/errPath": "請選擇資料夾。",
+                "settings/errMissing": "該資料夾不存在。",
+                "settings/errReadOnly": "你無法寫入該資料夾。",
+                "settings/errLibrary": "請選擇相片庫以外的資料夾,否則預覽圖會被當成相片顯示。",
+                "settings/errIndex": "無法開啟相片索引。",
+                "settings/errLoad": "無法載入設定。"
             },
             "titles": {
                 "Split the grid into Year / Month sections": "依年/月分區顯示",
@@ -258,8 +340,6 @@
                 "common/cancel": "取消",
                 "common/close": "關閉",
                 "common/download": "下載",
-                "sidebar/sortBy": "排序方式",
-                "sort/groupTip": "請關閉「依日期分組」以手動排序",
                 "sort/smart": "自然排序",
                 "sort/newest": "最新優先",
                 "sort/oldest": "最舊優先",
@@ -269,13 +349,8 @@
                 "sort/sizeDesc": "大小 大→小",
                 "sort/extAsc": "副檔名 A→Z",
                 "sort/extDesc": "副檔名 Z→A",
-                "sidebar/view": "檢視",
-                "view/groupByDate": "依日期分組",
                 "view/zoomHint": "按住 Ctrl / ⌘ 並捲動即可調整相片大小",
-                "sidebar/filterRating": "依評分篩選",
                 "rating/andUp": "評分 {n} 以上",
-                "rating/clear": "清除",
-                "rating/showing": "顯示 {n}★ 以上",
                 "sidebar/library": "媒體庫",
                 "sidebar/currentPath": "目前路徑",
                 "sidebar/subfolders": "子資料夾",
@@ -474,7 +549,96 @@
                 "editor/rotate": "旋轉",
                 "editor/aspect": "長寬比",
                 "editor/undo": "復原",
-                "editor/redo": "重做"
+                "editor/redo": "重做",
+                "toolbar/filter": "排序與篩選",
+                "toolbar/view": "檢視",
+                "toolbar/settings": "設定",
+                "filter/title": "排序與篩選",
+                "filter/reset": "重設篩選",
+                "filter/sort": "排序方式",
+                "filter/sortNote": "時間軸會依日期排列相片。如要依名稱、大小或類型排序,請在「檢視」中關閉時間軸。",
+                "filter/searchIn": "搜尋範圍",
+                "filter/thisFolder": "此資料夾",
+                "filter/everywhere": "所有相片",
+                "filter/scopeNote": "{folder} 及其中的資料夾",
+                "filter/rating": "評分",
+                "rating/unrated": "未評分",
+                "filter/taken": "拍攝日期",
+                "filter/from": "開始",
+                "filter/to": "結束",
+                "filter/camera": "相機",
+                "filter/anyCamera": "所有相機",
+                "filter/lens": "鏡頭",
+                "filter/anyLens": "所有鏡頭",
+                "filter/type": "檔案類型",
+                "filter/loading": "載入中…",
+                "filter/notIndexed": "這裡尚未建立索引",
+                "filter/orientation": "方向",
+                "filter/more": "相機設定與檔案詳細資料",
+                "filter/min": "最小",
+                "filter/max": "最大",
+                "filter/aperture": "光圈 (f/)",
+                "filter/focal": "焦距 (mm)",
+                "filter/megapixels": "像素",
+                "filter/atLeast": "至少",
+                "filter/shutter": "快門速度",
+                "filter/time": "拍攝時段",
+                "filter/any": "不限",
+                "filter/size": "檔案大小 (MB)",
+                "filter/syntaxTip": "提示:在搜尋框輸入 -字詞 可排除符合的相片,例如 -raw 或 -in:screenshots。",
+                "shutter/fast": "快於 1/1000 秒",
+                "shutter/action": "1/1000 – 1/250 秒",
+                "shutter/normal": "1/250 – 1/30 秒",
+                "shutter/slow": "1/30 – 1 秒",
+                "shutter/long": "長曝光(1 秒以上)",
+                "time/morning": "早上",
+                "time/afternoon": "下午",
+                "time/evening": "傍晚",
+                "time/night": "夜晚",
+                "tag/not": "排除 {v}",
+                "tag/from": "{v} 起",
+                "tag/until": "至 {v}",
+                "tag/size": "大小 {v}",
+                "view/timeline": "時間軸",
+                "view/timelineOff": "關閉",
+                "view/day": "日",
+                "view/month": "月",
+                "view/year": "年",
+                "view/layout": "版面",
+                "view/grid": "格狀",
+                "view/waterfall": "瀑布流",
+                "view/zoom": "縮放",
+                "search/everywhere": "搜尋所有相片",
+                "search/inFolder": "{folder} 中有 {results}",
+                "settings/title": "相片設定",
+                "settings/previews": "瀑布流預覽圖",
+                "settings/previewsDesc": "瀑布流版面會以原本的比例顯示每張相片。這些預覽圖由伺服器產生,可以保存起來,下次就能更快載入。",
+                "settings/modeAppdata": "保存在我的應用程式資料中(建議)",
+                "settings/modeCustom": "保存在我選擇的資料夾",
+                "settings/noFolder": "尚未選擇資料夾",
+                "settings/choose": "選擇…",
+                "settings/modeRealtime": "每次即時產生",
+                "settings/modeRealtimeDesc": "不佔用磁碟空間,但每次顯示時都要重新產生預覽圖。",
+                "settings/clearCache": "清除快取",
+                "settings/customNote": "預覽圖存放在名為 00 至 ff 的子資料夾中,清除快取只會刪除這些檔案。",
+                "settings/counting": "計算中…",
+                "settings/cacheSize": "{n} 張預覽圖,{size}",
+                "settings/index": "搜尋索引",
+                "settings/indexStatus": "已索引 {n} 張相片,上次更新:{time}",
+                "settings/neverIndexed": "尚未建立索引",
+                "settings/rebuild": "重建索引",
+                "settings/exclude": "排除的資料夾",
+                "settings/excludeDesc": "這些名稱的資料夾中的相片不會加入索引、搜尋與篩選。",
+                "settings/noExclude": "無",
+                "settings/excludePlaceholder": "資料夾名稱,例如 Screenshots",
+                "settings/add": "新增",
+                "settings/remove": "移除",
+                "settings/errPath": "請選擇資料夾。",
+                "settings/errMissing": "該資料夾不存在。",
+                "settings/errReadOnly": "你無法寫入該資料夾。",
+                "settings/errLibrary": "請選擇相片庫以外的資料夾,否則預覽圖會被當成相片顯示。",
+                "settings/errIndex": "無法開啟相片索引。",
+                "settings/errLoad": "無法載入設定。"
             },
             "titles": {
                 "Split the grid into Year / Month sections": "依年/月分區顯示",
@@ -505,8 +669,6 @@
                 "common/cancel": "取消",
                 "common/close": "关闭",
                 "common/download": "下载",
-                "sidebar/sortBy": "排序方式",
-                "sort/groupTip": "请关闭“按日期分组”以手动排序",
                 "sort/smart": "自然排序",
                 "sort/newest": "最新优先",
                 "sort/oldest": "最早优先",
@@ -516,13 +678,8 @@
                 "sort/sizeDesc": "大小 大→小",
                 "sort/extAsc": "扩展名 A→Z",
                 "sort/extDesc": "扩展名 Z→A",
-                "sidebar/view": "查看",
-                "view/groupByDate": "按日期分组",
                 "view/zoomHint": "按住 Ctrl / ⌘ 并滚动可调整照片大小",
-                "sidebar/filterRating": "按评分筛选",
                 "rating/andUp": "评分 {n} 及以上",
-                "rating/clear": "清除",
-                "rating/showing": "显示 {n}★ 及以上",
                 "sidebar/library": "资料库",
                 "sidebar/currentPath": "当前路径",
                 "sidebar/subfolders": "子文件夹",
@@ -721,7 +878,96 @@
                 "editor/rotate": "旋转",
                 "editor/aspect": "宽高比",
                 "editor/undo": "撤销",
-                "editor/redo": "重做"
+                "editor/redo": "重做",
+                "toolbar/filter": "排序与筛选",
+                "toolbar/view": "视图",
+                "toolbar/settings": "设置",
+                "filter/title": "排序与筛选",
+                "filter/reset": "重置筛选",
+                "filter/sort": "排序方式",
+                "filter/sortNote": "时间轴会按日期排列照片。如需按名称、大小或类型排序,请在“视图”中关闭时间轴。",
+                "filter/searchIn": "搜索范围",
+                "filter/thisFolder": "此文件夹",
+                "filter/everywhere": "所有照片",
+                "filter/scopeNote": "{folder} 及其中的文件夹",
+                "filter/rating": "评分",
+                "rating/unrated": "未评分",
+                "filter/taken": "拍摄日期",
+                "filter/from": "开始",
+                "filter/to": "结束",
+                "filter/camera": "相机",
+                "filter/anyCamera": "所有相机",
+                "filter/lens": "镜头",
+                "filter/anyLens": "所有镜头",
+                "filter/type": "文件类型",
+                "filter/loading": "加载中…",
+                "filter/notIndexed": "这里尚未建立索引",
+                "filter/orientation": "方向",
+                "filter/more": "相机设置与文件详细信息",
+                "filter/min": "最小",
+                "filter/max": "最大",
+                "filter/aperture": "光圈 (f/)",
+                "filter/focal": "焦距 (mm)",
+                "filter/megapixels": "像素",
+                "filter/atLeast": "至少",
+                "filter/shutter": "快门速度",
+                "filter/time": "拍摄时段",
+                "filter/any": "不限",
+                "filter/size": "文件大小 (MB)",
+                "filter/syntaxTip": "提示:在搜索框输入 -词语 可排除匹配的照片,例如 -raw 或 -in:screenshots。",
+                "shutter/fast": "快于 1/1000 秒",
+                "shutter/action": "1/1000 – 1/250 秒",
+                "shutter/normal": "1/250 – 1/30 秒",
+                "shutter/slow": "1/30 – 1 秒",
+                "shutter/long": "长曝光(1 秒以上)",
+                "time/morning": "早上",
+                "time/afternoon": "下午",
+                "time/evening": "傍晚",
+                "time/night": "夜晚",
+                "tag/not": "排除 {v}",
+                "tag/from": "{v} 起",
+                "tag/until": "至 {v}",
+                "tag/size": "大小 {v}",
+                "view/timeline": "时间轴",
+                "view/timelineOff": "关闭",
+                "view/day": "日",
+                "view/month": "月",
+                "view/year": "年",
+                "view/layout": "布局",
+                "view/grid": "网格",
+                "view/waterfall": "瀑布流",
+                "view/zoom": "缩放",
+                "search/everywhere": "搜索所有照片",
+                "search/inFolder": "{folder} 中有 {results}",
+                "settings/title": "照片设置",
+                "settings/previews": "瀑布流预览图",
+                "settings/previewsDesc": "瀑布流布局会以原始比例显示每张照片。这些预览图由服务器生成,可以保存下来,下次加载更快。",
+                "settings/modeAppdata": "保存在我的应用数据中(推荐)",
+                "settings/modeCustom": "保存在我选择的文件夹",
+                "settings/noFolder": "尚未选择文件夹",
+                "settings/choose": "选择…",
+                "settings/modeRealtime": "每次实时生成",
+                "settings/modeRealtimeDesc": "不占用磁盘空间,但每次显示时都要重新生成预览图。",
+                "settings/clearCache": "清除缓存",
+                "settings/customNote": "预览图存放在名为 00 至 ff 的子文件夹中,清除缓存只会删除这些文件。",
+                "settings/counting": "计算中…",
+                "settings/cacheSize": "{n} 张预览图,{size}",
+                "settings/index": "搜索索引",
+                "settings/indexStatus": "已索引 {n} 张照片,上次更新:{time}",
+                "settings/neverIndexed": "尚未建立索引",
+                "settings/rebuild": "重建索引",
+                "settings/exclude": "排除的文件夹",
+                "settings/excludeDesc": "这些名称的文件夹中的照片不会加入索引、搜索和筛选。",
+                "settings/noExclude": "无",
+                "settings/excludePlaceholder": "文件夹名称,例如 Screenshots",
+                "settings/add": "添加",
+                "settings/remove": "移除",
+                "settings/errPath": "请选择文件夹。",
+                "settings/errMissing": "该文件夹不存在。",
+                "settings/errReadOnly": "你无法写入该文件夹。",
+                "settings/errLibrary": "请选择照片库以外的文件夹,否则预览图会被当作照片显示。",
+                "settings/errIndex": "无法打开照片索引。",
+                "settings/errLoad": "无法加载设置。"
             },
             "titles": {
                 "Split the grid into Year / Month sections": "按年/月分区显示",
@@ -752,8 +998,6 @@
                 "common/cancel": "Cancel",
                 "common/close": "Close",
                 "common/download": "Download",
-                "sidebar/sortBy": "Sort By",
-                "sort/groupTip": "Turn off Group by date to sort manually",
                 "sort/smart": "Natural Order",
                 "sort/newest": "Newest First",
                 "sort/oldest": "Oldest First",
@@ -763,13 +1007,8 @@
                 "sort/sizeDesc": "Size Large→Small",
                 "sort/extAsc": "Extension A→Z",
                 "sort/extDesc": "Extension Z→A",
-                "sidebar/view": "View",
-                "view/groupByDate": "Group by date",
                 "view/zoomHint": "Hold Ctrl / ⌘ and scroll to resize photos",
-                "sidebar/filterRating": "Filter by Rating",
                 "rating/andUp": "Rating {n} and up",
-                "rating/clear": "Clear",
-                "rating/showing": "Showing {n}★ & up",
                 "sidebar/library": "Library",
                 "sidebar/currentPath": "Current Path",
                 "sidebar/subfolders": "Subfolders",
@@ -968,7 +1207,96 @@
                 "editor/rotate": "Rotate",
                 "editor/aspect": "Aspect ratio",
                 "editor/undo": "Undo",
-                "editor/redo": "Redo"
+                "editor/redo": "Redo",
+                "toolbar/filter": "Sort & filter",
+                "toolbar/view": "View",
+                "toolbar/settings": "Settings",
+                "filter/title": "Sort & filter",
+                "filter/reset": "Reset filters",
+                "filter/sort": "Sort by",
+                "filter/sortNote": "The timeline keeps photos in date order. Turn it off under View to sort by name, size or type.",
+                "filter/searchIn": "Look in",
+                "filter/thisFolder": "This folder",
+                "filter/everywhere": "All photos",
+                "filter/scopeNote": "{folder} and the folders inside it",
+                "filter/rating": "Rating",
+                "rating/unrated": "Unrated",
+                "filter/taken": "Date taken",
+                "filter/from": "From",
+                "filter/to": "To",
+                "filter/camera": "Camera",
+                "filter/anyCamera": "Any camera",
+                "filter/lens": "Lens",
+                "filter/anyLens": "Any lens",
+                "filter/type": "File type",
+                "filter/loading": "Loading…",
+                "filter/notIndexed": "Nothing indexed here yet",
+                "filter/orientation": "Orientation",
+                "filter/more": "Camera settings & file details",
+                "filter/min": "Min",
+                "filter/max": "Max",
+                "filter/aperture": "Aperture (f/)",
+                "filter/focal": "Focal length (mm)",
+                "filter/megapixels": "Megapixels",
+                "filter/atLeast": "At least",
+                "filter/shutter": "Shutter speed",
+                "filter/time": "Time of day",
+                "filter/any": "Any",
+                "filter/size": "File size (MB)",
+                "filter/syntaxTip": "Tip: type -word in the search box to leave matching photos out, e.g. -raw or -in:screenshots.",
+                "shutter/fast": "Faster than 1/1000 s",
+                "shutter/action": "1/1000 – 1/250 s",
+                "shutter/normal": "1/250 – 1/30 s",
+                "shutter/slow": "1/30 – 1 s",
+                "shutter/long": "Long exposure (1 s or longer)",
+                "time/morning": "Morning",
+                "time/afternoon": "Afternoon",
+                "time/evening": "Evening",
+                "time/night": "Night",
+                "tag/not": "Not {v}",
+                "tag/from": "From {v}",
+                "tag/until": "Until {v}",
+                "tag/size": "Size {v}",
+                "view/timeline": "Timeline",
+                "view/timelineOff": "Off",
+                "view/day": "Day",
+                "view/month": "Month",
+                "view/year": "Year",
+                "view/layout": "Layout",
+                "view/grid": "Grid",
+                "view/waterfall": "Waterfall",
+                "view/zoom": "Zoom",
+                "search/everywhere": "Search all photos",
+                "search/inFolder": "{results} in {folder}",
+                "settings/title": "Photo settings",
+                "settings/previews": "Waterfall previews",
+                "settings/previewsDesc": "The waterfall layout shows every photo in its own shape. Those previews are drawn on the server and can be kept, so they load quickly next time.",
+                "settings/modeAppdata": "Keep them in my app data (recommended)",
+                "settings/modeCustom": "Keep them in a folder I choose",
+                "settings/noFolder": "No folder chosen yet",
+                "settings/choose": "Choose…",
+                "settings/modeRealtime": "Draw them every time",
+                "settings/modeRealtimeDesc": "Uses no disk space, but every preview is drawn again each time it is shown.",
+                "settings/clearCache": "Clear cache",
+                "settings/customNote": "Previews are kept in sub folders named 00 to ff. Clearing the cache only removes those.",
+                "settings/counting": "Counting…",
+                "settings/cacheSize": "{n} previews, {size}",
+                "settings/index": "Search index",
+                "settings/indexStatus": "{n} photos indexed, last updated {time}",
+                "settings/neverIndexed": "not indexed yet",
+                "settings/rebuild": "Rebuild index",
+                "settings/exclude": "Excluded folders",
+                "settings/excludeDesc": "Photos in folders with these names are left out of the index, the search and the filters.",
+                "settings/noExclude": "None",
+                "settings/excludePlaceholder": "Folder name, e.g. Screenshots",
+                "settings/add": "Add",
+                "settings/remove": "Remove",
+                "settings/errPath": "Pick a folder.",
+                "settings/errMissing": "That folder does not exist.",
+                "settings/errReadOnly": "You cannot write to that folder.",
+                "settings/errLibrary": "Pick a folder outside the Photo library, or the previews would show up as photos.",
+                "settings/errIndex": "The photo index cannot be opened.",
+                "settings/errLoad": "Settings could not be loaded."
             },
             "titles": {
                 "Split the grid into Year / Month sections": "Split the grid into Year / Month sections",
@@ -999,8 +1327,6 @@
                 "common/cancel": "キャンセル",
                 "common/close": "閉じる",
                 "common/download": "ダウンロード",
-                "sidebar/sortBy": "並べ替え",
-                "sort/groupTip": "手動で並べ替えるには「日付でグループ化」をオフにしてください",
                 "sort/smart": "自然順",
                 "sort/newest": "新しい順",
                 "sort/oldest": "古い順",
@@ -1010,13 +1336,8 @@
                 "sort/sizeDesc": "サイズ 大→小",
                 "sort/extAsc": "拡張子 A→Z",
                 "sort/extDesc": "拡張子 Z→A",
-                "sidebar/view": "表示",
-                "view/groupByDate": "日付でグループ化",
                 "view/zoomHint": "Ctrl / ⌘ を押しながらスクロールすると写真の大きさを変更できます",
-                "sidebar/filterRating": "評価で絞り込む",
                 "rating/andUp": "評価 {n} 以上",
-                "rating/clear": "クリア",
-                "rating/showing": "{n}★ 以上を表示",
                 "sidebar/library": "ライブラリ",
                 "sidebar/currentPath": "現在のパス",
                 "sidebar/subfolders": "サブフォルダー",
@@ -1215,7 +1536,96 @@
                 "editor/rotate": "回転",
                 "editor/aspect": "縦横比",
                 "editor/undo": "元に戻す",
-                "editor/redo": "やり直す"
+                "editor/redo": "やり直す",
+                "toolbar/filter": "並べ替えと絞り込み",
+                "toolbar/view": "表示",
+                "toolbar/settings": "設定",
+                "filter/title": "並べ替えと絞り込み",
+                "filter/reset": "絞り込みをリセット",
+                "filter/sort": "並べ替え",
+                "filter/sortNote": "タイムラインは日付順に並べます。名前・サイズ・種類で並べ替えるには「表示」でタイムラインをオフにしてください。",
+                "filter/searchIn": "検索範囲",
+                "filter/thisFolder": "このフォルダー",
+                "filter/everywhere": "すべての写真",
+                "filter/scopeNote": "{folder} とその中のフォルダー",
+                "filter/rating": "評価",
+                "rating/unrated": "評価なし",
+                "filter/taken": "撮影日",
+                "filter/from": "開始",
+                "filter/to": "終了",
+                "filter/camera": "カメラ",
+                "filter/anyCamera": "すべてのカメラ",
+                "filter/lens": "レンズ",
+                "filter/anyLens": "すべてのレンズ",
+                "filter/type": "ファイルの種類",
+                "filter/loading": "読み込み中…",
+                "filter/notIndexed": "ここはまだインデックス化されていません",
+                "filter/orientation": "向き",
+                "filter/more": "撮影設定とファイルの詳細",
+                "filter/min": "最小",
+                "filter/max": "最大",
+                "filter/aperture": "絞り (f/)",
+                "filter/focal": "焦点距離 (mm)",
+                "filter/megapixels": "画素数",
+                "filter/atLeast": "以上",
+                "filter/shutter": "シャッタースピード",
+                "filter/time": "撮影時間帯",
+                "filter/any": "指定なし",
+                "filter/size": "ファイルサイズ (MB)",
+                "filter/syntaxTip": "ヒント:検索ボックスに -語句 と入力すると一致する写真を除外できます(例:-raw、-in:screenshots)。",
+                "shutter/fast": "1/1000 秒より高速",
+                "shutter/action": "1/1000 – 1/250 秒",
+                "shutter/normal": "1/250 – 1/30 秒",
+                "shutter/slow": "1/30 – 1 秒",
+                "shutter/long": "長時間露光(1 秒以上)",
+                "time/morning": "朝",
+                "time/afternoon": "午後",
+                "time/evening": "夕方",
+                "time/night": "夜",
+                "tag/not": "{v} を除外",
+                "tag/from": "{v} 以降",
+                "tag/until": "{v} まで",
+                "tag/size": "サイズ {v}",
+                "view/timeline": "タイムライン",
+                "view/timelineOff": "オフ",
+                "view/day": "日",
+                "view/month": "月",
+                "view/year": "年",
+                "view/layout": "レイアウト",
+                "view/grid": "グリッド",
+                "view/waterfall": "ウォーターフォール",
+                "view/zoom": "ズーム",
+                "search/everywhere": "すべての写真を検索",
+                "search/inFolder": "{folder} 内で {results}",
+                "settings/title": "写真の設定",
+                "settings/previews": "ウォーターフォールのプレビュー",
+                "settings/previewsDesc": "ウォーターフォールでは各写真を元の縦横比で表示します。プレビューはサーバーで作成され、保存しておくと次回から速く表示されます。",
+                "settings/modeAppdata": "アプリデータに保存する(推奨)",
+                "settings/modeCustom": "選んだフォルダーに保存する",
+                "settings/noFolder": "フォルダーが選ばれていません",
+                "settings/choose": "選択…",
+                "settings/modeRealtime": "毎回その場で作成する",
+                "settings/modeRealtimeDesc": "ディスク容量を使いませんが、表示するたびにプレビューを作り直します。",
+                "settings/clearCache": "キャッシュを消去",
+                "settings/customNote": "プレビューは 00〜ff という名前のサブフォルダーに保存されます。キャッシュの消去で削除されるのはそれらだけです。",
+                "settings/counting": "集計中…",
+                "settings/cacheSize": "プレビュー {n} 枚、{size}",
+                "settings/index": "検索インデックス",
+                "settings/indexStatus": "{n} 枚をインデックス化(最終更新:{time})",
+                "settings/neverIndexed": "未作成",
+                "settings/rebuild": "インデックスを再構築",
+                "settings/exclude": "除外するフォルダー",
+                "settings/excludeDesc": "これらの名前のフォルダーにある写真は、インデックス・検索・絞り込みの対象外になります。",
+                "settings/noExclude": "なし",
+                "settings/excludePlaceholder": "フォルダー名(例:Screenshots)",
+                "settings/add": "追加",
+                "settings/remove": "削除",
+                "settings/errPath": "フォルダーを選んでください。",
+                "settings/errMissing": "そのフォルダーは存在しません。",
+                "settings/errReadOnly": "そのフォルダーには書き込めません。",
+                "settings/errLibrary": "写真ライブラリの外にあるフォルダーを選んでください。中にあるとプレビューが写真として表示されます。",
+                "settings/errIndex": "写真のインデックスを開けません。",
+                "settings/errLoad": "設定を読み込めませんでした。"
             },
             "titles": {
                 "Split the grid into Year / Month sections": "年・月ごとに区切って表示",
@@ -1246,8 +1656,6 @@
                 "common/cancel": "취소",
                 "common/close": "닫기",
                 "common/download": "다운로드",
-                "sidebar/sortBy": "정렬 기준",
-                "sort/groupTip": "직접 정렬하려면 '날짜별 그룹'을 끄세요",
                 "sort/smart": "자연 순서",
                 "sort/newest": "최신순",
                 "sort/oldest": "오래된순",
@@ -1257,13 +1665,8 @@
                 "sort/sizeDesc": "크기 큰순",
                 "sort/extAsc": "확장자 A→Z",
                 "sort/extDesc": "확장자 Z→A",
-                "sidebar/view": "보기",
-                "view/groupByDate": "날짜별 그룹",
                 "view/zoomHint": "Ctrl / ⌘ 키를 누른 채 스크롤하면 사진 크기를 바꿀 수 있습니다",
-                "sidebar/filterRating": "별점으로 필터",
                 "rating/andUp": "별점 {n} 이상",
-                "rating/clear": "지우기",
-                "rating/showing": "{n}★ 이상 표시",
                 "sidebar/library": "라이브러리",
                 "sidebar/currentPath": "현재 경로",
                 "sidebar/subfolders": "하위 폴더",
@@ -1462,7 +1865,96 @@
                 "editor/rotate": "회전",
                 "editor/aspect": "화면 비율",
                 "editor/undo": "실행 취소",
-                "editor/redo": "다시 실행"
+                "editor/redo": "다시 실행",
+                "toolbar/filter": "정렬 및 필터",
+                "toolbar/view": "보기",
+                "toolbar/settings": "설정",
+                "filter/title": "정렬 및 필터",
+                "filter/reset": "필터 초기화",
+                "filter/sort": "정렬 기준",
+                "filter/sortNote": "타임라인은 사진을 날짜순으로 표시합니다. 이름, 크기, 형식으로 정렬하려면 보기에서 타임라인을 끄세요.",
+                "filter/searchIn": "검색 범위",
+                "filter/thisFolder": "이 폴더",
+                "filter/everywhere": "모든 사진",
+                "filter/scopeNote": "{folder} 및 그 안의 폴더",
+                "filter/rating": "별점",
+                "rating/unrated": "별점 없음",
+                "filter/taken": "촬영 날짜",
+                "filter/from": "시작",
+                "filter/to": "끝",
+                "filter/camera": "카메라",
+                "filter/anyCamera": "모든 카메라",
+                "filter/lens": "렌즈",
+                "filter/anyLens": "모든 렌즈",
+                "filter/type": "파일 형식",
+                "filter/loading": "불러오는 중…",
+                "filter/notIndexed": "아직 색인된 사진이 없습니다",
+                "filter/orientation": "방향",
+                "filter/more": "촬영 설정 및 파일 정보",
+                "filter/min": "최소",
+                "filter/max": "최대",
+                "filter/aperture": "조리개 (f/)",
+                "filter/focal": "초점 거리 (mm)",
+                "filter/megapixels": "화소",
+                "filter/atLeast": "최소",
+                "filter/shutter": "셔터 속도",
+                "filter/time": "촬영 시간대",
+                "filter/any": "전체",
+                "filter/size": "파일 크기 (MB)",
+                "filter/syntaxTip": "팁: 검색창에 -단어 를 입력하면 일치하는 사진을 제외합니다. 예: -raw, -in:screenshots",
+                "shutter/fast": "1/1000초보다 빠름",
+                "shutter/action": "1/1000 – 1/250초",
+                "shutter/normal": "1/250 – 1/30초",
+                "shutter/slow": "1/30 – 1초",
+                "shutter/long": "장노출 (1초 이상)",
+                "time/morning": "아침",
+                "time/afternoon": "오후",
+                "time/evening": "저녁",
+                "time/night": "밤",
+                "tag/not": "{v} 제외",
+                "tag/from": "{v}부터",
+                "tag/until": "{v}까지",
+                "tag/size": "크기 {v}",
+                "view/timeline": "타임라인",
+                "view/timelineOff": "끔",
+                "view/day": "일",
+                "view/month": "월",
+                "view/year": "연",
+                "view/layout": "레이아웃",
+                "view/grid": "격자",
+                "view/waterfall": "워터폴",
+                "view/zoom": "확대/축소",
+                "search/everywhere": "모든 사진 검색",
+                "search/inFolder": "{folder}에서 {results}",
+                "settings/title": "사진 설정",
+                "settings/previews": "워터폴 미리 보기",
+                "settings/previewsDesc": "워터폴 레이아웃은 사진을 원래 비율로 보여 줍니다. 미리 보기는 서버에서 만들어지며, 저장해 두면 다음에 더 빨리 열립니다.",
+                "settings/modeAppdata": "내 앱 데이터에 저장 (권장)",
+                "settings/modeCustom": "선택한 폴더에 저장",
+                "settings/noFolder": "선택한 폴더 없음",
+                "settings/choose": "선택…",
+                "settings/modeRealtime": "매번 새로 만들기",
+                "settings/modeRealtimeDesc": "디스크 공간을 쓰지 않지만, 표시할 때마다 미리 보기를 다시 만듭니다.",
+                "settings/clearCache": "캐시 지우기",
+                "settings/customNote": "미리 보기는 00~ff 이름의 하위 폴더에 저장됩니다. 캐시를 지우면 그 파일만 삭제됩니다.",
+                "settings/counting": "계산 중…",
+                "settings/cacheSize": "미리 보기 {n}개, {size}",
+                "settings/index": "검색 색인",
+                "settings/indexStatus": "사진 {n}장 색인됨, 마지막 업데이트: {time}",
+                "settings/neverIndexed": "아직 없음",
+                "settings/rebuild": "색인 다시 만들기",
+                "settings/exclude": "제외할 폴더",
+                "settings/excludeDesc": "이 이름의 폴더에 있는 사진은 색인, 검색, 필터에서 제외됩니다.",
+                "settings/noExclude": "없음",
+                "settings/excludePlaceholder": "폴더 이름 (예: Screenshots)",
+                "settings/add": "추가",
+                "settings/remove": "삭제",
+                "settings/errPath": "폴더를 선택하세요.",
+                "settings/errMissing": "해당 폴더가 없습니다.",
+                "settings/errReadOnly": "해당 폴더에 쓸 수 없습니다.",
+                "settings/errLibrary": "사진 보관함 밖의 폴더를 선택하세요. 안에 두면 미리 보기가 사진으로 표시됩니다.",
+                "settings/errIndex": "사진 색인을 열 수 없습니다.",
+                "settings/errLoad": "설정을 불러오지 못했습니다."
             },
             "titles": {
                 "Split the grid into Year / Month sections": "연/월 구역으로 나누어 표시",

File diff suppressed because it is too large
+ 582 - 212
src/web/Photo/photo.js


+ 70 - 1
src/web/Photo/search.js

@@ -42,11 +42,49 @@ function photoSuggestIcon(type) {
             return 'filter';
         case 'rating':
             return 'star';
+        case 'folder':
+            return 'folder outline';
+        case 'shutter':
+            return 'stopwatch';
+        case 'size':
+            return 'hdd outline';
+        case 'time':
+            return 'clock outline';
         default:
             return 'search';
     }
 }
 
+// The label of a preset token (shutter / time of day), or null
+function photoPresetTokenLabel(value) {
+    var lists = [PHOTO_SHUTTER_PRESETS, PHOTO_TIME_PRESETS];
+    for (var l = 0; l < lists.length; l++) {
+        for (var i = 0; i < lists[l].length; i++) {
+            if (lists[l][i].q === value) return T(lists[l][i].key, lists[l][i].en);
+        }
+    }
+    return null;
+}
+
+// "1 MB", "500 KB": a size bound as typed (MB when it has no unit)
+function photoSizeBoundLabel(s) {
+    var m = /^([0-9.]+)\s*(b|k|kb|m|mb|g|gb)?$/i.exec(('' + s).trim());
+    if (!m) return '' + s;
+    var u = (m[2] || 'mb').toLowerCase();
+    var unit = u === 'b' ? 'B' : (u.charAt(0) === 'k' ? 'KB' : (u.charAt(0) === 'g' ? 'GB' : 'MB'));
+    return m[1] + ' ' + unit;
+}
+
+// Label of a range value as typed after "key:" (">=1", "1/250..1/30", "5-10")
+function photoTypedRangeLabel(val, fmt) {
+    fmt = fmt || function (v) { return v; };
+    var s = ('' + val).trim(), m;
+    if ((m = /^>=?\s*(.+)$/.exec(s))) return '≥ ' + fmt(m[1]);
+    if ((m = /^<=?\s*(.+)$/.exec(s))) return '≤ ' + fmt(m[1]);
+    if ((m = /^(.+?)\.\.(.+)$/.exec(s)) || (m = /^([^\-]+)-([^\-]+)$/.exec(s))) return fmt(m[1]) + ' – ' + fmt(m[2]);
+    return fmt(s);
+}
+
 // Title-case a single word.
 function photoCap(s) {
     s = '' + s;
@@ -94,6 +132,11 @@ function photoLocalizeSuggestion(s) {
         label = T('suggest/andUp', '{n}★ & up', { n: m[1] });
     } else if (s.type === 'date' && (m = /month:(\d+)$/.exec(s.value))) {
         label = photoMonthName(parseInt(m[1], 10));
+    } else if (s.type === 'shutter' || s.type === 'size' || s.type === 'time') {
+        label = photoParseTagToken(s.value.split(' ').pop().replace(/^-/, '')).label;
+    }
+    if (/(^|\s)-\S/.test(s.value) && s.type !== 'file') {
+        label = T('tag/not', 'Not {v}', { v: label });
     }
     if (hint === 'orientation') {
         hint = T('suggest/orientation', 'orientation');
@@ -110,6 +153,15 @@ function photoLocalizeSuggestion(s) {
 // is the friendly text shown on the chip; `type` drives the chip icon/colour.
 function photoParseTagToken(token) {
     token = ('' + token).trim();
+    // "-token" leaves out what the token matches
+    if (token.length > 1 && token.charAt(0) === '-') {
+        var inner = photoParseTagToken(token.substring(1));
+        return { label: T('tag/not', 'Not {v}', { v: inner.label }), value: '-' + inner.value, type: inner.type, neg: true };
+    }
+    var preset = photoPresetTokenLabel(token);
+    if (preset) {
+        return { label: preset, value: token, type: token.indexOf('hour:') === 0 ? 'time' : 'shutter' };
+    }
     var lower = token.toLowerCase();
     var colon = token.indexOf(':');
     var key = colon > 0 ? lower.substring(0, colon) : '';
@@ -150,7 +202,24 @@ function photoParseTagToken(token) {
             case 'model': case 'camera': return { label: unq(val), value: token, type: 'camera' };
             case 'make': case 'brand': return { label: unq(val), value: token, type: 'camera' };
             case 'lens': return { label: unq(val), value: token, type: 'lens' };
-            case 'ext': case 'type': return { label: '.' + unq(val).replace(/^\./, ''), value: token, type: 'type' };
+            case 'ext': case 'type':
+                return {
+                    label: unq(val).split(',').map(function (e) {
+                        e = e.trim().replace(/^\./, '');
+                        return e.toLowerCase() === 'raw' ? 'RAW' : '.' + e;
+                    }).join(', '),
+                    value: token, type: 'type'
+                };
+            case 'shutter': case 'exposure': case 'ss':
+                return { label: photoTypedRangeLabel(unq(val), function (v) { return ('' + v).replace(/s$/i, '') + ' s'; }), value: token, type: 'shutter' };
+            case 'size': case 'filesize':
+                return { label: T('tag/size', 'Size {v}', { v: photoTypedRangeLabel(unq(val), photoSizeBoundLabel) }), value: token, type: 'size' };
+            case 'hour': case 'time':
+                return { label: photoTypedRangeLabel(unq(val), function (v) { return v + ':00'; }), value: token, type: 'time' };
+            case 'folder': case 'in': {
+                var fv = unq(val).replace(/\/+$/, '');
+                return { label: fv.split('/').pop() || fv, value: token, type: 'folder' };
+            }
             case 'name': case 'filename': return { label: unq(val), value: token, type: 'file' };
             case 'orientation': return { label: photoOrientationLabel(unq(val)), value: token, type: 'filter' };
             case 'month':

+ 7 - 0
src/web/Terminal/docs/api.json

@@ -358,6 +358,13 @@
           "desc": "Return EXIF data as a JSON string. Reads JPEG, TIFF based RAW and HEIC / HEIF photos.",
           "ret": "string (JSON)",
           "example": "requirelib(\"imagelib\");\nvar exif = JSON.parse(imagelib.getExif(\"user:/img.jpg\"));"
+        },
+        {
+          "name": "imagelib.renderPreview",
+          "sig": "imagelib.renderPreview(src, dest, maxWidth, maxHeight)",
+          "desc": "Draw a photo upright and scaled down to fit maxWidth x maxHeight, keeping its shape (0 leaves a side free, never enlarges). Reads JPEG, PNG, WebP, GIF, HEIC / HEIF and RAW, applying the EXIF orientation. dest is a .jpg or .png path (folders are created), or \"\" to get a JPEG data URL instead. Pictures over 120 MP are refused.",
+          "ret": "{width, height, dataURL?}",
+          "example": "requirelib(\"imagelib\");\nvar p = imagelib.renderPreview(\"user:/Photo/a.heic\", \"user:/.appdata/photo/previews/a.jpg\", 720, 1440);\nvar inline = imagelib.renderPreview(\"user:/Photo/b.jpg\", \"\", 480, 480).dataURL;"
         }
       ]
     },

Some files were not shown because too many files changed in this diff