/* Vio-PDF - shows PDF documents on Violyx.
   It reads the file itself: objects, cross-reference streams, damaged files, encryption (RC4, AES
   128 and 256), all the common stream filters, fonts (TrueType, OpenType/CFF, Type 1, Type 3,
   composite fonts), images (JPEG, also progressive; fax G3/G4), colour spaces, shadings,
   patterns, transparency groups, soft masks and blend modes, and the appearances of form fields.
   Pages are drawn with smooth edges into pixel cells; one can turn pages, zoom, rotate, follow the
   table of contents and search for text.

   Copyright (c) 2026, Merecete. BSD-3-Clause licence, see the Info window or LICENSE. The fonts used
   for PDFs that do not bring their own come from Liberation (SIL Open Font License) and DejaVu
   (Bitstream Vera licence), see LICENSE-FONTS; the glyph list from Adobe (BSD-3-Clause). */
#include "violyx.h"
#include "pdf_base.h"
#include "pdf_filter.h"
#include "pdf_crypt.h"
#include "pdf_parse.h"
#include "pdf_doc.h"
#include "pdf_raster.h"
#include "pdf_font.h"
#include "pdf_pfont.h"
#include "pdf_jpeg.h"
#include "pdf_ccitt.h"
#include "pdf_color.h"
#include "pdf_image.h"
#include "pdf_shade.h"
#include "pdf_render.h"
#include "pdf_text.h"

#define VERSION "1.0"
static int lang_en;
#define T(de, en) (lang_en ? (en) : (de))
#define A_BAR VX_ATTR(VC_PANEL, VC_SOFT)
#define A_DIM VX_ATTR(VC_PANEL, VC_MID)
#define A_HOT VX_ATTR(VC_PANEL, VC_HOT)
#define A_BOX VX_ATTR(VC_PANEL, VC_GLOW)
#define A_SEL VX_ATTR(VC_SEL, VC_GLOW)
#define A_KEY VX_ATTR(VC_PANEL, VC_NEON)

/* ---------------------------------------------------------------- memory */
static u8 *filebuf;
static long filecap, filelen;
static int mem_ok;
static canvas_t PC;  /* the page as drawn */
static long pc_cap;  /* the most pixels the page may have */
static long pc_have; /* pixels the canvas holds now */
static void init_memory(void) {
    /* Violyx gives a program up to 256 MB and maps every page at once: so only what is always
       needed is taken now, the rest in blocks when a document asks for it */
    ostack_cap = 1 << 16;
    ostack = vx_alloc(sizeof(obj_t) * (size_t)ostack_cap);
    mem_ok = ostack && render_init();
    A_ops.chunk = 1 << 20, A_ops.limit = 16 << 20;
    A_doc.chunk = 4 << 20, A_doc.limit = 112 << 20;
    A_draw.chunk = 8 << 20, A_draw.limit = 144 << 20;
    pc_cap = 6L << 20;
}
/* a canvas for n pixels: grown when a bigger zoom needs it (the old one is not given back) */
static int canvas_for(long n) {
    if (n <= pc_have)
        return 1;
    long want = n < (3L << 19) ? 3L << 19 : n;
    if (want > pc_cap)
        want = pc_cap;
    if (want < n)
        return 0;
    u8 *p = vx_alloc((size_t)want * 3);
    if (!p) {
        pc_cap = pc_have; /* no more: the zoom stays where it is */
        return 0;
    }
    PC.rgb = p;
    pc_have = want;
    return 1;
}
/* everything of the last document is forgotten */
static void forget_doc(void) {
    areset(&A_doc, 0);
    nfonts = 0;
    memset(subst_data, 0, sizeof subst_data);
    fx_tab[0] = fx_tab[1] = 0;
    npages = 0;
    noutl = 0;
}

/* ---------------------------------------------------------------- the state of the viewer */
enum { Z_WIDTH, Z_PAGE, Z_FREE };
static char path[256], pdfver[8];
static int open_ok, cur, zmode = Z_WIDTH, rot, full_on, full_zoomed;
static double zoom = 1; /* pixels per point */
static int ox, oy;      /* the view on the page canvas */
static int drawn_page = -1, drawn_rot = -1, render_bad;
static double drawn_zoom = -1;
static int W, H, VW, VH; /* screen cells, view pixels */
static int panel;        /* 0 none, 1 contents, 2 document, 3 info, 4 licences, 5 keys */
static int ptop, psel;   /* scrolling in panels */
static char msg[96];
static long msg_until;
static u8 *view; /* the image shown: VW x VH palette indices */

/* ---------------------------------------------------------------- colours of the screen */
static u8 lut[32 * 32 * 32];
static u8 c_desk, c_shadow, c_hilite_mix;
static u8 rgb_ix(int r, int g, int b) {
    static const int L[6] = {0, 95, 135, 175, 215, 255};
    int best = 16, bd = 1 << 30;
    for (int i = 16; i < 256; i++) {
        int cr, cg, cb;
        if (i < 232) {
            cr = L[(i - 16) / 36];
            cg = L[(i - 16) / 6 % 6];
            cb = L[(i - 16) % 6];
        } else
            cr = cg = cb = 8 + 10 * (i - 232);
        int d = (cr - r) * (cr - r) * 3 + (cg - g) * (cg - g) * 4 + (cb - b) * (cb - b) * 2;
        if (d < bd) {
            bd = d;
            best = i;
        }
    }
    return (u8)best;
}
static void init_colours(void) {
    for (int r = 0; r < 32; r++)
        for (int g = 0; g < 32; g++)
            for (int b = 0; b < 32; b++)
                lut[(r << 10) | (g << 5) | b] = rgb_ix(r * 255 / 31, g * 255 / 31, b * 255 / 31);
    c_desk = rgb_ix(30, 20, 52);
    c_shadow = rgb_ix(12, 8, 22);
    (void)c_hilite_mix;
}
static const int bayer[16] = {0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5};
static inline u8 to_ix(int r, int g, int b, int x, int y) {
    /* a light dither for colours; grey stays calm, which keeps text sharp */
    int mx = r > g ? (r > b ? r : b) : (g > b ? g : b), mn = r < g ? (r < b ? r : b) : (g < b ? g : b);
    if (mx - mn > 24) {
        int d = (bayer[(y & 3) * 4 + (x & 3)] - 8) * 3;
        r += d, g += d, b += d;
        r = r < 0 ? 0 : r > 255 ? 255 : r;
        g = g < 0 ? 0 : g > 255 ? 255 : g;
        b = b < 0 ? 0 : b > 255 ? 255 : b;
    }
    return lut[(r >> 3) << 10 | (g >> 3) << 5 | (b >> 3)];
}

