]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMathView.ml
481b8fd6c8c58e8dd528810de2490bb5f09aa368
[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 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
523   ()
524 =
525   let term_RE = Pcre.regexp "^term:(.*)" in
526   let whelp_RE = Pcre.regexp "^\\s*whelp" in
527   let uri_RE =
528     Pcre.regexp
529       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
530   in
531   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
532   let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
533   let trailing_slash_RE = Pcre.regexp "/$" in
534   let has_xpointer_RE = Pcre.regexp "#xpointer\\(\\d+/\\d+(/\\d+)?\\)$" in
535   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
536   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
537   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
538   let gui = get_gui () in
539   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
540   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
541   let combo,_ = GEdit.combo_box_text ~strings:queries () in
542   let activate_combo_query input q =
543     let q' = String.lowercase q in
544     let rec aux i = function
545       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
546       | h::_ when String.lowercase h = q' -> i
547       | _::tl -> aux (i+1) tl
548     in
549     combo#set_active (aux 0 queries);
550     win#queryInputText#set_text input
551   in
552   let set_whelp_query txt =
553     let query, arg = 
554       try
555         let q = Pcre.extract ~rex:whelp_query_RE txt in
556         q.(1), q.(2)
557       with Invalid_argument _ -> failwith "Malformed Whelp query"
558     in
559     activate_combo_query arg query
560   in
561   let toplevel = win#toplevel in
562   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
563   let fail message = 
564     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
565       ~parent:toplevel ()  
566   in
567   let tags =
568     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
569       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
570   in
571   let handle_error f =
572     try
573       f ()
574     with exn -> fail (MatitaExcPp.to_string exn)
575   in
576   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
577   object (self)
578     inherit scriptAccessor
579     
580     (* Whelp bar queries *)
581
582     initializer
583       activate_combo_query "" "locate";
584       win#whelpBarComboVbox#add combo#coerce;
585       let start_query () = 
586         let query = String.lowercase (List.nth queries combo#active) in
587         let input = win#queryInputText#text in
588         let statement = "whelp " ^ query ^ " " ^ input ^ "." in
589         (MatitaScript.instance ())#advance ~statement ()
590       in
591       ignore(win#queryInputText#connect#activate ~callback:start_query);
592       ignore(combo#connect#changed ~callback:start_query);
593       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
594       win#mathOrListNotebook#set_show_tabs false;
595       win#browserForwardButton#misc#set_sensitive false;
596       win#browserBackButton#misc#set_sensitive false;
597       ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
598         self#loadInput win#browserUri#entry#text)));
599       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
600         self#load (`About `Current_proof))));
601       ignore (win#browserRefreshButton#connect#clicked
602         (handle_error' (self#refresh ~force:true)));
603       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
604       ignore (win#browserForwardButton#connect#clicked
605         (handle_error' self#forward));
606       ignore (win#toplevel#event#connect#delete (fun _ ->
607         let my_id = Oo.id self in
608         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
609         if !cicBrowsers = [] &&
610           Helm_registry.get "matita.mode" = "cicbrowser"
611         then
612           GMain.quit ();
613         false));
614       ignore(win#whelpResultTreeview#connect#row_activated 
615         ~callback:(fun _ _ ->
616           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
617       mathView#set_href_callback (Some (fun uri ->
618         handle_error (fun () ->
619           self#load (`Uri (UriManager.uri_of_string uri)))));
620       self#_load (`About `Blank);
621       toplevel#show ()
622
623     val mutable current_entry = `About `Blank 
624     val mutable current_infos = None
625
626     val model =
627       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
628
629     val mutable lastDir = ""  (* last loaded "directory" *)
630
631     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
632
633     method private _getSelectedUri () =
634       match model#easy_selection () with
635       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
636 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
637       | [sel] -> lastDir ^ sel
638       | _ -> assert false
639
640     (** history RATIONALE 
641      *
642      * All operations about history are done using _historyFoo.
643      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
644      *)
645           
646     method private _historyAdd item = 
647       history#add item;
648       win#browserBackButton#misc#set_sensitive true;
649       win#browserForwardButton#misc#set_sensitive false
650
651     method private _historyPrev () =
652       let item = history#previous in
653       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
654       win#browserForwardButton#misc#set_sensitive true;
655       item
656     
657     method private _historyNext () =
658       let item = history#next in
659       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
660       win#browserBackButton#misc#set_sensitive true;
661       item
662
663     (** notebook RATIONALE 
664      * 
665      * Use only these functions to switch between the tabs
666      *)
667     method private _showList = win#mathOrListNotebook#goto_page 1
668     method private _showMath = win#mathOrListNotebook#goto_page 0
669     
670     method private back () =
671       try
672         self#_load (self#_historyPrev ())
673       with MatitaMisc.History_failure -> ()
674
675     method private forward () =
676       try
677         self#_load (self#_historyNext ())
678       with MatitaMisc.History_failure -> ()
679
680       (* loads a uri which can be a cic uri or an about:* uri
681       * @param uri string *)
682     method private _load ?(force=false) entry =
683       try
684        if entry <> current_entry || entry = `About `Current_proof || force then
685         begin
686           (match entry with
687           | `About `Current_proof -> self#home ()
688           | `About `Blank -> self#blank ()
689           | `About `Us -> () (* TODO implement easter egg here :-] *)
690           | `Check term -> self#_loadCheck term
691           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
692           | `Dir dir -> self#_loadDir dir
693           | `Uri uri -> self#_loadUriManagerUri uri
694           | `Whelp (query, results) -> 
695               set_whelp_query query;
696               self#_loadList (List.map (fun r -> "obj",
697                 UriManager.string_of_uri r) results));
698           self#setEntry entry
699         end
700       with exn -> fail (MatitaExcPp.to_string exn)
701
702     method private blank () =
703       self#_showMath;
704       mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
705
706     method private _loadCheck term =
707       failwith "not implemented _loadCheck";
708       self#_showMath
709
710     method private home () =
711       self#_showMath;
712       match self#script#status.proof_status with
713       | Proof  (uri, metasenv, bo, ty) ->
714           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
715           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
716           self#_loadObj obj
717       | Incomplete_proof ((uri, metasenv, bo, ty), _) -> 
718           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
719           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
720           self#_loadObj obj
721       | _ -> self#blank ()
722
723       (** loads a cic uri from the environment
724       * @param uri UriManager.uri *)
725     method private _loadUriManagerUri uri =
726       let uri = UriManager.strip_xpointer uri in
727       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
728       self#_loadObj obj
729       
730     method private _loadDir dir = 
731       let content = Http_getter.ls dir in
732       let l =
733         List.fast_sort
734           Pervasives.compare
735           (List.map
736             (function 
737               | Http_getter_types.Ls_section s -> "dir", s
738               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
739             content)
740       in
741       lastDir <- dir;
742       self#_loadList l
743
744     method private setEntry entry =
745       win#browserUri#entry#set_text (string_of_entry entry);
746       current_entry <- entry
747
748     method private _loadObj obj =
749       (* showMath must be done _before_ loading the document, since if the
750        * widget is not mapped (hidden by the notebook) the document is not
751        * rendered *)
752       self#_showMath;
753       mathView#load_object obj
754
755     method private _loadTermCic term metasenv =
756       let context = self#script#proofContext in
757       let dummyno = CicMkImplicit.new_meta metasenv [] in
758       let sequent = (dummyno, context, term) in
759       mathView#load_sequent (sequent :: metasenv) dummyno;
760       self#_showMath
761
762     method private _loadList l =
763       model#list_store#clear ();
764       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
765       self#_showList
766     
767     (** { public methods, all must call _load!! } *)
768       
769     method load entry =
770       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
771
772     (**  this is what the browser does when you enter a string an hit enter *)
773     method loadInput txt =
774       let txt = strip_blanks txt in
775       let fix_uri txt =
776         UriManager.string_of_uri
777           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
778       in
779       if is_whelp txt then begin
780         set_whelp_query txt;  
781         (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
782       end else begin
783         let entry =
784           match txt with
785           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
786           | txt when is_dir txt -> `Dir (add_trailing_slash txt)
787           | txt ->
788               (try
789                 entry_of_string txt
790               with Invalid_argument _ ->
791                 command_error (sprintf "unsupported uri: %s" txt))
792         in
793         self#_load entry;
794         self#_historyAdd entry
795       end
796
797       (** {2 methods accessing underlying GtkMathView} *)
798
799     method updateFontSize = mathView#set_font_size !current_font_size
800
801       (** {2 methods used by constructor only} *)
802
803     method win = win
804     method history = history
805     method currentEntry = current_entry
806     method refresh ~force () = self#_load ~force current_entry
807
808   end
809   
810 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
811   new sequentsViewer ~notebook ~cicMathView ()
812
813 let cicBrowser () =
814   let size = BuildTimeConf.browser_history_size in
815   let rec aux history =
816     let browser = new cicBrowser_impl ~history () in
817     let win = browser#win in
818     ignore (win#browserNewButton#connect#clicked (fun () ->
819       let history =
820         new MatitaMisc.browser_history ~memento:history#save size
821           (`About `Blank)
822       in
823       let newBrowser = aux history in
824       newBrowser#load browser#currentEntry));
825 (*
826       (* attempt (failed) to close windows on CTRL-W ... *)
827     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
828       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
829 *)
830     cicBrowsers := browser :: !cicBrowsers;
831     (browser :> MatitaGuiTypes.cicBrowser)
832   in
833   let history = new MatitaMisc.browser_history size (`About `Blank) in
834   aux history
835
836 let default_cicMathView () = cicMathView ~show:true ()
837 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
838
839 let default_sequentsViewer () =
840   let gui = get_gui () in
841   let cicMathView = cicMathView_instance () in
842   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
843 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
844
845 let mathViewer () = 
846   object(self)
847     method private get_browser reuse = 
848       if reuse then
849         (match !cicBrowsers with
850         | [] -> cicBrowser ()
851         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
852       else
853         (cicBrowser ())
854           
855     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
856       
857     method show_uri_list ?(reuse=false) ~entry l =
858       (self#get_browser reuse)#load entry
859   end
860
861 let refresh_all_browsers () =
862  List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
863
864 let update_font_sizes () =
865   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
866   (cicMathView_instance ())#update_font_size
867
868 let get_math_views () =
869   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
870   :: (List.map (fun b -> b#mathView) !cicBrowsers)
871
872 let get_selections () =
873   if (MatitaScript.instance ())#onGoingProof () then
874     let rec aux =
875       function
876       | [] -> None
877       | mv :: tl ->
878           (match mv#string_of_selections with
879           | [] -> aux tl
880           | sels -> Some sels)
881     in
882     aux (get_math_views ())
883   else
884     None
885
886 let reset_selections () =
887   List.iter (fun mv -> mv#remove_selections) (get_math_views ())
888