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