/* ---------------------------------------------------------------- small helpers of the screen */
static void text_clip(int x, int y, const char *s, u8 a) {
    for (; *s && x < W; s++, x++)
        if (x >= 0 && y >= 0 && y < H)
            vx_put(x, y, *s, a);
}
static void fill_row(int y, int x0, int x1, u8 a) {
    for (int x = x0; x < x1 && x < W; x++)
        if (x >= 0 && y >= 0 && y < H)
            vx_put(x, y, ' ', a);
}
static void box(int x, int y, int w, int h) {
    for (int j = 0; j < h; j++)
        fill_row(y + j, x, x + w, A_BOX);
}
static void say(const char *s) {
    scpy(msg, s, sizeof msg);
    msg_until = vx_ms() + 4000;
}
static int lower437(int c) {
    if (c >= 'A' && c <= 'Z')
        return c + 32;
    if (c == 0x8E)
        return 0x84;
    if (c == 0x99)
        return 0x94;
    if (c == 0x9A)
        return 0x81;
    return c;
}
static const char *base_name(const char *p) {
    const char *b = p;
    for (; *p; p++)
        if (*p == '/')
            b = p + 1;
    return b;
}

/* ---------------------------------------------------------------- the page */
static void view_size(void) {
    W = vx_cols();
    H = vx_rows();
    int cw = W > 240 ? 240 : W, rh = H - 2 > 100 ? 100 : H - 2;
    if (rh < 1)
        rh = 1;
    VW = cw * 4;
    VH = rh * 8;
}
static double fit_zoom(int mode) {
    if (!npages)
        return 1;
    page_t *pg = &pages[cur];
    double pw = pg->box[2] - pg->box[0], ph = pg->box[3] - pg->box[1];
    int r = (pg->rot + rot) % 180;
    if (r) {
        double t = pw;
        pw = ph;
        ph = t;
    }
    double zw = (VW - 16) / pw, zp = dmin(zw, (VH - 16) / ph);
    return mode == Z_PAGE ? zp : zw;
}
static double max_zoom(void) {
    page_t *pg = &pages[cur];
    double pw = pg->box[2] - pg->box[0], ph = pg->box[3] - pg->box[1];
    double z = sqrt((double)pc_cap / (pw * ph));
    return dmin(z, 16);
}
static void clamp_view(void) {
    int pw, ph;
    page_size(&pages[cur], zoom, rot, &pw, &ph);
    if (pw <= VW)
        ox = -(VW - pw) / 2;
    else {
        if (ox > pw - VW)
            ox = pw - VW;
        if (ox < 0)
            ox = 0;
    }
    if (ph <= VH)
        oy = -(VH - ph) / 2;
    else {
        if (oy > ph - VH)
            oy = ph - VH;
        if (oy < 0)
            oy = 0;
    }
}
static void status_now(const char *s);
static void render_now(void) {
    if (!open_ok || !npages)
        return;
    if (zmode != Z_FREE)
        zoom = fit_zoom(zmode);
    double mz = max_zoom();
    if (zoom > mz)
        zoom = mz;
    if (zoom < 0.05)
        zoom = 0.05;
    if (drawn_page == cur && drawn_zoom == zoom && drawn_rot == rot)
        return;
    int w, h;
    page_size(&pages[cur], zoom, rot, &w, &h);
    while (!canvas_for((long)w * h) && zoom > 0.06) {
        zoom *= 0.8;
        page_size(&pages[cur], zoom, rot, &w, &h);
    }
    if ((long)w * h > pc_have) {
        say(T("Es ist nicht genug Speicher frei.", "There is not enough memory."));
        return;
    }
    status_now(T("Die Seite wird gezeichnet ...", "Drawing the page ..."));
    PC.w = w;
    PC.h = h;
    PC.alpha = 0;
    ops_limit = 30000000;
    render_bad = !render_page(&pages[cur], &PC, page_matrix(&pages[cur], zoom, rot));
    if (render_bad)
        say(T("Die Seite war zu gro\xE1 oder besch\x84" "digt und ist nicht vollst\x84ndig.",
              "The page was too big or damaged and is not complete."));
    else if (render_cancel)
        say(T("Die Seite ist sehr aufwendig und wurde nur teilweise gezeichnet.", "The page is very complex and was drawn in part."));
    drawn_page = cur;
    drawn_zoom = zoom;
    drawn_rot = rot;
    find_page_hits(cur, zoom, rot);
}

/* ---------------------------------------------------------------- opening */
static void save_last(void) {
    char b[300] = "";
    if (!open_ok)
        return;
    scpy(b, path, sizeof b);
    scat(b, "\n", sizeof b);
    snum(b, cur, sizeof b);
    scat(b, "\n", sizeof b);
    vx_write("zuletzt.txt", b, (size_t)slen(b));
}
static int read_whole(const char *p) {
    vx_stat_t st;
    if (vx_stat(p, &st) < 0 || st.dir)
        return 0;
    long n = (long)st.size;
    if (n <= 0)
        return 0;
    if (n + 16 > filecap) {
        long cap = n + 16 > (4L << 20) ? n + 16 : 4L << 20;
        u8 *b = vx_alloc((size_t)cap);
        if (!b) {
            say(T("Die Datei ist zu gro\xE1 f\x81r den Speicher.", "The file is too big for the memory."));
            return -1;
        }
        filebuf = b;
        filecap = cap;
    }
    long got = 0;
    while (got < n) {
        long part = n - got > 512 * 1024 ? 512 * 1024 : n - got;
        long r = vx_read_at(p, filebuf + got, (unsigned long)got, (size_t)part);
        if (r <= 0)
            break;
        got += r;
        if (n > 4 << 20 && (got & ((4 << 20) - 1)) < 512 * 1024) {
            char b[64];
            scpy(b, T("Lade ... ", "Loading ... "), sizeof b);
            snum(b, got * 100 / n, sizeof b);
            scat(b, " %", sizeof b);
            status_now(b);
        }
    }
    filelen = got;
    memset(filebuf + got, 0, 16);
    return got > 0;
}
static int open_file(const char *p, int page) {
    status_now(T("\x99" "ffne ...", "Opening ..."));
    int r = read_whole(p);
    if (r <= 0) {
        if (!r)
            say(T("Die Datei l\x84\xE1t sich nicht lesen.", "The file cannot be read."));
        return 0;
    }
    forget_doc();
    open_ok = 0;
    drawn_page = -1;
    char pw[64] = "";
    int res = -1, tries = 0;
    for (;;) {
        pdf_jb_set = 1;
        if (__builtin_setjmp(pdf_jb) == 0)
            res = open_doc(filebuf, filelen, pw);
        else
            res = -1;
        pdf_jb_set = 0;
        if (res != 0 || tries >= 3)
            break;
        pw[0] = 0;
        forget_doc();
        if (!vx_input("Vio-PDF", T("Das Dokument ist mit einem Kennwort gesch\x81tzt:", "The document is protected by a password:"), pw,
                      sizeof pw))
            break;
        tries++;
    }
    if (res <= 0) {
        forget_doc();
        if (res == 0)
            say(T("Ohne das richtige Kennwort l\x84\xE1t sich das Dokument nicht \x94" "ffnen.",
                  "Without the right password the document cannot be opened."));
        else
            vx_message("Vio-PDF", T("Das ist keine PDF-Datei, die sich lesen l\x84\xE1t.", "This is not a PDF file that can be read."));
        return 0;
    }
    pdf_jb_set = 1;
    if (__builtin_setjmp(pdf_jb) == 0)
        load_outline();
    else
        noutl = 0;
    pdf_jb_set = 0;
    pdfver[0] = 0;
    if (filelen > 8 && bmem(filebuf, "%PDF-", 5)) {
        int k = 0;
        for (int i = 5; i < 12 && i < filelen && k < 7 && ((filebuf[i] >= '0' && filebuf[i] <= '9') || filebuf[i] == '.'); i++)
            pdfver[k++] = (char)filebuf[i];
        pdfver[k] = 0;
    }
    scpy(path, p, sizeof path);
    open_ok = 1;
    cur = page >= 0 && page < npages ? page : 0;
    zmode = Z_WIDTH;
    rot = 0;
    ox = oy = 0;
    panel = 0;
    search_reset();
    vx_title("Vio-PDF");
    save_last();
    return 1;
}
static void cmd_open(void) {
    char p[256];
    scpy(p, path, sizeof p);
    if (vx_choose_file(T("PDF-Dokument \x94" "ffnen", "Open a PDF document"), p, sizeof p))
        open_file(p, 0);
}

