]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMathView.ml
cosmetic changes
[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 (** inherit from this class if you want to access current script *)
32 class scriptAccessor =
33 object (self)
34   method private script = MatitaScript.instance ()
35 end
36
37 let cicBrowsers = ref []
38 let gui_instance = ref None
39 let set_gui gui = gui_instance := Some gui
40 let get_gui () =
41   match !gui_instance with
42   | None -> assert false
43   | Some gui -> gui
44
45 let default_font_size () =
46   Helm_registry.get_opt_default Helm_registry.int
47     ~default:BuildTimeConf.default_font_size "matita.font_size"
48 let current_font_size = ref ~-1
49 let increase_font_size () = incr current_font_size
50 let decrease_font_size () = decr current_font_size
51 let reset_font_size () = current_font_size := default_font_size ()
52
53   (* is there any lablgtk2 constant corresponding to the various mouse
54    * buttons??? *)
55 let left_button = 1
56 let middle_button = 2
57 let right_button = 3
58
59 let near (x1, y1) (x2, y2) =
60   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
61   (distance < 4.)
62
63 let href_ds = Gdome.domString "href"
64 let xref_ds = Gdome.domString "xref"
65
66 (* ids_to_terms should not be passed here, is just for debugging *)
67 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
68   let find_parent id ids =
69     let rec aux id =
70 (*       (prerr_endline (sprintf "id %s = %s" id
71         (try
72           CicPp.ppterm (Hashtbl.find ids_to_terms id)
73         with Not_found -> "NONE"))); *)
74       if List.mem id ids then Some id
75       else
76         (match
77           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
78         with
79         | None -> None
80         | Some id' -> aux id')
81     in
82     aux id
83   in
84   let return_father id ids =
85     match find_parent id ids with
86     | None -> assert false
87     | Some parent_id -> parent_id
88   in
89   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
90   let inner_types =
91    Hashtbl.fold
92     (fun _ types acc ->
93       match types.Cic2acic.annexpected with
94          None -> types.Cic2acic.annsynthesized :: acc
95        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
96     ) ids_to_inner_types [] in
97   match annobj with
98   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
99   | Cic.AVariable (_, _, Some bo, ty, _, _)
100   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
101       return_father id (mk_ids (ty :: bo :: inner_types))
102   | Cic.AConstant (_, _, _, None, ty, _, _)
103   | Cic.AVariable (_, _, None, ty, _, _) ->
104       return_father id (mk_ids (ty::inner_types))
105   | Cic.AInductiveDefinition _ ->
106       assert false  (* TODO *)
107
108 class clickableMathView obj =
109 let text_width = 80 in
110 object (self)
111   inherit GMathViewAux.multi_selection_math_view obj
112
113   val mutable href_callback: (string -> unit) option = None
114   method set_href_callback f = href_callback <- f
115
116   val mutable _cic_info = None
117   method private set_cic_info info = _cic_info <- info
118   method private cic_info = _cic_info
119
120   initializer
121     self#set_font_size !current_font_size;
122     ignore (self#connect#selection_changed self#choose_selection_cb);
123     ignore (self#event#connect#button_press self#button_press_cb);
124     ignore (self#event#connect#button_release self#button_release_cb);
125     ignore (self#event#connect#selection_clear self#selection_clear_cb);
126     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
127
128   val mutable button_press_x = -1.
129   val mutable button_press_y = -1.
130   val mutable selection_changed = false
131
132   method private selection_get_cb ctxt ~info ~time =
133     (match self#get_selections with
134     | [] -> ()
135     | node :: _ -> ctxt#return (self#string_of_node node))
136
137   method private selection_clear_cb sel_event =
138     self#remove_selections;
139     false
140
141   method private button_press_cb gdk_button =
142     let button = GdkEvent.Button.button gdk_button in
143     if  button = left_button then begin
144       button_press_x <- GdkEvent.Button.x gdk_button;
145       button_press_y <- GdkEvent.Button.y gdk_button;
146       selection_changed <- false
147     end else if button = right_button then
148       self#popup_contextual_menu (GdkEvent.Button.time gdk_button);
149     false
150
151   method private popup_contextual_menu time =
152     match self#string_of_selection with
153     | None -> ()
154     | Some s ->
155         let clipboard = GData.clipboard Gdk.Atom.clipboard in
156         let menu = GMenu.menu () in
157         let copy_menu_item =
158           GMenu.image_menu_item
159             ~label:"_Copy" ~stock:`COPY ~packing:menu#append ()
160         in
161         connect_menu_item copy_menu_item (fun () -> clipboard#set_text s);
162         menu#popup ~button:right_button ~time
163
164   method private button_release_cb gdk_button =
165     let clipboard = GData.clipboard Gdk.Atom.primary in
166     if GdkEvent.Button.button gdk_button = left_button then begin
167       let button_release_x = GdkEvent.Button.x gdk_button in
168       let button_release_y = GdkEvent.Button.y gdk_button in
169       if selection_changed then
170         ()
171       else  (* selection _not_ changed *)
172         if near (button_press_x, button_press_y)
173           (button_release_x, button_release_y)
174         then
175           let x = int_of_float button_press_x in
176           let y = int_of_float button_press_y in
177           (match self#get_element_at x y with
178           | None -> ()
179           | Some elt ->
180               let namespaceURI = DomMisc.xlink_ns in
181               let localName = href_ds in
182               if elt#hasAttributeNS ~namespaceURI ~localName then
183                 self#invoke_href_callback
184                   (elt#getAttributeNS ~namespaceURI ~localName)#to_string
185                   gdk_button
186               else
187                 ignore (self#action_toggle elt));
188     end;
189     false
190
191   method private invoke_href_callback href_value gdk_button =
192     let button = GdkEvent.Button.button gdk_button in
193     if button = left_button then
194       let time = GdkEvent.Button.time gdk_button in
195       match href_callback with
196       | None -> ()
197       | Some f ->
198           (match MatitaMisc.split href_value with
199           | [ uri ] ->  f uri
200           | uris ->
201               let menu = GMenu.menu () in
202               List.iter
203                 (fun uri ->
204                   let menu_item =
205                     GMenu.menu_item ~label:uri ~packing:menu#append ()
206                   in
207                   connect_menu_item menu_item (fun () -> f uri))
208                 uris;
209               menu#popup ~button ~time)
210
211   method private choose_selection_cb gdome_elt =
212     let (gui: MatitaGuiTypes.gui) = get_gui () in
213     let clipboard = GData.clipboard Gdk.Atom.primary in
214     let rec aux elt =
215       if (elt#getAttributeNS ~namespaceURI:DomMisc.helm_ns
216             ~localName:xref_ds)#to_string <> ""
217 (*         if elt#hasAttributeNS ~namespaceURI:DomMisc.helm_ns ~localName:xref_ds
218         && (elt#getAttributeNS ~namespaceURI:DomMisc.helm_ns
219             ~localName:xref_ds)#to_string <> "" *)
220       then begin
221         self#set_selection (Some elt);
222         self#coerce#misc#add_selection_target
223           ~target:(Gdk.Atom.name Gdk.Atom.string) Gdk.Atom.primary;
224         ignore (self#coerce#misc#grab_selection Gdk.Atom.primary)
225       end else
226         try
227           (match elt#get_parentNode with
228           | None -> assert false
229           | Some p -> aux (new Gdome.element_of_node p))
230         with GdomeInit.DOMCastException _ -> ()
231     in
232     (match gdome_elt with
233     | Some elt -> aux elt
234     | None -> self#set_selection None);
235     selection_changed <- true
236
237   method update_font_size = self#set_font_size !current_font_size
238
239   method private get_term_by_id context cic_info id =
240     let ids_to_terms, ids_to_hypotheses, _, _, _ = cic_info in
241     try
242       `Term (Hashtbl.find ids_to_terms id)
243     with Not_found ->
244       try
245         let hyp = Hashtbl.find ids_to_hypotheses id in
246         let context' = MatitaMisc.list_tl_at hyp context in
247         `Hyp context'
248       with Not_found -> assert false
249     
250   method private find_obj_conclusion id =
251     match self#cic_info with
252     | None
253     | Some (_, _, _, _, None) -> assert false
254     | Some (ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
255         let id =
256          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
257         in
258          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
259
260   method private string_of_node node =
261     let get_id (node: Gdome.element) =
262       let xref_attr =
263         node#getAttributeNS ~namespaceURI:DomMisc.helm_ns ~localName:xref_ds
264       in
265       xref_attr#to_string
266     in
267     let id = get_id node in
268     let script = MatitaScript.instance () in
269     let metasenv = script#proofMetasenv in
270     let context = script#proofContext in
271     let metasenv, context, conclusion =
272       if script#onGoingProof () then
273         script#proofMetasenv, script#proofContext, script#proofConclusion
274       else
275         [], [],
276         let t = self#find_obj_conclusion id in
277         MatitaLog.debug (CicPp.ppterm t);
278         t
279     in
280 (* TODO: code for patterns
281     let conclusion = (MatitaScript.instance ())#proofConclusion in
282     let conclusion_pattern =
283       ProofEngineHelpers.pattern_of ~term:conclusion cic_terms
284     in
285 *)
286     let string_of_cic_sequent cic_sequent =
287       let acic_sequent, _, _, ids_to_inner_sorts, _ =
288         Cic2acic.asequent_of_sequent metasenv cic_sequent
289       in
290       let _, _, _, annterm = acic_sequent in
291       let ast, ids_to_uris =
292         CicNotationRew.ast_of_acic ids_to_inner_sorts annterm
293       in
294       let pped_ast = CicNotationRew.pp_ast ast in
295       let markup = CicNotationPres.render ids_to_uris pped_ast in
296       BoxPp.render_to_string text_width markup
297     in
298     let cic_info =
299       match self#cic_info with Some info -> info | None -> assert false
300     in
301     let cic_sequent =
302       match self#get_term_by_id context cic_info id with
303       | `Term t ->
304           let context' =
305             match
306               ProofEngineHelpers.locate_in_conjecture t
307                 (~-1, context, conclusion)
308             with
309               [context,_] -> context
310             | _ -> assert false (* since it uses physical equality *)
311           in
312           ~-1, context', t
313       | `Hyp context -> ~-1, context, Cic.Rel 1
314     in
315     string_of_cic_sequent cic_sequent
316
317   method string_of_selections =
318     List.map self#string_of_node (List.rev self#get_selections)
319
320   method string_of_selection =
321     match self#get_selections with
322     | [] -> None
323     | node :: _ -> Some (self#string_of_node node)
324
325 end
326
327 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
328   GtkBase.Widget.size_params
329     ~cont:(OgtkMathViewProps.pack_return (fun p ->
330       OgtkMathViewProps.set_params
331         (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
332         ~font_size:None ~log_verbosity:None))
333     []
334
335 class cicMathView obj =
336 object (self)
337   inherit clickableMathView obj
338
339   val mutable current_mathml = None
340
341   method load_sequent metasenv metano =
342     let sequent = CicUtil.lookup_meta metano metasenv in
343     let (mathml, (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ ))) =
344       ApplyTransformation.mml_of_cic_sequent metasenv sequent
345     in
346     self#set_cic_info
347       (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, Hashtbl.create 1, None));
348     let name = "sequent_viewer.xml" in
349     MatitaLog.debug ("load_sequent: dumping MathML to ./" ^ name);
350     ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
351     self#load_root ~root:mathml#get_documentElement
352
353   method load_object obj =
354     let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
355     let (mathml,
356       (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
357     =
358       ApplyTransformation.mml_of_cic_object obj
359     in
360     self#set_cic_info
361       (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
362     (match current_mathml with
363     | Some current_mathml when use_diff ->
364         self#freeze;
365         XmlDiff.update_dom ~from:current_mathml mathml;
366         self#thaw
367     |  _ ->
368         let name = "cic_browser.xml" in
369         MatitaLog.debug ("cic_browser: dumping MathML to ./" ^ name);
370         ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
371         self#load_root ~root:mathml#get_documentElement;
372         current_mathml <- Some mathml);
373 end
374
375 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
376   object (self)
377     inherit scriptAccessor
378
379     val mutable pages = 0
380     val mutable switch_page_callback = None
381     val mutable page2goal = []  (* associative list: page no -> goal no *)
382     val mutable goal2page = []  (* the other way round *)
383     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
384     val mutable _metasenv = []
385     val mutable scrolledWin: GBin.scrolled_window option = None
386       (* scrolled window to which the sequentViewer is currently attached *)
387     val logo = (GMisc.image
388       ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_medium.png") ()
389       :> GObj.widget)
390             
391     val logo_with_qed = (GMisc.image
392       ~file:(BuildTimeConf.runtime_base_dir ^ "/logo/matita_small.png") ()
393       :> 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:`ALWAYS
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
625     val model =
626       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
627
628     val mutable lastDir = ""  (* last loaded "directory" *)
629
630     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
631
632     method private _getSelectedUri () =
633       match model#easy_selection () with
634       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
635 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
636       | [sel] -> lastDir ^ sel
637       | _ -> assert false
638
639     (** history RATIONALE 
640      *
641      * All operations about history are done using _historyFoo.
642      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
643      *)
644           
645     method private _historyAdd item = 
646       history#add item;
647       win#browserBackButton#misc#set_sensitive true;
648       win#browserForwardButton#misc#set_sensitive false
649
650     method private _historyPrev () =
651       let item = history#previous in
652       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
653       win#browserForwardButton#misc#set_sensitive true;
654       item
655     
656     method private _historyNext () =
657       let item = history#next in
658       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
659       win#browserBackButton#misc#set_sensitive true;
660       item
661
662     (** notebook RATIONALE 
663      * 
664      * Use only these functions to switch between the tabs
665      *)
666     method private _showList = win#mathOrListNotebook#goto_page 1
667     method private _showMath = win#mathOrListNotebook#goto_page 0
668     
669     method private back () =
670       try
671         self#_load (self#_historyPrev ())
672       with MatitaMisc.History_failure -> ()
673
674     method private forward () =
675       try
676         self#_load (self#_historyNext ())
677       with MatitaMisc.History_failure -> ()
678
679       (* loads a uri which can be a cic uri or an about:* uri
680       * @param uri string *)
681     method private _load ?(force=false) entry =
682       try
683        if entry <> current_entry || entry = `About `Current_proof || force then
684         begin
685           (match entry with
686           | `About `Current_proof -> self#home ()
687           | `About `Blank -> self#blank ()
688           | `About `Us -> () (* TODO implement easter egg here :-] *)
689           | `Check term -> self#_loadCheck term
690           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
691           | `Dir dir -> self#_loadDir dir
692           | `Uri uri -> self#_loadUriManagerUri uri
693           | `Whelp (query, results) -> 
694               set_whelp_query query;
695               self#_loadList (List.map (fun r -> "obj",
696                 UriManager.string_of_uri r) results));
697           self#setEntry entry
698         end
699       with exn -> fail (MatitaExcPp.to_string exn)
700
701     method private blank () =
702       self#_showMath;
703       mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
704
705     method private _loadCheck term =
706       failwith "not implemented _loadCheck";
707       self#_showMath
708
709     method private home () =
710       self#_showMath;
711       match self#script#status.proof_status with
712       | Proof  (uri, metasenv, bo, ty) ->
713           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
714           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
715           self#_loadObj obj
716       | Incomplete_proof ((uri, metasenv, bo, ty), _) -> 
717           let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
718           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
719           self#_loadObj obj
720       | _ -> self#blank ()
721
722       (** loads a cic uri from the environment
723       * @param uri UriManager.uri *)
724     method private _loadUriManagerUri uri =
725       let uri = UriManager.strip_xpointer uri in
726       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
727       self#_loadObj obj
728       
729     method private _loadDir dir = 
730       let content = Http_getter.ls dir in
731       let l =
732         List.fast_sort
733           Pervasives.compare
734           (List.map
735             (function 
736               | Http_getter_types.Ls_section s -> "dir", s
737               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
738             content)
739       in
740       lastDir <- dir;
741       self#_loadList l
742
743     method private setEntry entry =
744       win#browserUri#entry#set_text (string_of_entry entry);
745       current_entry <- entry
746
747     method private _loadObj obj =
748       (* showMath must be done _before_ loading the document, since if the
749        * widget is not mapped (hidden by the notebook) the document is not
750        * rendered *)
751       self#_showMath;
752       mathView#load_object obj
753
754     method private _loadTermCic term metasenv =
755       let context = self#script#proofContext in
756       let dummyno = CicMkImplicit.new_meta metasenv [] in
757       let sequent = (dummyno, context, term) in
758       mathView#load_sequent (sequent :: metasenv) dummyno;
759       self#_showMath
760
761     method private _loadList l =
762       model#list_store#clear ();
763       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
764       self#_showList
765     
766     (** { public methods, all must call _load!! } *)
767       
768     method load entry =
769       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
770
771     (**  this is what the browser does when you enter a string an hit enter *)
772     method loadInput txt =
773       let txt = MatitaMisc.trim_blanks txt in
774       let fix_uri txt =
775         UriManager.string_of_uri
776           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
777       in
778       if is_whelp txt then begin
779         set_whelp_query txt;  
780         (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
781       end else begin
782         let entry =
783           match txt with
784           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
785           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
786           | txt ->
787               (try
788                 entry_of_string txt
789               with Invalid_argument _ ->
790                 command_error (sprintf "unsupported uri: %s" txt))
791         in
792         self#_load entry;
793         self#_historyAdd entry
794       end
795
796       (** {2 methods accessing underlying GtkMathView} *)
797
798     method updateFontSize = mathView#set_font_size !current_font_size
799
800       (** {2 methods used by constructor only} *)
801
802     method win = win
803     method history = history
804     method currentEntry = current_entry
805     method refresh ~force () = self#_load ~force current_entry
806
807   end
808   
809 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
810   new sequentsViewer ~notebook ~cicMathView ()
811
812 let cicBrowser () =
813   let size = BuildTimeConf.browser_history_size in
814   let rec aux history =
815     let browser = new cicBrowser_impl ~history () in
816     let win = browser#win in
817     ignore (win#browserNewButton#connect#clicked (fun () ->
818       let history =
819         new MatitaMisc.browser_history ~memento:history#save size
820           (`About `Blank)
821       in
822       let newBrowser = aux history in
823       newBrowser#load browser#currentEntry));
824 (*
825       (* attempt (failed) to close windows on CTRL-W ... *)
826     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
827       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
828 *)
829     cicBrowsers := browser :: !cicBrowsers;
830     (browser :> MatitaGuiTypes.cicBrowser)
831   in
832   let history = new MatitaMisc.browser_history size (`About `Blank) in
833   aux history
834
835 let default_cicMathView () = cicMathView ~show:true ()
836 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
837
838 let default_sequentsViewer () =
839   let gui = get_gui () in
840   let cicMathView = cicMathView_instance () in
841   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
842 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
843
844 let mathViewer () = 
845   object(self)
846     method private get_browser reuse = 
847       if reuse then
848         (match !cicBrowsers with
849         | [] -> cicBrowser ()
850         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
851       else
852         (cicBrowser ())
853           
854     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
855       
856     method show_uri_list ?(reuse=false) ~entry l =
857       (self#get_browser reuse)#load entry
858   end
859
860 let refresh_all_browsers () =
861  List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
862
863 let update_font_sizes () =
864   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
865   (cicMathView_instance ())#update_font_size
866
867 let get_math_views () =
868   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
869   :: (List.map (fun b -> b#mathView) !cicBrowsers)
870
871 let get_selections () =
872   if (MatitaScript.instance ())#onGoingProof () then
873     let rec aux =
874       function
875       | [] -> None
876       | mv :: tl ->
877           (match mv#string_of_selections with
878           | [] -> aux tl
879           | sels -> Some sels)
880     in
881     aux (get_math_views ())
882   else
883     None
884
885 let reset_selections () =
886   List.iter (fun mv -> mv#remove_selections) (get_math_views ())
887