]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/matita/matitaMathView.ml
ocaml 3.09 transition
[helm.git] / helm / matita / matitaMathView.ml
index 47f8c5a5c13d33320deb010b7a81df0187d6d285..710efdf021a118aada8820ede5c009b242a11495 100644 (file)
@@ -28,10 +28,12 @@ open Printf
 open MatitaTypes
 open MatitaGtkMisc
 
+module Stack = Continuationals.Stack
+
 (** inherit from this class if you want to access current script *)
 class scriptAccessor =
 object (self)
-  method private script = MatitaScript.instance ()
+  method private script = MatitaScript.current ()
 end
 
 let cicBrowsers = ref []
@@ -60,9 +62,27 @@ let near (x1, y1) (x2, y2) =
   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
   (distance < 4.)
 
+let xlink_ns = Gdome.domString "http://www.w3.org/1999/xlink"
+let helm_ns = Gdome.domString "http://www.cs.unibo.it/helm"
 let href_ds = Gdome.domString "href"
 let xref_ds = Gdome.domString "xref"
 
+let domImpl = Gdome.domImplementation ()
+
+  (** Gdome.element of a MathML document whose rendering should be blank. Used
+  * by cicBrowser to render "about:blank" document *)
+let empty_mathml = lazy (
+  domImpl#createDocument ~namespaceURI:(Some DomMisc.mathml_ns)
+    ~qualifiedName:(Gdome.domString "math") ~doctype:None)
+
+let empty_boxml = lazy (
+  domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns) 
+    ~qualifiedName:(Gdome.domString "box") ~doctype:None)
+
+  (** shown for goals closed by side effects *)
+let closed_goal_mathml = lazy (
+  domImpl#createDocumentFromURI ~uri:BuildTimeConf.closed_xml ())
+
 (* 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 =
@@ -188,11 +208,11 @@ object (self)
           (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
+              if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
                 self#invoke_href_callback
-                  (elt#getAttributeNS ~namespaceURI ~localName)#to_string
+                  (elt#getAttributeNS ~namespaceURI:xlink_ns
+                    ~localName)#to_string
                   gdk_button
               else
                 ignore (self#action_toggle elt));
@@ -206,7 +226,7 @@ object (self)
       match href_callback with
       | None -> ()
       | Some f ->
-          (match MatitaMisc.split href_value with
+          (match HExtlib.split href_value with
           | [ uri ] ->  f uri
           | uris ->
               let menu = GMenu.menu () in
@@ -229,7 +249,7 @@ object (self)
       ignore (self#coerce#misc#grab_selection Gdk.Atom.primary)
     in
     let rec aux elt =
-      if (elt#getAttributeNS ~namespaceURI:DomMisc.helm_ns
+      if (elt#getAttributeNS ~namespaceURI:helm_ns
             ~localName:xref_ds)#to_string <> ""
       then
         set_selection elt
@@ -241,7 +261,7 @@ object (self)
         with GdomeInit.DOMCastException _ -> ()
     in
     (match gdome_elt with
-    | Some elt when (elt#getAttributeNS ~namespaceURI:DomMisc.xlink_ns
+    | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
         ~localName:href_ds)#to_string <> "" ->
           set_selection elt
     | Some elt -> aux elt
@@ -250,13 +270,18 @@ object (self)
 
   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
+  method private get_term_by_id cic_info id =
+    let unsh_item, 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, _ =
+          match unsh_item with
+          | Some seq -> seq
+          | None -> assert false
+        in
         let context' = MatitaMisc.list_tl_at hyp context in
         `Hyp context'
       with Not_found -> assert false
@@ -264,37 +289,32 @@ object (self)
   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) ->
+    | 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)
 
   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
+    if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
+    then self#string_of_id_node node
+    else string_of_dom_node node
 
   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
+        node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
       in
-      xref_attr#to_string
+      List.hd (HExtlib.split ~sep:' ' 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 =
+    let script = MatitaScript.current () in
+    let metasenv =
       if script#onGoingProof () then
-        script#proofMetasenv, script#proofContext, script#proofConclusion
+        script#proofMetasenv
       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
@@ -303,7 +323,7 @@ object (self)
     in
 *)
     let string_of_cic_sequent cic_sequent =
-      let acic_sequent, _, _, ids_to_inner_sorts, _ =
+      let _, (acic_sequent, _, _, ids_to_inner_sorts, _) =
         Cic2acic.asequent_of_sequent metasenv cic_sequent
       in
       let _, _, _, annterm = acic_sequent in
@@ -314,19 +334,27 @@ object (self)
       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
+    let cic_info, unsh_sequent =
+      match self#cic_info with
+      | Some ((Some unsh_sequent, _, _, _, _, _) as info) ->
+          info, unsh_sequent
+      | Some ((None, _, _, _, _, _) as info) ->
+          (* building a dummy sequent for obj *)
+          let t = self#find_obj_conclusion id in
+          MatitaLog.debug (CicPp.ppterm t);
+          info, (~-1, [], t)
+      | None -> assert false
     in
     let cic_sequent =
-      match self#get_term_by_id context cic_info id with
+      match self#get_term_by_id cic_info id with
       | `Term t ->
           let context' =
-            match
-              ProofEngineHelpers.locate_in_conjecture t
-                (~-1, context, conclusion)
-            with
+            match ProofEngineHelpers.locate_in_conjecture t unsh_sequent with
               [context,_] -> context
-            | _ -> assert false (* since it uses physical equality *)
+            | _ ->
+(*                 prerr_endline (sprintf "%d\nt=%s\ncontext=%s"
+                  (List.length l) (CicPp.ppterm t) (CicPp.ppcontext context)); *)
+                assert false (* since it uses physical equality *)
           in
           ~-1, context', t
       | `Hyp context -> ~-1, context, Cic.Rel 1
@@ -359,14 +387,18 @@ object (self)
 
   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, unsh_sequent,
+      (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ )))
+    =
       ApplyTransformation.mml_of_cic_sequent metasenv sequent
     in
     self#set_cic_info
-      (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, Hashtbl.create 1, None));
+      (Some (Some unsh_sequent,
+        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 ());
+    ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ());
     self#load_root ~root:mathml#get_documentElement
 
   method load_object obj =
@@ -377,7 +409,7 @@ object (self)
       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));
+      (Some (None, 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;
@@ -386,11 +418,24 @@ object (self)
     |  _ ->
         let name = "cic_browser.xml" in
         MatitaLog.debug ("cic_browser: dumping MathML to ./" ^ name);
-        ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
+        ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ());
         self#load_root ~root:mathml#get_documentElement;
         current_mathml <- Some mathml);
 end
 
+let tab_label meta_markup =
+  let rec aux =
+    function
+    | `Current m -> sprintf "<b>%s</b>" (aux m)
+    | `Closed m -> sprintf "<s>%s</s>" (aux m)
+    | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
+    | `Meta n -> sprintf "?%d" n
+  in
+  let markup = aux meta_markup in
+  (GMisc.label ~markup ~show:true ())#coerce
+
+let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
+
 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
   object (self)
     inherit scriptAccessor
@@ -404,11 +449,11 @@ class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
     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") ()
+      ~file:(MatitaMisc.image_path "matita_medium.png") ()
       :> GObj.widget)
             
     val logo_with_qed = (GMisc.image
-      ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_small.png") ()
+      ~file:(MatitaMisc.image_path "matita_small.png") ()
       :> GObj.widget)
 
     method load_logo =
@@ -419,9 +464,6 @@ class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
      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
-
     method reset =
       (match scrolledWin with
       | Some w ->
@@ -430,27 +472,25 @@ class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
           w#remove cicMathView#coerce;
           scrolledWin <- None
       | None -> ());
-      for i = 0 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
+    method load_sequents { proof = (_,metasenv,_,_) as proof; stack = stack } =
       let sequents_no = List.length metasenv in
       _metasenv <- metasenv;
-      pages <- sequents_no;
-      self#script#setGoal goal;
-      let win metano =
+      pages <- 0;
+      let win goal_switch =
         let w =
           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
             ~shadow_type:`IN ~show:true ()
@@ -468,42 +508,82 @@ class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
               parent#remove cicMathView#coerce;
               w#add cicMathView#coerce
         in
-        goal2win <- (metano, reparent) :: goal2win;
+        goal2win <- (goal_switch, reparent) :: goal2win;
         w#coerce
       in
+      assert (
+        let stack_goals = Stack.open_goals stack in
+        let proof_goals = ProofEngineTypes.goals_of_proof proof in
+        if
+          HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
+          <> List.sort Pervasives.compare proof_goals
+        then begin
+          prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
+          prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
+          false
+        end
+        else true
+      );
+      let render_switch =
+        function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
+      in
       let page = ref 0 in
-      List.iter
-        (fun (metano, _, _) ->
-          page2goal <- (!page, metano) :: page2goal;
-          goal2page <- (metano, !page) :: goal2page;
+      let added_goals = ref [] in
+        (* goals can be duplicated on the tack due to focus, but we should avoid
+         * multiple labels in the user interface *)
+      let add_tab markup goal_switch =
+        let goal = Stack.goal_of_switch goal_switch in
+        if not (List.mem goal !added_goals) then begin
+          notebook#append_page ~tab_label:(tab_label markup) (win goal_switch);
+          page2goal <- (!page, goal_switch) :: page2goal;
+          goal2page <- (goal_switch, !page) :: goal2page;
           incr page;
-          notebook#append_page ~tab_label:(self#tab_label metano) (win metano))
-        metasenv;
+          pages <- pages + 1;
+          added_goals := goal :: !added_goals
+        end
+      in
+      let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
+      Stack.iter  (** populate notebook with tabs *)
+        ~env:(fun depth tag (pos, sw) ->
+          let markup =
+            match depth, pos with
+            | 0, _ -> `Current (render_switch sw)
+            | 1, pos when Stack.head_tag stack = `BranchTag ->
+                `Shift (pos, render_switch sw)
+            | _ -> render_switch sw
+          in
+          add_tab markup sw)
+        ~cont:add_switch ~todo:add_switch
+        stack;
       switch_page_callback <-
         Some (notebook#connect#switch_page ~callback:(fun page ->
-          let goal =
-            try
-              List.assoc page page2goal
-            with Not_found -> assert false
+          let goal_switch =
+            try List.assoc page page2goal with Not_found -> assert false
           in
-          self#script#setGoal goal;
-          self#render_page ~page ~goal))
-
-    method private render_page ~page ~goal =
-      cicMathView#load_sequent _metasenv goal;
-      try
-        List.assoc goal goal2win ();
-        cicMathView#set_selection None
-      with Not_found -> assert false
+          self#script#setGoal (goal_of_switch goal_switch);
+          self#render_page ~page ~goal_switch))
+
+    method private render_page ~page ~goal_switch =
+      (match goal_switch with
+      | Stack.Open goal -> cicMathView#load_sequent _metasenv goal
+      | Stack.Closed goal ->
+          let doc = Lazy.force closed_goal_mathml in
+          cicMathView#load_root ~root:doc#get_documentElement);
+      (try
+        cicMathView#set_selection None;
+        List.assoc goal_switch goal2win ()
+      with Not_found -> assert false)
 
     method goto_sequent goal =
-      let page =
+      let goal_switch, page =
         try
-          List.assoc goal goal2page
+          List.find
+            (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
+            goal2page
         with Not_found -> assert false
       in
       notebook#goto_page page;
-      self#render_page page goal
+      self#render_page page goal_switch
 
   end
 
@@ -590,9 +670,15 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
   let handle_error f =
     try
       f ()
-    with exn -> fail (MatitaExcPp.to_string exn)
+    with exn ->
+      if not (Helm_registry.get_bool "matita.debug") then
+        fail (MatitaExcPp.to_string exn)
+      else raise exn
   in
   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
+  let load_easter_egg = lazy (
+    win#easterEggImage#set_file (MatitaMisc.image_path "meegg.png"))
+  in
   object (self)
     inherit scriptAccessor
     
@@ -605,7 +691,7 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
         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 ()
+        (MatitaScript.current ())#advance ~statement ()
       in
       ignore(win#queryInputText#connect#activate ~callback:start_query);
       ignore(combo#connect#changed ~callback:start_query);
@@ -682,9 +768,9 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
      * 
      * 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 _showList = win#mathOrListNotebook#goto_page 1
+
     method private back () =
       try
         self#_load (self#_historyPrev ())
@@ -698,13 +784,13 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
       (* loads a uri which can be a cic uri or an about:* uri
       * @param uri string *)
     method private _load ?(force=false) entry =
-      try
+      handle_error (fun () ->
        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 :-] *)
+          | `About `Us -> self#egg ()
           | `Check term -> self#_loadCheck term
           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
           | `Dir dir -> self#_loadDir dir
@@ -714,26 +800,29 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
               self#_loadList (List.map (fun r -> "obj",
                 UriManager.string_of_uri r) results));
           self#setEntry entry
-        end
-      with exn -> fail (MatitaExcPp.to_string exn)
+        end)
 
     method private blank () =
       self#_showMath;
-      mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
+      mathView#load_root (Lazy.force empty_mathml)#get_documentElement
 
     method private _loadCheck term =
       failwith "not implemented _loadCheck";
       self#_showMath
 
+    method private egg () =
+      win#mathOrListNotebook#goto_page 2;
+      Lazy.force load_easter_egg
+
     method private home () =
       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 name = UriManager.name_of_uri (HExtlib.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
+      | Incomplete_proof { proof = (uri, metasenv, bo, ty) } ->
+          let name = UriManager.name_of_uri (HExtlib.unopt uri) in
           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
           self#_loadObj obj
       | _ -> self#blank ()
@@ -789,14 +878,14 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
 
     (**  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 txt = HExtlib.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 ^ ".") ()
+        (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
       end else begin
         let entry =
           match txt with
@@ -825,7 +914,9 @@ class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
 
   end
   
-let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
+let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
+  MatitaGuiTypes.sequentsViewer
+=
   new sequentsViewer ~notebook ~cicMathView ()
 
 let cicBrowser () =
@@ -888,7 +979,7 @@ let get_math_views () =
   :: (List.map (fun b -> b#mathView) !cicBrowsers)
 
 let get_selections () =
-  if (MatitaScript.instance ())#onGoingProof () then
+  if (MatitaScript.current ())#onGoingProof () then
     let rec aux =
       function
       | [] -> None