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