open Unix
open Document
open Viewers
open Feed


(* Wrapping up
 * When EMBED is recognized by the HTML display machine, the "embedded object"
 * is passed to the embed manager/scheduler. We thus have to define only
 * the viewer.
 *)

(* This is called on the continuation of the retrieval of the bytecode file,
   or, if the bytecode file has already been retrieved, it is invoked
   immediately. But at this point we don't know in what case we are.
 *)
let applet_viewer parms frame context doc =
  if Applets.invoke doc.document_address frame context then
    let fname = 
      match doc.document_data with
	FileData(f,_) -> f
      | MemoryData _ -> raise Not_found (* puke *)
    in
    Dload.load doc fname context.viewer_base

(* If we load code directly (no embed) *)
let code_viewer parms frame ctx dh =
  let fname = Msys.mktemp "bytc"
  and buffer = String.create 2048 in
  let oc = open_out_bin fname in
    dh.document_feed.feed_schedule
       (fun _ ->
         try
          let n = dh.document_feed.feed_read buffer 0 1024 in
            if n = 0 then begin
              dclose true dh;
              close_out oc;
	      Dload.load {
                document_address = dh.document_id.document_url;
	        document_data = FileData(fname,true);
	        document_info = dh.document_headers} 
               fname ctx.viewer_base
              end
         with
           Unix_error(_,_,_) ->
              dclose true dh;
	      close_out oc;
	      Msys.rm fname;
	      Error.f (I18n.sprintf "Error during loading of bytecode")
       );
    None (* no window *)


(* Pref stuff *)
let active = ref false

let types = [
  "application","x-caml-applet";
  "application","x-caml-signed-applet"
] 

let activate () =
  List.iter (fun ctype -> 
    Viewers.add_viewer ctype code_viewer;
    Embed.add_viewer ctype applet_viewer)
  types

let deactivate () =
  List.iter (fun ctype ->
    Viewers.rem_viewer ctype;
    Embed.rem_viewer ctype)
  types

(* set display from prefs *)
let pref_init v =
  Textvariable.set v (if !active then "1" else "0")

let pref_set v =
  match Textvariable.get v with
    "1" -> if !active then () else begin
             active := true;
             activate()
            end
  | _ -> if not !active then () else begin
           active := false;
           deactivate()
         end

