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