/* ---------------------------------------------------------------- moving around */
static void goto_page(int p, int top) {
    if (!open_ok)
        return;
    if (p < 0)
        p = 0;
    if (p >= npages)
        p = npages - 1;
    if (p != cur) {
        cur = p;
        save_last();
    }
    render_now();
    int pw, ph;
    page_size(&pages[cur], zoom, rot, &pw, &ph);
    oy = top ? 0 : ph;
    clamp_view();
}
static void scroll_by(int dx, int dy) {
    int pw, ph;
    page_size(&pages[cur], zoom, rot, &pw, &ph);
    if (dy > 0 && (ph <= VH || oy >= ph - VH)) { /* at the bottom: the next page */
        if (cur + 1 < npages)
            goto_page(cur + 1, 1);
        return;
    }
    if (dy < 0 && (ph <= VH || oy <= 0)) {
        if (cur > 0)
            goto_page(cur - 1, 0);
        return;
    }
    ox += dx;
    oy += dy;
    clamp_view();
}
static void set_zoom(double z) {
    /* keeps the middle of the view where it is */
    int pw, ph;
    page_size(&pages[cur], zoom, rot, &pw, &ph);
    double cx = (ox + VW / 2.0) / dmax(pw, 1), cy = (oy + VH / 2.0) / dmax(ph, 1);
    zmode = Z_FREE;
    zoom = dclamp(z, 0.1, max_zoom());
    page_size(&pages[cur], zoom, rot, &pw, &ph);
    ox = (int)(cx * pw - VW / 2.0);
    oy = (int)(cy * ph - VH / 2.0);
    render_now();
    clamp_view();
}
static void ask_page(void) {
    if (!open_ok)
        return;
    char b[16] = "";
    snum(b, cur + 1, sizeof b);
    char pr[64];
    scpy(pr, T("Seite (1 bis ", "Page (1 to "), sizeof pr);
    snum(pr, npages, sizeof pr);
    scat(pr, "):", sizeof pr);
    if (!vx_input("Vio-PDF", pr, b, sizeof b))
        return;
    long v = 0;
    for (int i = 0; b[i] >= '0' && b[i] <= '9'; i++)
        v = v * 10 + (b[i] - '0');
    if (v >= 1)
        goto_page((int)v - 1, 1);
}

