]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMathView.ml
bugfixes:
[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:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_medium.png") ()
408       :> GObj.widget)
409             
410     val logo_with_qed = (GMisc.image
411       ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/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   object (self)
597     inherit scriptAccessor
598     
599     (* Whelp bar queries *)
600
601     initializer
602       activate_combo_query "" "locate";
603       win#whelpBarComboVbox#add combo#coerce;
604       let start_query () = 
605         let query = String.lowercase (List.nth queries combo#active) in
606         let input = win#queryInputText#text in
607         let statement = "whelp " ^ query ^ " " ^ input ^ "." in
608         (MatitaScript.instance ())#advance ~statement ()
609       in
610       ignore(win#queryInputText#connect#activate ~callback:start_query);
611       ignore(combo#connect#changed ~callback:start_query);
612       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
613       win#mathOrListNotebook#set_show_tabs false;
614       win#browserForwardButton#misc#set_sensitive false;
615       win#browserBackButton#misc#set_sensitive false;
616       ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
617         self#loadInput win#browserUri#entry#text)));
618       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
619         self#load (`About `Current_proof))));
620       ignore (win#browserRefreshButton#connect#clicked
621         (handle_error' (self#refresh ~force:true)));
622       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
623       ignore (win#browserForwardButton#connect#clicked
624         (handle_error' self#forward));
625       ignore (win#toplevel#event#connect#delete (fun _ ->
626         let my_id = Oo.id self in
627         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
628         if !cicBrowsers = [] &&
629           Helm_registry.get "matita.mode" = "cicbrowser"
630         then
631           GMain.quit ();
632         false));
633       ignore(win#whelpResultTreeview#connect#row_activated 
634         ~callback:(fun _ _ ->
635           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
636       mathView#set_href_callback (Some (fun uri ->
637         handle_error (fun () ->
638           self#load (`Uri (UriManager.uri_of_string uri)))));
639       self#_load (`About `Blank);
640       toplevel#show ()
641
642     val mutable current_entry = `About `Blank 
643
644     val model =
645       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
646
647     val mutable lastDir = ""  (* last loaded "directory" *)
648
649     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
650
651     method private _getSelectedUri () =
652       match model#easy_selection () with
653       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
654 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
655       | [sel] -> lastDir ^ sel
656       | _ -> assert false
657
658     (** history RATIONALE 
659      *
660      * All operations about history are done using _historyFoo.
661      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
662      *)
663           
664     method private _historyAdd item = 
665       history#add item;
666       win#browserBackButton#misc#set_sensitive true;
667       win#browserForwardButton#misc#set_sensitive false
668
669     method private _historyPrev () =
670       let item = history#previous in
671       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
672       win#browserForwardButton#misc#set_sensitive true;
673       item
674     
675     method private _historyNext () =
676       let item = history#next in
677       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
678       win#browserBackButton#misc#set_sensitive true;
679       item
680
681     (** notebook RATIONALE 
682      * 
683      * Use only these functions to switch between the tabs
684      *)
685     method private _showList = win#mathOrListNotebook#goto_page 1
686     method private _showMath = win#mathOrListNotebook#goto_page 0
687     
688     method private back () =
689       try
690         self#_load (self#_historyPrev ())
691       with MatitaMisc.History_failure -> ()
692
693     method private forward () =
694       try
695         self#_load (self#_historyNext ())
696       with MatitaMisc.History_failure -> ()
697
698       (* loads a uri which can be a cic uri or an about:* uri
699       * @param uri string *)
700     method private _load ?(force=false) entry =
701       try
702        if entry <> current_entry || entry = `About `Current_proof || force then
703         begin
704           (match entry with
705           | `About `Current_proof -> self#home ()
706           | `About `Blank -> self#blank ()
707           | `About `Us -> () (* TODO implement easter egg here :-] *)
708           | `Check term -> self#_loadCheck term
709           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
710           | `Dir dir -> self#_loadDir dir
711           | `Uri uri -> self#_loadUriManagerUri uri
712           | `Whelp (query, results) -> 
713               set_whelp_query query;
714               self#_loadList (List.map (fun r -> "obj",
715                 UriManager.string_of_uri r) results));
716           self#setEntry entry
717         end
718       with exn -> fail (MatitaExcPp.to_string exn)
719
720     method private blank () =
721       self#_showMath;
722       mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
723
724     method private _loadCheck term =
725       failwith "not implemented _loadCheck";
726       self#_showMath
727
728     method private home () =
729       self#_showMath;
730       match self#script#status.proof_status with
731       | Proof  (uri, metasenv, bo, ty) ->
732           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
733           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
734           self#_loadObj obj
735       | Incomplete_proof ((uri, metasenv, bo, ty), _) -> 
736           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
737           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
738           self#_loadObj obj
739       | _ -> self#blank ()
740
741       (** loads a cic uri from the environment
742       * @param uri UriManager.uri *)
743     method private _loadUriManagerUri uri =
744       let uri = UriManager.strip_xpointer uri in
745       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
746       self#_loadObj obj
747       
748     method private _loadDir dir = 
749       let content = Http_getter.ls dir in
750       let l =
751         List.fast_sort
752           Pervasives.compare
753           (List.map
754             (function 
755               | Http_getter_types.Ls_section s -> "dir", s
756               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
757             content)
758       in
759       lastDir <- dir;
760       self#_loadList l
761
762     method private setEntry entry =
763       win#browserUri#entry#set_text (string_of_entry entry);
764       current_entry <- entry
765
766     method private _loadObj obj =
767       (* showMath must be done _before_ loading the document, since if the
768        * widget is not mapped (hidden by the notebook) the document is not
769        * rendered *)
770       self#_showMath;
771       mathView#load_object obj
772
773     method private _loadTermCic term metasenv =
774       let context = self#script#proofContext in
775       let dummyno = CicMkImplicit.new_meta metasenv [] in
776       let sequent = (dummyno, context, term) in
777       mathView#load_sequent (sequent :: metasenv) dummyno;
778       self#_showMath
779
780     method private _loadList l =
781       model#list_store#clear ();
782       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
783       self#_showList
784     
785     (** { public methods, all must call _load!! } *)
786       
787     method load entry =
788       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
789
790     (**  this is what the browser does when you enter a string an hit enter *)
791     method loadInput txt =
792       let txt = MatitaMisc.trim_blanks txt in
793       let fix_uri txt =
794         UriManager.string_of_uri
795           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
796       in
797       if is_whelp txt then begin
798         set_whelp_query txt;  
799         (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
800       end else begin
801         let entry =
802           match txt with
803           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
804           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
805           | txt ->
806               (try
807                 entry_of_string txt
808               with Invalid_argument _ ->
809                 command_error (sprintf "unsupported uri: %s" txt))
810         in
811         self#_load entry;
812         self#_historyAdd entry
813       end
814
815       (** {2 methods accessing underlying GtkMathView} *)
816
817     method updateFontSize = mathView#set_font_size !current_font_size
818
819       (** {2 methods used by constructor only} *)
820
821     method win = win
822     method history = history
823     method currentEntry = current_entry
824     method refresh ~force () = self#_load ~force current_entry
825
826   end
827   
828 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
829   new sequentsViewer ~notebook ~cicMathView ()
830
831 let cicBrowser () =
832   let size = BuildTimeConf.browser_history_size in
833   let rec aux history =
834     let browser = new cicBrowser_impl ~history () in
835     let win = browser#win in
836     ignore (win#browserNewButton#connect#clicked (fun () ->
837       let history =
838         new MatitaMisc.browser_history ~memento:history#save size
839           (`About `Blank)
840       in
841       let newBrowser = aux history in
842       newBrowser#load browser#currentEntry));
843 (*
844       (* attempt (failed) to close windows on CTRL-W ... *)
845     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
846       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
847 *)
848     cicBrowsers := browser :: !cicBrowsers;
849     (browser :> MatitaGuiTypes.cicBrowser)
850   in
851   let history = new MatitaMisc.browser_history size (`About `Blank) in
852   aux history
853
854 let default_cicMathView () = cicMathView ~show:true ()
855 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
856
857 let default_sequentsViewer () =
858   let gui = get_gui () in
859   let cicMathView = cicMathView_instance () in
860   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
861 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
862
863 let mathViewer () = 
864   object(self)
865     method private get_browser reuse = 
866       if reuse then
867         (match !cicBrowsers with
868         | [] -> cicBrowser ()
869         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
870       else
871         (cicBrowser ())
872           
873     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
874       
875     method show_uri_list ?(reuse=false) ~entry l =
876       (self#get_browser reuse)#load entry
877   end
878
879 let refresh_all_browsers () =
880  List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
881
882 let update_font_sizes () =
883   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
884   (cicMathView_instance ())#update_font_size
885
886 let get_math_views () =
887   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
888   :: (List.map (fun b -> b#mathView) !cicBrowsers)
889
890 let get_selections () =
891   if (MatitaScript.instance ())#onGoingProof () then
892     let rec aux =
893       function
894       | [] -> None
895       | mv :: tl ->
896           (match mv#string_of_selections with
897           | [] -> aux tl
898           | sels -> Some sels)
899     in
900     aux (get_math_views ())
901   else
902     None
903
904 let reset_selections () =
905   List.iter (fun mv -> mv#remove_selections) (get_math_views ())
906