]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMathView.ml
moved matita logo in the right place
[helm.git] / helm / matita / matitaMathView.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 open Printf
27
28 open MatitaTypes
29 open MatitaGtkMisc
30
31 (** inherit from this class if you want to access current script *)
32 class scriptAccessor =
33 object (self)
34   method private script = MatitaScript.instance ()
35 end
36
37 let cicBrowsers = ref []
38 let gui_instance = ref None
39 let set_gui gui = gui_instance := Some gui
40 let get_gui () =
41   match !gui_instance with
42   | None -> assert false
43   | Some gui -> gui
44
45 let default_font_size () =
46   Helm_registry.get_opt_default Helm_registry.int
47     ~default:BuildTimeConf.default_font_size "matita.font_size"
48 let current_font_size = ref ~-1
49 let increase_font_size () = incr current_font_size
50 let decrease_font_size () = decr current_font_size
51 let reset_font_size () = current_font_size := default_font_size ()
52
53   (* is there any lablgtk2 constant corresponding to the various mouse
54    * buttons??? *)
55 let left_button = 1
56 let middle_button = 2
57 let right_button = 3
58
59 let near (x1, y1) (x2, y2) =
60   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
61   (distance < 4.)
62
63 let href_ds = Gdome.domString "href"
64 let xref_ds = Gdome.domString "xref"
65
66 (* ids_to_terms should not be passed here, is just for debugging *)
67 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
68   let find_parent id ids =
69     let rec aux id =
70 (*       (prerr_endline (sprintf "id %s = %s" id
71         (try
72           CicPp.ppterm (Hashtbl.find ids_to_terms id)
73         with Not_found -> "NONE"))); *)
74       if List.mem id ids then Some id
75       else
76         (match
77           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
78         with
79         | None -> None
80         | Some id' -> aux id')
81     in
82     aux id
83   in
84   let return_father id ids =
85     match find_parent id ids with
86     | None -> assert false
87     | Some parent_id -> parent_id
88   in
89   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
90   let inner_types =
91    Hashtbl.fold
92     (fun _ types acc ->
93       match types.Cic2acic.annexpected with
94          None -> types.Cic2acic.annsynthesized :: acc
95        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
96     ) ids_to_inner_types [] in
97   match annobj with
98   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
99   | Cic.AVariable (_, _, Some bo, ty, _, _)
100   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
101       return_father id (mk_ids (ty :: bo :: inner_types))
102   | Cic.AConstant (_, _, _, None, ty, _, _)
103   | Cic.AVariable (_, _, None, ty, _, _) ->
104       return_father id (mk_ids (ty::inner_types))
105   | Cic.AInductiveDefinition _ ->
106       assert false  (* TODO *)
107
108   (** @return string content of a dom node having a single text child node, e.g.
109    * <m:mi xlink:href="...">bool</m:mi> *)
110 let string_of_dom_node node =
111   match node#get_firstChild with
112   | None -> ""
113   | Some node ->
114       (try
115         let text = new Gdome.text_of_node node in
116         text#get_data#to_string
117       with GdomeInit.DOMCastException _ -> "")
118
119 class clickableMathView obj =
120 let text_width = 80 in
121 object (self)
122   inherit GMathViewAux.multi_selection_math_view obj
123
124   val mutable href_callback: (string -> unit) option = None
125   method set_href_callback f = href_callback <- f
126
127   val mutable _cic_info = None
128   method private set_cic_info info = _cic_info <- info
129   method private cic_info = _cic_info
130
131   initializer
132     self#set_font_size !current_font_size;
133     ignore (self#connect#selection_changed self#choose_selection_cb);
134     ignore (self#event#connect#button_press self#button_press_cb);
135     ignore (self#event#connect#button_release self#button_release_cb);
136     ignore (self#event#connect#selection_clear self#selection_clear_cb);
137     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
138
139   val mutable button_press_x = -1.
140   val mutable button_press_y = -1.
141   val mutable selection_changed = false
142
143   method private selection_get_cb ctxt ~info ~time =
144     (match self#get_selections with
145     | [] -> ()
146     | node :: _ -> ctxt#return (self#string_of_node node))
147
148   method private selection_clear_cb sel_event =
149     self#remove_selections;
150     false
151
152   method private button_press_cb gdk_button =
153     let button = GdkEvent.Button.button gdk_button in
154     if  button = left_button then begin
155       button_press_x <- GdkEvent.Button.x gdk_button;
156       button_press_y <- GdkEvent.Button.y gdk_button;
157       selection_changed <- false
158     end else if button = right_button then
159       self#popup_contextual_menu (GdkEvent.Button.time gdk_button);
160     false
161
162   method private popup_contextual_menu time =
163     match self#string_of_selection with
164     | None -> ()
165     | Some s ->
166         let clipboard = GData.clipboard Gdk.Atom.clipboard in
167         let menu = GMenu.menu () in
168         let copy_menu_item =
169           GMenu.image_menu_item
170             ~label:"_Copy" ~stock:`COPY ~packing:menu#append ()
171         in
172         connect_menu_item copy_menu_item (fun () -> clipboard#set_text s);
173         menu#popup ~button:right_button ~time
174
175   method private button_release_cb gdk_button =
176     let clipboard = GData.clipboard Gdk.Atom.primary in
177     if GdkEvent.Button.button gdk_button = left_button then begin
178       let button_release_x = GdkEvent.Button.x gdk_button in
179       let button_release_y = GdkEvent.Button.y gdk_button in
180       if selection_changed then
181         ()
182       else  (* selection _not_ changed *)
183         if near (button_press_x, button_press_y)
184           (button_release_x, button_release_y)
185         then
186           let x = int_of_float button_press_x in
187           let y = int_of_float button_press_y in
188           (match self#get_element_at x y with
189           | None -> ()
190           | Some elt ->
191               let namespaceURI = DomMisc.xlink_ns in
192               let localName = href_ds in
193               if elt#hasAttributeNS ~namespaceURI ~localName then
194                 self#invoke_href_callback
195                   (elt#getAttributeNS ~namespaceURI ~localName)#to_string
196                   gdk_button
197               else
198                 ignore (self#action_toggle elt));
199     end;
200     false
201
202   method private invoke_href_callback href_value gdk_button =
203     let button = GdkEvent.Button.button gdk_button in
204     if button = left_button then
205       let time = GdkEvent.Button.time gdk_button in
206       match href_callback with
207       | None -> ()
208       | Some f ->
209           (match MatitaMisc.split href_value with
210           | [ uri ] ->  f uri
211           | uris ->
212               let menu = GMenu.menu () in
213               List.iter
214                 (fun uri ->
215                   let menu_item =
216                     GMenu.menu_item ~label:uri ~packing:menu#append ()
217                   in
218                   connect_menu_item menu_item (fun () -> f uri))
219                 uris;
220               menu#popup ~button ~time)
221
222   method private choose_selection_cb gdome_elt =
223     let (gui: MatitaGuiTypes.gui) = get_gui () in
224     let clipboard = GData.clipboard Gdk.Atom.primary in
225     let set_selection elt =
226       self#set_selection (Some elt);
227       self#coerce#misc#add_selection_target
228         ~target:(Gdk.Atom.name Gdk.Atom.string) Gdk.Atom.primary;
229       ignore (self#coerce#misc#grab_selection Gdk.Atom.primary)
230     in
231     let rec aux elt =
232       if (elt#getAttributeNS ~namespaceURI:DomMisc.helm_ns
233             ~localName:xref_ds)#to_string <> ""
234       then
235         set_selection elt
236       else
237         try
238           (match elt#get_parentNode with
239           | None -> assert false
240           | Some p -> aux (new Gdome.element_of_node p))
241         with GdomeInit.DOMCastException _ -> ()
242     in
243     (match gdome_elt with
244     | Some elt when (elt#getAttributeNS ~namespaceURI:DomMisc.xlink_ns
245         ~localName:href_ds)#to_string <> "" ->
246           set_selection elt
247     | Some elt -> aux elt
248     | None -> self#set_selection None);
249     selection_changed <- true
250
251   method update_font_size = self#set_font_size !current_font_size
252
253   method private get_term_by_id context cic_info id =
254     let ids_to_terms, ids_to_hypotheses, _, _, _ = cic_info in
255     try
256       `Term (Hashtbl.find ids_to_terms id)
257     with Not_found ->
258       try
259         let hyp = Hashtbl.find ids_to_hypotheses id in
260         let context' = MatitaMisc.list_tl_at hyp context in
261         `Hyp context'
262       with Not_found -> assert false
263     
264   method private find_obj_conclusion id =
265     match self#cic_info with
266     | None
267     | Some (_, _, _, _, None) -> assert false
268     | Some (ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
269         let id =
270          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
271         in
272          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
273
274   method private string_of_node node =
275     if node#hasAttributeNS ~namespaceURI:DomMisc.xlink_ns ~localName:href_ds
276     then string_of_dom_node node
277     else self#string_of_id_node node
278
279   method private string_of_id_node node =
280     let get_id (node: Gdome.element) =
281       let xref_attr =
282         node#getAttributeNS ~namespaceURI:DomMisc.helm_ns ~localName:xref_ds
283       in
284       xref_attr#to_string
285     in
286     let id = get_id node in
287     let script = MatitaScript.instance () in
288     let metasenv = script#proofMetasenv in
289     let context = script#proofContext in
290     let metasenv, context, conclusion =
291       if script#onGoingProof () then
292         script#proofMetasenv, script#proofContext, script#proofConclusion
293       else
294         [], [],
295         let t = self#find_obj_conclusion id in
296         MatitaLog.debug (CicPp.ppterm t);
297         t
298     in
299 (* TODO: code for patterns
300     let conclusion = (MatitaScript.instance ())#proofConclusion in
301     let conclusion_pattern =
302       ProofEngineHelpers.pattern_of ~term:conclusion cic_terms
303     in
304 *)
305     let string_of_cic_sequent cic_sequent =
306       let acic_sequent, _, _, ids_to_inner_sorts, _ =
307         Cic2acic.asequent_of_sequent metasenv cic_sequent
308       in
309       let _, _, _, annterm = acic_sequent in
310       let ast, ids_to_uris =
311         CicNotationRew.ast_of_acic ids_to_inner_sorts annterm
312       in
313       let pped_ast = CicNotationRew.pp_ast ast in
314       let markup = CicNotationPres.render ids_to_uris pped_ast in
315       BoxPp.render_to_string text_width markup
316     in
317     let cic_info =
318       match self#cic_info with Some info -> info | None -> assert false
319     in
320     let cic_sequent =
321       match self#get_term_by_id context cic_info id with
322       | `Term t ->
323           let context' =
324             match
325               ProofEngineHelpers.locate_in_conjecture t
326                 (~-1, context, conclusion)
327             with
328               [context,_] -> context
329             | _ -> assert false (* since it uses physical equality *)
330           in
331           ~-1, context', t
332       | `Hyp context -> ~-1, context, Cic.Rel 1
333     in
334     string_of_cic_sequent cic_sequent
335
336   method string_of_selections =
337     List.map self#string_of_node (List.rev self#get_selections)
338
339   method string_of_selection =
340     match self#get_selections with
341     | [] -> None
342     | node :: _ -> Some (self#string_of_node node)
343
344 end
345
346 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
347   GtkBase.Widget.size_params
348     ~cont:(OgtkMathViewProps.pack_return (fun p ->
349       OgtkMathViewProps.set_params
350         (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
351         ~font_size:None ~log_verbosity:None))
352     []
353
354 class cicMathView obj =
355 object (self)
356   inherit clickableMathView obj
357
358   val mutable current_mathml = None
359
360   method load_sequent metasenv metano =
361     let sequent = CicUtil.lookup_meta metano metasenv in
362     let (mathml, (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ ))) =
363       ApplyTransformation.mml_of_cic_sequent metasenv sequent
364     in
365     self#set_cic_info
366       (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, Hashtbl.create 1, None));
367     let name = "sequent_viewer.xml" in
368     MatitaLog.debug ("load_sequent: dumping MathML to ./" ^ name);
369     ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
370     self#load_root ~root:mathml#get_documentElement
371
372   method load_object obj =
373     let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
374     let (mathml,
375       (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
376     =
377       ApplyTransformation.mml_of_cic_object obj
378     in
379     self#set_cic_info
380       (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
381     (match current_mathml with
382     | Some current_mathml when use_diff ->
383         self#freeze;
384         XmlDiff.update_dom ~from:current_mathml mathml;
385         self#thaw
386     |  _ ->
387         let name = "cic_browser.xml" in
388         MatitaLog.debug ("cic_browser: dumping MathML to ./" ^ name);
389         ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
390         self#load_root ~root:mathml#get_documentElement;
391         current_mathml <- Some mathml);
392 end
393
394 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
395   object (self)
396     inherit scriptAccessor
397
398     val mutable pages = 0
399     val mutable switch_page_callback = None
400     val mutable page2goal = []  (* associative list: page no -> goal no *)
401     val mutable goal2page = []  (* the other way round *)
402     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
403     val mutable _metasenv = []
404     val mutable scrolledWin: GBin.scrolled_window option = None
405       (* scrolled window to which the sequentViewer is currently attached *)
406     val logo = (GMisc.image
407       ~file:(MatitaMisc.image_path "matita_medium.png") ()
408       :> GObj.widget)
409             
410     val logo_with_qed = (GMisc.image
411       ~file:(MatitaMisc.image_path "matita_small.png") ()
412       :> GObj.widget)
413
414     method load_logo =
415      notebook#set_show_tabs false;
416      notebook#append_page logo
417
418     method load_logo_with_qed =
419      notebook#set_show_tabs false;
420      notebook#append_page logo_with_qed
421
422     method private tab_label metano =
423       (GMisc.label ~text:(sprintf "?%d" metano) ~show:true ())#coerce
424
425     method reset =
426       (match scrolledWin with
427       | Some w ->
428           (* removing page from the notebook will destroy all contained widget,
429           * we do not want the cicMathView to be destroyed as well *)
430           w#remove cicMathView#coerce;
431           scrolledWin <- None
432       | None -> ());
433       (match switch_page_callback with
434       | Some id ->
435           GtkSignal.disconnect notebook#as_widget id;
436           switch_page_callback <- None
437       | None -> ());
438       for i = 0 to pages do notebook#remove_page 0 done; 
439       notebook#set_show_tabs true;
440       pages <- 0;
441       page2goal <- [];
442       goal2page <- [];
443       goal2win <- [];
444       _metasenv <- []; 
445       self#script#setGoal ~-1;
446
447     method load_sequents (status: ProofEngineTypes.status) =
448       let ((_, metasenv, _, _), goal) = status in
449       let sequents_no = List.length metasenv in
450       _metasenv <- metasenv;
451       pages <- sequents_no;
452       self#script#setGoal goal;
453       let win metano =
454         let w =
455           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
456             ~shadow_type:`IN ~show:true ()
457         in
458         let reparent () =
459           scrolledWin <- Some w;
460           match cicMathView#misc#parent with
461           | None -> w#add cicMathView#coerce
462           | Some parent ->
463              let parent =
464               match cicMathView#misc#parent with
465                  None -> assert false
466                | Some p -> GContainer.cast_container p
467              in
468               parent#remove cicMathView#coerce;
469               w#add cicMathView#coerce
470         in
471         goal2win <- (metano, reparent) :: goal2win;
472         w#coerce
473       in
474       let page = ref 0 in
475       List.iter
476         (fun (metano, _, _) ->
477           page2goal <- (!page, metano) :: page2goal;
478           goal2page <- (metano, !page) :: goal2page;
479           incr page;
480           notebook#append_page ~tab_label:(self#tab_label metano) (win metano))
481         metasenv;
482       switch_page_callback <-
483         Some (notebook#connect#switch_page ~callback:(fun page ->
484           let goal =
485             try
486               List.assoc page page2goal
487             with Not_found -> assert false
488           in
489           self#script#setGoal goal;
490           self#render_page ~page ~goal))
491
492     method private render_page ~page ~goal =
493       cicMathView#load_sequent _metasenv goal;
494       try
495         List.assoc goal goal2win ();
496         cicMathView#set_selection None
497       with Not_found -> assert false
498
499     method goto_sequent goal =
500       let page =
501         try
502           List.assoc goal goal2page
503         with Not_found -> assert false
504       in
505       notebook#goto_page page;
506       self#render_page page goal
507
508   end
509
510  (** constructors *)
511
512 type 'widget constructor =
513   ?hadjustment:GData.adjustment ->
514   ?vadjustment:GData.adjustment ->
515   ?font_size:int ->
516   ?log_verbosity:int ->
517   ?width:int ->
518   ?height:int ->
519   ?packing:(GObj.widget -> unit) ->
520   ?show:bool ->
521   unit ->
522     'widget
523
524 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
525   GtkBase.Widget.size_params
526     ~cont:(OgtkMathViewProps.pack_return (fun p ->
527       OgtkMathViewProps.set_params
528         (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
529         ~font_size ~log_verbosity))
530     []
531
532 let blank_uri = BuildTimeConf.blank_uri
533 let current_proof_uri = BuildTimeConf.current_proof_uri
534
535 type term_source =
536   [ `Ast of DisambiguateTypes.term
537   | `Cic of Cic.term * Cic.metasenv
538   | `String of string
539   ]
540
541 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
542   ()
543 =
544   let term_RE = Pcre.regexp "^term:(.*)" in
545   let whelp_RE = Pcre.regexp "^\\s*whelp" in
546   let uri_RE =
547     Pcre.regexp
548       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
549   in
550   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
551   let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
552   let trailing_slash_RE = Pcre.regexp "/$" in
553   let has_xpointer_RE = Pcre.regexp "#xpointer\\(\\d+/\\d+(/\\d+)?\\)$" in
554   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
555   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
556   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
557   let gui = get_gui () in
558   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
559   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
560   let combo,_ = GEdit.combo_box_text ~strings:queries () in
561   let activate_combo_query input q =
562     let q' = String.lowercase q in
563     let rec aux i = function
564       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
565       | h::_ when String.lowercase h = q' -> i
566       | _::tl -> aux (i+1) tl
567     in
568     combo#set_active (aux 0 queries);
569     win#queryInputText#set_text input
570   in
571   let set_whelp_query txt =
572     let query, arg = 
573       try
574         let q = Pcre.extract ~rex:whelp_query_RE txt in
575         q.(1), q.(2)
576       with Invalid_argument _ -> failwith "Malformed Whelp query"
577     in
578     activate_combo_query arg query
579   in
580   let toplevel = win#toplevel in
581   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
582   let fail message = 
583     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
584       ~parent:toplevel ()  
585   in
586   let tags =
587     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
588       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
589   in
590   let handle_error f =
591     try
592       f ()
593     with exn -> fail (MatitaExcPp.to_string exn)
594   in
595   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
596   let load_easter_egg = lazy (
597     win#easterEggImage#set_file (MatitaMisc.image_path "meegg.png"))
598   in
599   object (self)
600     inherit scriptAccessor
601     
602     (* Whelp bar queries *)
603
604     initializer
605       activate_combo_query "" "locate";
606       win#whelpBarComboVbox#add combo#coerce;
607       let start_query () = 
608         let query = String.lowercase (List.nth queries combo#active) in
609         let input = win#queryInputText#text in
610         let statement = "whelp " ^ query ^ " " ^ input ^ "." in
611         (MatitaScript.instance ())#advance ~statement ()
612       in
613       ignore(win#queryInputText#connect#activate ~callback:start_query);
614       ignore(combo#connect#changed ~callback:start_query);
615       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
616       win#mathOrListNotebook#set_show_tabs false;
617       win#browserForwardButton#misc#set_sensitive false;
618       win#browserBackButton#misc#set_sensitive false;
619       ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
620         self#loadInput win#browserUri#entry#text)));
621       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
622         self#load (`About `Current_proof))));
623       ignore (win#browserRefreshButton#connect#clicked
624         (handle_error' (self#refresh ~force:true)));
625       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
626       ignore (win#browserForwardButton#connect#clicked
627         (handle_error' self#forward));
628       ignore (win#toplevel#event#connect#delete (fun _ ->
629         let my_id = Oo.id self in
630         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
631         if !cicBrowsers = [] &&
632           Helm_registry.get "matita.mode" = "cicbrowser"
633         then
634           GMain.quit ();
635         false));
636       ignore(win#whelpResultTreeview#connect#row_activated 
637         ~callback:(fun _ _ ->
638           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
639       mathView#set_href_callback (Some (fun uri ->
640         handle_error (fun () ->
641           self#load (`Uri (UriManager.uri_of_string uri)))));
642       self#_load (`About `Blank);
643       toplevel#show ()
644
645     val mutable current_entry = `About `Blank 
646
647     val model =
648       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
649
650     val mutable lastDir = ""  (* last loaded "directory" *)
651
652     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
653
654     method private _getSelectedUri () =
655       match model#easy_selection () with
656       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
657 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
658       | [sel] -> lastDir ^ sel
659       | _ -> assert false
660
661     (** history RATIONALE 
662      *
663      * All operations about history are done using _historyFoo.
664      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
665      *)
666           
667     method private _historyAdd item = 
668       history#add item;
669       win#browserBackButton#misc#set_sensitive true;
670       win#browserForwardButton#misc#set_sensitive false
671
672     method private _historyPrev () =
673       let item = history#previous in
674       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
675       win#browserForwardButton#misc#set_sensitive true;
676       item
677     
678     method private _historyNext () =
679       let item = history#next in
680       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
681       win#browserBackButton#misc#set_sensitive true;
682       item
683
684     (** notebook RATIONALE 
685      * 
686      * Use only these functions to switch between the tabs
687      *)
688     method private _showMath = win#mathOrListNotebook#goto_page 0
689     method private _showList = win#mathOrListNotebook#goto_page 1
690
691     method private back () =
692       try
693         self#_load (self#_historyPrev ())
694       with MatitaMisc.History_failure -> ()
695
696     method private forward () =
697       try
698         self#_load (self#_historyNext ())
699       with MatitaMisc.History_failure -> ()
700
701       (* loads a uri which can be a cic uri or an about:* uri
702       * @param uri string *)
703     method private _load ?(force=false) entry =
704       try
705        if entry <> current_entry || entry = `About `Current_proof || force then
706         begin
707           (match entry with
708           | `About `Current_proof -> self#home ()
709           | `About `Blank -> self#blank ()
710           | `About `Us -> self#egg ()
711           | `Check term -> self#_loadCheck term
712           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
713           | `Dir dir -> self#_loadDir dir
714           | `Uri uri -> self#_loadUriManagerUri uri
715           | `Whelp (query, results) -> 
716               set_whelp_query query;
717               self#_loadList (List.map (fun r -> "obj",
718                 UriManager.string_of_uri r) results));
719           self#setEntry entry
720         end
721       with exn -> fail (MatitaExcPp.to_string exn)
722
723     method private blank () =
724       self#_showMath;
725       mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
726
727     method private _loadCheck term =
728       failwith "not implemented _loadCheck";
729       self#_showMath
730
731     method private egg () =
732       win#mathOrListNotebook#goto_page 2;
733       Lazy.force load_easter_egg
734
735     method private home () =
736       self#_showMath;
737       match self#script#status.proof_status with
738       | Proof  (uri, metasenv, bo, ty) ->
739           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
740           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
741           self#_loadObj obj
742       | Incomplete_proof ((uri, metasenv, bo, ty), _) -> 
743           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
744           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
745           self#_loadObj obj
746       | _ -> self#blank ()
747
748       (** loads a cic uri from the environment
749       * @param uri UriManager.uri *)
750     method private _loadUriManagerUri uri =
751       let uri = UriManager.strip_xpointer uri in
752       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
753       self#_loadObj obj
754       
755     method private _loadDir dir = 
756       let content = Http_getter.ls dir in
757       let l =
758         List.fast_sort
759           Pervasives.compare
760           (List.map
761             (function 
762               | Http_getter_types.Ls_section s -> "dir", s
763               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
764             content)
765       in
766       lastDir <- dir;
767       self#_loadList l
768
769     method private setEntry entry =
770       win#browserUri#entry#set_text (string_of_entry entry);
771       current_entry <- entry
772
773     method private _loadObj obj =
774       (* showMath must be done _before_ loading the document, since if the
775        * widget is not mapped (hidden by the notebook) the document is not
776        * rendered *)
777       self#_showMath;
778       mathView#load_object obj
779
780     method private _loadTermCic term metasenv =
781       let context = self#script#proofContext in
782       let dummyno = CicMkImplicit.new_meta metasenv [] in
783       let sequent = (dummyno, context, term) in
784       mathView#load_sequent (sequent :: metasenv) dummyno;
785       self#_showMath
786
787     method private _loadList l =
788       model#list_store#clear ();
789       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
790       self#_showList
791     
792     (** { public methods, all must call _load!! } *)
793       
794     method load entry =
795       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
796
797     (**  this is what the browser does when you enter a string an hit enter *)
798     method loadInput txt =
799       let txt = MatitaMisc.trim_blanks txt in
800       let fix_uri txt =
801         UriManager.string_of_uri
802           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
803       in
804       if is_whelp txt then begin
805         set_whelp_query txt;  
806         (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
807       end else begin
808         let entry =
809           match txt with
810           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
811           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
812           | txt ->
813               (try
814                 entry_of_string txt
815               with Invalid_argument _ ->
816                 command_error (sprintf "unsupported uri: %s" txt))
817         in
818         self#_load entry;
819         self#_historyAdd entry
820       end
821
822       (** {2 methods accessing underlying GtkMathView} *)
823
824     method updateFontSize = mathView#set_font_size !current_font_size
825
826       (** {2 methods used by constructor only} *)
827
828     method win = win
829     method history = history
830     method currentEntry = current_entry
831     method refresh ~force () = self#_load ~force current_entry
832
833   end
834   
835 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
836   new sequentsViewer ~notebook ~cicMathView ()
837
838 let cicBrowser () =
839   let size = BuildTimeConf.browser_history_size in
840   let rec aux history =
841     let browser = new cicBrowser_impl ~history () in
842     let win = browser#win in
843     ignore (win#browserNewButton#connect#clicked (fun () ->
844       let history =
845         new MatitaMisc.browser_history ~memento:history#save size
846           (`About `Blank)
847       in
848       let newBrowser = aux history in
849       newBrowser#load browser#currentEntry));
850 (*
851       (* attempt (failed) to close windows on CTRL-W ... *)
852     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
853       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
854 *)
855     cicBrowsers := browser :: !cicBrowsers;
856     (browser :> MatitaGuiTypes.cicBrowser)
857   in
858   let history = new MatitaMisc.browser_history size (`About `Blank) in
859   aux history
860
861 let default_cicMathView () = cicMathView ~show:true ()
862 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
863
864 let default_sequentsViewer () =
865   let gui = get_gui () in
866   let cicMathView = cicMathView_instance () in
867   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
868 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
869
870 let mathViewer () = 
871   object(self)
872     method private get_browser reuse = 
873       if reuse then
874         (match !cicBrowsers with
875         | [] -> cicBrowser ()
876         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
877       else
878         (cicBrowser ())
879           
880     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
881       
882     method show_uri_list ?(reuse=false) ~entry l =
883       (self#get_browser reuse)#load entry
884   end
885
886 let refresh_all_browsers () =
887  List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
888
889 let update_font_sizes () =
890   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
891   (cicMathView_instance ())#update_font_size
892
893 let get_math_views () =
894   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
895   :: (List.map (fun b -> b#mathView) !cicBrowsers)
896
897 let get_selections () =
898   if (MatitaScript.instance ())#onGoingProof () then
899     let rec aux =
900       function
901       | [] -> None
902       | mv :: tl ->
903           (match mv#string_of_selections with
904           | [] -> aux tl
905           | sels -> Some sels)
906     in
907     aux (get_math_views ())
908   else
909     None
910
911 let reset_selections () =
912   List.iter (fun mv -> mv#remove_selections) (get_math_views ())
913