/* ---------------------------------------------------------------- drawing the screen */
static void compose_view(void) {
    int pw = PC.w, ph = PC.h;
    for (int y = 0; y < VH; y++) {
        u8 *o = view + (size_t)y * VW;
        int py = y + oy;
        for (int x = 0; x < VW; x++) {
            int px = x + ox;
            if (open_ok && px >= 0 && py >= 0 && px < pw && py < ph) {
                const u8 *s = PC.rgb + ((size_t)py * pw + px) * 3;
                o[x] = to_ix(s[0], s[1], s[2], x, y);
            } else if (open_ok && px >= 3 && py >= 3 && px < pw + 3 && py < ph + 3)
                o[x] = c_shadow;
            else
                o[x] = c_desk;
        }
    }
    /* found text: marked yellow, the current find orange */
    for (int i = 0; open_ok && i < nhits; i++) {
        hit_t *h = &hits[i];
        for (int py = imax(h->y0 - 1, 0); py < imin(h->y1 + 1, ph); py++) {
            int y = py - oy;
            if (y < 0 || y >= VH)
                continue;
            for (int px = imax(h->x0 - 1, 0); px < imin(h->x1 + 1, pw); px++) {
                int x = px - ox;
                if (x < 0 || x >= VW)
                    continue;
                const u8 *s = PC.rgb + ((size_t)py * pw + px) * 3;
                int r = s[0], g = s[1], b = s[2];
                if (h->cur)
                    r = (r + 255) / 2, g = (g + 150) / 2, b = b / 2;
                else
                    r = (r + 255) / 2, g = (g + 235) / 2, b = (b + 60) / 2;
                view[(size_t)y * VW + x] = to_ix(r, g, b, x, y);
            }
        }
    }
}
static void draw_status(void) {
    fill_row(H - 1, 0, W, A_BAR);
    const char *k = T("Bild\x18\x19 bl\x84ttern  +/- Zoom  B Breite  S Seite  G Gehe zu  I Inhalt  / Suchen  O \x99" "ffnen",
                      "PgUp/PgDn pages  +/- zoom  B width  S page  G go to  I contents  / find  O open");
    if (msg[0] && vx_ms() < msg_until)
        text_clip(1, H - 1, msg, A_HOT);
    else
        text_clip(1, H - 1, k, A_DIM);
}
static int status_showing; /* for the test harness: not a finished screen */
static void status_now(const char *s) {
    view_size();
    fill_row(H - 1, 0, W, A_BAR);
    text_clip(1, H - 1, s, A_HOT);
    status_showing = 1;
    vx_show();
    status_showing = 0;
}
static void draw_top(void) {
    fill_row(0, 0, W, A_BAR);
    if (!open_ok) {
        text_clip(1, 0, "Vio-PDF", A_HOT);
        return;
    }
    char b[160];
    scpy(b, T("Seite ", "Page "), sizeof b);
    snum(b, cur + 1, sizeof b);
    scat(b, " / ", sizeof b);
    snum(b, npages, sizeof b);
    scat(b, "   ", sizeof b);
    snum(b, (long)(zoom * 100 + 0.5), sizeof b);
    scat(b, " %", sizeof b);
    if (zmode == Z_WIDTH)
        scat(b, T(" (Breite)", " (width)"), sizeof b);
    else if (zmode == Z_PAGE)
        scat(b, T(" (Seite)", " (page)"), sizeof b);
    if (rot) {
        scat(b, "   ", sizeof b);
        snum(b, rot, sizeof b);
        scat(b, "\xF8", sizeof b);
    }
    int bl = slen(b);
    char t[200];
    text_437(dget(dget(&D.trailer, "Info"), "Title"), t, sizeof t);
    if (!t[0] || slen(t) > W - bl - 6)
        scpy(t, base_name(path), sizeof t);
    text_clip(1, 0, t, A_HOT);
    text_clip(W - bl - 1 > slen(t) + 3 ? W - bl - 1 : slen(t) + 3, 0, b, A_BAR);
    if (search_q[0] && nhits_total >= 0) {
        char s[80];
        scpy(s, "\"", sizeof s);
        scat(s, search_shown, sizeof s);
        scat(s, "\" ", sizeof s);
        if (nhits_total)
            snum(s, nhits_total, sizeof s), scat(s, T(" auf dieser Seite", " on this page"), sizeof s);
        else
            scat(s, T("nicht auf dieser Seite", "not on this page"), sizeof s);
        int x = (W - slen(s)) / 2;
        if (x > slen(t) + 3 && x + slen(s) < W - bl - 2)
            text_clip(x, 0, s, A_KEY);
    }
}
/* ---------------------------------------------------------------- panels */
static const char *const lic[] = {
    "Vio-PDF " VERSION,
    "Copyright (c) 2026, Merecete",
    "",
    "Redistribution and use in source and binary forms, with or without",
    "modification, are permitted provided that the following conditions",
    "are met:",
    "",
    "1. Redistributions of source code must retain the above copyright",
    "   notice, this list of conditions and the following disclaimer.",
    "",
    "2. Redistributions in binary form must reproduce the above copyright",
    "   notice, this list of conditions and the following disclaimer in the",
    "   documentation and/or other materials provided with the distribution.",
    "",
    "3. Neither the name of the copyright holder nor the names of its",
    "   contributors may be used to endorse or promote products derived from",
    "   this software without specific prior written permission.",
    "",
    "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
    "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
    "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
    "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
    "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
    "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
    "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
    "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
    "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
    "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
    "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    "",
    "",
    "Fonts for PDFs that do not bring their own: Liberation Sans, Serif, Mono",
    "(subsets, without their names)",
    "Digitized data copyright (c) 2010 Google Corporation",
    "with Reserved Font Arimo, Tinos and Cousine.",
    "Copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation.",
    "",
    "This Font Software is licensed under the SIL Open Font License,",
    "Version 1.1. This license is copied below, and is also available with",
    "a FAQ at: http://scripts.sil.org/OFL",
    "",
    "SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007",
    "",
    "PREAMBLE",
    "The goals of the Open Font License (OFL) are to stimulate worldwide",
    "development of collaborative font projects, to support the font creation",
    "efforts of academic and linguistic communities, and to provide a free and",
    "open framework in which fonts may be shared and improved in partnership",
    "with others.",
    "",
    "The OFL allows the licensed fonts to be used, studied, modified and",
    "redistributed freely as long as they are not sold by themselves. The",
    "fonts, including any derivative works, can be bundled, embedded,",
    "redistributed and/or sold with any software provided that any reserved",
    "names are not used by derivative works. The fonts and derivatives,",
    "however, cannot be released under any other type of license. The",
    "requirement for fonts to remain under this license does not apply to any",
    "document created using the fonts or their derivatives.",
    "",
    "DEFINITIONS",
    "\"Font Software\" refers to the set of files released by the Copyright",
    "Holder(s) under this license and clearly marked as such. This may include",
    "source files, build scripts and documentation.",
    "",
    "\"Reserved Font Name\" refers to any names specified as such after the",
    "copyright statement(s).",
    "",
    "\"Original Version\" refers to the collection of Font Software components",
    "as distributed by the Copyright Holder(s).",
    "",
    "\"Modified Version\" refers to any derivative made by adding to, deleting,",
    "or substituting -- in part or in whole -- any of the components of the",
    "Original Version, by changing formats or by porting the Font Software to",
    "a new environment.",
    "",
    "\"Author\" refers to any designer, engineer, programmer, technical writer",
    "or other person who contributed to the Font Software.",
    "",
    "PERMISSION & CONDITIONS",
    "Permission is hereby granted, free of charge, to any person obtaining a",
    "copy of the Font Software, to use, study, copy, merge, embed, modify,",
    "redistribute, and sell modified and unmodified copies of the Font",
    "Software, subject to the following conditions:",
    "",
    "1) Neither the Font Software nor any of its individual components, in",
    "Original or Modified Versions, may be sold by itself.",
    "",
    "2) Original or Modified Versions of the Font Software may be bundled,",
    "redistributed and/or sold with any software, provided that each copy",
    "contains the above copyright notice and this license. These can be",
    "included either as stand-alone text files, human-readable headers or in",
    "the appropriate machine-readable metadata fields within text or binary",
    "files as long as those fields can be easily viewed by the user.",
    "",
    "3) No Modified Version of the Font Software may use the Reserved Font",
    "Name(s) unless explicit written permission is granted by the",
    "corresponding Copyright Holder. This restriction only applies to the",
    "primary font name as presented to the users.",
    "",
    "4) The name(s) of the Copyright Holder(s) and the Author(s) of the Font",
    "Software shall not be used to promote, endorse or advertise any Modified",
    "Version, except to acknowledge the contribution(s) of the Copyright",
    "Holder(s) and the Author(s) or with their explicit written permission.",
    "",
    "5) The Font Software, modified or unmodified, in part or in whole, must",
    "be distributed entirely under this license, and must not be distributed",
    "under any other license. The requirement for fonts to remain under this",
    "license does not apply to any document created using the Font Software.",
    "",
    "TERMINATION",
    "This license becomes null and void if any of the above conditions are",
    "not met.",
    "",
    "DISCLAIMER",
    "THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
    "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF",
    "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF",
    "COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE",
    "COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
    "INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL",
    "DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
    "FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER",
    "DEALINGS IN THE FONT SOFTWARE.",
    "",
    "",
    "Symbols: DejaVu Sans (a subset)",
    "Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.",
    "Bitstream Vera is a trademark of Bitstream, Inc.",
    "DejaVu changes are in public domain.",
    "Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below).",
    "",
    "Permission is hereby granted, free of charge, to any person obtaining",
    "a copy of the fonts accompanying this license (\"Fonts\") and associated",
    "documentation files (the \"Font Software\"), to reproduce and distribute",
    "the Font Software, including without limitation the rights to use, copy,",
    "merge, publish, distribute, and/or sell copies of the Font Software, and",
    "to permit persons to whom the Font Software is furnished to do so,",
    "subject to the following conditions:",
    "",
    "The above copyright and trademark notices and this permission notice",
    "shall be included in all copies of one or more of the Font Software",
    "typefaces.",
    "",
    "The Font Software may be modified, altered, or added to, and in",
    "particular the designs of glyphs or characters in the Fonts may be",
    "modified and additional glyphs or characters may be added to the Fonts,",
    "only if the fonts are renamed to names not containing either the words",
    "\"Bitstream\" or the word \"Vera\".",
    "",
    "This License becomes null and void to the extent applicable to Fonts or",
    "Font Software that has been modified and is distributed under the",
    "\"Bitstream Vera\" names.",
    "",
    "The Font Software may be sold as part of a larger software package but",
    "no copy of one or more of the Font Software typefaces may be sold by",
    "itself.",
    "",
    "THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
    "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF",
    "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT",
    "OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL",
    "BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR",
    "OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL,",
    "OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
    "OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT",
    "SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.",
    "",
    "Except as contained in this notice, the names of Gnome, the Gnome",
    "Foundation, and Bitstream Inc., shall not be used in advertising or",
    "otherwise to promote the sale, use or other dealings in this Font",
    "Software without prior written authorization from the Gnome Foundation",
    "or Bitstream Inc., respectively.",
    "",
    "Glyphs imported from Arev fonts are (c) Tavmjong Bah:",
    "",
    "Arev Fonts Copyright Copyright (c) 2006 by Tavmjong Bah. All Rights",
    "Reserved.",
    "",
    "Permission is hereby granted, free of charge, to any person obtaining a",
    "copy of the fonts accompanying this license (\"Fonts\") and associated",
    "documentation files (the \"Font Software\"), to reproduce and distribute",
    "the modifications to the Bitstream Vera Font Software, including without",
    "limitation the rights to use, copy, merge, publish, distribute, and/or",
    "sell copies of the Font Software, and to permit persons to whom the Font",
    "Software is furnished to do so, subject to the following conditions:",
    "",
    "The above copyright and trademark notices and this permission notice",
    "shall be included in all copies of one or more of the Font Software",
    "typefaces.",
    "",
    "The Font Software may be modified, altered, or added to, and in",
    "particular the designs of glyphs or characters in the Fonts may be",
    "modified and additional glyphs or characters may be added to the Fonts,",
    "only if the fonts are renamed to names not containing either the words",
    "\"Tavmjong Bah\" or the word \"Arev\".",
    "",
    "This License becomes null and void to the extent applicable to Fonts or",
    "Font Software that has been modified and is distributed under the",
    "\"Tavmjong Bah Arev\" names.",
    "",
    "The Font Software may be sold as part of a larger software package but",
    "no copy of one or more of the Font Software typefaces may be sold by",
    "itself.",
    "",
    "THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
    "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF",
    "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF",
    "COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL TAVMJONG",
    "BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY",
    "GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,",
    "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
    "OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS",
    "IN THE FONT SOFTWARE.",
    "",
    "Except as contained in this notice, the name of Tavmjong Bah shall not",
    "be used in advertising or otherwise to promote the sale, use or other",
    "dealings in this Font Software without prior written authorization from",
    "Tavmjong Bah. For further information, contact: tavmjong @ free . fr.",
    "",
    "",
    "The system font of Vio-Pad (sysfont in viopad-font.h) is the Violyx",
    "system font, Spleen 8x16:",
    "",
    "Copyright (c) 2018-2026, Frederic Cambus All rights reserved.",
    "",
    "Redistribution and use in source and binary forms, with or without",
    "modification, are permitted provided that the following conditions are",
    "met:",
    "",
    "* Redistributions of source code must retain the above copyright notice,",
    "this list of conditions and the following disclaimer.",
    "",
    "* Redistributions in binary form must reproduce the above copyright",
    "notice, this list of conditions and the following disclaimer in the",
    "documentation and/or other materials provided with the distribution.",
    "",
    "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
    "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
    "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
    "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
    "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
    "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
    "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
    "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
    "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
    "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
    "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    "",
    "",
    "The Adobe Glyph List (names of glyphs to Unicode)",
    "Copyright 2002-2019 Adobe (http://www.adobe.com/).",
    "",
    "Redistribution and use in source and binary forms, with or without",
    "modification, are permitted provided that the following conditions are",
    "met: Redistributions of source code must retain the above copyright",
    "notice, this list of conditions and the following disclaimer.",
    "Redistributions in binary form must reproduce the above copyright",
    "notice, this list of conditions and the following disclaimer in the",
    "documentation and/or other materials provided with the distribution.",
    "Neither the name of Adobe nor the names of its contributors may be used",
    "to endorse or promote products derived from this software without",
    "specific prior written permission.",
    "",
    "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
    "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
    "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
    "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT",
    "HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
    "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
    "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
    "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
    "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
    "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
    "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    0};
static const char *const keys_de[] = {
    "TASTEN",
    "Bild runter/hoch, Leertaste   n\x84" "chste / vorige Seite",
    "Pfeile                        verschieben (am Ende: n\x84" "chste Seite)",
    "Pos1 / Ende                   erste / letzte Seite",
    "G                             gehe zu Seite ...",
    "+ / -                         gr\x94\xE1" "er / kleiner",
    "B / S                         Seitenbreite / ganze Seite",
    "D                             um 90\xF8 drehen",
    "I                             Inhaltsverzeichnis",
    "/ oder Strg+F, dann N         Text suchen, n\x84" "chster Treffer",
    "O                             PDF \x94" "ffnen",
    "F                             Vollbild",
    "E                             Eigenschaften des Dokuments",
    "Esc                           Fenster schlie\xE1" "en, dann Vio-PDF",
    0};
static const char *const keys_en[] = {
    "KEYS",
    "Page down/up, space           next / previous page",
    "Arrows                        move (at the end: next page)",
    "Home / End                    first / last page",
    "G                             go to page ...",
    "+ / -                         bigger / smaller",
    "B / S                         page width / whole page",
    "D                             turn by 90\xF8",
    "I                             table of contents",
    "/ or Ctrl+F, then N           find text, next match",
    "O                             open a PDF",
    "F                             full screen",
    "E                             properties of the document",
    "Esc                           close a window, then Vio-PDF",
    0};
static void draw_lines(const char *const *l, int hot_first, const char *foot) {
    int n = 0;
    while (l[n])
        n++;
    int bw = W - 2 < 76 ? W - 2 : 76, bh = H - 2, x = (W - bw) / 2, y = 1, rows = bh - 3;
    if (n + 3 < bh) {
        bh = n + 3;
        y = (H - bh) / 2;
        rows = n;
    }
    if (ptop > n - rows)
        ptop = n - rows;
    if (ptop < 0)
        ptop = 0;
    box(x, y, bw, bh);
    for (int r = 0; r < rows && ptop + r < n; r++)
        text_clip(x + 2, y + 1 + r, l[ptop + r], hot_first && ptop + r == 0 ? A_HOT : A_BOX);
    text_clip(x + 2, y + bh - 1, foot, A_DIM);
}
static void draw_info(void) {
    int bw = 48, bh = 14, x = (W - bw) / 2, y = (H - bh) / 2;
    box(x, y, bw, bh);
    const char *l[] = {"Vio-PDF", "Version " VERSION, "(c) 2026 Merecete", T("Lizenz: BSD-3-Clause", "Licence: BSD-3-Clause"),
                       T("Schriften: Liberation (SIL OFL 1.1),", "Fonts: Liberation (SIL OFL 1.1),"),
                       "DejaVu (Bitstream Vera, Arev)", T("Glyphenliste: Adobe (BSD-3-Clause)", "Glyph list: Adobe (BSD-3-Clause)")};
    int ly[] = {1, 3, 5, 6, 8, 9, 10};
    for (int i = 0; i < 7; i++)
        text_clip(x + (bw - slen(l[i])) / 2, y + ly[i], l[i], i ? A_BOX : A_HOT);
    const char *h = T("L Lizenzen  T Tasten  Enter zur\x81" "ck", "L licences  K keys  Enter back");
    text_clip(x + (bw - slen(h)) / 2, y + bh - 2, h, A_DIM);
}
static void prop_line(int x, int y, int bw, const char *k, const char *v) {
    text_clip(x + 2, y, k, A_DIM);
    char b[200];
    scpy(b, v, sizeof b);
    int maxv = bw - 18;
    if (slen(b) > maxv && maxv > 3)
        b[maxv - 3] = '.', b[maxv - 2] = '.', b[maxv - 1] = '.', b[maxv] = 0;
    text_clip(x + 16, y, b, A_BOX);
}
static void draw_props(void) {
    int bw = W - 4 < 72 ? W - 4 : 72, bh = 15, x = (W - bw) / 2, y = (H - bh) / 2;
    if (y < 1)
        y = 1;
    box(x, y, bw, bh);
    text_clip(x + 2, y, T("EIGENSCHAFTEN", "PROPERTIES"), A_HOT);
    obj_t *info = dget(&D.trailer, "Info");
    static const char *keys[6] = {"Title", "Author", "Subject", "Keywords", "Creator", "Producer"};
    const char *de[6] = {"Titel", "Verfasser", "Thema", "Stichw\x94rter", "Erstellt mit", "PDF von"},
               *en[6] = {"Title", "Author", "Subject", "Keywords", "Creator", "Producer"};
    char b[200];
    prop_line(x, y + 2, bw, T("Datei", "File"), base_name(path));
    for (int i = 0; i < 6; i++) {
        text_437(dget(info, keys[i]), b, sizeof b);
        prop_line(x, y + 3 + i, bw, lang_en ? en[i] : de[i], b[0] ? b : "-");
    }
    b[0] = 0;
    snum(b, npages, sizeof b);
    prop_line(x, y + 10, bw, T("Seiten", "Pages"), b);
    b[0] = 0;
    snum(b, (filelen + 1023) / 1024, sizeof b);
    scat(b, " KB", sizeof b);
    prop_line(x, y + 11, bw, T("Gr\x94\xE1" "e", "Size"), b);
    scpy(b, pdfver[0] ? pdfver : "?", sizeof b);
    if (D.enc)
        scat(b, D.enc == CM_AES256 ? T(", verschl\x81sselt (AES-256)", ", encrypted (AES-256)")
                                   : D.strm_cm == CM_AES ? T(", verschl\x81sselt (AES-128)", ", encrypted (AES-128)")
                                                         : T(", verschl\x81sselt (RC4)", ", encrypted (RC4)"),
             sizeof b);
    if (D.repaired)
        scat(b, T(", repariert", ", repaired"), sizeof b);
    prop_line(x, y + 12, bw, "PDF", b);
    text_clip(x + 2, y + bh - 1, T("Enter zur\x81" "ck", "Enter back"), A_DIM);
}
static void draw_outline(void) {
    int bw = W - 4 < 64 ? W - 4 : 64, bh = H - 2, x = W - bw - 1, y = 1, rows = bh - 3;
    if (x < 0)
        x = 0;
    box(x, y, bw, bh);
    text_clip(x + 2, y, T("INHALT", "CONTENTS"), A_HOT);
    if (!noutl) {
        text_clip(x + 2, y + 2, T("Dieses Dokument hat kein Inhaltsverzeichnis.", "This document has no table of contents."), A_BOX);
        text_clip(x + 2, y + bh - 1, T("Enter zur\x81" "ck", "Enter back"), A_DIM);
        return;
    }
    if (psel < 0)
        psel = 0;
    if (psel >= noutl)
        psel = noutl - 1;
    if (psel < ptop)
        ptop = psel;
    if (psel >= ptop + rows)
        ptop = psel - rows + 1;
    for (int r = 0; r < rows && ptop + r < noutl; r++) {
        outl_t *o = &outl[ptop + r];
        int i = ptop + r, ind = o->level * 2 > 16 ? 16 : o->level * 2;
        u8 a = i == psel ? A_SEL : A_BOX;
        fill_row(y + 1 + r, x + 1, x + bw - 1, a);
        char num[12] = "";
        if (o->page >= 0)
            snum(num, o->page + 1, sizeof num);
        char t[80];
        scpy(t, o->title[0] ? o->title : "-", sizeof t);
        int maxl = bw - 4 - ind - 6;
        if (slen(t) > maxl && maxl > 3)
            t[maxl - 1] = '.', t[maxl] = 0;
        text_clip(x + 2 + ind, y + 1 + r, t, a);
        text_clip(x + bw - 2 - slen(num), y + 1 + r, num, i == psel ? A_SEL : A_DIM);
    }
    text_clip(x + 2, y + bh - 1, T("Pfeile w\x84hlen  Enter springt  Esc zur\x81" "ck", "Arrows choose  Enter jumps  Esc back"), A_DIM);
}
static void draw(void) {
    view_size();
    if (W < 20 || H < 5) {
        vx_clear(VX_ATTR(VC_BLACK, VC_GLOW));
        vx_show();
        return;
    }
    if (!mem_ok) {
        vx_clear(VX_ATTR(VC_BLACK, VC_GLOW));
        text_clip(1, 1, T("Es ist nicht genug Speicher frei.", "There is not enough memory."), VX_ATTR(VC_BLACK, VC_HOT));
        vx_show();
        return;
    }
    if (open_ok) {
        render_now();
        clamp_view();
    }
    compose_view();
    vx_image(view, VW, VH);
    vx_clear(A_BAR);
    for (int y = 0; y < VH / 8; y++)
        for (int x = 0; x < VW / 4; x++)
            vx_pixcell(x, y + 1, x, y);
    draw_top();
    draw_status();
    if (!open_ok) {
        const char *l1 = T("Kein Dokument ge\x94" "ffnet.", "No document open."),
                   *l2 = T("O oder Strg+O \x94" "ffnet eine PDF-Datei.", "O or Ctrl+O opens a PDF file.");
        int bw = 44, x = (W - bw) / 2, y = H / 2 - 2;
        box(x, y, bw, 5);
        text_clip(x + (bw - slen(l1)) / 2, y + 1, l1, A_HOT);
        text_clip(x + (bw - slen(l2)) / 2, y + 3, l2, A_BOX);
    }
    if (panel == 1)
        draw_outline();
    else if (panel == 2)
        draw_props();
    else if (panel == 3)
        draw_info();
    else if (panel == 4)
        draw_lines(lic, 1, T("Pfeile, Bild\x18\x19 bl\x84ttern  Enter zur\x81" "ck", "Arrows, PgUp/PgDn scroll  Enter back"));
    else if (panel == 5)
        draw_lines(lang_en ? keys_en : keys_de, 1, T("Enter zur\x81" "ck", "Enter back"));
    vx_show();
}

/* ---------------------------------------------------------------- full screen (as Vio-Island) */
static void set_full(int on) {
    if (on)
        full_zoomed = (int)vx_sys(23, 13, 0, 0);
    vx_sys(23, 11, on, 0);
    if (on)
        return;
    if (vx_sys(23, 13, 0, 0))
        vx_sys(23, 13, 1, 0);
    if (full_zoomed)
        vx_sys(23, 13, 1, 0);
}

/* ---------------------------------------------------------------- searching */
static void search_next(int dir) {
    if (!open_ok || !npages)
        return;
    if (!search_q[0]) {
        say(T("Erst mit / einen Suchbegriff eingeben.", "First type what to find with /."));
        return;
    }
    for (int step = 0; step <= npages; step++) {
        int p = ((cur + dir * step) % npages + npages) % npages;
        if (step && (step & 7) == 1) {
            char b[64];
            scpy(b, T("Suche auf Seite ", "Searching page "), sizeof b);
            snum(b, p + 1, sizeof b);
            scat(b, " ...", sizeof b);
            status_now(b);
        }
        if (!extract_page(p, zoom, rot))
            return;
        int pos;
        if (step == 0 && search_page == p)
            pos = dir > 0 ? find_in_text(search_pos + 1) : find_last_before(search_pos);
        else if (step == 0)
            pos = dir > 0 ? find_in_text(0) : find_last_before(ntext + 1);
        else
            pos = dir > 0 ? find_in_text(0) : find_last_before(ntext + 1);
        if (step == npages && search_page == p && pos == search_pos)
            pos = -1;
        if (pos < 0)
            continue;
        search_page = p;
        search_pos = pos;
        if (p != cur)
            goto_page(p, 1);
        render_now();
        find_page_hits(cur, zoom, rot);
        /* the find into view */
        if (pos < ntext) {
            tglyph_t *g = &tg[tmap[pos]];
            int cx = (int)((g->x0 + g->x1) / 2), cy = (int)((g->y0 + g->y1) / 2);
            if (cx < ox + 8 || cx > ox + VW - 8)
                ox = cx - VW / 2;
            if (cy < oy + 8 || cy > oy + VH - 8)
                oy = cy - VH / 3;
            clamp_view();
        }
        return;
    }
    if (search_page >= 0) { /* the find there is the only one */
        find_page_hits(cur, zoom, rot);
        say(T("Keine weiteren Treffer.", "No further finds."));
        return;
    }
    nhits = 0;
    say(T("Nicht gefunden.", "Not found."));
}

/* ---------------------------------------------------------------- keys */
static void cmd_search(void) {
    if (!open_ok)
        return;
    char b[64];
    scpy(b, search_shown, sizeof b);
    if (!vx_input("Vio-PDF", T("Suchen nach:", "Find:"), b, sizeof b))
        return;
    if (!b[0]) {
        search_reset();
        return;
    }
    search_start(b);
    search_next(1);
}
static void menu_cmd(int n) {
    switch (n) {
        case 0: cmd_open(); break;
        case 1: ask_page(); break;
        case 2: panel = 1; ptop = 0; break;
        case 3: cmd_search(); break;
        case 4: zmode = Z_WIDTH; render_now(); break;
        case 5: zmode = Z_PAGE; render_now(); break;
        case 6: if (open_ok) set_zoom(zoom * 1.25); break;
        case 7: if (open_ok) set_zoom(zoom / 1.25); break;
        case 8: rot = (rot + 90) % 360; render_now(); break;
        case 9: if (open_ok) panel = 2; break;
        case 10: panel = 3; break;
    }
}
static int panel_key(int k) {
    if (panel == 1 && noutl) {
        int rows = H - 5;
#define PSEL(v)                                                                                                        \
    do {                                                                                                               \
        psel = (v);                                                                                                    \
        if (psel >= noutl)                                                                                             \
            psel = noutl - 1;                                                                                          \
        if (psel < 0)                                                                                                  \
            psel = 0;                                                                                                  \
    } while (0)
        switch (k) {
            case VK_UP: PSEL(psel - 1); return 1;
            case VK_DOWN: PSEL(psel + 1); return 1;
            case VK_PGUP: PSEL(psel - rows); return 1;
            case VK_PGDN: PSEL(psel + rows); return 1;
            case VK_HOME: PSEL(0); return 1;
            case VK_END: PSEL(noutl - 1); return 1;
            case VK_ENTER:
                if (psel >= 0 && psel < noutl && outl[psel].page >= 0) {
                    panel = 0;
                    goto_page(outl[psel].page, 1);
                }
                return 1;
        }
        return k != 'i' && k != 'I';
    }
    if (panel == 4 || panel == 5) {
        switch (k) {
            case VK_UP: ptop--; return 1;
            case VK_DOWN: ptop++; return 1;
            case VK_PGUP: ptop -= H - 6; return 1;
            case VK_PGDN: ptop += H - 6; return 1;
            case VK_ENTER: panel = 3; return 1;
        }
        return 1;
    }
    if (panel == 3) {
        if (k == 'l' || k == 'L') {
            panel = 4;
            ptop = 0;
        } else if (k == 't' || k == 'T' || k == 'k' || k == 'K') {
            panel = 5;
            ptop = 0;
        } else if (k == VK_ENTER)
            panel = 0;
        return 1;
    }
    if (panel == 2) {
        if (k == VK_ENTER)
            panel = 0;
        return 1;
    }
    return 0;
}
static void key(int k, int mods) {
    int ctrl = mods & 2;
    if (k == VK_ESC) {
        if (panel) {
            panel = panel >= 4 ? 3 : 0;
            return;
        }
        if (full_on) {
            full_on = 0;
            set_full(0);
            return;
        }
        save_last();
        vx_exit();
    }
    if (k >= VK_MENU && k < VK_MENU + 16) {
        menu_cmd(k - VK_MENU);
        return;
    }
    if (k == VK_F1) {
        panel = panel == 5 ? 0 : 5;
        ptop = 0;
        return;
    }
    if (panel && panel_key(k))
        return;
    if (ctrl) {
        int c = lower437(k);
        if (c == 'o')
            cmd_open();
        else if (c == 'f')
            cmd_search();
        else if (c == 'g')
            ask_page();
        return;
    }
    if (!open_ok) {
        if (k == 'o' || k == 'O' || k == VK_ENTER)
            cmd_open();
        else if (k == 'f' || k == 'F') {
            full_on = !full_on;
            set_full(full_on);
        }
        return;
    }
    int pw, ph;
    page_size(&pages[cur], zoom, rot, &pw, &ph);
    switch (k) {
        case VK_PGDN:
        case ' ':
            if (ph > VH && oy < ph - VH) {
                oy += VH * 9 / 10;
                clamp_view();
            } else if (cur + 1 < npages)
                goto_page(cur + 1, 1);
            return;
        case VK_PGUP:
        case VK_BS:
            if (ph > VH && oy > 0) {
                oy -= VH * 9 / 10;
                clamp_view();
            } else if (cur > 0)
                goto_page(cur - 1, 0);
            return;
        case VK_DOWN: scroll_by(0, VH / 8); return;
        case VK_UP: scroll_by(0, -VH / 8); return;
        case VK_LEFT:
            if (pw > VW)
                scroll_by(-VW / 8, 0);
            else if (cur > 0)
                goto_page(cur - 1, 1);
            return;
        case VK_RIGHT:
            if (pw > VW)
                scroll_by(VW / 8, 0);
            else if (cur + 1 < npages)
                goto_page(cur + 1, 1);
            return;
        case VK_HOME: goto_page(0, 1); return;
        case VK_END: goto_page(npages - 1, 1); return;
        case VK_ENTER: if (cur + 1 < npages) goto_page(cur + 1, 1); return;
    }
    switch (lower437(k)) {
        case '+': case '=': set_zoom(zoom * 1.25); break;
        case '-': set_zoom(zoom / 1.25); break;
        case 'b': zmode = Z_WIDTH; render_now(); break;
        case 's': zmode = Z_PAGE; render_now(); break;
        case 'g': ask_page(); break;
        case 'd': rot = (rot + 90) % 360; render_now(); break;
        case 'i': panel = 1; psel = 0; ptop = 0;
            for (int i = 0; i < noutl; i++) /* the entry of the page shown */
                if (outl[i].page >= 0 && outl[i].page <= cur)
                    psel = i;
            break;
        case 'e': panel = 2; break;
        case 'o': cmd_open(); break;
        case '/': cmd_search(); break;
        case 'n': search_next(1); break;
        case 'p': search_next(-1); break;
        case 'f': full_on = !full_on; set_full(full_on); break;
    }
}

/* ---------------------------------------------------------------- start */
int main(void) {
    lang_en = vx_english();
    vx_title("Vio-PDF");
    vx_menu(T("Oeffnen|Gehe zu Seite|Inhalt|Suchen|Seitenbreite|Ganze Seite|Vergroessern|Verkleinern|Drehen|Eigenschaften|Info",
              "Open|Go to page|Contents|Find|Page width|Whole page|Zoom in|Zoom out|Turn|Properties|Info"));
    vx_sys(23, 3, 2, 0); /* Esc comes as a key: open windows close first */
    vx_sys(23, 8, 1, 0); /* F1 too */
    if (!vx_sys(23, 13, 0, 0))
        vx_sys(23, 13, 1, 0); /* the whole screen for the page */
    init_colours();
    init_memory();
    view = vx_alloc(960 * 800);
    if (!view)
        mem_ok = 0;
    if (mem_ok) {
        /* the document of last time, at its page */
        char b[300];
        long n = vx_read("zuletzt.txt", b, sizeof b - 1);
        int opened = 0;
        if (n > 0) {
            b[n] = 0;
            int i = 0;
            while (b[i] && b[i] != '\n')
                i++;
            int pg = 0;
            if (b[i]) {
                b[i] = 0;
                for (int j = i + 1; b[j] >= '0' && b[j] <= '9'; j++)
                    pg = pg * 10 + (b[j] - '0');
            }
            vx_stat_t st;
            if (b[0] && vx_stat(b, &st) >= 0)
                opened = open_file(b, pg);
        }
        if (!opened) {
            draw();
            cmd_open();
        }
    }
    int last_w = 0, last_h = 0, msg_shown = 0;
    for (;;) {
        int any = 0;
        for (;;) {
            long r = vx_sys(3, 0, 0, 0);
            if (r < 0)
                break;
            int k = (int)(r & 0xFFFF), mods = (int)(r >> 16 & 0xFF);
            if (!k)
                continue;
            if (mem_ok)
                key(k, mods);
            else if (k == VK_ESC)
                vx_exit();
            any = 1;
        }
        /* drawn again only when something changed: a key, the size of the window, a message */
        int msg_now = msg[0] && vx_ms() < msg_until;
        if (any || vx_cols() != last_w || vx_rows() != last_h || msg_now != msg_shown) {
            draw();
            last_w = vx_cols();
            last_h = vx_rows();
            msg_shown = msg_now;
        }
        vx_wait(any ? 10 : msg_now ? 250 : 500);
    }
}
