]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMathView.ml
Bug fixed: the small logo was searched in the wrong path.
[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:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_medium.png") () :> GObj.widget)
402             
403     val logo_with_qed = (GMisc.image ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_small.png") () :> GObj.widget)
404
405     method load_logo =
406      notebook#set_show_tabs false;
407      notebook#append_page logo
408
409     method load_logo_with_qed =
410      notebook#set_show_tabs false;
411      notebook#append_page logo_with_qed
412
413     method private tab_label metano =
414       (GMisc.label ~text:(sprintf "?%d" metano) ~show:true ())#coerce
415
416     method reset =
417       (match scrolledWin with
418       | Some w ->
419           (* removing page from the notebook will destroy all contained widget,
420           * we do not want the cicMathView to be destroyed as well *)
421           w#remove cicMathView#coerce;
422           scrolledWin <- None
423       | None -> ());
424       for i = 0 to pages do notebook#remove_page 0 done;
425       notebook#set_show_tabs true;
426       pages <- 0;
427       page2goal <- [];
428       goal2page <- [];
429       goal2win <- [];
430       _metasenv <- [];
431       self#script#setGoal ~-1;
432       (match switch_page_callback with
433       | Some id ->
434           GtkSignal.disconnect notebook#as_widget id;
435           switch_page_callback <- None
436       | None -> ())
437
438     method load_sequents (status: ProofEngineTypes.status) =
439       let ((_, metasenv, _, _), goal) = status in
440       let sequents_no = List.length metasenv in
441       _metasenv <- metasenv;
442       pages <- sequents_no;
443       self#script#setGoal goal;
444       let win metano =
445         let w =
446           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
447             ~shadow_type:`IN ~show:true ()
448         in
449         let reparent () =
450           scrolledWin <- Some w;
451           match cicMathView#misc#parent with
452           | None -> w#add cicMathView#coerce
453           | Some parent ->
454              let parent =
455               match cicMathView#misc#parent with
456                  None -> assert false
457                | Some p -> GContainer.cast_container p
458              in
459               parent#remove cicMathView#coerce;
460               w#add cicMathView#coerce
461         in
462         goal2win <- (metano, reparent) :: goal2win;
463         w#coerce
464       in
465       let page = ref 0 in
466       List.iter
467         (fun (metano, _, _) ->
468           page2goal <- (!page, metano) :: page2goal;
469           goal2page <- (metano, !page) :: goal2page;
470           incr page;
471           notebook#append_page ~tab_label:(self#tab_label metano) (win metano))
472         metasenv;
473       switch_page_callback <-
474         Some (notebook#connect#switch_page ~callback:(fun page ->
475           let goal =
476             try
477               List.assoc page page2goal
478             with Not_found -> assert false
479           in
480           self#script#setGoal goal;
481           self#render_page ~page ~goal))
482
483     method private render_page ~page ~goal =
484       cicMathView#load_sequent _metasenv goal;
485       try
486         List.assoc goal goal2win ();
487         cicMathView#set_selection None
488       with Not_found -> assert false
489
490     method goto_sequent goal =
491       let page =
492         try
493           List.assoc goal goal2page
494         with Not_found -> assert false
495       in
496       notebook#goto_page page;
497       self#render_page page goal
498
499   end
500
501  (** constructors *)
502
503 type 'widget constructor =
504   ?hadjustment:GData.adjustment ->
505   ?vadjustment:GData.adjustment ->
506   ?font_size:int ->
507   ?log_verbosity:int ->
508   ?width:int ->
509   ?height:int ->
510   ?packing:(GObj.widget -> unit) ->
511   ?show:bool ->
512   unit ->
513     'widget
514
515 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
516   GtkBase.Widget.size_params
517     ~cont:(OgtkMathViewProps.pack_return (fun p ->
518       OgtkMathViewProps.set_params
519         (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
520         ~font_size ~log_verbosity))
521     []
522
523 let blank_uri = BuildTimeConf.blank_uri
524 let current_proof_uri = BuildTimeConf.current_proof_uri
525
526 type term_source =
527   [ `Ast of DisambiguateTypes.term
528   | `Cic of Cic.term * Cic.metasenv
529   | `String of string
530   ]
531
532 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
533   ()
534 =
535   let term_RE = Pcre.regexp "^term:(.*)" in
536   let whelp_RE = Pcre.regexp "^\\s*whelp" in
537   let uri_RE =
538     Pcre.regexp
539       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
540   in
541   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
542   let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
543   let trailing_slash_RE = Pcre.regexp "/$" in
544   let has_xpointer_RE = Pcre.regexp "#xpointer\\(\\d+/\\d+(/\\d+)?\\)$" in
545   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
546   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
547   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
548   let gui = get_gui () in
549   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
550   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
551   let combo,_ = GEdit.combo_box_text ~strings:queries () in
552   let activate_combo_query input q =
553     let q' = String.lowercase q in
554     let rec aux i = function
555       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
556       | h::_ when String.lowercase h = q' -> i
557       | _::tl -> aux (i+1) tl
558     in
559     combo#set_active (aux 0 queries);
560     win#queryInputText#set_text input
561   in
562   let set_whelp_query txt =
563     let query, arg = 
564       try
565         let q = Pcre.extract ~rex:whelp_query_RE txt in
566         q.(1), q.(2)
567       with Invalid_argument _ -> failwith "Malformed Whelp query"
568     in
569     activate_combo_query arg query
570   in
571   let toplevel = win#toplevel in
572   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
573   let fail message = 
574     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
575       ~parent:toplevel ()  
576   in
577   let tags =
578     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
579       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
580   in
581   let handle_error f =
582     try
583       f ()
584     with exn -> fail (MatitaExcPp.to_string exn)
585   in
586   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
587   object (self)
588     inherit scriptAccessor
589     
590     (* Whelp bar queries *)
591
592     initializer
593       activate_combo_query "" "locate";
594       win#whelpBarComboVbox#add combo#coerce;
595       let start_query () = 
596         let query = String.lowercase (List.nth queries combo#active) in
597         let input = win#queryInputText#text in
598         let statement = "whelp " ^ query ^ " " ^ input ^ "." in
599         (MatitaScript.instance ())#advance ~statement ()
600       in
601       ignore(win#queryInputText#connect#activate ~callback:start_query);
602       ignore(combo#connect#changed ~callback:start_query);
603       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
604       win#mathOrListNotebook#set_show_tabs false;
605       win#browserForwardButton#misc#set_sensitive false;
606       win#browserBackButton#misc#set_sensitive false;
607       ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
608         self#loadInput win#browserUri#entry#text)));
609       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
610         self#load (`About `Current_proof))));
611       ignore (win#browserRefreshButton#connect#clicked
612         (handle_error' (self#refresh ~force:true)));
613       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
614       ignore (win#browserForwardButton#connect#clicked
615         (handle_error' self#forward));
616       ignore (win#toplevel#event#connect#delete (fun _ ->
617         let my_id = Oo.id self in
618         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
619         if !cicBrowsers = [] &&
620           Helm_registry.get "matita.mode" = "cicbrowser"
621         then
622           GMain.quit ();
623         false));
624       ignore(win#whelpResultTreeview#connect#row_activated 
625         ~callback:(fun _ _ ->
626           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
627       mathView#set_href_callback (Some (fun uri ->
628         handle_error (fun () ->
629           self#load (`Uri (UriManager.uri_of_string uri)))));
630       self#_load (`About `Blank);
631       toplevel#show ()
632
633     val mutable current_entry = `About `Blank 
634
635     val model =
636       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
637
638     val mutable lastDir = ""  (* last loaded "directory" *)
639
640     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
641
642     method private _getSelectedUri () =
643       match model#easy_selection () with
644       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
645 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
646       | [sel] -> lastDir ^ sel
647       | _ -> assert false
648
649     (** history RATIONALE 
650      *
651      * All operations about history are done using _historyFoo.
652      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
653      *)
654           
655     method private _historyAdd item = 
656       history#add item;
657       win#browserBackButton#misc#set_sensitive true;
658       win#browserForwardButton#misc#set_sensitive false
659
660     method private _historyPrev () =
661       let item = history#previous in
662       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
663       win#browserForwardButton#misc#set_sensitive true;
664       item
665     
666     method private _historyNext () =
667       let item = history#next in
668       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
669       win#browserBackButton#misc#set_sensitive true;
670       item
671
672     (** notebook RATIONALE 
673      * 
674      * Use only these functions to switch between the tabs
675      *)
676     method private _showList = win#mathOrListNotebook#goto_page 1
677     method private _showMath = win#mathOrListNotebook#goto_page 0
678     
679     method private back () =
680       try
681         self#_load (self#_historyPrev ())
682       with MatitaMisc.History_failure -> ()
683
684     method private forward () =
685       try
686         self#_load (self#_historyNext ())
687       with MatitaMisc.History_failure -> ()
688
689       (* loads a uri which can be a cic uri or an about:* uri
690       * @param uri string *)
691     method private _load ?(force=false) entry =
692       try
693        if entry <> current_entry || entry = `About `Current_proof || force then
694         begin
695           (match entry with
696           | `About `Current_proof -> self#home ()
697           | `About `Blank -> self#blank ()
698           | `About `Us -> () (* TODO implement easter egg here :-] *)
699           | `Check term -> self#_loadCheck term
700           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
701           | `Dir dir -> self#_loadDir dir
702           | `Uri uri -> self#_loadUriManagerUri uri
703           | `Whelp (query, results) -> 
704               set_whelp_query query;
705               self#_loadList (List.map (fun r -> "obj",
706                 UriManager.string_of_uri r) results));
707           self#setEntry entry
708         end
709       with exn -> fail (MatitaExcPp.to_string exn)
710
711     method private blank () =
712       self#_showMath;
713       mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
714
715     method private _loadCheck term =
716       failwith "not implemented _loadCheck";
717       self#_showMath
718
719     method private home () =
720       self#_showMath;
721       match self#script#status.proof_status with
722       | Proof  (uri, metasenv, bo, ty) ->
723           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
724           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
725           self#_loadObj obj
726       | Incomplete_proof ((uri, metasenv, bo, ty), _) -> 
727           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
728           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
729           self#_loadObj obj
730       | _ -> self#blank ()
731
732       (** loads a cic uri from the environment
733       * @param uri UriManager.uri *)
734     method private _loadUriManagerUri uri =
735       let uri = UriManager.strip_xpointer uri in
736       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
737       self#_loadObj obj
738       
739     method private _loadDir dir = 
740       let content = Http_getter.ls dir in
741       let l =
742         List.fast_sort
743           Pervasives.compare
744           (List.map
745             (function 
746               | Http_getter_types.Ls_section s -> "dir", s
747               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
748             content)
749       in
750       lastDir <- dir;
751       self#_loadList l
752
753     method private setEntry entry =
754       win#browserUri#entry#set_text (string_of_entry entry);
755       current_entry <- entry
756
757     method private _loadObj obj =
758       (* showMath must be done _before_ loading the document, since if the
759        * widget is not mapped (hidden by the notebook) the document is not
760        * rendered *)
761       self#_showMath;
762       mathView#load_object obj
763
764     method private _loadTermCic term metasenv =
765       let context = self#script#proofContext in
766       let dummyno = CicMkImplicit.new_meta metasenv [] in
767       let sequent = (dummyno, context, term) in
768       mathView#load_sequent (sequent :: metasenv) dummyno;
769       self#_showMath
770
771     method private _loadList l =
772       model#list_store#clear ();
773       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
774       self#_showList
775     
776     (** { public methods, all must call _load!! } *)
777       
778     method load entry =
779       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
780
781     (**  this is what the browser does when you enter a string an hit enter *)
782     method loadInput txt =
783       let txt = strip_blanks txt in
784       let fix_uri txt =
785         UriManager.string_of_uri
786           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
787       in
788       if is_whelp txt then begin
789         set_whelp_query txt;  
790         (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
791       end else begin
792         let entry =
793           match txt with
794           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
795           | txt when is_dir txt -> `Dir (add_trailing_slash txt)
796           | txt ->
797               (try
798                 entry_of_string txt
799               with Invalid_argument _ ->
800                 command_error (sprintf "unsupported uri: %s" txt))
801         in
802         self#_load entry;
803         self#_historyAdd entry
804       end
805
806       (** {2 methods accessing underlying GtkMathView} *)
807
808     method updateFontSize = mathView#set_font_size !current_font_size
809
810       (** {2 methods used by constructor only} *)
811
812     method win = win
813     method history = history
814     method currentEntry = current_entry
815     method refresh ~force () = self#_load ~force current_entry
816
817   end
818   
819 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
820   new sequentsViewer ~notebook ~cicMathView ()
821
822 let cicBrowser () =
823   let size = BuildTimeConf.browser_history_size in
824   let rec aux history =
825     let browser = new cicBrowser_impl ~history () in
826     let win = browser#win in
827     ignore (win#browserNewButton#connect#clicked (fun () ->
828       let history =
829         new MatitaMisc.browser_history ~memento:history#save size
830           (`About `Blank)
831       in
832       let newBrowser = aux history in
833       newBrowser#load browser#currentEntry));
834 (*
835       (* attempt (failed) to close windows on CTRL-W ... *)
836     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
837       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
838 *)
839     cicBrowsers := browser :: !cicBrowsers;
840     (browser :> MatitaGuiTypes.cicBrowser)
841   in
842   let history = new MatitaMisc.browser_history size (`About `Blank) in
843   aux history
844
845 let default_cicMathView () = cicMathView ~show:true ()
846 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
847
848 let default_sequentsViewer () =
849   let gui = get_gui () in
850   let cicMathView = cicMathView_instance () in
851   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
852 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
853
854 let mathViewer () = 
855   object(self)
856     method private get_browser reuse = 
857       if reuse then
858         (match !cicBrowsers with
859         | [] -> cicBrowser ()
860         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
861       else
862         (cicBrowser ())
863           
864     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
865       
866     method show_uri_list ?(reuse=false) ~entry l =
867       (self#get_browser reuse)#load entry
868   end
869
870 let refresh_all_browsers () =
871  List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
872
873 let update_font_sizes () =
874   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
875   (cicMathView_instance ())#update_font_size
876
877 let get_math_views () =
878   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
879   :: (List.map (fun b -> b#mathView) !cicBrowsers)
880
881 let get_selections () =
882   if (MatitaScript.instance ())#onGoingProof () then
883     let rec aux =
884       function
885       | [] -> None
886       | mv :: tl ->
887           (match mv#string_of_selections with
888           | [] -> aux tl
889           | sels -> Some sels)
890     in
891     aux (get_math_views ())
892   else
893     None
894
895 let reset_selections () =
896   List.iter (fun mv -> mv#remove_selections) (get_math_views ())
897