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