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