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