]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/matita/matitaMathView.ml
fixed a finalization issue for connections closed twice
[helm.git] / helm / matita / matitaMathView.ml
index addf9763cc2350125be11b57792f8d41d1a5f506..532c3dd975a3a2fe4d1364dca912273a51562fd0 100644 (file)
 open Printf
 
 open MatitaTypes
-
-let list_map_fail f =
-  let rec aux = function
-    | [] -> []
-    | he::tl ->
-        try
-          let he' = f he in
-          he'::(aux tl)
-        with Exit ->
-          (aux tl)
-  in
-  aux
+open MatitaGtkMisc
 
 (** inherit from this class if you want to access current script *)
 class scriptAccessor =
@@ -45,46 +34,314 @@ object (self)
   method private script = MatitaScript.instance ()
 end
 
+let cicBrowsers = ref []
+let gui_instance = ref None
+let set_gui gui = gui_instance := Some gui
+let get_gui () =
+  match !gui_instance with
+  | None -> assert false
+  | Some gui -> gui
+
+let default_font_size () =
+  Helm_registry.get_opt_default Helm_registry.int
+    ~default:BuildTimeConf.default_font_size "matita.font_size"
+let current_font_size = ref ~-1
+let increase_font_size () = incr current_font_size
+let decrease_font_size () = decr current_font_size
+let reset_font_size () = current_font_size := default_font_size ()
+
+  (* is there any lablgtk2 constant corresponding to the various mouse
+   * buttons??? *)
+let left_button = 1
+let middle_button = 2
+let right_button = 3
+
+let near (x1, y1) (x2, y2) =
+  let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
+  (distance < 4.)
+
+let href_ds = Gdome.domString "href"
+let xref_ds = Gdome.domString "xref"
+
+(* ids_to_terms should not be passed here, is just for debugging *)
+let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
+  let find_parent id ids =
+    let rec aux id =
+(*       (prerr_endline (sprintf "id %s = %s" id
+        (try
+          CicPp.ppterm (Hashtbl.find ids_to_terms id)
+        with Not_found -> "NONE"))); *)
+      if List.mem id ids then Some id
+      else
+        (match
+          (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
+        with
+        | None -> None
+        | Some id' -> aux id')
+    in
+    aux id
+  in
+  let return_father id ids =
+    match find_parent id ids with
+    | None -> assert false
+    | Some parent_id -> parent_id
+  in
+  let mk_ids terms = List.map CicUtil.id_of_annterm terms in
+  let inner_types =
+   Hashtbl.fold
+    (fun _ types acc ->
+      match types.Cic2acic.annexpected with
+         None -> types.Cic2acic.annsynthesized :: acc
+       | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
+    ) ids_to_inner_types [] in
+  match annobj with
+  | Cic.AConstant (_, _, _, Some bo, ty, _, _)
+  | Cic.AVariable (_, _, Some bo, ty, _, _)
+  | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
+      return_father id (mk_ids (ty :: bo :: inner_types))
+  | Cic.AConstant (_, _, _, None, ty, _, _)
+  | Cic.AVariable (_, _, None, ty, _, _) ->
+      return_father id (mk_ids (ty::inner_types))
+  | Cic.AInductiveDefinition _ ->
+      assert false  (* TODO *)
+
+  (** @return string content of a dom node having a single text child node, e.g.
+   * <m:mi xlink:href="...">bool</m:mi> *)
+let string_of_dom_node node =
+  match node#get_firstChild with
+  | None -> ""
+  | Some node ->
+      (try
+        let text = new Gdome.text_of_node node in
+        text#get_data#to_string
+      with GdomeInit.DOMCastException _ -> "")
+
 class clickableMathView obj =
-  let href = Gdome.domString "href" in
-  let xref = Gdome.domString "xref" in
-  object (self)
-    inherit GMathViewAux.multi_selection_math_view obj
+let text_width = 80 in
+object (self)
+  inherit GMathViewAux.multi_selection_math_view obj
+
+  val mutable href_callback: (string -> unit) option = None
+  method set_href_callback f = href_callback <- f
+
+  val mutable _cic_info = None
+  method private set_cic_info info = _cic_info <- info
+  method private cic_info = _cic_info
+
+  initializer
+    self#set_font_size !current_font_size;
+    ignore (self#connect#selection_changed self#choose_selection_cb);
+    ignore (self#event#connect#button_press self#button_press_cb);
+    ignore (self#event#connect#button_release self#button_release_cb);
+    ignore (self#event#connect#selection_clear self#selection_clear_cb);
+    ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
+
+  val mutable button_press_x = -1.
+  val mutable button_press_y = -1.
+  val mutable selection_changed = false
+
+  method private selection_get_cb ctxt ~info ~time =
+    (match self#get_selections with
+    | [] -> ()
+    | node :: _ -> ctxt#return (self#string_of_node node))
+
+  method private selection_clear_cb sel_event =
+    self#remove_selections;
+    false
+
+  method private button_press_cb gdk_button =
+    let button = GdkEvent.Button.button gdk_button in
+    if  button = left_button then begin
+      button_press_x <- GdkEvent.Button.x gdk_button;
+      button_press_y <- GdkEvent.Button.y gdk_button;
+      selection_changed <- false
+    end else if button = right_button then
+      self#popup_contextual_menu (GdkEvent.Button.time gdk_button);
+    false
+
+  method private popup_contextual_menu time =
+    match self#string_of_selection with
+    | None -> ()
+    | Some s ->
+        let clipboard = GData.clipboard Gdk.Atom.clipboard in
+        let menu = GMenu.menu () in
+        let copy_menu_item =
+          GMenu.image_menu_item
+            ~label:"_Copy" ~stock:`COPY ~packing:menu#append ()
+        in
+        connect_menu_item copy_menu_item (fun () -> clipboard#set_text s);
+        menu#popup ~button:right_button ~time
+
+  method private button_release_cb gdk_button =
+    let clipboard = GData.clipboard Gdk.Atom.primary in
+    if GdkEvent.Button.button gdk_button = left_button then begin
+      let button_release_x = GdkEvent.Button.x gdk_button in
+      let button_release_y = GdkEvent.Button.y gdk_button in
+      if selection_changed then
+        ()
+      else  (* selection _not_ changed *)
+        if near (button_press_x, button_press_y)
+          (button_release_x, button_release_y)
+        then
+          let x = int_of_float button_press_x in
+          let y = int_of_float button_press_y in
+          (match self#get_element_at x y with
+          | None -> ()
+          | Some elt ->
+              let namespaceURI = DomMisc.xlink_ns in
+              let localName = href_ds in
+              if elt#hasAttributeNS ~namespaceURI ~localName then
+                self#invoke_href_callback
+                  (elt#getAttributeNS ~namespaceURI ~localName)#to_string
+                  gdk_button
+              else
+                ignore (self#action_toggle elt));
+    end;
+    false
+
+  method private invoke_href_callback href_value gdk_button =
+    let button = GdkEvent.Button.button gdk_button in
+    if button = left_button then
+      let time = GdkEvent.Button.time gdk_button in
+      match href_callback with
+      | None -> ()
+      | Some f ->
+          (match MatitaMisc.split href_value with
+          | [ uri ] ->  f uri
+          | uris ->
+              let menu = GMenu.menu () in
+              List.iter
+                (fun uri ->
+                  let menu_item =
+                    GMenu.menu_item ~label:uri ~packing:menu#append ()
+                  in
+                  connect_menu_item menu_item (fun () -> f uri))
+                uris;
+              menu#popup ~button ~time)
+
+  method private choose_selection_cb gdome_elt =
+    let (gui: MatitaGuiTypes.gui) = get_gui () in
+    let clipboard = GData.clipboard Gdk.Atom.primary in
+    let set_selection elt =
+      self#set_selection (Some elt);
+      self#coerce#misc#add_selection_target
+        ~target:(Gdk.Atom.name Gdk.Atom.string) Gdk.Atom.primary;
+      ignore (self#coerce#misc#grab_selection Gdk.Atom.primary)
+    in
+    let rec aux elt =
+      if (elt#getAttributeNS ~namespaceURI:DomMisc.helm_ns
+            ~localName:xref_ds)#to_string <> ""
+      then
+        set_selection elt
+      else
+        try
+          (match elt#get_parentNode with
+          | None -> assert false
+          | Some p -> aux (new Gdome.element_of_node p))
+        with GdomeInit.DOMCastException _ -> ()
+    in
+    (match gdome_elt with
+    | Some elt when (elt#getAttributeNS ~namespaceURI:DomMisc.xlink_ns
+        ~localName:href_ds)#to_string <> "" ->
+          set_selection elt
+    | Some elt -> aux elt
+    | None -> self#set_selection None);
+    selection_changed <- true
+
+  method update_font_size = self#set_font_size !current_font_size
+
+  method private get_term_by_id context cic_info id =
+    let ids_to_terms, ids_to_hypotheses, _, _, _ = cic_info in
+    try
+      `Term (Hashtbl.find ids_to_terms id)
+    with Not_found ->
+      try
+        let hyp = Hashtbl.find ids_to_hypotheses id in
+        let context' = MatitaMisc.list_tl_at hyp context in
+        `Hyp context'
+      with Not_found -> assert false
+    
+  method private find_obj_conclusion id =
+    match self#cic_info with
+    | None
+    | Some (_, _, _, _, None) -> assert false
+    | Some (ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
+        let id =
+         find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
+        in
+         (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
 
-    val mutable href_callback: (string -> unit) option = None
-    method set_href_callback f = href_callback <- f
+  method private string_of_node node =
+    if node#hasAttributeNS ~namespaceURI:DomMisc.xlink_ns ~localName:href_ds
+    then string_of_dom_node node
+    else self#string_of_id_node node
 
-    initializer
-      ignore (self#connect#selection_changed self#choose_selection);
-      ignore (self#connect#click (fun (gdome_elt, _, _, _) ->
-        match gdome_elt with
-        | Some elt  (* element is an hyperlink, use href_callback on it *)
-          when elt#hasAttributeNS ~namespaceURI:Misc.xlink_ns ~localName:href ->
-            (match href_callback with
-            | None -> ()
-            | Some f ->
-                let uri =
-                  elt#getAttributeNS ~namespaceURI:Misc.xlink_ns ~localName:href
-                in
-                f (uri#to_string))
-        | Some elt -> ignore (self#action_toggle elt)
-        | None -> ()))
-    method private choose_selection gdome_elt =
-      let rec aux elt =
-        if elt#hasAttributeNS ~namespaceURI:Misc.helm_ns ~localName:xref then
-          self#set_selection (Some elt)
-        else
-          try
-            (match elt#get_parentNode with
-            | None -> assert false
-            | Some p -> aux (new Gdome.element_of_node p))
-          with GdomeInit.DOMCastException _ -> ()
-(*             debug_print "trying to select above the document root" *)
+  method private string_of_id_node node =
+    let get_id (node: Gdome.element) =
+      let xref_attr =
+        node#getAttributeNS ~namespaceURI:DomMisc.helm_ns ~localName:xref_ds
       in
-      match gdome_elt with
-      | Some elt -> aux elt
-      | None   -> self#set_selection None
-  end
+      xref_attr#to_string
+    in
+    let id = get_id node in
+    let script = MatitaScript.instance () in
+    let metasenv = script#proofMetasenv in
+    let context = script#proofContext in
+    let metasenv, context, conclusion =
+      if script#onGoingProof () then
+        script#proofMetasenv, script#proofContext, script#proofConclusion
+      else
+        [], [],
+        let t = self#find_obj_conclusion id in
+        MatitaLog.debug (CicPp.ppterm t);
+        t
+    in
+(* TODO: code for patterns
+    let conclusion = (MatitaScript.instance ())#proofConclusion in
+    let conclusion_pattern =
+      ProofEngineHelpers.pattern_of ~term:conclusion cic_terms
+    in
+*)
+    let string_of_cic_sequent cic_sequent =
+      let acic_sequent, _, _, ids_to_inner_sorts, _ =
+        Cic2acic.asequent_of_sequent metasenv cic_sequent
+      in
+      let _, _, _, annterm = acic_sequent in
+      let ast, ids_to_uris =
+        CicNotationRew.ast_of_acic ids_to_inner_sorts annterm
+      in
+      let pped_ast = CicNotationRew.pp_ast ast in
+      let markup = CicNotationPres.render ids_to_uris pped_ast in
+      BoxPp.render_to_string text_width markup
+    in
+    let cic_info =
+      match self#cic_info with Some info -> info | None -> assert false
+    in
+    let cic_sequent =
+      match self#get_term_by_id context cic_info id with
+      | `Term t ->
+          let context' =
+            match
+              ProofEngineHelpers.locate_in_conjecture t
+                (~-1, context, conclusion)
+            with
+              [context,_] -> context
+            | _ -> assert false (* since it uses physical equality *)
+          in
+          ~-1, context', t
+      | `Hyp context -> ~-1, context, Cic.Rel 1
+    in
+    string_of_cic_sequent cic_sequent
+
+  method string_of_selections =
+    List.map self#string_of_node (List.rev self#get_selections)
+
+  method string_of_selection =
+    match self#get_selections with
+    | [] -> None
+    | node :: _ -> Some (self#string_of_node node)
+
+end
 
 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
   GtkBase.Widget.size_params
@@ -94,63 +351,47 @@ let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
         ~font_size:None ~log_verbosity:None))
     []
 
-class sequentViewer obj =
-  object(self)
-
-    inherit clickableMathView obj
+class cicMathView obj =
+object (self)
+  inherit clickableMathView obj
 
-    val mutable current_infos = None
+  val mutable current_mathml = None
 
-    method get_selected_terms =
-      let selections = self#get_selections in
-      list_map_fail
-        (fun node ->
-          let xpath =
-            ((node : Gdome.element)#getAttributeNS
-              ~namespaceURI:Misc.helm_ns
-              ~localName:(Gdome.domString "xref"))#to_string
-          in
-          if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
-          else
-            match current_infos with
-            | Some (ids_to_terms,_,_) ->
-                (try Hashtbl.find ids_to_terms xpath with _ -> raise Exit)
-            | None -> assert false) (* "ERROR: No current term!!!" *)
-        selections
-
-    method get_selected_hypotheses =
-      let selections = self#get_selections in
-      list_map_fail
-        (fun node ->
-          let xpath =
-            ((node : Gdome.element)#getAttributeNS
-              ~namespaceURI:Misc.helm_ns
-              ~localName:(Gdome.domString "xref"))#to_string
-          in
-          if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
-          else
-            match current_infos with
-            | Some (_,_,ids_to_hypotheses) ->
-                (try Hashtbl.find ids_to_hypotheses xpath with _ -> raise Exit)
-            | None -> assert false) (* "ERROR: No current term!!!" *)
-        selections
-  
   method load_sequent metasenv metano =
     let sequent = CicUtil.lookup_meta metano metasenv in
-    let (mathml,(_,(ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_))) =
+    let (mathml, (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ ))) =
       ApplyTransformation.mml_of_cic_sequent metasenv sequent
     in
-    current_infos <- Some (ids_to_terms, ids_to_father_ids, ids_to_hypotheses);
-(*
-    debug_print "load_sequent: dumping MathML to ./prova";
-    ignore (Misc.domImpl#saveDocumentToFile ~name:"./prova" ~doc:mathml ());
-*)
+    self#set_cic_info
+      (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, Hashtbl.create 1, None));
+    let name = "sequent_viewer.xml" in
+    MatitaLog.debug ("load_sequent: dumping MathML to ./" ^ name);
+    ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
     self#load_root ~root:mathml#get_documentElement
- end
 
-class sequentsViewer ~(notebook:GPack.notebook)
-  ~(sequentViewer:sequentViewer) ()
-=
+  method load_object obj =
+    let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
+    let (mathml,
+      (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
+    =
+      ApplyTransformation.mml_of_cic_object obj
+    in
+    self#set_cic_info
+      (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
+    (match current_mathml with
+    | Some current_mathml when use_diff ->
+        self#freeze;
+        XmlDiff.update_dom ~from:current_mathml mathml;
+        self#thaw
+    |  _ ->
+        let name = "cic_browser.xml" in
+        MatitaLog.debug ("cic_browser: dumping MathML to ./" ^ name);
+        ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
+        self#load_root ~root:mathml#get_documentElement;
+        current_mathml <- Some mathml);
+end
+
+class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
   object (self)
     inherit scriptAccessor
 
@@ -162,6 +403,21 @@ class sequentsViewer ~(notebook:GPack.notebook)
     val mutable _metasenv = []
     val mutable scrolledWin: GBin.scrolled_window option = None
       (* scrolled window to which the sequentViewer is currently attached *)
+    val logo = (GMisc.image
+      ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_medium.png") ()
+      :> GObj.widget)
+            
+    val logo_with_qed = (GMisc.image
+      ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_small.png") ()
+      :> GObj.widget)
+
+    method load_logo =
+     notebook#set_show_tabs false;
+     notebook#append_page logo
+
+    method load_logo_with_qed =
+     notebook#set_show_tabs false;
+     notebook#append_page logo_with_qed
 
     method private tab_label metano =
       (GMisc.label ~text:(sprintf "?%d" metano) ~show:true ())#coerce
@@ -170,22 +426,23 @@ class sequentsViewer ~(notebook:GPack.notebook)
       (match scrolledWin with
       | Some w ->
           (* removing page from the notebook will destroy all contained widget,
-          * we do not want the sequentViewer to be destroyed as well *)
-          w#remove sequentViewer#coerce;
+          * we do not want the cicMathView to be destroyed as well *)
+          w#remove cicMathView#coerce;
           scrolledWin <- None
       | None -> ());
-      for i = 1 to pages do notebook#remove_page 0 done;
+      (match switch_page_callback with
+      | Some id ->
+          GtkSignal.disconnect notebook#as_widget id;
+          switch_page_callback <- None
+      | None -> ());
+      for i = 0 to pages do notebook#remove_page 0 done; 
+      notebook#set_show_tabs true;
       pages <- 0;
       page2goal <- [];
       goal2page <- [];
       goal2win <- [];
-      _metasenv <- [];
+      _metasenv <- []; 
       self#script#setGoal ~-1;
-      (match switch_page_callback with
-      | Some id ->
-          GtkSignal.disconnect notebook#as_widget id;
-          switch_page_callback <- None
-      | None -> ())
 
     method load_sequents (status: ProofEngineTypes.status) =
       let ((_, metasenv, _, _), goal) = status in
@@ -195,14 +452,21 @@ class sequentsViewer ~(notebook:GPack.notebook)
       self#script#setGoal goal;
       let win metano =
         let w =
-          GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
+          GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
             ~shadow_type:`IN ~show:true ()
         in
         let reparent () =
           scrolledWin <- Some w;
-          match sequentViewer#misc#parent with
-          | None -> w#add sequentViewer#coerce
-          | Some _ -> sequentViewer#misc#reparent w#coerce
+          match cicMathView#misc#parent with
+          | None -> w#add cicMathView#coerce
+          | Some parent ->
+             let parent =
+              match cicMathView#misc#parent with
+                 None -> assert false
+               | Some p -> GContainer.cast_container p
+             in
+              parent#remove cicMathView#coerce;
+              w#add cicMathView#coerce
         in
         goal2win <- (metano, reparent) :: goal2win;
         w#coerce
@@ -226,10 +490,10 @@ class sequentsViewer ~(notebook:GPack.notebook)
           self#render_page ~page ~goal))
 
     method private render_page ~page ~goal =
-      sequentViewer#load_sequent _metasenv goal;
+      cicMathView#load_sequent _metasenv goal;
       try
         List.assoc goal goal2win ();
-        sequentViewer#set_selection None
+        cicMathView#set_selection None
       with Not_found -> assert false
 
     method goto_sequent goal =
@@ -257,11 +521,11 @@ type 'widget constructor =
   unit ->
     'widget
 
-let sequentViewer ?hadjustment ?vadjustment ?font_size ?log_verbosity =
+let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
   GtkBase.Widget.size_params
     ~cont:(OgtkMathViewProps.pack_return (fun p ->
       OgtkMathViewProps.set_params
-        (new sequentViewer (GtkMathViewProps.MathView_GMetaDOM.create p))
+        (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
         ~font_size ~log_verbosity))
     []
 
@@ -274,44 +538,87 @@ type term_source =
   | `String of string
   ]
 
-exception Browser_failure of string
-
-let cicBrowsers = ref []
-
-class type cicBrowser =
-object
-  method loadUri: string -> unit
-  method loadTerm: term_source -> unit
-end
-
-class cicBrowser_impl ~(history:string MatitaMisc.history) () =
+class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
+  ()
+=
   let term_RE = Pcre.regexp "^term:(.*)" in
+  let whelp_RE = Pcre.regexp "^\\s*whelp" in
+  let uri_RE =
+    Pcre.regexp
+      "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
+  in
+  let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
+  let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
   let trailing_slash_RE = Pcre.regexp "/$" in
-  let gui = MatitaGui.instance () in
-  let win = gui#newBrowserWin () in
+  let has_xpointer_RE = Pcre.regexp "#xpointer\\(\\d+/\\d+(/\\d+)?\\)$" in
+  let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
+  let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
+  let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
+  let gui = get_gui () in
+  let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
+  let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
+  let combo,_ = GEdit.combo_box_text ~strings:queries () in
+  let activate_combo_query input q =
+    let q' = String.lowercase q in
+    let rec aux i = function
+      | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
+      | h::_ when String.lowercase h = q' -> i
+      | _::tl -> aux (i+1) tl
+    in
+    combo#set_active (aux 0 queries);
+    win#queryInputText#set_text input
+  in
+  let set_whelp_query txt =
+    let query, arg = 
+      try
+        let q = Pcre.extract ~rex:whelp_query_RE txt in
+        q.(1), q.(2)
+      with Invalid_argument _ -> failwith "Malformed Whelp query"
+    in
+    activate_combo_query arg query
+  in
   let toplevel = win#toplevel in
-  let mathView = sequentViewer ~packing:win#scrolledBrowser#add () in
-  let fail msg =
-    ignore (MatitaGtkMisc.ask_confirmation ~gui:(MatitaGui.instance ())
-      ~title:"Cic browser" ~msg ~cancel:false ());
+  let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
+  let fail message = 
+    MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
+      ~parent:toplevel ()  
+  in
+  let tags =
+    [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
+      "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
   in
   let handle_error f =
     try
       f ()
-    with exn ->
-      fail (sprintf "Uncaught exception:\n%s" (Printexc.to_string exn))
+    with exn -> fail (MatitaExcPp.to_string exn)
   in
-  let handle_error' f = fun () -> handle_error f in  (* used in callbacks *)
+  let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
   object (self)
     inherit scriptAccessor
+    
+    (* Whelp bar queries *)
 
     initializer
-      ignore (win#browserUri#connect#activate (handle_error' (fun () ->
-        self#_loadUri win#browserUri#text)));
+      activate_combo_query "" "locate";
+      win#whelpBarComboVbox#add combo#coerce;
+      let start_query () = 
+        let query = String.lowercase (List.nth queries combo#active) in
+        let input = win#queryInputText#text in
+        let statement = "whelp " ^ query ^ " " ^ input ^ "." in
+        (MatitaScript.instance ())#advance ~statement ()
+      in
+      ignore(win#queryInputText#connect#activate ~callback:start_query);
+      ignore(combo#connect#changed ~callback:start_query);
+      win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
+      win#mathOrListNotebook#set_show_tabs false;
+      win#browserForwardButton#misc#set_sensitive false;
+      win#browserBackButton#misc#set_sensitive false;
+      ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
+        self#loadInput win#browserUri#entry#text)));
       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
-        self#_loadUri current_proof_uri)));
+        self#load (`About `Current_proof))));
       ignore (win#browserRefreshButton#connect#clicked
-        (handle_error' self#refresh));
+        (handle_error' (self#refresh ~force:true)));
       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
       ignore (win#browserForwardButton#connect#clicked
         (handle_error' self#forward));
@@ -323,160 +630,203 @@ class cicBrowser_impl ~(history:string MatitaMisc.history) () =
         then
           GMain.quit ();
         false));
+      ignore(win#whelpResultTreeview#connect#row_activated 
+        ~callback:(fun _ _ ->
+          handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
       mathView#set_href_callback (Some (fun uri ->
-        handle_error (fun () -> self#_loadUri uri)));
-      self#_loadUri ~add_to_history:false blank_uri;
-      toplevel#show ();
-
-    val mutable current_uri = ""
-    val mutable current_infos = None
-    val mutable current_mathml = None
-
+        handle_error (fun () ->
+          self#load (`Uri (UriManager.uri_of_string uri)))));
+      self#_load (`About `Blank);
+      toplevel#show ()
+
+    val mutable current_entry = `About `Blank 
+
+    val model =
+      new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
+
+    val mutable lastDir = ""  (* last loaded "directory" *)
+
+    method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
+
+    method private _getSelectedUri () =
+      match model#easy_selection () with
+      | [sel] when is_uri sel -> sel  (* absolute URI selected *)
+(*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
+      | [sel] -> lastDir ^ sel
+      | _ -> assert false
+
+    (** history RATIONALE 
+     *
+     * All operations about history are done using _historyFoo.
+     * Only toplevel functions (ATM load and loadInput) call _historyAdd.
+     *)
+          
+    method private _historyAdd item = 
+      history#add item;
+      win#browserBackButton#misc#set_sensitive true;
+      win#browserForwardButton#misc#set_sensitive false
+
+    method private _historyPrev () =
+      let item = history#previous in
+      if history#is_begin then win#browserBackButton#misc#set_sensitive false;
+      win#browserForwardButton#misc#set_sensitive true;
+      item
+    
+    method private _historyNext () =
+      let item = history#next in
+      if history#is_end then win#browserForwardButton#misc#set_sensitive false;
+      win#browserBackButton#misc#set_sensitive true;
+      item
+
+    (** notebook RATIONALE 
+     * 
+     * Use only these functions to switch between the tabs
+     *)
+    method private _showList = win#mathOrListNotebook#goto_page 1
+    method private _showMath = win#mathOrListNotebook#goto_page 0
+    
     method private back () =
       try
-        self#_loadUri ~add_to_history:false history#previous
+        self#_load (self#_historyPrev ())
       with MatitaMisc.History_failure -> ()
 
     method private forward () =
       try
-        self#_loadUri ~add_to_history:false history#next
+        self#_load (self#_historyNext ())
       with MatitaMisc.History_failure -> ()
 
       (* loads a uri which can be a cic uri or an about:* uri
       * @param uri string *)
-    method private _loadUri ?(add_to_history = true) uri =
+    method private _load ?(force=false) entry =
       try
-        if current_uri <> uri || uri = current_proof_uri then begin
-          (match uri with
-          | uri when uri = blank_uri -> self#blank ()
-          | uri when uri = current_proof_uri -> self#home ()
-          | uri when Pcre.pmatch ~rex:term_RE uri ->
-              self#loadTerm (`String (Pcre.extract ~rex:term_RE uri).(1))
-          | uri when Pcre.pmatch ~rex:trailing_slash_RE uri -> self#loadDir uri
-          | _ -> self#loadUriManagerUri (UriManager.uri_of_string uri));
-          self#setUri uri;
-          if add_to_history then history#add uri
+       if entry <> current_entry || entry = `About `Current_proof || force then
+        begin
+          (match entry with
+          | `About `Current_proof -> self#home ()
+          | `About `Blank -> self#blank ()
+          | `About `Us -> () (* TODO implement easter egg here :-] *)
+          | `Check term -> self#_loadCheck term
+          | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
+          | `Dir dir -> self#_loadDir dir
+          | `Uri uri -> self#_loadUriManagerUri uri
+          | `Whelp (query, results) -> 
+              set_whelp_query query;
+              self#_loadList (List.map (fun r -> "obj",
+                UriManager.string_of_uri r) results));
+          self#setEntry entry
         end
-      with
-      | UriManager.IllFormedUri _ -> fail (sprintf "invalid uri: %s" uri)
-      | CicEnvironment.Object_not_found _ ->
-          fail (sprintf "object not found: %s" uri)
-      | Browser_failure msg -> fail msg
-
-    method loadUri uri =
-      handle_error (fun () -> self#_loadUri ~add_to_history:true uri)
+      with exn -> fail (MatitaExcPp.to_string exn)
 
     method private blank () =
+      self#_showMath;
       mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
 
+    method private _loadCheck term =
+      failwith "not implemented _loadCheck";
+      self#_showMath
+
     method private home () =
-      if self#script#onGoingProof () then
-        let ((uri, metasenv, bo, ty), _) = self#script#proofStatus in
-        let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
-        let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
-        self#loadObj obj
-      else
-        self#blank ()
+      self#_showMath;
+      match self#script#status.proof_status with
+      | Proof  (uri, metasenv, bo, ty) ->
+          let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
+          let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
+          self#_loadObj obj
+      | Incomplete_proof ((uri, metasenv, bo, ty), _) -> 
+          let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
+          let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
+          self#_loadObj obj
+      | _ -> self#blank ()
 
       (** loads a cic uri from the environment
       * @param uri UriManager.uri *)
-    method private loadUriManagerUri uri =
+    method private _loadUriManagerUri uri =
       let uri = UriManager.strip_xpointer uri in
       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
-      self#loadObj obj
-
-    method private loadDir dir =
-      let mathml = MatitaMisc.empty_boxml () in
+      self#_loadObj obj
+      
+    method private _loadDir dir = 
       let content = Http_getter.ls dir in
-      let root = mathml#get_documentElement in
-      let new_box_elt name =
-        mathml#createElementNS ~namespaceURI:(Some Misc.boxml_ns)
-          ~qualifiedName:(Gdome.domString ("b:" ^ name))
-      in
-      let new_text content = mathml#createTextNode (Gdome.domString content) in
-      let b_v = new_box_elt "v" in
-      List.iter
-        (fun item ->
-          let b_text = new_box_elt "text" in
-          let uri, elt =
-            match item with
-            | Http_getter_types.Ls_section subdir ->
-                (dir ^ subdir ^ "/"), (new_text (subdir ^ "/"))
-            | Http_getter_types.Ls_object obj ->
-                (dir ^ obj.Http_getter_types.uri),
-                (new_text obj.Http_getter_types.uri)
-          in
-          b_text#setAttributeNS ~namespaceURI:(Some Misc.xlink_ns)
-            ~qualifiedName:(Gdome.domString "xlink:href")
-            ~value:(Gdome.domString uri);
-          ignore (b_v#appendChild ~newChild:(b_text :> Gdome.node));
-          ignore (b_text#appendChild ~newChild:(elt :> Gdome.node)))
-        content;
-      ignore (root#appendChild ~newChild:(b_v :> Gdome.node));
-(*       Misc.domImpl#saveDocumentToFile ~doc:mathml ~name:"pippo" (); *)
-      mathView#load_root ~root:root
-
-    method private setUri uri =
-        win#browserUri#set_text uri;
-        current_uri <- uri
-
-    method private loadObj obj =
-      let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
-      let (mathml, (_,(ids_to_terms, ids_to_father_ids, ids_to_conjectures,
-           ids_to_hypotheses,_,_))) =
-        ApplyTransformation.mml_of_cic_object obj
+      let l =
+        List.fast_sort
+          Pervasives.compare
+          (List.map
+            (function 
+              | Http_getter_types.Ls_section s -> "dir", s
+              | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
+            content)
       in
-      current_infos <- Some (ids_to_terms, ids_to_father_ids,
-        ids_to_conjectures, ids_to_hypotheses);
-      match current_mathml with
-      | Some current_mathml when use_diff ->
-          mathView#freeze;
-          XmlDiff.update_dom ~from:current_mathml mathml;
-          mathView#thaw
-      |  _ ->
-          mathView#load_root ~root:mathml#get_documentElement;
-          current_mathml <- Some mathml
-
-    method private _loadTerm s = failwith "not implemented _loadTerm"
-(* TODO  self#_loadTermAst (disambiguator#parserr#parseTerm (Stream.of_string s)) *)
-
-    method private _loadTermAst ast = failwith "not implemented _loadTermAst"
-(* TODO
-      let (_, metasenv, term, _) =
-        MatitaCicMisc.disambiguate ~disambiguator ~currentProof ast
-      in
-      self#_loadTermCic term metasenv
-*)
+      lastDir <- dir;
+      self#_loadList l
+
+    method private setEntry entry =
+      win#browserUri#entry#set_text (string_of_entry entry);
+      current_entry <- entry
+
+    method private _loadObj obj =
+      (* showMath must be done _before_ loading the document, since if the
+       * widget is not mapped (hidden by the notebook) the document is not
+       * rendered *)
+      self#_showMath;
+      mathView#load_object obj
 
     method private _loadTermCic term metasenv =
       let context = self#script#proofContext in
       let dummyno = CicMkImplicit.new_meta metasenv [] in
       let sequent = (dummyno, context, term) in
-      mathView#load_sequent (sequent :: metasenv) dummyno
+      mathView#load_sequent (sequent :: metasenv) dummyno;
+      self#_showMath
+
+    method private _loadList l =
+      model#list_store#clear ();
+      List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
+      self#_showList
+    
+    (** { public methods, all must call _load!! } *)
+      
+    method load entry =
+      handle_error (fun () -> self#_load entry; self#_historyAdd entry)
+
+    (**  this is what the browser does when you enter a string an hit enter *)
+    method loadInput txt =
+      let txt = MatitaMisc.trim_blanks txt in
+      let fix_uri txt =
+        UriManager.string_of_uri
+          (UriManager.strip_xpointer (UriManager.uri_of_string txt))
+      in
+      if is_whelp txt then begin
+        set_whelp_query txt;  
+        (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
+      end else begin
+        let entry =
+          match txt with
+          | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
+          | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
+          | txt ->
+              (try
+                entry_of_string txt
+              with Invalid_argument _ ->
+                command_error (sprintf "unsupported uri: %s" txt))
+        in
+        self#_load entry;
+        self#_historyAdd entry
+      end
 
-    method loadTerm (src:term_source) =
-      handle_error (fun () ->
-        (match src with
-        | `Ast ast -> self#_loadTermAst ast
-        | `Cic (cic, metasenv) -> self#_loadTermCic cic metasenv
-        | `String s -> self#_loadTerm s);
-        self#setUri "check")
+      (** {2 methods accessing underlying GtkMathView} *)
+
+    method updateFontSize = mathView#set_font_size !current_font_size
 
       (** {2 methods used by constructor only} *)
 
     method win = win
     method history = history
-    method currentUri = current_uri
-    method refresh () =
-      if current_uri = current_proof_uri then
-      self#_loadUri ~add_to_history:false current_proof_uri
+    method currentEntry = current_entry
+    method refresh ~force () = self#_load ~force current_entry
 
   end
-
-let sequentsViewer ~(notebook:GPack.notebook)
-  ~(sequentViewer:sequentViewer) ()
-=
-  new sequentsViewer ~notebook ~sequentViewer ()
+  
+let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
+  new sequentsViewer ~notebook ~cicMathView ()
 
 let cicBrowser () =
   let size = BuildTimeConf.browser_history_size in
@@ -485,29 +835,72 @@ let cicBrowser () =
     let win = browser#win in
     ignore (win#browserNewButton#connect#clicked (fun () ->
       let history =
-        new MatitaMisc.browser_history ~memento:history#save size ""
+        new MatitaMisc.browser_history ~memento:history#save size
+          (`About `Blank)
       in
       let newBrowser = aux history in
-      newBrowser#loadUri browser#currentUri));
+      newBrowser#load browser#currentEntry));
 (*
       (* attempt (failed) to close windows on CTRL-W ... *)
     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
 *)
     cicBrowsers := browser :: !cicBrowsers;
-    (browser :> cicBrowser)
+    (browser :> MatitaGuiTypes.cicBrowser)
   in
-  let history = new MatitaMisc.browser_history size blank_uri in
+  let history = new MatitaMisc.browser_history size (`About `Blank) in
   aux history
 
-let refresh_all_browsers () = List.iter (fun b -> b#refresh ()) !cicBrowsers
-
-let default_sequentViewer () = sequentViewer ~show:true ()
-let sequentViewer_instance = MatitaMisc.singleton default_sequentViewer
+let default_cicMathView () = cicMathView ~show:true ()
+let cicMathView_instance = MatitaMisc.singleton default_cicMathView
 
 let default_sequentsViewer () =
-  let gui = MatitaGui.instance () in
-  let sequentViewer = sequentViewer_instance () in
-  sequentsViewer ~notebook:gui#main#sequentsNotebook ~sequentViewer ()
+  let gui = get_gui () in
+  let cicMathView = cicMathView_instance () in
+  sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
 
+let mathViewer () = 
+  object(self)
+    method private get_browser reuse = 
+      if reuse then
+        (match !cicBrowsers with
+        | [] -> cicBrowser ()
+        | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
+      else
+        (cicBrowser ())
+          
+    method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
+      
+    method show_uri_list ?(reuse=false) ~entry l =
+      (self#get_browser reuse)#load entry
+  end
+
+let refresh_all_browsers () =
+ List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
+
+let update_font_sizes () =
+  List.iter (fun b -> b#updateFontSize) !cicBrowsers;
+  (cicMathView_instance ())#update_font_size
+
+let get_math_views () =
+  ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
+  :: (List.map (fun b -> b#mathView) !cicBrowsers)
+
+let get_selections () =
+  if (MatitaScript.instance ())#onGoingProof () then
+    let rec aux =
+      function
+      | [] -> None
+      | mv :: tl ->
+          (match mv#string_of_selections with
+          | [] -> aux tl
+          | sels -> Some sels)
+    in
+    aux (get_math_views ())
+  else
+    None
+
+let reset_selections () =
+  List.iter (fun mv -> mv#remove_selections) (get_math_views ())
+