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