Throttle mode
[llpp.git] / main.ml
blob5258b28dffe6f7265af57e09bb56f6ed359b84ab
1 let log fmt = Printf.kprintf prerr_endline fmt;;
2 let dolog fmt = Printf.kprintf prerr_endline fmt;;
4 external init : Unix.file_descr -> unit = "ml_init";;
5 external draw : int -> int -> int -> int -> string -> unit = "ml_draw";;
6 external gettext : string -> (int * int * int * int) -> int -> bool -> unit =
7 "ml_gettext";;
8 external checklink : string -> int -> int -> bool = "ml_checklink";;
9 external getlink : string -> int -> int -> (int * int) option = "ml_getlink";;
10 external getpagewh : int -> float array = "ml_getpagewh";;
12 type mstate = Msel of ((int * int) * (int * int)) | Mnone;;
14 type textentry = char * string * (string -> int -> te) * (string -> unit)
15 and te =
16 | TEstop
17 | TEdone of string
18 | TEcont of string
19 | TEswitch of textentry
22 type 'a circbuf =
23 { store : 'a array
24 ; mutable rc : int
25 ; mutable wc : int
26 ; mutable len : int
30 let cbnew n v =
31 { store = Array.create n v
32 ; rc = 0
33 ; wc = 0
34 ; len = 0
38 let cblen b = Array.length b.store;;
40 let cbput b v =
41 let len = cblen b in
42 b.store.(b.wc) <- v;
43 b.wc <- (b.wc + 1) mod len;
44 b.len <- min (b.len + 1) len;
47 let cbpeekw b = b.store.(b.wc);;
49 let cbget b =
50 let v = b.store.(b.rc) in
51 if b.len = 0
52 then
54 else (
55 let rc = if b.rc = 0 then b.len - 1 else b.rc - 1 in
56 b.rc <- rc;
61 let cbrfollowlen b =
62 b.rc <- b.len - 1;
65 type layout =
66 { pageno : int
67 ; pagedimno : int
68 ; pagew : int
69 ; pageh : int
70 ; pagedispy : int
71 ; pagey : int
72 ; pagevh : int
76 type conf =
77 { mutable scrollw : int
78 ; mutable scrollh : int
79 ; mutable rectsel : bool
80 ; mutable icase : bool
81 ; mutable preload : bool
82 ; mutable pagebias : int
83 ; mutable redispimm : bool
84 ; mutable verbose : bool
85 ; mutable scrollincr : int
86 ; mutable maxhfit : bool
87 ; mutable crophack : bool
88 ; mutable autoscroll : bool
89 ; mutable showall : bool
93 type outline = string * int * int * int;;
94 type outlines = Oarray of outline array | Olist of outline list;;
96 type state =
97 { mutable csock : Unix.file_descr
98 ; mutable ssock : Unix.file_descr
99 ; mutable w : int
100 ; mutable h : int
101 ; mutable rotate : int
102 ; mutable y : int
103 ; mutable ty : int
104 ; mutable prevy : int
105 ; mutable maxy : int
106 ; mutable layout : layout list
107 ; pagemap : ((int * int * int), string) Hashtbl.t
108 ; mutable pages : (int * int * int) list
109 ; mutable pagecount : int
110 ; pagecache : string circbuf
111 ; navhist : float circbuf
112 ; mutable inflight : int
113 ; mutable mstate : mstate
114 ; mutable searchpattern : string
115 ; mutable rects : (int * int * Gl.point2 * Gl.point2) list
116 ; mutable rects1 : (int * int * Gl.point2 * Gl.point2) list
117 ; mutable text : string
118 ; mutable fullscreen : (int * int) option
119 ; mutable textentry : textentry option
120 ; mutable outlines : outlines
121 ; mutable outline : (bool * int * int * outline array * string) option
122 ; mutable bookmarks : outline list
123 ; mutable path : string
127 let conf =
128 { scrollw = 5
129 ; scrollh = 12
130 ; icase = true
131 ; rectsel = true
132 ; preload = false
133 ; pagebias = 0
134 ; redispimm = false
135 ; verbose = false
136 ; scrollincr = 24
137 ; maxhfit = true
138 ; crophack = false
139 ; autoscroll = false
140 ; showall = false
144 let state =
145 { csock = Unix.stdin
146 ; ssock = Unix.stdin
147 ; w = 900
148 ; h = 900
149 ; rotate = 0
150 ; y = 0
151 ; ty = 0
152 ; prevy = 0
153 ; layout = []
154 ; maxy = max_int
155 ; pagemap = Hashtbl.create 10
156 ; pagecache = cbnew 10 ""
157 ; pages = []
158 ; pagecount = 0
159 ; inflight = 0
160 ; mstate = Mnone
161 ; navhist = cbnew 100 0.0
162 ; rects = []
163 ; rects1 = []
164 ; text = ""
165 ; fullscreen = None
166 ; textentry = None
167 ; searchpattern = ""
168 ; outlines = Olist []
169 ; outline = None
170 ; bookmarks = []
171 ; path = ""
175 let vlog fmt =
176 if conf.verbose
177 then
178 Printf.kprintf prerr_endline fmt
179 else
180 Printf.kprintf ignore fmt
183 let writecmd fd s =
184 let len = String.length s in
185 let n = 4 + len in
186 let b = Buffer.create n in
187 Buffer.add_char b (Char.chr ((len lsr 24) land 0xff));
188 Buffer.add_char b (Char.chr ((len lsr 16) land 0xff));
189 Buffer.add_char b (Char.chr ((len lsr 8) land 0xff));
190 Buffer.add_char b (Char.chr ((len lsr 0) land 0xff));
191 Buffer.add_string b s;
192 let s' = Buffer.contents b in
193 let n' = Unix.write fd s' 0 n in
194 if n' != n then failwith "write failed";
197 let readcmd fd =
198 let s = "xxxx" in
199 let n = Unix.read fd s 0 4 in
200 if n != 4 then failwith "incomplete read(len)";
201 let len = 0
202 lor (Char.code s.[0] lsl 24)
203 lor (Char.code s.[1] lsl 16)
204 lor (Char.code s.[2] lsl 8)
205 lor (Char.code s.[3] lsl 0)
207 let s = String.create len in
208 let n = Unix.read fd s 0 len in
209 if n != len then failwith "incomplete read(data)";
213 let yratio y =
214 if y = state.maxy then 1.0
215 else float y /. float state.maxy
218 let makecmd s l =
219 let b = Buffer.create 10 in
220 Buffer.add_string b s;
221 let rec combine = function
222 | [] -> b
223 | x :: xs ->
224 Buffer.add_char b ' ';
225 let s =
226 match x with
227 | `b b -> if b then "1" else "0"
228 | `s s -> s
229 | `i i -> string_of_int i
230 | `f f -> string_of_float f
231 | `I f -> string_of_int (truncate f)
233 Buffer.add_string b s;
234 combine xs;
236 combine l;
239 let wcmd s l =
240 let cmd = Buffer.contents (makecmd s l) in
241 writecmd state.csock cmd;
244 let calcheight () =
245 let rec f pn ph fh l =
246 match l with
247 | (n, _, h) :: rest ->
248 let fh = fh + (n - pn) * ph in
249 f n h fh rest
251 | [] ->
252 let fh = fh + (ph * (state.pagecount - pn)) in
253 max 0 fh
255 let fh = f 0 0 0 state.pages in
259 let getpagey pageno =
260 let rec f pn ph y l =
261 match l with
262 | (n, _, h) :: rest ->
263 if n >= pageno
264 then
265 y + (pageno - pn) * ph
266 else
267 let y = y + (n - pn) * ph in
268 f n h y rest
270 | [] ->
271 y + (pageno - pn) * ph
273 f 0 0 0 state.pages;
276 let layout y sh =
277 let rec f pageno pdimno prev vy py dy l cacheleft accu =
278 if pageno = state.pagecount || cacheleft = 0
279 then accu
280 else
281 let ((_, w, h) as curr), rest, pdimno =
282 match l with
283 | ((pageno', _, _) as curr) :: rest when pageno' = pageno ->
284 curr, rest, pdimno + 1
285 | _ ->
286 prev, l, pdimno
288 let pageno' = pageno + 1 in
289 if py + h > vy
290 then
291 let py' = vy - py in
292 let vh = h - py' in
293 if dy + vh > sh
294 then
295 let vh = sh - dy in
296 if vh <= 0
297 then
298 accu
299 else
300 let e =
301 { pageno = pageno
302 ; pagedimno = pdimno
303 ; pagew = w
304 ; pageh = h
305 ; pagedispy = dy
306 ; pagey = py'
307 ; pagevh = vh
310 e :: accu
311 else
312 let e =
313 { pageno = pageno
314 ; pagedimno = pdimno
315 ; pagew = w
316 ; pageh = h
317 ; pagedispy = dy
318 ; pagey = py'
319 ; pagevh = vh
322 let accu = e :: accu in
323 f pageno' pdimno curr
324 (vy + vh) (py + h) (dy + vh + 2) rest
325 (pred cacheleft) accu
326 else
327 f pageno' pdimno curr vy (py + h) dy rest cacheleft accu
329 let accu = f 0 ~-1 (0,0,0) y 0 0 state.pages (cblen state.pagecache) [] in
330 state.maxy <- calcheight ();
331 List.rev accu
334 let clamp incr =
335 let y = state.y + incr in
336 let y = max 0 y in
337 let y = min y (state.maxy - (if conf.maxhfit then state.h else 0)) in
341 let getopaque pageno =
342 try Some (Hashtbl.find state.pagemap (pageno + 1, state.w - conf.scrollw,
343 state.rotate))
344 with Not_found -> None
347 let cache pageno opaque =
348 Hashtbl.replace state.pagemap (pageno + 1, state.w - conf.scrollw,
349 state.rotate) opaque
352 let validopaque opaque = String.length opaque > 0;;
354 let preload l =
355 match getopaque l.pageno with
356 | None when state.inflight < 2+0*(cblen state.pagecache) ->
357 state.inflight <- succ state.inflight;
358 cache l.pageno "";
359 wcmd "render" [`i (l.pageno + 1)
360 ;`i l.pagedimno
361 ;`i l.pagew
362 ;`i l.pageh];
364 | _ -> ()
367 let gotoy y =
368 let y = max 0 y in
369 let y = min state.maxy y in
370 let pages = layout y state.h in
371 let rec f all = function
372 | l :: ls ->
373 begin match getopaque l.pageno with
374 | None -> preload l; f false ls
375 | Some opaque -> f (all && validopaque opaque) ls
377 | [] -> all
379 if not conf.showall || f true pages
380 then (
381 state.y <- y;
382 state.layout <- pages;
384 state.ty <- y;
385 if conf.redispimm
386 then
387 Glut.postRedisplay ()
391 let addnav () =
392 cbput state.navhist (yratio state.y);
393 cbrfollowlen state.navhist;
396 let getnav () =
397 let y = cbget state.navhist in
398 truncate (y *. float state.maxy)
401 let gotopage n top =
402 let y = getpagey n in
403 addnav ();
404 state.y <- y + top;
405 gotoy state.y;
408 let reshape ~w ~h =
409 let ratio = float w /. float state.w in
410 let fixbookmark (s, l, pageno, pagey) =
411 let pagey = truncate (float pagey *. ratio) in
412 (s, l, pageno, pagey)
414 state.bookmarks <- List.map fixbookmark state.bookmarks;
415 state.w <- w;
416 state.h <- h;
417 GlDraw.viewport 0 0 w h;
418 GlMat.mode `modelview;
419 GlMat.load_identity ();
420 GlMat.mode `projection;
421 GlMat.load_identity ();
422 GlMat.rotate ~x:1.0 ~angle:180.0 ();
423 GlMat.translate ~x:~-.1.0 ~y:~-.1.0 ();
424 GlMat.scale3 (2.0 /. float w, 2.0 /. float state.h, 1.0);
425 GlClear.color (1., 1., 1.);
426 GlClear.clear [`color];
427 state.layout <- [];
428 state.pages <- [];
429 state.rects <- [];
430 state.text <- "";
431 wcmd "geometry" [`i (state.w - conf.scrollw); `i h];
434 let showtext c s =
435 GlDraw.color (0.0, 0.0, 0.0);
436 GlDraw.rect
437 (0.0, float (state.h - 18))
438 (float (state.w - conf.scrollw - 1), float state.h)
440 let font = Glut.BITMAP_8_BY_13 in
441 GlDraw.color (1.0, 1.0, 1.0);
442 GlPix.raster_pos ~x:0.0 ~y:(float (state.h - 5)) ();
443 Glut.bitmapCharacter ~font ~c:(Char.code c);
444 String.iter (fun c -> Glut.bitmapCharacter ~font ~c:(Char.code c)) s;
447 let enttext () =
448 let len = String.length state.text in
449 match state.textentry with
450 | None ->
451 if len > 0 then showtext ' ' state.text
453 | Some (c, text, _, _) ->
454 let s =
455 if len > 0
456 then
457 text ^ " [" ^ state.text ^ "]"
458 else
459 text
461 showtext c s;
464 let act cmd =
465 match cmd.[0] with
466 | 'c' ->
467 state.pages <- [];
468 state.outlines <- Olist []
470 | 'D' ->
471 state.rects <- state.rects1;
472 Glut.postRedisplay ()
474 | 'd' ->
475 state.rects <- state.rects1;
476 Glut.postRedisplay ()
478 | 'C' ->
479 let n = Scanf.sscanf cmd "C %d" (fun n -> n) in
480 state.pagecount <- n;
481 let rely = yratio state.y in
482 let maxy = calcheight () in
483 state.y <- truncate (float maxy *. rely);
484 let pages = layout state.y state.h in
485 state.layout <- pages;
486 Glut.postRedisplay ();
488 | 't' ->
489 let s = Scanf.sscanf cmd "t %n"
490 (fun n -> String.sub cmd n (String.length cmd - n))
492 Glut.setWindowTitle s
494 | 'T' ->
495 let s = Scanf.sscanf cmd "T %n"
496 (fun n -> String.sub cmd n (String.length cmd - n))
498 state.text <- s;
499 showtext ' ' s;
500 Glut.swapBuffers ();
502 | 'V' ->
503 if conf.verbose
504 then
505 let s = Scanf.sscanf cmd "V %n"
506 (fun n -> String.sub cmd n (String.length cmd - n))
508 state.text <- s;
509 showtext ' ' s;
510 Glut.swapBuffers ();
512 | 'F' ->
513 let pageno, c, x0, y0, x1, y1 =
514 Scanf.sscanf cmd "F %d %d %f %f %f %f"
515 (fun p c x0 y0 x1 y1 -> (p, c, x0, y0, x1, y1))
517 let y = (getpagey pageno) + truncate y0 in
518 addnav ();
519 gotoy y;
520 state.rects1 <- [pageno, c, (x0, y0), (x1, y1)]
522 | 'R' ->
523 let pageno, c, x0, y0, x1, y1 =
524 Scanf.sscanf cmd "R %d %d %f %f %f %f"
525 (fun pageno c x0 y0 x1 y1 -> (pageno, c, x0, y0, x1, y1))
527 state.rects1 <- (pageno, c, (x0, y0), (x1, y1)) :: state.rects1
529 | 'r' ->
530 let n, w, h, r, p =
531 Scanf.sscanf cmd "r %d %d %d %d %s"
532 (fun n w h r p -> (n, w, h, r, p))
534 Hashtbl.replace state.pagemap (n, w, r) p;
535 let evicted = cbpeekw state.pagecache in
536 if String.length evicted > 0
537 then begin
538 wcmd "free" [`s evicted];
539 let l = Hashtbl.fold (fun k p a ->
540 if evicted = p then k :: a else a) state.pagemap []
542 List.iter (fun k -> Hashtbl.remove state.pagemap k) l;
543 end;
544 cbput state.pagecache p;
545 state.inflight <- pred state.inflight;
546 if conf.showall then gotoy state.ty;
547 Glut.postRedisplay ()
549 | 'l' ->
550 let (n, w, h) as pagelayout =
551 Scanf.sscanf cmd "l %d %d %d" (fun n w h -> n, w, h)
553 state.pages <- pagelayout :: state.pages
555 | 'o' ->
556 let (l, n, t, pos) =
557 Scanf.sscanf cmd "o %d %d %d %n" (fun l n t pos -> l, n, t, pos)
559 let s = String.sub cmd pos (String.length cmd - pos) in
560 let outline = (s, l, n, t) in
561 let outlines =
562 match state.outlines with
563 | Olist outlines -> Olist (outline :: outlines)
564 | Oarray _ -> Olist [outline]
566 state.outlines <- outlines
568 | _ ->
569 log "unknown cmd `%S'" cmd
572 let idle () =
573 if not conf.redispimm && state.y != state.prevy
574 then (
575 state.prevy <- state.y;
576 Glut.postRedisplay ();
578 else
579 let r, _, _ = Unix.select [state.csock] [] [] 0.001 in
581 begin match r with
582 | [] ->
583 if conf.preload then begin
584 let h = state.h in
585 let y = if state.y < state.h then 0 else state.y - state.h in
586 let pages = layout y (h*3) in
587 List.iter preload pages;
588 end;
589 if conf.autoscroll then begin
590 let y = state.y + conf.scrollincr in
591 let y = if y >= state.maxy then 0 else y in
592 gotoy y;
593 state.text <- "";
594 state.prevy <- state.y;
595 Glut.postRedisplay ();
596 end;
598 | _ ->
599 let cmd = readcmd state.csock in
600 act cmd;
601 end;
604 let search pattern forward =
605 if String.length pattern > 0
606 then
607 let pn, py =
608 match state.layout with
609 | [] -> 0, 0
610 | l :: _ ->
611 l.pageno, (l.pagey + if forward then 0 else 0*l.pagevh)
613 let cmd =
614 let b = makecmd "search"
615 [`b conf.icase; `i pn; `i py; `i (if forward then 1 else 0)]
617 Buffer.add_char b ',';
618 Buffer.add_string b pattern;
619 Buffer.add_char b '\000';
620 Buffer.contents b;
622 writecmd state.csock cmd;
625 let intentry text key =
626 let c = Char.unsafe_chr key in
627 match c with
628 | '0' .. '9' ->
629 let s = "x" in s.[0] <- c;
630 let text = text ^ s in
631 TEcont text
633 | _ ->
634 state.text <- Printf.sprintf "invalid char (%d, `%c')" key c;
635 TEcont text
638 let addchar s c =
639 let b = Buffer.create (String.length s + 1) in
640 Buffer.add_string b s;
641 Buffer.add_char b c;
642 Buffer.contents b;
645 let textentry text key =
646 let c = Char.unsafe_chr key in
647 match c with
648 | _ when key >= 32 && key < 127 ->
649 let text = addchar text c in
650 TEcont text
652 | _ ->
653 log "unhandled key %d char `%c'" key (Char.unsafe_chr key);
654 TEcont text
657 let optentry text key =
658 let btos b = if b then "on" else "off" in
659 let c = Char.unsafe_chr key in
660 match c with
661 | 'r' ->
662 conf.rectsel <- not conf.rectsel;
663 TEdone ("rectsel " ^ (btos conf.rectsel))
665 | 's' ->
666 let ondone s =
667 try conf.scrollincr <- int_of_string s with exc ->
668 state.text <- Printf.sprintf "bad integer `%s': %s"
669 s (Printexc.to_string exc)
671 TEswitch ('#', "", intentry, ondone)
673 | 'R' ->
674 let ondone s =
676 state.rotate <- int_of_string s;
677 wcmd "rotate" [`i state.rotate]
678 with exc ->
679 state.text <- Printf.sprintf "bad integer `%s': %s"
680 s (Printexc.to_string exc)
682 TEswitch ('^', "", intentry, ondone)
684 | 'i' ->
685 conf.icase <- not conf.icase;
686 TEdone ("case insensitive search " ^ (btos conf.icase))
688 | 'p' ->
689 conf.preload <- not conf.preload;
690 TEdone ("preload " ^ (btos conf.preload))
692 | 'd' ->
693 conf.redispimm <- not conf.redispimm;
694 TEdone ("immediate redisplay " ^ (btos conf.redispimm))
696 | 'v' ->
697 conf.verbose <- not conf.verbose;
698 TEdone ("verbose " ^ (btos conf.verbose))
700 | 'h' ->
701 conf.maxhfit <- not conf.maxhfit;
702 state.maxy <- state.maxy + (if conf.maxhfit then -state.h else state.h);
703 TEdone ("maxhfit " ^ (btos conf.maxhfit))
705 | 'c' ->
706 conf.crophack <- not conf.crophack;
707 TEdone ("crophack " ^ btos conf.crophack)
709 | 'a' ->
710 conf.showall <- not conf.showall;
711 TEdone ("showall " ^ btos conf.showall)
713 | _ ->
714 state.text <- Printf.sprintf "bad option %d `%c'" key c;
715 TEstop
718 let maxoutlinerows () = (state.h - 31) / 16;;
720 let enterselector allowdel outlines errmsg =
721 if Array.length outlines = 0
722 then (
723 showtext ' ' errmsg;
724 Glut.swapBuffers ()
726 else
727 let pageno =
728 match state.layout with
729 | [] -> -1
730 | {pageno=pageno} :: rest -> pageno
732 let active =
733 let rec loop n =
734 if n = Array.length outlines
735 then 0
736 else
737 let (_, _, outlinepageno, _) = outlines.(n) in
738 if outlinepageno >= pageno then n else loop (n+1)
740 loop 0
742 state.outline <-
743 Some (allowdel, active, max 0 (active - maxoutlinerows ()), outlines, "");
744 Glut.postRedisplay ();
747 let enteroutlinemode () =
748 let outlines =
749 match state.outlines with
750 | Oarray a -> a
751 | Olist l ->
752 let a = Array.of_list (List.rev l) in
753 state.outlines <- Oarray a;
756 enterselector false outlines "Documents has no outline";
759 let enterbookmarkmode () =
760 let bookmarks = Array.of_list state.bookmarks in
761 enterselector true bookmarks "Documents has no bookmarks (yet)";
765 let quickbookmark ?title () =
766 match state.layout with
767 | [] -> ()
768 | l :: _ ->
769 let title =
770 match title with
771 | None ->
772 let sec = Unix.gettimeofday () in
773 let tm = Unix.localtime sec in
774 Printf.sprintf "Quick %d visited (%d/%d/%d %d:%d)"
775 l.pageno
776 tm.Unix.tm_mday
777 tm.Unix.tm_mon
778 (tm.Unix.tm_year + 1900)
779 tm.Unix.tm_hour
780 tm.Unix.tm_min
781 | Some title -> title
783 state.bookmarks <-
784 (title, 0, l.pageno, l.pagey) :: state.bookmarks
787 let viewkeyboard ~key ~x ~y =
788 let enttext te =
789 state.textentry <- te;
790 state.text <- "";
791 enttext ();
792 Glut.postRedisplay ()
794 match state.textentry with
795 | None ->
796 let c = Char.chr key in
797 begin match c with
798 | '\027' | 'q' ->
799 exit 0
801 | '\008' ->
802 let y = getnav () in
803 gotoy y
805 | 'o' ->
806 enteroutlinemode ()
808 | 'u' ->
809 state.rects <- [];
810 state.text <- "";
811 Glut.postRedisplay ()
813 | '/' | '?' ->
814 let ondone isforw s =
815 state.searchpattern <- s;
816 search s isforw
818 enttext (Some (c, "", textentry, ondone (c ='/')))
820 | '+' ->
821 let ondone s =
822 let n =
823 try int_of_string s with exc ->
824 state.text <- Printf.sprintf "bad integer `%s': %s"
825 s (Printexc.to_string exc);
826 max_int
828 if n != max_int
829 then (
830 conf.pagebias <- n;
831 state.text <- "page bias is now " ^ string_of_int n;
834 enttext (Some ('+', "", intentry, ondone))
836 | '-' ->
837 let ondone msg =
838 state.text <- msg;
840 enttext (Some ('-', "", optentry, ondone))
842 | '0' .. '9' ->
843 let ondone s =
844 let n =
845 try int_of_string s with exc ->
846 state.text <- Printf.sprintf "bad integer `%s': %s"
847 s (Printexc.to_string exc);
850 if n >= 0
851 then (
852 addnav ();
853 state.y <- y;
854 gotoy (getpagey (n + conf.pagebias - 1))
857 let pageentry text key =
858 match Char.unsafe_chr key with
859 | 'g' -> TEdone text
860 | _ -> intentry text key
862 let text = "x" in text.[0] <- c;
863 enttext (Some (':', text, pageentry, ondone))
865 | 'b' ->
866 conf.scrollw <- if conf.scrollw > 0 then 0 else 5;
867 reshape state.w state.h;
869 | 'a' ->
870 conf.autoscroll <- not conf.autoscroll
872 | 'f' ->
873 begin match state.fullscreen with
874 | None ->
875 state.fullscreen <- Some (state.w, state.h);
876 Glut.fullScreen ()
877 | Some (w, h) ->
878 state.fullscreen <- None;
879 Glut.reshapeWindow ~w ~h
882 | 'n' ->
883 search state.searchpattern true
885 | 'p' ->
886 search state.searchpattern false
888 | 't' ->
889 begin match state.layout with
890 | [] -> ()
891 | l :: _ ->
892 gotoy (state.y - l.pagey);
895 | ' ' | 'N' ->
896 begin match List.rev state.layout with
897 | [] -> ()
898 | l :: _ ->
899 gotoy (clamp (l.pageh - l.pagey))
902 | '\127' | 'P' ->
903 begin match state.layout with
904 | [] -> ()
905 | l :: _ ->
906 gotoy (clamp (-l.pageh));
909 | '=' ->
910 let f (fn, ln) l =
911 if fn = -1 then l.pageno, l.pageno else fn, l.pageno
913 let fn, ln = List.fold_left f (-1, -1) state.layout in
914 let s =
915 let maxy = state.maxy - (if conf.maxhfit then state.h else 0) in
916 let percent =
917 if maxy <= 0
918 then 100.
919 else (100. *. (float state.y /. float maxy)) in
920 if fn = ln
921 then
922 Printf.sprintf "Page %d of %d %.2f%%"
923 (fn+1) state.pagecount percent
924 else
925 Printf.sprintf
926 "Pages %d-%d of %d %.2f%%"
927 (fn+1) (ln+1) state.pagecount percent
929 showtext ' ' s;
930 Glut.swapBuffers ()
932 | 'w' ->
933 begin match state.layout with
934 | [] -> ()
935 | l :: _ ->
936 Glut.reshapeWindow (l.pagew + conf.scrollw) l.pageh;
937 Glut.postRedisplay ();
940 | '\'' ->
941 enterbookmarkmode ()
943 | 'm' ->
944 let ondone s =
945 match state.layout with
946 | l :: _ ->
947 state.bookmarks <- (s, 0, l.pageno, l.pagey) :: state.bookmarks
948 | _ -> ()
950 enttext (Some ('~', "", textentry, ondone))
952 | '~' ->
953 quickbookmark ();
954 showtext ' ' "Quick bookmark added";
955 Glut.swapBuffers ()
957 | 'z' ->
958 begin match state.layout with
959 | l :: _ ->
960 let a = getpagewh l.pagedimno in
961 let w, h =
962 if conf.crophack
963 then
964 (truncate (1.8 *. (a.(1) -. a.(0))),
965 truncate (1.4 *. (a.(3) -. a.(0))))
966 else
967 (truncate (a.(1) -. a.(0)),
968 truncate (a.(3) -. a.(0)))
970 Glut.reshapeWindow (w + conf.scrollw) h;
971 Glut.postRedisplay ();
973 | [] -> ()
976 | '<' | '>' ->
977 state.rotate <- state.rotate + (if c = '>' then 30 else -30);
978 wcmd "rotate" [`i state.rotate]
980 | _ ->
981 vlog "huh? %d %c" key (Char.chr key);
984 | Some (c, text, onkey, ondone) when key = 8 ->
985 let len = String.length text in
986 if len = 0
987 then (
988 state.textentry <- None;
989 Glut.postRedisplay ();
991 else (
992 let s = String.sub text 0 (len - 1) in
993 enttext (Some (c, s, onkey, ondone))
996 | Some (c, text, onkey, ondone) ->
997 begin match Char.unsafe_chr key with
998 | '\r' | '\n' ->
999 ondone text;
1000 state.textentry <- None;
1001 Glut.postRedisplay ()
1003 | '\027' ->
1004 state.textentry <- None;
1005 Glut.postRedisplay ()
1007 | _ ->
1008 begin match onkey text key with
1009 | TEdone text ->
1010 state.textentry <- None;
1011 ondone text;
1012 Glut.postRedisplay ()
1014 | TEcont text ->
1015 enttext (Some (c, text, onkey, ondone));
1017 | TEstop ->
1018 state.textentry <- None;
1019 Glut.postRedisplay ()
1021 | TEswitch te ->
1022 state.textentry <- Some te;
1023 Glut.postRedisplay ()
1024 end;
1025 end;
1028 let outlinekeyboard ~key ~x ~y (allowdel, active, first, outlines, qsearch) =
1029 let search active pattern incr =
1030 let dosearch re =
1031 let rec loop n =
1032 if n = Array.length outlines || n = -1 then None else
1033 let (s, _, _, _) = outlines.(n) in
1035 (try ignore (Str.search_forward re s 0); true
1036 with Not_found -> false)
1037 then (
1038 let maxrows = (min (Array.length outlines) (maxoutlinerows ())) / 2 in
1039 if first > n
1040 then Some (n, max 0 (n - maxrows))
1041 else Some (n, max first (n - maxrows))
1043 else loop (n + incr)
1045 loop active
1048 let re = Str.regexp_case_fold pattern in
1049 dosearch re
1050 with Failure s ->
1051 state.text <- s;
1052 None
1054 match key with
1055 | 27 ->
1056 if String.length qsearch = 0
1057 then (
1058 state.text <- "";
1059 state.outline <- None;
1060 Glut.postRedisplay ();
1062 else (
1063 state.text <- "";
1064 state.outline <- Some (allowdel, active, first, outlines, "");
1065 Glut.postRedisplay ();
1068 | 18 | 19 ->
1069 let incr = if key = 18 then -1 else 1 in
1070 let active, first =
1071 match search (active + incr) qsearch incr with
1072 | None ->
1073 state.text <- qsearch ^ " [not found]";
1074 active, first
1075 | Some af ->
1076 state.text <- qsearch;
1079 state.outline <- Some (allowdel, active, first, outlines, qsearch);
1080 Glut.postRedisplay ();
1082 | 8 ->
1083 let len = String.length qsearch in
1084 if len = 0
1085 then ()
1086 else (
1087 if len = 1
1088 then (
1089 state.text <- "";
1090 state.outline <- Some (allowdel, active, first, outlines, "");
1092 else
1093 let qsearch = String.sub qsearch 0 (len - 1) in
1094 state.text <- qsearch;
1095 state.outline <- Some (allowdel, active, first, outlines, qsearch);
1097 Glut.postRedisplay ()
1099 | 13 ->
1100 if active < Array.length outlines
1101 then (
1102 let (_, _, n, t) = outlines.(active) in
1103 gotopage n t;
1105 state.text <- "";
1106 if allowdel then state.bookmarks <- Array.to_list outlines;
1107 state.outline <- None;
1108 Glut.postRedisplay ();
1110 | _ when key >= 32 && key < 127 ->
1111 let pattern = addchar qsearch (Char.chr key) in
1112 let active, first =
1113 match search active pattern 1 with
1114 | None ->
1115 state.text <- pattern ^ " [not found]";
1116 active, first
1117 | Some (active, first) ->
1118 state.text <- pattern;
1119 active, first
1121 state.outline <- Some (allowdel, active, first, outlines, pattern);
1122 Glut.postRedisplay ()
1124 | 127 when allowdel ->
1125 let len = Array.length outlines - 1 in
1126 if len = 0
1127 then (
1128 state.outline <- None;
1129 state.bookmarks <- [];
1131 else (
1132 let bookmarks = Array.init len
1133 (fun i ->
1134 let i = if i >= active then i + 1 else i in
1135 outlines.(i)
1138 state.outline <-
1139 Some (allowdel,
1140 min active (len-1),
1141 min first (len-1),
1142 bookmarks, qsearch)
1145 Glut.postRedisplay ()
1147 | _ -> log "unknown key %d" key
1150 let keyboard ~key ~x ~y =
1151 match state.outline with
1152 | None -> viewkeyboard ~key ~x ~y
1153 | Some outline -> outlinekeyboard ~key ~x ~y outline
1156 let special ~key ~x ~y =
1157 match state.outline with
1158 | None ->
1159 let y =
1160 match key with
1161 | Glut.KEY_F3 -> search state.searchpattern true; state.y
1162 | Glut.KEY_UP -> clamp (-conf.scrollincr)
1163 | Glut.KEY_DOWN -> clamp conf.scrollincr
1164 | Glut.KEY_PAGE_UP -> clamp (-state.h)
1165 | Glut.KEY_PAGE_DOWN -> clamp state.h
1166 | Glut.KEY_HOME -> addnav (); 0
1167 | Glut.KEY_END ->
1168 addnav ();
1169 state.maxy - (if conf.maxhfit then state.h else 0)
1170 | _ -> state.y
1172 state.text <- "";
1173 gotoy y
1175 | Some (allowdel, active, first, outlines, qsearch) ->
1176 let maxrows = maxoutlinerows () in
1177 let navigate incr =
1178 let active = active + incr in
1179 let active = max 0 (min active (Array.length outlines - 1)) in
1180 let first =
1181 if active > first
1182 then
1183 let rows = active - first in
1184 if rows > maxrows then first + incr else first
1185 else active
1187 state.outline <- Some (allowdel, active, first, outlines, qsearch);
1188 Glut.postRedisplay ()
1190 match key with
1191 | Glut.KEY_UP -> navigate ~-1
1192 | Glut.KEY_DOWN -> navigate 1
1193 | Glut.KEY_PAGE_UP -> navigate ~-maxrows
1194 | Glut.KEY_PAGE_DOWN -> navigate maxrows
1196 | Glut.KEY_HOME ->
1197 state.outline <- Some (allowdel, 0, 0, outlines, qsearch);
1198 Glut.postRedisplay ()
1200 | Glut.KEY_END ->
1201 let active = Array.length outlines - 1 in
1202 let first = max 0 (active - maxrows) in
1203 state.outline <- Some (allowdel, active, first, outlines, qsearch);
1204 Glut.postRedisplay ()
1206 | _ -> ()
1209 let drawplaceholder l =
1210 GlDraw.color (1.0, 1.0, 1.0);
1211 GlDraw.rect
1212 (0.0, float l.pagedispy)
1213 (float l.pagew, float (l.pagedispy + l.pagevh))
1215 let x = 0.0
1216 and y = float (l.pagedispy + 13) in
1217 let font = Glut.BITMAP_8_BY_13 in
1218 GlDraw.color (0.0, 0.0, 0.0);
1219 GlPix.raster_pos ~x ~y ();
1220 String.iter (fun c -> Glut.bitmapCharacter ~font ~c:(Char.code c))
1221 ("Loading " ^ string_of_int l.pageno);
1224 let now () = Unix.gettimeofday ();;
1226 let drawpage i l =
1227 begin match getopaque l.pageno with
1228 | Some opaque when validopaque opaque ->
1229 if state.textentry = None
1230 then GlDraw.color (1.0, 1.0, 1.0)
1231 else GlDraw.color (0.4, 0.4, 0.4);
1232 let a = now () in
1233 draw l.pagedispy l.pagew l.pagevh l.pagey opaque;
1234 let b = now () in
1235 let d = b-.a in
1236 vlog "draw %f sec" d;
1238 | Some _ ->
1239 drawplaceholder l
1241 | None ->
1242 drawplaceholder l;
1243 if state.inflight < cblen state.pagecache
1244 then (
1245 List.iter preload state.layout;
1247 else (
1248 vlog "inflight %d" state.inflight;
1250 end;
1251 GlDraw.color (0.5, 0.5, 0.5);
1252 GlDraw.rect
1253 (0., float i)
1254 (float (state.w - conf.scrollw), float (i + (l.pagedispy - i)))
1256 l.pagedispy + l.pagevh;
1259 let scrollindicator () =
1260 let maxy = state.maxy - (if conf.maxhfit then state.h else 0) in
1261 GlDraw.color (0.64 , 0.64, 0.64);
1262 GlDraw.rect
1263 (float (state.w - conf.scrollw), 0.)
1264 (float state.w, float state.h)
1266 GlDraw.color (0.0, 0.0, 0.0);
1267 let sh = (float (maxy + state.h) /. float state.h) in
1268 let sh = float state.h /. sh in
1269 let sh = max sh (float conf.scrollh) in
1271 let percent =
1272 if state.y = state.maxy
1273 then 1.0
1274 else float state.y /. float maxy
1276 let position = (float state.h -. sh) *. percent in
1278 let position =
1279 if position +. sh > float state.h
1280 then
1281 float state.h -. sh
1282 else
1283 position
1285 GlDraw.rect
1286 (float (state.w - conf.scrollw), position)
1287 (float state.w, position +. sh)
1291 let showsel () =
1292 match state.mstate with
1293 | Mnone ->
1296 | Msel ((x0, y0), (x1, y1)) ->
1297 let y0' = min y0 y1
1298 and y1 = max y0 y1 in
1299 let y0 = y0' in
1300 let f l =
1301 if (y0 >= l.pagedispy && y0 <= (l.pagedispy + l.pagevh))
1302 || ((y1 >= l.pagedispy)) (* && y1 <= (dy + vh))) *)
1303 then
1304 match getopaque l.pageno with
1305 | Some opaque when validopaque opaque ->
1306 let oy = -l.pagey + l.pagedispy in
1307 gettext opaque (min x0 x1, y0, max x1 x0, y1) oy conf.rectsel
1308 | _ -> ()
1310 List.iter f state.layout
1313 let showrects () =
1314 Gl.enable `blend;
1315 GlDraw.color (0.0, 0.0, 1.0) ~alpha:0.5;
1316 GlFunc.blend_func `src_alpha `one_minus_src_alpha;
1317 List.iter
1318 (fun (pageno, c, (x0, y0), (x1, y1)) ->
1319 List.iter (fun l ->
1320 if l.pageno = pageno
1321 then (
1322 let d = float (l.pagedispy - l.pagey) in
1323 GlDraw.color (0.0, 0.0, 1.0 /. float c) ~alpha:0.5;
1324 GlDraw.rect (x0, y0 +. d) (x1, y1 +. d)
1326 ) state.layout
1327 ) state.rects
1329 Gl.disable `blend;
1332 let showoutline = function
1333 | None -> ()
1334 | Some (allowdel, active, first, outlines, qsearch) ->
1335 Gl.enable `blend;
1336 GlFunc.blend_func `src_alpha `one_minus_src_alpha;
1337 GlDraw.color (0., 0., 0.) ~alpha:0.85;
1338 GlDraw.rect (0., 0.) (float state.w, float state.h);
1339 Gl.disable `blend;
1341 GlDraw.color (1., 1., 1.);
1342 let font = Glut.BITMAP_9_BY_15 in
1343 let draw_string x y s =
1344 GlPix.raster_pos ~x ~y ();
1345 String.iter (fun c -> Glut.bitmapCharacter ~font ~c:(Char.code c)) s
1347 let rec loop row =
1348 if row = Array.length outlines || (row - first) * 16 > state.h
1349 then ()
1350 else (
1351 let (s, l, _, _) = outlines.(row) in
1352 let y = (row - first) * 16 in
1353 let x = 5 + 5*l in
1354 if row = active
1355 then (
1356 Gl.enable `blend;
1357 GlDraw.polygon_mode `both `line;
1358 GlFunc.blend_func `src_alpha `one_minus_src_alpha;
1359 GlDraw.color (1., 1., 1.) ~alpha:0.9;
1360 GlDraw.rect (0., float (y + 1))
1361 (float (state.w - conf.scrollw - 1), float (y + 18));
1362 GlDraw.polygon_mode `both `fill;
1363 Gl.disable `blend;
1364 GlDraw.color (1., 1., 1.);
1366 draw_string (float x) (float (y + 16)) s;
1367 loop (row+1)
1370 loop first
1373 let display () =
1374 let lasty = List.fold_left drawpage 0 (state.layout) in
1375 GlDraw.color (0.5, 0.5, 0.5);
1376 GlDraw.rect
1377 (0., float lasty)
1378 (float (state.w - conf.scrollw), float state.h)
1380 showrects ();
1381 scrollindicator ();
1382 showsel ();
1383 showoutline state.outline;
1384 enttext ();
1385 Glut.swapBuffers ();
1388 let getlink x y =
1389 let rec f = function
1390 | l :: rest ->
1391 begin match getopaque l.pageno with
1392 | Some opaque when validopaque opaque ->
1393 let y = y - l.pagedispy in
1394 if y > 0
1395 then
1396 let y = l.pagey + y in
1397 match getlink opaque x y with
1398 | None -> f rest
1399 | some -> some
1400 else
1401 f rest
1402 | _ ->
1403 f rest
1405 | [] -> None
1407 f state.layout
1410 let checklink x y =
1411 let rec f = function
1412 | l :: rest ->
1413 begin match getopaque l.pageno with
1414 | Some opaque when validopaque opaque ->
1415 let y = y - l.pagedispy in
1416 if y > 0
1417 then
1418 let y = l.pagey + y in
1419 if checklink opaque x y then true else f rest
1420 else
1421 f rest
1422 | _ ->
1423 f rest
1425 | [] -> false
1427 f state.layout
1430 let mouse ~button ~bstate ~x ~y =
1431 match button with
1432 | Glut.OTHER_BUTTON n when n == 3 || n == 4 && bstate = Glut.UP ->
1433 let incr =
1434 if n = 3
1435 then
1436 -conf.scrollincr
1437 else
1438 conf.scrollincr
1440 let incr = incr * 2 in
1441 let y = clamp incr in
1442 gotoy y
1444 | Glut.LEFT_BUTTON when state.outline = None ->
1445 let dest = if bstate = Glut.DOWN then getlink x y else None in
1446 begin match dest with
1447 | Some (pageno, top) ->
1448 gotopage pageno top
1450 | None ->
1451 if bstate = Glut.DOWN
1452 then (
1453 Glut.setCursor Glut.CURSOR_CROSSHAIR;
1454 state.mstate <- Msel ((x, y), (x, y));
1455 Glut.postRedisplay ()
1457 else (
1458 Glut.setCursor Glut.CURSOR_INHERIT;
1459 state.mstate <- Mnone;
1463 | _ ->
1466 let mouse ~button ~state ~x ~y = mouse button state x y;;
1468 let motion ~x ~y =
1469 if state.outline = None
1470 then
1471 match state.mstate with
1472 | Mnone -> ()
1473 | Msel (a, _) ->
1474 state.mstate <- Msel (a, (x, y));
1475 Glut.postRedisplay ()
1478 let pmotion ~x ~y =
1479 if state.outline = None
1480 then
1481 match state.mstate with
1482 | Mnone when (checklink x y) ->
1483 Glut.setCursor Glut.CURSOR_INFO
1485 | Mnone ->
1486 Glut.setCursor Glut.CURSOR_INHERIT
1488 | Msel (a, _) ->
1492 let () =
1493 let statepath =
1494 let home =
1495 if Sys.os_type = "Win32"
1496 then
1497 try Sys.getenv "HOMEPATH" with Not_found -> ""
1498 else
1499 try Filename.concat (Sys.getenv "HOME") ".config" with Not_found -> ""
1501 Filename.concat home "llpp"
1503 let pstate =
1505 let ic = open_in_bin statepath in
1506 let hash = input_value ic in
1507 close_in ic;
1508 hash
1509 with exn ->
1510 if false
1511 then
1512 prerr_endline ("Error loading state " ^ Printexc.to_string exn)
1514 Hashtbl.create 1
1516 let savestate () =
1518 let w, h =
1519 match state.fullscreen with
1520 | None -> state.w, state.h
1521 | Some wh -> wh
1523 Hashtbl.replace pstate state.path (state.bookmarks, w, h);
1524 let oc = open_out_bin statepath in
1525 output_value oc pstate
1526 with exn ->
1527 if false
1528 then
1529 prerr_endline ("Error saving state " ^ Printexc.to_string exn)
1532 let setstate () =
1534 let statebookmarks, statew, stateh = Hashtbl.find pstate state.path in
1535 state.w <- statew;
1536 state.h <- stateh;
1537 state.bookmarks <- statebookmarks;
1538 with Not_found -> ()
1539 | exn ->
1540 prerr_endline ("Error setting state " ^ Printexc.to_string exn)
1543 Arg.parse [] (fun s -> state.path <- s) "options:";
1544 let name =
1545 if String.length state.path = 0
1546 then (prerr_endline "filename missing"; exit 1)
1547 else state.path
1550 setstate ();
1551 let _ = Glut.init Sys.argv in
1552 let () = Glut.initDisplayMode ~depth:false ~double_buffer:true () in
1553 let () = Glut.initWindowSize state.w state.h in
1554 let _ = Glut.createWindow ("llpp " ^ Filename.basename name) in
1556 let csock, ssock =
1557 if Sys.os_type = "Unix"
1558 then
1559 Unix.socketpair Unix.PF_UNIX Unix.SOCK_STREAM 0
1560 else
1561 let addr = Unix.ADDR_INET (Unix.inet_addr_loopback, 1337) in
1562 let sock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
1563 Unix.setsockopt sock Unix.SO_REUSEADDR true;
1564 Unix.bind sock addr;
1565 Unix.listen sock 1;
1566 let csock = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
1567 Unix.connect csock addr;
1568 let ssock, _ = Unix.accept sock in
1569 Unix.close sock;
1570 let opts sock =
1571 Unix.setsockopt sock Unix.TCP_NODELAY true;
1572 Unix.setsockopt_optint sock Unix.SO_LINGER None;
1574 opts ssock;
1575 opts csock;
1576 at_exit (fun () -> Unix.shutdown ssock Unix.SHUTDOWN_ALL);
1577 ssock, csock
1580 let () = Glut.displayFunc display in
1581 let () = Glut.reshapeFunc reshape in
1582 let () = Glut.keyboardFunc keyboard in
1583 let () = Glut.specialFunc special in
1584 let () = Glut.idleFunc (Some idle) in
1585 let () = Glut.mouseFunc mouse in
1586 let () = Glut.motionFunc motion in
1587 let () = Glut.passiveMotionFunc pmotion in
1589 init ssock;
1590 state.csock <- csock;
1591 state.ssock <- ssock;
1592 writecmd csock ("open " ^ name ^ "\000");
1594 at_exit savestate;
1596 let rec handlelablglutbug () =
1598 Glut.mainLoop ();
1599 with Glut.BadEnum "key in special_of_int" ->
1600 showtext '!' " LablGlut bug: special key not recognized";
1601 Glut.swapBuffers ();
1602 handlelablglutbug ()
1604 handlelablglutbug ();