]> matita.cs.unibo.it Git - helm.git/blob - helm/software/matita/matitaMathView.ml
- renamed ocaml/ to components/
[helm.git] / helm / software / 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 (* $Id$ *)
27
28 open Printf
29
30 open GrafiteTypes
31 open MatitaGtkMisc
32 open MatitaGuiTypes
33
34 module Stack = Continuationals.Stack
35
36 (** inherit from this class if you want to access current script *)
37 class scriptAccessor =
38 object (self)
39   method private script = MatitaScript.current ()
40 end
41
42 let cicBrowsers = ref []
43 let gui_instance = ref None
44 let set_gui gui = gui_instance := Some gui
45 let get_gui () =
46   match !gui_instance with
47   | None -> assert false
48   | Some gui -> gui
49
50 let default_font_size () =
51   Helm_registry.get_opt_default Helm_registry.int
52     ~default:BuildTimeConf.default_font_size "matita.font_size"
53 let current_font_size = ref ~-1
54 let increase_font_size () = incr current_font_size
55 let decrease_font_size () = decr current_font_size
56 let reset_font_size () = current_font_size := default_font_size ()
57
58   (* is there any lablgtk2 constant corresponding to the various mouse
59    * buttons??? *)
60 let left_button = 1
61 let middle_button = 2
62 let right_button = 3
63
64 let near (x1, y1) (x2, y2) =
65   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
66   (distance < 4.)
67
68 let xlink_ns = Gdome.domString "http://www.w3.org/1999/xlink"
69 let helm_ns = Gdome.domString "http://www.cs.unibo.it/helm"
70 let href_ds = Gdome.domString "href"
71 let xref_ds = Gdome.domString "xref"
72
73 let domImpl = Gdome.domImplementation ()
74
75   (** Gdome.element of a MathML document whose rendering should be blank. Used
76   * by cicBrowser to render "about:blank" document *)
77 let empty_mathml = lazy (
78   domImpl#createDocument ~namespaceURI:(Some DomMisc.mathml_ns)
79     ~qualifiedName:(Gdome.domString "math") ~doctype:None)
80
81 let empty_boxml = lazy (
82   domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns) 
83     ~qualifiedName:(Gdome.domString "box") ~doctype:None)
84
85   (** shown for goals closed by side effects *)
86 let closed_goal_mathml = lazy (
87   domImpl#createDocumentFromURI ~uri:BuildTimeConf.closed_xml ())
88
89 (* ids_to_terms should not be passed here, is just for debugging *)
90 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
91   let find_parent id ids =
92     let rec aux id =
93 (*       (prerr_endline (sprintf "id %s = %s" id
94         (try
95           CicPp.ppterm (Hashtbl.find ids_to_terms id)
96         with Not_found -> "NONE"))); *)
97       if List.mem id ids then Some id
98       else
99         (match
100           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
101         with
102         | None -> None
103         | Some id' -> aux id')
104     in
105     aux id
106   in
107   let return_father id ids =
108     match find_parent id ids with
109     | None -> assert false
110     | Some parent_id -> parent_id
111   in
112   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
113   let inner_types =
114    Hashtbl.fold
115     (fun _ types acc ->
116       match types.Cic2acic.annexpected with
117          None -> types.Cic2acic.annsynthesized :: acc
118        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
119     ) ids_to_inner_types [] in
120   match annobj with
121   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
122   | Cic.AVariable (_, _, Some bo, ty, _, _)
123   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
124       return_father id (mk_ids (ty :: bo :: inner_types))
125   | Cic.AConstant (_, _, _, None, ty, _, _)
126   | Cic.AVariable (_, _, None, ty, _, _) ->
127       return_father id (mk_ids (ty::inner_types))
128   | Cic.AInductiveDefinition _ ->
129       assert false  (* TODO *)
130
131   (** @return string content of a dom node having a single text child node, e.g.
132    * <m:mi xlink:href="...">bool</m:mi> *)
133 let string_of_dom_node node =
134   match node#get_firstChild with
135   | None -> ""
136   | Some node ->
137       (try
138         let text = new Gdome.text_of_node node in
139         text#get_data#to_string
140       with GdomeInit.DOMCastException _ -> "")
141
142 let name_of_hypothesis = function
143   | Some (Cic.Name s, _) -> s
144   | _ -> assert false
145
146 let id_of_node (node: Gdome.element) =
147   let xref_attr =
148     node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds in
149   try
150     List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
151   with Failure _ -> assert false
152
153 type selected_term =
154   | SelTerm of Cic.term * string option (* term, parent hypothesis (if any) *)
155   | SelHyp of string * Cic.context (* hypothesis, context *)
156
157 class clickableMathView obj =
158 let text_width = 80 in
159 object (self)
160   inherit GMathViewAux.multi_selection_math_view obj
161
162   val mutable href_callback: (string -> unit) option = None
163   method set_href_callback f = href_callback <- f
164
165   val mutable _cic_info = None
166   method private set_cic_info info = _cic_info <- info
167   method private cic_info = _cic_info
168
169   initializer
170     self#set_font_size !current_font_size;
171     ignore (self#connect#selection_changed self#choose_selection_cb);
172     ignore (self#event#connect#button_press self#button_press_cb);
173     ignore (self#event#connect#button_release self#button_release_cb);
174     ignore (self#event#connect#selection_clear self#selection_clear_cb);
175     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
176
177   val mutable button_press_x = -1.
178   val mutable button_press_y = -1.
179   val mutable selection_changed = false
180
181   method private selection_get_cb ctxt ~info ~time =
182     let text =
183       match ctxt#target with
184       | "PATTERN" -> self#text_of_selection `Pattern
185       | "TERM" | _ -> self#text_of_selection `Term
186     in
187     match text with
188     | None -> ()
189     | Some s -> ctxt#return s
190
191   method private text_of_selection fmt =
192     match self#get_selections with
193     | [] -> None
194     | node :: _ -> Some (self#string_of_node ~paste_kind:fmt node)
195
196   method private selection_clear_cb sel_event =
197     self#remove_selections;
198     (GData.clipboard Gdk.Atom.clipboard)#clear ();
199     false
200
201   method private button_press_cb gdk_button =
202     let button = GdkEvent.Button.button gdk_button in
203     if  button = left_button then begin
204       button_press_x <- GdkEvent.Button.x gdk_button;
205       button_press_y <- GdkEvent.Button.y gdk_button;
206       selection_changed <- false
207     end else if button = right_button then
208       self#popup_contextual_menu (GdkEvent.Button.time gdk_button);
209     false
210
211     (** @return a pattern structure which contains pretty printed terms *)
212   method private tactic_text_pattern_of_selection =
213     match self#get_selections with
214     | [] -> assert false (* this method is invoked only if there's a sel. *)
215     | node :: _ ->
216         let id = id_of_node node in
217         let cic_info, unsh_sequent = self#get_cic_info id in
218         match self#get_term_by_id cic_info id with
219         | SelTerm (t, father_hyp) ->
220             let sequent = self#sequent_of_id ~paste_kind:`Pattern id in
221             let text = self#string_of_cic_sequent sequent in
222             (match father_hyp with
223             | None -> None, [], Some text
224             | Some hyp_name -> None, [ hyp_name, text ], None)
225         | SelHyp (hyp_name, _ctxt) -> None, [ hyp_name, "%" ], None
226
227   method private popup_contextual_menu time =
228     let menu = GMenu.menu () in
229     let add_menu_item ?(menu = menu) ?stock ?label () =
230       GMenu.image_menu_item ?stock ?label ~packing:menu#append () in
231     let check = add_menu_item ~label:"Check" () in
232     let reductions_menu_item = GMenu.menu_item ~label:"βδιζ-reduce" () in
233     menu#append reductions_menu_item;
234     let reductions = GMenu.menu () in
235     reductions_menu_item#set_submenu reductions;
236     let normalize = add_menu_item ~menu:reductions ~label:"Normalize" () in
237     let reduce = add_menu_item ~menu:reductions ~label:"Reduce" () in
238     let simplify = add_menu_item ~menu:reductions ~label:"Simplify" () in
239     let whd = add_menu_item ~menu:reductions ~label:"Weak head" () in
240     menu#append (GMenu.separator_item ());
241     let copy = add_menu_item ~stock:`COPY () in
242     let gui = get_gui () in
243     List.iter (fun item -> item#misc#set_sensitive gui#canCopy)
244       [ copy; check; normalize; reduce; simplify; whd ];
245     let reduction_action kind () =
246       let pat = self#tactic_text_pattern_of_selection in
247       let statement =
248         let loc = HExtlib.dummy_floc in
249         "\n" ^
250         GrafiteAstPp.pp_executable ~term_pp:(fun s -> s)
251           ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
252           (GrafiteAst.Tactical (loc,
253             GrafiteAst.Tactic (loc, GrafiteAst.Reduce (loc, kind, pat)),
254             Some (GrafiteAst.Semicolon loc))) in
255       (MatitaScript.current ())#advance ~statement () in
256     connect_menu_item copy gui#copy;
257     connect_menu_item normalize (reduction_action `Normalize);
258     connect_menu_item reduce (reduction_action `Reduce);
259     connect_menu_item simplify (reduction_action `Simpl);
260     connect_menu_item whd (reduction_action `Whd);
261     menu#popup ~button:right_button ~time
262
263   method private button_release_cb gdk_button =
264     if GdkEvent.Button.button gdk_button = left_button then begin
265       let button_release_x = GdkEvent.Button.x gdk_button in
266       let button_release_y = GdkEvent.Button.y gdk_button in
267       if selection_changed then
268         ()
269       else  (* selection _not_ changed *)
270         if near (button_press_x, button_press_y)
271           (button_release_x, button_release_y)
272         then
273           let x = int_of_float button_press_x in
274           let y = int_of_float button_press_y in
275           (match self#get_element_at x y with
276           | None -> ()
277           | Some elt ->
278               let localName = href_ds in
279               if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
280                 self#invoke_href_callback
281                   (elt#getAttributeNS ~namespaceURI:xlink_ns
282                     ~localName)#to_string
283                   gdk_button
284               else
285                 ignore (self#action_toggle elt));
286     end;
287     false
288
289   method private invoke_href_callback href_value gdk_button =
290     let button = GdkEvent.Button.button gdk_button in
291     if button = left_button then
292       let time = GdkEvent.Button.time gdk_button in
293       match href_callback with
294       | None -> ()
295       | Some f ->
296           (match HExtlib.split href_value with
297           | [ uri ] ->  f uri
298           | uris ->
299               let menu = GMenu.menu () in
300               List.iter
301                 (fun uri ->
302                   let menu_item =
303                     GMenu.menu_item ~label:uri ~packing:menu#append () in
304                   connect_menu_item menu_item (fun () -> f uri))
305                 uris;
306               menu#popup ~button ~time)
307
308   method private choose_selection_cb gdome_elt =
309     let set_selection elt =
310       let misc = self#coerce#misc in
311       self#set_selection (Some elt);
312       misc#add_selection_target ~target:"STRING" Gdk.Atom.primary;
313       ignore (misc#grab_selection Gdk.Atom.primary);
314     in
315     let rec aux elt =
316       if (elt#getAttributeNS ~namespaceURI:helm_ns
317             ~localName:xref_ds)#to_string <> ""
318       then
319         set_selection elt
320       else
321         try
322           (match elt#get_parentNode with
323           | None -> assert false
324           | Some p -> aux (new Gdome.element_of_node p))
325         with GdomeInit.DOMCastException _ -> ()
326     in
327     (match gdome_elt with
328     | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
329         ~localName:href_ds)#to_string <> "" ->
330           set_selection elt
331     | Some elt -> aux elt
332     | None -> self#set_selection None);
333     selection_changed <- true
334
335   method update_font_size = self#set_font_size !current_font_size
336
337     (** find a term by id from stored CIC infos @return either `Hyp if the id
338      * correspond to an hypothesis or `Term (cic, hyp) if the id correspond to a
339      * term. In the latter case hyp is either None (if the term is a subterm of
340      * the sequent conclusion) or Some hyp_name if the term belongs to an
341      * hypothesis *)
342   method private get_term_by_id cic_info id =
343     let unsh_item, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, _, _ =
344       cic_info in
345     let rec find_father_hyp id =
346       if Hashtbl.mem ids_to_hypotheses id
347       then Some (name_of_hypothesis (Hashtbl.find ids_to_hypotheses id))
348       else
349         let father_id =
350           try Hashtbl.find ids_to_father_ids id
351           with Not_found -> assert false in
352         match father_id with
353         | Some id -> find_father_hyp id
354         | None -> None
355     in
356     try
357       let term = Hashtbl.find ids_to_terms id in
358       let father_hyp = find_father_hyp id in
359       SelTerm (term, father_hyp)
360     with Not_found ->
361       try
362         let hyp = Hashtbl.find ids_to_hypotheses id in
363         let _, context, _ =
364           match unsh_item with Some seq -> seq | None -> assert false in
365         let context' = MatitaMisc.list_tl_at hyp context in
366         SelHyp (name_of_hypothesis hyp, context')
367       with Not_found -> assert false
368     
369   method private find_obj_conclusion id =
370     match self#cic_info with
371     | None
372     | Some (_, _, _, _, _, None) -> assert false
373     | Some (_, ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
374         let id =
375          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
376         in
377          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
378
379   method private string_of_node ~(paste_kind:paste_kind) node =
380     if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
381     then
382       let id = id_of_node node in
383       self#string_of_cic_sequent (self#sequent_of_id ~paste_kind id)
384     else string_of_dom_node node
385
386   method private string_of_cic_sequent cic_sequent =
387     let script = MatitaScript.current () in
388     let metasenv =
389       if script#onGoingProof () then script#proofMetasenv else [] in
390     let _, (acic_sequent, _, _, ids_to_inner_sorts, _) =
391       Cic2acic.asequent_of_sequent metasenv cic_sequent in
392     let _, _, _, annterm = acic_sequent in
393     let ast, ids_to_uris =
394       TermAcicContent.ast_of_acic ids_to_inner_sorts annterm in
395     let pped_ast = TermContentPres.pp_ast ast in
396     let markup = CicNotationPres.render ids_to_uris pped_ast in
397     BoxPp.render_to_string text_width markup
398
399   method private pattern_of term context unsh_sequent =
400     let context_len = List.length context in
401     let _, unsh_context, conclusion = unsh_sequent in
402     try
403       (match
404         List.nth unsh_context (List.length unsh_context - context_len - 1)
405       with
406       | None -> assert false (* can't select a restricted hypothesis *)
407       | Some (name, Cic.Decl ty) ->
408           ProofEngineHelpers.pattern_of ~term:ty [term]
409       | Some (name, Cic.Def (bo, _)) ->
410           ProofEngineHelpers.pattern_of ~term:bo [term])
411     with Failure _ | Invalid_argument _ ->
412       ProofEngineHelpers.pattern_of ~term:conclusion [term]
413
414   method private get_cic_info id =
415     match self#cic_info with
416     | Some ((Some unsh_sequent, _, _, _, _, _) as info) -> info, unsh_sequent
417     | Some ((None, _, _, _, _, _) as info) ->
418         let t = self#find_obj_conclusion id in
419         info, (~-1, [], t) (* dummy sequent for obj *)
420     | None -> assert false
421
422   method private sequent_of_id ~(paste_kind:paste_kind) id =
423     let cic_info, unsh_sequent = self#get_cic_info id in
424     let cic_sequent =
425       match self#get_term_by_id cic_info id with
426       | SelTerm (t, _father_hyp) ->
427           let occurrences =
428             ProofEngineHelpers.locate_in_conjecture t unsh_sequent in
429           (match occurrences with
430           | [ context, _t ] ->
431               (match paste_kind with
432               | `Term -> ~-1, context, t
433               | `Pattern -> ~-1, [], self#pattern_of t context unsh_sequent)
434           | _ ->
435               HLog.error (sprintf "found %d occurrences while 1 was expected"
436                 (List.length occurrences));
437               assert false) (* since it uses physical equality *)
438       | SelHyp (_name, context) -> ~-1, context, Cic.Rel 1 in
439     cic_sequent
440
441   method private string_of_selection ~(paste_kind:paste_kind) =
442     match self#get_selections with
443     | [] -> None
444     | node :: _ -> Some (self#string_of_node ~paste_kind node)
445
446   method has_selection = self#get_selections <> []
447
448     (** @return an associative list format -> string with all possible selection
449      * formats. Rationale: in order to convert the selection to TERM or PATTERN
450      * format we need the sequent, the metasenv, ... keeping all of them in a
451      * closure would be more expensive than keeping their already converted
452      * forms *)
453   method strings_of_selection =
454     try
455       let misc = self#coerce#misc in
456       List.iter
457         (fun target -> misc#add_selection_target ~target Gdk.Atom.clipboard)
458         [ "TERM"; "PATTERN"; "STRING" ];
459       ignore (misc#grab_selection Gdk.Atom.clipboard);
460       List.map
461         (fun paste_kind ->
462           paste_kind, HExtlib.unopt (self#string_of_selection ~paste_kind))
463         [ `Term; `Pattern ]
464     with Failure _ -> failwith "no selection"
465
466 end
467
468 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
469   GtkBase.Widget.size_params
470     ~cont:(OgtkMathViewProps.pack_return (fun p ->
471       OgtkMathViewProps.set_params
472         (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
473         ~font_size:None ~log_verbosity:None))
474     []
475
476 class cicMathView obj =
477 object (self)
478   inherit clickableMathView obj
479
480   val mutable current_mathml = None
481
482   method load_sequent metasenv metano =
483     let sequent = CicUtil.lookup_meta metano metasenv in
484     let (mathml, unsh_sequent,
485       (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ )))
486     =
487       ApplyTransformation.mml_of_cic_sequent metasenv sequent
488     in
489     self#set_cic_info
490       (Some (Some unsh_sequent,
491         ids_to_terms, ids_to_hypotheses, ids_to_father_ids,
492         Hashtbl.create 1, None));
493     if BuildTimeConf.debug then begin
494       let name = "sequent_viewer.xml" in
495       HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
496       ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
497     end;
498     self#load_root ~root:mathml#get_documentElement
499
500   method load_object obj =
501     let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
502     let (mathml,
503       (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
504     =
505       ApplyTransformation.mml_of_cic_object obj
506     in
507     self#set_cic_info
508       (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
509     (match current_mathml with
510     | Some current_mathml when use_diff ->
511         self#freeze;
512         XmlDiff.update_dom ~from:current_mathml mathml;
513         self#thaw
514     |  _ ->
515         if BuildTimeConf.debug then begin
516           let name = "cic_browser.xml" in
517           HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
518           ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
519         end;
520         self#load_root ~root:mathml#get_documentElement;
521         current_mathml <- Some mathml);
522 end
523
524 let tab_label meta_markup =
525   let rec aux =
526     function
527     | `Current m -> sprintf "<b>%s</b>" (aux m)
528     | `Closed m -> sprintf "<s>%s</s>" (aux m)
529     | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
530     | `Meta n -> sprintf "?%d" n
531   in
532   let markup = aux meta_markup in
533   (GMisc.label ~markup ~show:true ())#coerce
534
535 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
536
537 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
538   object (self)
539     inherit scriptAccessor
540
541     val mutable pages = 0
542     val mutable switch_page_callback = None
543     val mutable page2goal = []  (* associative list: page no -> goal no *)
544     val mutable goal2page = []  (* the other way round *)
545     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
546     val mutable _metasenv = []
547     val mutable scrolledWin: GBin.scrolled_window option = None
548       (* scrolled window to which the sequentViewer is currently attached *)
549     val logo = (GMisc.image
550       ~file:(MatitaMisc.image_path "matita_medium.png") ()
551       :> GObj.widget)
552             
553     val logo_with_qed = (GMisc.image
554       ~file:(MatitaMisc.image_path "matita_small.png") ()
555       :> GObj.widget)
556
557     method load_logo =
558      notebook#set_show_tabs false;
559      notebook#append_page logo
560
561     method load_logo_with_qed =
562      notebook#set_show_tabs false;
563      notebook#append_page logo_with_qed
564
565     method reset =
566       cicMathView#remove_selections;
567       (match scrolledWin with
568       | Some w ->
569           (* removing page from the notebook will destroy all contained widget,
570           * we do not want the cicMathView to be destroyed as well *)
571           w#remove cicMathView#coerce;
572           scrolledWin <- None
573       | None -> ());
574       (match switch_page_callback with
575       | Some id ->
576           GtkSignal.disconnect notebook#as_widget id;
577           switch_page_callback <- None
578       | None -> ());
579       for i = 0 to pages do notebook#remove_page 0 done; 
580       notebook#set_show_tabs true;
581       pages <- 0;
582       page2goal <- [];
583       goal2page <- [];
584       goal2win <- [];
585       _metasenv <- []; 
586       self#script#setGoal None
587
588     method load_sequents { proof = (_,metasenv,_,_) as proof; stack = stack } =
589       _metasenv <- metasenv;
590       pages <- 0;
591       let win goal_switch =
592         let w =
593           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
594             ~shadow_type:`IN ~show:true ()
595         in
596         let reparent () =
597           scrolledWin <- Some w;
598           match cicMathView#misc#parent with
599           | None -> w#add cicMathView#coerce
600           | Some parent ->
601              let parent =
602               match cicMathView#misc#parent with
603                  None -> assert false
604                | Some p -> GContainer.cast_container p
605              in
606               parent#remove cicMathView#coerce;
607               w#add cicMathView#coerce
608         in
609         goal2win <- (goal_switch, reparent) :: goal2win;
610         w#coerce
611       in
612       assert (
613         let stack_goals = Stack.open_goals stack in
614         let proof_goals = ProofEngineTypes.goals_of_proof proof in
615         if
616           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
617           <> List.sort Pervasives.compare proof_goals
618         then begin
619           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
620           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
621           false
622         end
623         else true
624       );
625       let render_switch =
626         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
627       in
628       let page = ref 0 in
629       let added_goals = ref [] in
630         (* goals can be duplicated on the tack due to focus, but we should avoid
631          * multiple labels in the user interface *)
632       let add_tab markup goal_switch =
633         let goal = Stack.goal_of_switch goal_switch in
634         if not (List.mem goal !added_goals) then begin
635           notebook#append_page ~tab_label:(tab_label markup) (win goal_switch);
636           page2goal <- (!page, goal_switch) :: page2goal;
637           goal2page <- (goal_switch, !page) :: goal2page;
638           incr page;
639           pages <- pages + 1;
640           added_goals := goal :: !added_goals
641         end
642       in
643       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
644       Stack.iter  (** populate notebook with tabs *)
645         ~env:(fun depth tag (pos, sw) ->
646           let markup =
647             match depth, pos with
648             | 0, _ -> `Current (render_switch sw)
649             | 1, pos when Stack.head_tag stack = `BranchTag ->
650                 `Shift (pos, render_switch sw)
651             | _ -> render_switch sw
652           in
653           add_tab markup sw)
654         ~cont:add_switch ~todo:add_switch
655         stack;
656       switch_page_callback <-
657         Some (notebook#connect#switch_page ~callback:(fun page ->
658           let goal_switch =
659             try List.assoc page page2goal with Not_found -> assert false
660           in
661           self#script#setGoal (Some (goal_of_switch goal_switch));
662           self#render_page ~page ~goal_switch))
663
664     method private render_page ~page ~goal_switch =
665       (match goal_switch with
666       | Stack.Open goal -> cicMathView#load_sequent _metasenv goal
667       | Stack.Closed goal ->
668           let doc = Lazy.force closed_goal_mathml in
669           cicMathView#load_root ~root:doc#get_documentElement);
670       (try
671         cicMathView#set_selection None;
672         List.assoc goal_switch goal2win ()
673       with Not_found -> assert false)
674
675     method goto_sequent goal =
676       let goal_switch, page =
677         try
678           List.find
679             (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
680             goal2page
681         with Not_found -> assert false
682       in
683       notebook#goto_page page;
684       self#render_page page goal_switch
685
686   end
687
688  (** constructors *)
689
690 type 'widget constructor =
691   ?hadjustment:GData.adjustment ->
692   ?vadjustment:GData.adjustment ->
693   ?font_size:int ->
694   ?log_verbosity:int ->
695   ?width:int ->
696   ?height:int ->
697   ?packing:(GObj.widget -> unit) ->
698   ?show:bool ->
699   unit ->
700     'widget
701
702 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
703   GtkBase.Widget.size_params
704     ~cont:(OgtkMathViewProps.pack_return (fun p ->
705       OgtkMathViewProps.set_params
706         (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
707         ~font_size ~log_verbosity))
708     []
709
710 let blank_uri = BuildTimeConf.blank_uri
711 let current_proof_uri = BuildTimeConf.current_proof_uri
712
713 type term_source =
714   [ `Ast of CicNotationPt.term
715   | `Cic of Cic.term * Cic.metasenv
716   | `String of string
717   ]
718
719 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
720   ()
721 =
722   let whelp_RE = Pcre.regexp "^\\s*whelp" in
723   let uri_RE =
724     Pcre.regexp
725       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
726   in
727   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
728   let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
729   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
730   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
731   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
732   let gui = get_gui () in
733   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
734   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
735   let combo,_ = GEdit.combo_box_text ~strings:queries () in
736   let activate_combo_query input q =
737     let q' = String.lowercase q in
738     let rec aux i = function
739       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
740       | h::_ when String.lowercase h = q' -> i
741       | _::tl -> aux (i+1) tl
742     in
743     combo#set_active (aux 0 queries);
744     win#queryInputText#set_text input
745   in
746   let set_whelp_query txt =
747     let query, arg = 
748       try
749         let q = Pcre.extract ~rex:whelp_query_RE txt in
750         q.(1), q.(2)
751       with Invalid_argument _ -> failwith "Malformed Whelp query"
752     in
753     activate_combo_query arg query
754   in
755   let toplevel = win#toplevel in
756   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
757   let fail message = 
758     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
759       ~parent:toplevel ()  
760   in
761   let tags =
762     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
763       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
764   in
765   let handle_error f =
766     try
767       f ()
768     with exn ->
769       if not (Helm_registry.get_bool "matita.debug") then
770         fail (snd (MatitaExcPp.to_string exn))
771       else raise exn
772   in
773   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
774   let load_easter_egg = lazy (
775     win#easterEggImage#set_file (MatitaMisc.image_path "meegg.png"))
776   in
777   object (self)
778     inherit scriptAccessor
779     
780     (* Whelp bar queries *)
781
782     initializer
783       activate_combo_query "" "locate";
784       win#whelpBarComboVbox#add combo#coerce;
785       let start_query () = 
786         let query = String.lowercase (List.nth queries combo#active) in
787         let input = win#queryInputText#text in
788         let statement = "whelp " ^ query ^ " " ^ input ^ "." in
789         (MatitaScript.current ())#advance ~statement ()
790       in
791       ignore(win#queryInputText#connect#activate ~callback:start_query);
792       ignore(combo#connect#changed ~callback:start_query);
793       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
794       win#mathOrListNotebook#set_show_tabs false;
795       win#browserForwardButton#misc#set_sensitive false;
796       win#browserBackButton#misc#set_sensitive false;
797       ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
798         self#loadInput win#browserUri#entry#text)));
799       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
800         self#load (`About `Current_proof))));
801       ignore (win#browserRefreshButton#connect#clicked
802         (handle_error' (self#refresh ~force:true)));
803       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
804       ignore (win#browserForwardButton#connect#clicked
805         (handle_error' self#forward));
806       ignore (win#toplevel#event#connect#delete (fun _ ->
807         let my_id = Oo.id self in
808         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
809         if !cicBrowsers = [] &&
810           Helm_registry.get "matita.mode" = "cicbrowser"
811         then
812           GMain.quit ();
813         false));
814       ignore(win#whelpResultTreeview#connect#row_activated 
815         ~callback:(fun _ _ ->
816           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
817       mathView#set_href_callback (Some (fun uri ->
818         handle_error (fun () ->
819           self#load (`Uri (UriManager.uri_of_string uri)))));
820       self#_load (`About `Blank);
821       toplevel#show ()
822
823     val mutable current_entry = `About `Blank 
824
825     val model =
826       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
827
828     val mutable lastDir = ""  (* last loaded "directory" *)
829
830     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
831
832     method private _getSelectedUri () =
833       match model#easy_selection () with
834       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
835 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
836       | [sel] -> lastDir ^ sel
837       | _ -> assert false
838
839     (** history RATIONALE 
840      *
841      * All operations about history are done using _historyFoo.
842      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
843      *)
844           
845     method private _historyAdd item = 
846       history#add item;
847       win#browserBackButton#misc#set_sensitive true;
848       win#browserForwardButton#misc#set_sensitive false
849
850     method private _historyPrev () =
851       let item = history#previous in
852       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
853       win#browserForwardButton#misc#set_sensitive true;
854       item
855     
856     method private _historyNext () =
857       let item = history#next in
858       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
859       win#browserBackButton#misc#set_sensitive true;
860       item
861
862     (** notebook RATIONALE 
863      * 
864      * Use only these functions to switch between the tabs
865      *)
866     method private _showMath = win#mathOrListNotebook#goto_page 0
867     method private _showList = win#mathOrListNotebook#goto_page 1
868
869     method private back () =
870       try
871         self#_load (self#_historyPrev ())
872       with MatitaMisc.History_failure -> ()
873
874     method private forward () =
875       try
876         self#_load (self#_historyNext ())
877       with MatitaMisc.History_failure -> ()
878
879       (* loads a uri which can be a cic uri or an about:* uri
880       * @param uri string *)
881     method private _load ?(force=false) entry =
882       handle_error (fun () ->
883        if entry <> current_entry || entry = `About `Current_proof || force then
884         begin
885           (match entry with
886           | `About `Current_proof -> self#home ()
887           | `About `Blank -> self#blank ()
888           | `About `Us -> self#egg ()
889           | `Check term -> self#_loadCheck term
890           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
891           | `Dir dir -> self#_loadDir dir
892           | `Uri uri -> self#_loadUriManagerUri uri
893           | `Whelp (query, results) -> 
894               set_whelp_query query;
895               self#_loadList (List.map (fun r -> "obj",
896                 UriManager.string_of_uri r) results));
897           self#setEntry entry
898         end)
899
900     method private blank () =
901       self#_showMath;
902       mathView#load_root (Lazy.force empty_mathml)#get_documentElement
903
904     method private _loadCheck term =
905       failwith "not implemented _loadCheck";
906 (*       self#_showMath *)
907
908     method private egg () =
909       win#mathOrListNotebook#goto_page 2;
910       Lazy.force load_easter_egg
911
912     method private home () =
913       self#_showMath;
914       match self#script#grafite_status.proof_status with
915       | Proof  (uri, metasenv, bo, ty) ->
916           let name = UriManager.name_of_uri (HExtlib.unopt uri) in
917           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
918           self#_loadObj obj
919       | Incomplete_proof { proof = (uri, metasenv, bo, ty) } ->
920           let name = UriManager.name_of_uri (HExtlib.unopt uri) in
921           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
922           self#_loadObj obj
923       | _ -> self#blank ()
924
925       (** loads a cic uri from the environment
926       * @param uri UriManager.uri *)
927     method private _loadUriManagerUri uri =
928       let uri = UriManager.strip_xpointer uri in
929       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
930       self#_loadObj obj
931       
932     method private _loadDir dir = 
933       let content = Http_getter.ls dir in
934       let l =
935         List.fast_sort
936           Pervasives.compare
937           (List.map
938             (function 
939               | Http_getter_types.Ls_section s -> "dir", s
940               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
941             content)
942       in
943       lastDir <- dir;
944       self#_loadList l
945
946     method private setEntry entry =
947       win#browserUri#entry#set_text (MatitaTypes.string_of_entry entry);
948       current_entry <- entry
949
950     method private _loadObj obj =
951       (* showMath must be done _before_ loading the document, since if the
952        * widget is not mapped (hidden by the notebook) the document is not
953        * rendered *)
954       self#_showMath;
955       mathView#load_object obj
956
957     method private _loadTermCic term metasenv =
958       let context = self#script#proofContext in
959       let dummyno = CicMkImplicit.new_meta metasenv [] in
960       let sequent = (dummyno, context, term) in
961       mathView#load_sequent (sequent :: metasenv) dummyno;
962       self#_showMath
963
964     method private _loadList l =
965       model#list_store#clear ();
966       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
967       self#_showList
968     
969     (** { public methods, all must call _load!! } *)
970       
971     method load entry =
972       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
973
974     (**  this is what the browser does when you enter a string an hit enter *)
975     method loadInput txt =
976       let txt = HExtlib.trim_blanks txt in
977       let fix_uri txt =
978         UriManager.string_of_uri
979           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
980       in
981       if is_whelp txt then begin
982         set_whelp_query txt;  
983         (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
984       end else begin
985         let entry =
986           match txt with
987           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
988           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
989           | txt ->
990              (try
991                MatitaTypes.entry_of_string txt
992               with Invalid_argument _ ->
993                raise
994                 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
995         in
996         self#_load entry;
997         self#_historyAdd entry
998       end
999
1000       (** {2 methods accessing underlying GtkMathView} *)
1001
1002     method updateFontSize = mathView#set_font_size !current_font_size
1003
1004       (** {2 methods used by constructor only} *)
1005
1006     method win = win
1007     method history = history
1008     method currentEntry = current_entry
1009     method refresh ~force () = self#_load ~force current_entry
1010
1011   end
1012   
1013 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
1014   MatitaGuiTypes.sequentsViewer
1015 =
1016   new sequentsViewer ~notebook ~cicMathView ()
1017
1018 let cicBrowser () =
1019   let size = BuildTimeConf.browser_history_size in
1020   let rec aux history =
1021     let browser = new cicBrowser_impl ~history () in
1022     let win = browser#win in
1023     ignore (win#browserNewButton#connect#clicked (fun () ->
1024       let history =
1025         new MatitaMisc.browser_history ~memento:history#save size
1026           (`About `Blank)
1027       in
1028       let newBrowser = aux history in
1029       newBrowser#load browser#currentEntry));
1030 (*
1031       (* attempt (failed) to close windows on CTRL-W ... *)
1032     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
1033       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
1034 *)
1035     cicBrowsers := browser :: !cicBrowsers;
1036     (browser :> MatitaGuiTypes.cicBrowser)
1037   in
1038   let history = new MatitaMisc.browser_history size (`About `Blank) in
1039   aux history
1040
1041 let default_cicMathView () = cicMathView ~show:true ()
1042 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
1043
1044 let default_sequentsViewer () =
1045   let gui = get_gui () in
1046   let cicMathView = cicMathView_instance () in
1047   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
1048 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
1049
1050 let mathViewer () = 
1051   object(self)
1052     method private get_browser reuse = 
1053       if reuse then
1054         (match !cicBrowsers with
1055         | [] -> cicBrowser ()
1056         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
1057       else
1058         (cicBrowser ())
1059           
1060     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
1061       
1062     method show_uri_list ?(reuse=false) ~entry l =
1063       (self#get_browser reuse)#load entry
1064   end
1065
1066 let refresh_all_browsers () =
1067   List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
1068
1069 let update_font_sizes () =
1070   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
1071   (cicMathView_instance ())#update_font_size
1072
1073 let get_math_views () =
1074   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
1075   :: (List.map (fun b -> b#mathView) !cicBrowsers)
1076
1077 let find_selection_owner () =
1078   let rec aux =
1079     function
1080     | [] -> raise Not_found
1081     | mv :: tl ->
1082         (match mv#get_selections with
1083         | [] -> aux tl
1084         | sel :: _ -> mv)
1085   in
1086   aux (get_math_views ())
1087
1088 let has_selection () =
1089   try ignore (find_selection_owner ()); true
1090   with Not_found -> false
1091
1092 let math_view_clipboard = ref None (* associative list target -> string *)
1093 let has_clipboard () = !math_view_clipboard <> None
1094 let empty_clipboard () = math_view_clipboard := None
1095
1096 let copy_selection () =
1097   try
1098     math_view_clipboard :=
1099       Some ((find_selection_owner ())#strings_of_selection)
1100   with Not_found -> failwith "no selection"
1101
1102 let paste_clipboard paste_kind =
1103   match !math_view_clipboard with
1104   | None -> failwith "empty clipboard"
1105   | Some cb ->
1106       (try List.assoc paste_kind cb with Not_found -> assert false)
1107