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