]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaMathView.ml
3364b55f32270aee5e57e65bd425fc08216bf10a
[helm.git] / matita / 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 mathml_ns = Gdome.domString "http://www.w3.org/1998/Math/MathML"
69 let xlink_ns = Gdome.domString "http://www.w3.org/1999/xlink"
70 let helm_ns = Gdome.domString "http://www.cs.unibo.it/helm"
71 let href_ds = Gdome.domString "href"
72 let maction_ds = Gdome.domString "maction"
73 let xref_ds = Gdome.domString "xref"
74
75 let domImpl = Gdome.domImplementation ()
76
77   (** Gdome.element of a MathML document whose rendering should be blank. Used
78   * by cicBrowser to render "about:blank" document *)
79 let empty_mathml = lazy (
80   domImpl#createDocument ~namespaceURI:(Some DomMisc.mathml_ns)
81     ~qualifiedName:(Gdome.domString "math") ~doctype:None)
82
83 let empty_boxml = lazy (
84   domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns) 
85     ~qualifiedName:(Gdome.domString "box") ~doctype:None)
86
87   (** shown for goals closed by side effects *)
88 let closed_goal_mathml = lazy "chiuso per side effect..."
89
90 (* ids_to_terms should not be passed here, is just for debugging *)
91 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
92   let find_parent id ids =
93     let rec aux id =
94 (*       (prerr_endline (sprintf "id %s = %s" id
95         (try
96           CicPp.ppterm (Hashtbl.find ids_to_terms id)
97         with Not_found -> "NONE"))); *)
98       if List.mem id ids then Some id
99       else
100         (match
101           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
102         with
103         | None -> None
104         | Some id' -> aux id')
105     in
106     aux id
107   in
108   let return_father id ids =
109     match find_parent id ids with
110     | None -> assert false
111     | Some parent_id -> parent_id
112   in
113   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
114   let inner_types =
115    Hashtbl.fold
116     (fun _ types acc ->
117       match types.Cic2acic.annexpected with
118          None -> types.Cic2acic.annsynthesized :: acc
119        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
120     ) ids_to_inner_types [] in
121   match annobj with
122   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
123   | Cic.AVariable (_, _, Some bo, ty, _, _)
124   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
125       return_father id (mk_ids (ty :: bo :: inner_types))
126   | Cic.AConstant (_, _, _, None, ty, _, _)
127   | Cic.AVariable (_, _, None, ty, _, _) ->
128       return_father id (mk_ids (ty::inner_types))
129   | Cic.AInductiveDefinition _ ->
130       assert false  (* TODO *)
131
132   (** @return string content of a dom node having a single text child node, e.g.
133    * <m:mi xlink:href="...">bool</m:mi> *)
134 let string_of_dom_node node =
135   match node#get_firstChild with
136   | None -> ""
137   | Some node ->
138       (try
139         let text = new Gdome.text_of_node node in
140         text#get_data#to_string
141       with GdomeInit.DOMCastException _ -> "")
142
143 let name_of_hypothesis = function
144   | Some (Cic.Name s, _) -> s
145   | _ -> assert false
146
147 let id_of_node (node: Gdome.element) =
148   let xref_attr =
149     node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds in
150   try
151     List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
152   with Failure _ -> assert false
153
154 type selected_term =
155   | SelTerm of Cic.term * string option (* term, parent hypothesis (if any) *)
156   | SelHyp of string * Cic.context (* hypothesis, context *)
157
158 let hrefs_of_elt elt =
159   let localName = href_ds in
160   if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
161     let text =
162       (elt#getAttributeNS ~namespaceURI:xlink_ns ~localName)#to_string in
163     Some (HExtlib.split text)
164   else
165     None
166
167 let rec has_maction (elt :Gdome.element) = 
168   (* fix this comparison *)
169   if elt#get_tagName#to_string = "m:maction" ||
170    elt#get_tagName#to_string = "b:action" then
171     true
172   else 
173     match elt#get_parentNode with
174     | Some node when node#get_nodeType = GdomeNodeTypeT.ELEMENT_NODE -> 
175         has_maction (new Gdome.element_of_node node)
176     | _ -> false
177 ;;
178
179 class clickableMathView obj =
180 let text_width = 80 in
181 object (self)
182   inherit GSourceView2.source_view obj
183
184   method has_selection = (assert false : bool)
185   method strings_of_selection = (assert false : (paste_kind * string) list)
186   method update_font_size = (assert false : unit)
187   method set_href_callback = (function _ -> () : (string -> unit) option -> unit)
188   method private set_cic_info = (function _ -> () : (Cic.conjecture option * (Cic.id, Cic.term) Hashtbl.t *
189          (Cic.id, Cic.hypothesis) Hashtbl.t *
190          (Cic.id, Cic.id option) Hashtbl.t * ('a, 'b) Hashtbl.t * 'c option) option -> unit)
191   (* dal widget di Luca *)
192   method load_root ~root =
193     self#buffer#delete ~start:(self#buffer#get_iter `START)
194     ~stop:(self#buffer#get_iter `END);
195     self#buffer#insert root
196   method remove_selections = (() : unit)
197   method set_selection = (fun _ -> () : Gdome.element option -> unit)
198   method get_selections = (assert false : Gdome.element list)
199   method set_font_size font_size =
200    self#misc#modify_font_by_name
201      (sprintf "%s %d" BuildTimeConf.script_font font_size)
202
203 (* MATITA1.0
204   inherit GMathViewAux.multi_selection_math_view obj
205
206   val mutable href_callback: (string -> unit) option = None
207   method set_href_callback f = href_callback <- f
208
209   val mutable _cic_info = None
210   method private set_cic_info info = _cic_info <- info
211   method private cic_info = _cic_info
212
213   val normal_cursor = Gdk.Cursor.create `LEFT_PTR
214   val href_cursor = Gdk.Cursor.create `HAND2
215   val maction_cursor = Gdk.Cursor.create `QUESTION_ARROW
216
217   initializer
218     self#set_font_size !current_font_size;
219     ignore (self#connect#selection_changed self#choose_selection_cb);
220     ignore (self#event#connect#button_press self#button_press_cb);
221     ignore (self#event#connect#button_release self#button_release_cb);
222     ignore (self#event#connect#selection_clear self#selection_clear_cb);
223     ignore (self#connect#element_over self#element_over_cb);
224     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
225
226   val mutable button_press_x = -1.
227   val mutable button_press_y = -1.
228   val mutable selection_changed = false
229   val mutable href_statusbar_msg:
230     (GMisc.statusbar_context * Gtk.statusbar_message) option = None
231     (* <statusbar ctxt, statusbar msg> *)
232
233   method private selection_get_cb ctxt ~info ~time =
234     let text =
235       match ctxt#target with
236       | "PATTERN" -> self#text_of_selection `Pattern
237       | "TERM" | _ -> self#text_of_selection `Term
238     in
239     match text with
240     | None -> ()
241     | Some s -> ctxt#return s
242
243   method private text_of_selection fmt =
244     match self#get_selections with
245     | [] -> None
246     | node :: _ -> Some (self#string_of_node ~paste_kind:fmt node)
247
248   method private selection_clear_cb sel_event =
249     self#remove_selections;
250     (GData.clipboard Gdk.Atom.clipboard)#clear ();
251     false
252
253   method private button_press_cb gdk_button =
254     let button = GdkEvent.Button.button gdk_button in
255     if  button = left_button then begin
256       button_press_x <- GdkEvent.Button.x gdk_button;
257       button_press_y <- GdkEvent.Button.y gdk_button;
258       selection_changed <- false
259     end else if button = right_button then
260       self#popup_contextual_menu 
261         (self#get_element_at 
262           (int_of_float (GdkEvent.Button.x gdk_button)) 
263           (int_of_float (GdkEvent.Button.y gdk_button)))  
264         (GdkEvent.Button.time gdk_button);
265     false
266
267   method private element_over_cb (elt_opt, _, _, _) =
268     let win () = self#misc#window in
269     let leave_href () =
270       Gdk.Window.set_cursor (win ()) normal_cursor;
271       HExtlib.iter_option (fun (ctxt, msg) -> ctxt#remove msg)
272         href_statusbar_msg
273     in
274     match elt_opt with
275     | Some elt ->
276         if has_maction elt then
277           Gdk.Window.set_cursor (win ()) maction_cursor
278         else
279         (match hrefs_of_elt elt with
280         | Some ((_ :: _) as hrefs) ->
281             Gdk.Window.set_cursor (win ()) href_cursor;
282             let msg_text = (* now create statusbar msg and store it *)
283               match hrefs with
284               | [ href ] -> sprintf "Hyperlink to %s" href
285               | _ -> sprintf "Hyperlinks to: %s" (String.concat ", " hrefs) in
286             let ctxt = (get_gui ())#main#statusBar#new_context ~name:"href" in
287             let msg = ctxt#push msg_text in
288             href_statusbar_msg <- Some (ctxt, msg)
289         | _ -> leave_href ())
290     | None -> leave_href ()
291
292   method private tactic_text_pattern_of_node node =
293    let id = id_of_node node in
294    let cic_info, unsh_sequent = self#get_cic_info id in
295    match self#get_term_by_id cic_info id with
296    | SelTerm (t, father_hyp) ->
297        let sequent = self#sequent_of_id ~paste_kind:`Pattern id in
298        let text = self#string_of_cic_sequent ~output_type:`Pattern sequent in
299        (match father_hyp with
300        | None -> None, [], Some text
301        | Some hyp_name -> None, [ hyp_name, text ], None)
302    | SelHyp (hyp_name, _ctxt) -> None, [ hyp_name, "%" ], None
303
304   method private tactic_text_of_node node =
305    let id = id_of_node node in
306    let cic_info, unsh_sequent = self#get_cic_info id in
307    match self#get_term_by_id cic_info id with
308    | SelTerm (t, father_hyp) ->
309        let sequent = self#sequent_of_id ~paste_kind:`Term id in
310        let text = self#string_of_cic_sequent ~output_type:`Term sequent in
311        text
312    | SelHyp (hyp_name, _ctxt) -> hyp_name
313
314     (** @return a pattern structure which contains pretty printed terms *)
315   method private tactic_text_pattern_of_selection =
316     match self#get_selections with
317     | [] -> assert false (* this method is invoked only if there's a sel. *)
318     | node :: _ -> self#tactic_text_pattern_of_node node
319
320   method private popup_contextual_menu element time =
321     let menu = GMenu.menu () in
322     let add_menu_item ?(menu = menu) ?stock ?label () =
323       GMenu.image_menu_item ?stock ?label ~packing:menu#append () in
324     let check = add_menu_item ~label:"Check" () in
325     let reductions_menu_item = GMenu.menu_item ~label:"βδιζ-reduce" () in
326     let tactics_menu_item = GMenu.menu_item ~label:"Apply tactic" () in
327     let hyperlinks_menu_item = GMenu.menu_item ~label:"Hyperlinks" () in
328     menu#append reductions_menu_item;
329     menu#append tactics_menu_item;
330     menu#append hyperlinks_menu_item;
331     let reductions = GMenu.menu () in
332     let tactics = GMenu.menu () in
333     let hyperlinks = GMenu.menu () in
334     reductions_menu_item#set_submenu reductions;
335     tactics_menu_item#set_submenu tactics;
336     hyperlinks_menu_item#set_submenu hyperlinks;
337     let normalize = add_menu_item ~menu:reductions ~label:"Normalize" () in
338     let simplify = add_menu_item ~menu:reductions ~label:"Simplify" () in
339     let whd = add_menu_item ~menu:reductions ~label:"Weak head" () in
340     (match element with 
341     | None -> hyperlinks_menu_item#misc#set_sensitive false
342     | Some elt -> 
343         match hrefs_of_elt elt, href_callback with
344         | Some l, Some f ->
345             List.iter 
346               (fun h ->
347                 let item = add_menu_item ~menu:hyperlinks ~label:h () in
348                 connect_menu_item item (fun () -> f h)) l
349         | _ -> hyperlinks_menu_item#misc#set_sensitive false);
350     menu#append (GMenu.separator_item ());
351     let copy = add_menu_item ~stock:`COPY () in
352     let gui = get_gui () in
353     List.iter (fun item -> item#misc#set_sensitive gui#canCopy)
354       [ copy; check; normalize; simplify; whd ];
355     let reduction_action kind () =
356       let pat = self#tactic_text_pattern_of_selection in
357       let statement =
358         let loc = HExtlib.dummy_floc in
359         "\n" ^
360         GrafiteAstPp.pp_executable ~term_pp:(fun s -> s)
361           ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
362           ~map_unicode_to_tex:(Helm_registry.get_bool
363             "matita.paste_unicode_as_tex")
364           (GrafiteAst.Tactic (loc,
365             Some (GrafiteAst.Reduce (loc, kind, pat)),
366             GrafiteAst.Semicolon loc)) in
367       (MatitaScript.current ())#advance ~statement () in
368     connect_menu_item copy gui#copy;
369     connect_menu_item normalize (reduction_action `Normalize);
370     connect_menu_item simplify (reduction_action `Simpl);
371     connect_menu_item whd (reduction_action `Whd);
372     menu#popup ~button:right_button ~time
373
374   method private button_release_cb gdk_button =
375     if GdkEvent.Button.button gdk_button = left_button then begin
376       let button_release_x = GdkEvent.Button.x gdk_button in
377       let button_release_y = GdkEvent.Button.y gdk_button in
378       if selection_changed then
379         ()
380       else  (* selection _not_ changed *)
381         if near (button_press_x, button_press_y)
382           (button_release_x, button_release_y)
383         then
384           let x = int_of_float button_press_x in
385           let y = int_of_float button_press_y in
386           (match self#get_element_at x y with
387           | None -> ()
388           | Some elt ->
389               if has_maction elt then ignore(self#action_toggle elt) else
390               (match hrefs_of_elt elt with
391               | Some hrefs -> self#invoke_href_callback hrefs gdk_button
392               | None -> ()))
393     end;
394     false
395
396   method private invoke_href_callback hrefs gdk_button =
397     let button = GdkEvent.Button.button gdk_button in
398     if button = left_button then
399       let time = GdkEvent.Button.time gdk_button in
400       match href_callback with
401       | None -> ()
402       | Some f ->
403           (match hrefs with
404           | [ uri ] ->  f uri
405           | uris ->
406               let menu = GMenu.menu () in
407               List.iter
408                 (fun uri ->
409                   let menu_item =
410                     GMenu.menu_item ~label:uri ~packing:menu#append () in
411                   connect_menu_item menu_item 
412                   (fun () -> try f uri with Not_found -> assert false))
413                 uris;
414               menu#popup ~button ~time)
415
416   method private choose_selection_cb gdome_elt =
417     let set_selection elt =
418       let misc = self#coerce#misc in
419       self#set_selection (Some elt);
420       misc#add_selection_target ~target:"STRING" Gdk.Atom.primary;
421       ignore (misc#grab_selection Gdk.Atom.primary);
422     in
423     let rec aux elt =
424       if (elt#getAttributeNS ~namespaceURI:helm_ns
425             ~localName:xref_ds)#to_string <> ""
426       then
427         set_selection elt
428       else
429         try
430           (match elt#get_parentNode with
431           | None -> assert false
432           | Some p -> aux (new Gdome.element_of_node p))
433         with GdomeInit.DOMCastException _ -> ()
434     in
435     (match gdome_elt with
436     | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
437         ~localName:href_ds)#to_string <> "" ->
438           set_selection elt
439     | Some elt -> aux elt
440     | None -> self#set_selection None);
441     selection_changed <- true
442
443   method update_font_size = self#set_font_size !current_font_size
444
445     (** find a term by id from stored CIC infos @return either `Hyp if the id
446      * correspond to an hypothesis or `Term (cic, hyp) if the id correspond to a
447      * term. In the latter case hyp is either None (if the term is a subterm of
448      * the sequent conclusion) or Some hyp_name if the term belongs to an
449      * hypothesis *)
450   method private get_term_by_id cic_info id =
451     let unsh_item, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, _, _ =
452       cic_info in
453     let rec find_father_hyp id =
454       if Hashtbl.mem ids_to_hypotheses id
455       then Some (name_of_hypothesis (Hashtbl.find ids_to_hypotheses id))
456       else
457         let father_id =
458           try Hashtbl.find ids_to_father_ids id
459           with Not_found -> assert false in
460         match father_id with
461         | Some id -> find_father_hyp id
462         | None -> None
463     in
464     try
465       let term = Hashtbl.find ids_to_terms id in
466       let father_hyp = find_father_hyp id in
467       SelTerm (term, father_hyp)
468     with Not_found ->
469       try
470         let hyp = Hashtbl.find ids_to_hypotheses id in
471         let _, context, _ =
472           match unsh_item with Some seq -> seq | None -> assert false in
473         let context' = MatitaMisc.list_tl_at hyp context in
474         SelHyp (name_of_hypothesis hyp, context')
475       with Not_found -> assert false
476     
477   method private find_obj_conclusion id =
478     match self#cic_info with
479     | None
480     | Some (_, _, _, _, _, None) -> assert false
481     | Some (_, ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
482         let id =
483          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
484         in
485          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
486
487   method private string_of_node ~(paste_kind:paste_kind) node =
488     if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
489     then
490       match paste_kind with
491       | `Pattern ->
492           let tactic_text_pattern =  self#tactic_text_pattern_of_node node in
493           GrafiteAstPp.pp_tactic_pattern
494             ~term_pp:(fun s -> s) ~lazy_term_pp:(fun _ -> assert false)
495             ~map_unicode_to_tex:(Helm_registry.get_bool
496               "matita.paste_unicode_as_tex")
497             tactic_text_pattern
498       | `Term -> self#tactic_text_of_node node
499     else string_of_dom_node node
500
501   method private string_of_cic_sequent ~output_type cic_sequent =
502     let script = MatitaScript.current () in
503     let metasenv =
504       if script#onGoingProof () then script#proofMetasenv else [] in
505     let map_unicode_to_tex =
506       Helm_registry.get_bool "matita.paste_unicode_as_tex" in
507     ApplyTransformation.txt_of_cic_sequent_conclusion ~map_unicode_to_tex
508      ~output_type text_width metasenv cic_sequent
509
510   method private pattern_of term father_hyp unsh_sequent =
511     let _, unsh_context, conclusion = unsh_sequent in
512     let where =
513      match father_hyp with
514         None -> conclusion
515       | Some name ->
516          let rec aux =
517           function
518              [] -> assert false
519            | Some (Cic.Name name', Cic.Decl ty)::_ when name' = name -> ty
520            | Some (Cic.Name name', Cic.Def (bo,_))::_ when name' = name-> bo
521            | _::tl -> aux tl
522          in
523           aux unsh_context
524     in
525      ProofEngineHelpers.pattern_of ~term:where [term]
526
527   method private get_cic_info id =
528     match self#cic_info with
529     | Some ((Some unsh_sequent, _, _, _, _, _) as info) -> info, unsh_sequent
530     | Some ((None, _, _, _, _, _) as info) ->
531         let t = self#find_obj_conclusion id in
532         info, (~-1, [], t) (* dummy sequent for obj *)
533     | None -> assert false
534
535   method private sequent_of_id ~(paste_kind:paste_kind) id =
536     let cic_info, unsh_sequent = self#get_cic_info id in
537     let cic_sequent =
538       match self#get_term_by_id cic_info id with
539       | SelTerm (t, father_hyp) ->
540 (*
541 IDIOTA: PRIMA SI FA LA LOCATE, POI LA PATTERN_OF. MEGLIO UN'UNICA pattern_of CHE PRENDA IN INPUT UN TERMINE E UN SEQUENTE. PER IL MOMENTO RISOLVO USANDO LA father_hyp PER RITROVARE L'IPOTESI PERDUTA
542 *)
543           let occurrences =
544             ProofEngineHelpers.locate_in_conjecture t unsh_sequent in
545           (match occurrences with
546           | [ context, _t ] ->
547               (match paste_kind with
548               | `Term -> ~-1, context, t
549               | `Pattern -> ~-1, [], self#pattern_of t father_hyp unsh_sequent)
550           | _ ->
551               HLog.error (sprintf "found %d occurrences while 1 was expected"
552                 (List.length occurrences));
553               assert false) (* since it uses physical equality *)
554       | SelHyp (_name, context) -> ~-1, context, Cic.Rel 1 in
555     cic_sequent
556
557   method private string_of_selection ~(paste_kind:paste_kind) =
558     match self#get_selections with
559     | [] -> None
560     | node :: _ -> Some (self#string_of_node ~paste_kind node)
561
562   method has_selection = self#get_selections <> []
563
564     (** @return an associative list format -> string with all possible selection
565      * formats. Rationale: in order to convert the selection to TERM or PATTERN
566      * format we need the sequent, the metasenv, ... keeping all of them in a
567      * closure would be more expensive than keeping their already converted
568      * forms *)
569   method strings_of_selection =
570     try
571       let misc = self#coerce#misc in
572       List.iter
573         (fun target -> misc#add_selection_target ~target Gdk.Atom.clipboard)
574         [ "TERM"; "PATTERN"; "STRING" ];
575       ignore (misc#grab_selection Gdk.Atom.clipboard);
576       List.map
577         (fun paste_kind ->
578           paste_kind, HExtlib.unopt (self#string_of_selection ~paste_kind))
579         [ `Term; `Pattern ]
580     with Failure _ -> failwith "no selection"
581 *)
582 end
583
584 open GtkSourceView2
585
586 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
587   SourceView.make_params [] ~cont:(
588     GtkText.View.make_params ~cont:(
589       GContainer.pack_container ~create:(fun pl ->
590         let obj = SourceView.new_ () in
591         Gobject.set_params (Gobject.try_cast obj "GtkSourceView") pl;
592         new clickableMathView obj)))
593   (* MATITA1.0
594   GtkBase.Widget.size_params
595     ~cont:(OgtkSourceView2Props.pack_return (fun p ->
596       OgtkSourceView2Props.set_params
597         (new clickableMathView (GtkSourceView2Props.MathView_GMetaDOM.create p))
598         ~font_size:None ~log_verbosity:None))
599     []
600     *)
601
602 class cicMathView obj =
603 object (self)
604   inherit clickableMathView obj
605
606   val mutable current_mathml = None
607
608   method load_sequent metasenv metano =
609     let sequent = CicUtil.lookup_meta metano metasenv in
610     let (txt, unsh_sequent,
611       (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ )))
612     =
613       ApplyTransformation.txt_of_cic_sequent_all
614        ~map_unicode_to_tex:false 80 (*MATITA 1.0??*) metasenv sequent
615     in
616     self#set_cic_info
617       (Some (Some unsh_sequent,
618         ids_to_terms, ids_to_hypotheses, ids_to_father_ids,
619         Hashtbl.create 1, None));
620    (*MATITA 1.0
621     if BuildTimeConf.debug then begin
622       let name =
623        "/tmp/sequent_viewer_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
624       HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
625       ignore (domImpl#saveDocumentToFile ~name ~doc:txt ())
626     end; *)
627     self#load_root ~root:txt
628
629   method nload_sequent:
630    'status. #NCicCoercion.status as 'status -> NCic.metasenv ->
631      NCic.substitution -> int -> unit
632    = fun status metasenv subst metano ->
633     let sequent = List.assoc metano metasenv in
634     let txt =
635      ApplyTransformation.ntxt_of_cic_sequent
636       ~map_unicode_to_tex:false 80 status metasenv subst (metano,sequent)
637     in
638     (* MATITA 1.0 if BuildTimeConf.debug then begin
639       let name =
640        "/tmp/sequent_viewer_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
641       HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
642       ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
643     end;*)
644     self#load_root ~root:txt
645
646   method load_object obj =
647     let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
648     let (txt,
649       (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
650     =
651       ApplyTransformation.txt_of_cic_object_all ~map_unicode_to_tex:false
652        80 [] obj
653     in
654     self#set_cic_info
655       (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
656     (match current_mathml with
657     | Some current_mathml when use_diff ->
658 assert false (*MATITA1.0
659         self#freeze;
660         XmlDiff.update_dom ~from:current_mathml mathml;
661         self#thaw*)
662     |  _ ->
663         (* MATITA1.0 if BuildTimeConf.debug then begin
664           let name =
665            "/tmp/cic_browser_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
666           HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
667           ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
668         end;*)
669         self#load_root ~root:txt;
670         current_mathml <- Some txt);
671
672   method load_nobject :
673    'status. #NCicCoercion.status as 'status -> NCic.obj -> unit
674    = fun status obj ->
675     let txt = ApplyTransformation.ntxt_of_cic_object ~map_unicode_to_tex:false
676     80 status obj in
677 (*
678     self#set_cic_info
679       (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
680     (match current_mathml with
681     | Some current_mathml when use_diff ->
682         self#freeze;
683         XmlDiff.update_dom ~from:current_mathml mathml;
684         self#thaw
685     |  _ ->
686 *)
687         (* MATITA1.0 if BuildTimeConf.debug then begin
688           let name =
689            "/tmp/cic_browser_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
690           HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
691           ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
692         end;*)
693         self#load_root ~root:txt;
694         (*current_mathml <- Some mathml*)(*)*);
695 end
696
697 let tab_label meta_markup =
698   let rec aux =
699     function
700     | `Closed m -> sprintf "<s>%s</s>" (aux m)
701     | `Current m -> sprintf "<b>%s</b>" (aux m)
702     | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
703     | `Meta n -> sprintf "?%d" n
704   in
705   let markup = aux meta_markup in
706   (GMisc.label ~markup ~show:true ())#coerce
707
708 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
709
710 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
711   object (self)
712     inherit scriptAccessor
713
714     method cicMathView = cicMathView  (** clickableMathView accessor *)
715
716     val mutable pages = 0
717     val mutable switch_page_callback = None
718     val mutable page2goal = []  (* associative list: page no -> goal no *)
719     val mutable goal2page = []  (* the other way round *)
720     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
721     val mutable _metasenv = `Old []
722     val mutable scrolledWin: GBin.scrolled_window option = None
723       (* scrolled window to which the sequentViewer is currently attached *)
724     val logo = (GMisc.image
725       ~file:(MatitaMisc.image_path "matita_medium.png") ()
726       :> GObj.widget)
727             
728     val logo_with_qed = (GMisc.image
729       ~file:(MatitaMisc.image_path "matita_small.png") ()
730       :> GObj.widget)
731
732     method load_logo =
733      notebook#set_show_tabs false;
734      ignore(notebook#append_page logo)
735
736     method load_logo_with_qed =
737      notebook#set_show_tabs false;
738      ignore(notebook#append_page logo_with_qed)
739
740     method reset =
741       cicMathView#remove_selections;
742       (match scrolledWin with
743       | Some w ->
744           (* removing page from the notebook will destroy all contained widget,
745           * we do not want the cicMathView to be destroyed as well *)
746           w#remove cicMathView#coerce;
747           scrolledWin <- None
748       | None -> ());
749       (match switch_page_callback with
750       | Some id ->
751           GtkSignal.disconnect notebook#as_widget id;
752           switch_page_callback <- None
753       | None -> ());
754       for i = 0 to pages do notebook#remove_page 0 done; 
755       notebook#set_show_tabs true;
756       pages <- 0;
757       page2goal <- [];
758       goal2page <- [];
759       goal2win <- [];
760       _metasenv <- `Old []; 
761       self#script#setGoal None
762
763     method load_sequents : 'status. #NCicCoercion.status as 'status -> 'a
764      = fun status { proof= (_,metasenv,_subst,_,_, _) as proof; stack = stack } 
765      ->
766       _metasenv <- `Old metasenv;
767       pages <- 0;
768       let win goal_switch =
769         let w =
770           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
771             ~shadow_type:`IN ~show:true ()
772         in
773         let reparent () =
774           scrolledWin <- Some w;
775           match cicMathView#misc#parent with
776           | None -> w#add cicMathView#coerce
777           | Some parent ->
778              let parent =
779               match cicMathView#misc#parent with
780                  None -> assert false
781                | Some p -> GContainer.cast_container p
782              in
783               parent#remove cicMathView#coerce;
784               w#add cicMathView#coerce
785         in
786         goal2win <- (goal_switch, reparent) :: goal2win;
787         w#coerce
788       in
789       assert (
790         let stack_goals = Stack.open_goals stack in
791         let proof_goals = ProofEngineTypes.goals_of_proof proof in
792         if
793           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
794           <> List.sort Pervasives.compare proof_goals
795         then begin
796           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
797           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
798           false
799         end
800         else true
801       );
802       let render_switch =
803         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
804       in
805       let page = ref 0 in
806       let added_goals = ref [] in
807         (* goals can be duplicated on the tack due to focus, but we should avoid
808          * multiple labels in the user interface *)
809       let add_tab markup goal_switch =
810         let goal = Stack.goal_of_switch goal_switch in
811         if not (List.mem goal !added_goals) then begin
812           ignore(notebook#append_page 
813             ~tab_label:(tab_label markup) (win goal_switch));
814           page2goal <- (!page, goal_switch) :: page2goal;
815           goal2page <- (goal_switch, !page) :: goal2page;
816           incr page;
817           pages <- pages + 1;
818           added_goals := goal :: !added_goals
819         end
820       in
821       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
822       Stack.iter  (** populate notebook with tabs *)
823         ~env:(fun depth tag (pos, sw) ->
824           let markup =
825             match depth, pos with
826             | 0, 0 -> `Current (render_switch sw)
827             | 0, _ -> `Shift (pos, `Current (render_switch sw))
828             | 1, pos when Stack.head_tag stack = `BranchTag ->
829                 `Shift (pos, render_switch sw)
830             | _ -> render_switch sw
831           in
832           add_tab markup sw)
833         ~cont:add_switch ~todo:add_switch
834         stack;
835       switch_page_callback <-
836         Some (notebook#connect#switch_page ~callback:(fun page ->
837           let goal_switch =
838             try List.assoc page page2goal with Not_found -> assert false
839           in
840           self#script#setGoal (Some (goal_of_switch goal_switch));
841           self#render_page status ~page ~goal_switch))
842
843     method nload_sequents : 'status. #NTacStatus.tac_status as 'status -> unit
844     = fun status ->
845      let _,_,metasenv,subst,_ = status#obj in
846       _metasenv <- `New (metasenv,subst);
847       pages <- 0;
848       let win goal_switch =
849         let w =
850           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
851             ~shadow_type:`IN ~show:true ()
852         in
853         let reparent () =
854           scrolledWin <- Some w;
855           match cicMathView#misc#parent with
856           | None -> w#add cicMathView#coerce
857           | Some parent ->
858              let parent =
859               match cicMathView#misc#parent with
860                  None -> assert false
861                | Some p -> GContainer.cast_container p
862              in
863               parent#remove cicMathView#coerce;
864               w#add cicMathView#coerce
865         in
866         goal2win <- (goal_switch, reparent) :: goal2win;
867         w#coerce
868       in
869       assert (
870         let stack_goals = Stack.open_goals status#stack in
871         let proof_goals = List.map fst metasenv in
872         if
873           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
874           <> List.sort Pervasives.compare proof_goals
875         then begin
876           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
877           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
878           false
879         end
880         else true
881       );
882       let render_switch =
883         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
884       in
885       let page = ref 0 in
886       let added_goals = ref [] in
887         (* goals can be duplicated on the tack due to focus, but we should avoid
888          * multiple labels in the user interface *)
889       let add_tab markup goal_switch =
890         let goal = Stack.goal_of_switch goal_switch in
891         if not (List.mem goal !added_goals) then begin
892           ignore(notebook#append_page 
893             ~tab_label:(tab_label markup) (win goal_switch));
894           page2goal <- (!page, goal_switch) :: page2goal;
895           goal2page <- (goal_switch, !page) :: goal2page;
896           incr page;
897           pages <- pages + 1;
898           added_goals := goal :: !added_goals
899         end
900       in
901       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
902       Stack.iter  (** populate notebook with tabs *)
903         ~env:(fun depth tag (pos, sw) ->
904           let markup =
905             match depth, pos with
906             | 0, 0 -> `Current (render_switch sw)
907             | 0, _ -> `Shift (pos, `Current (render_switch sw))
908             | 1, pos when Stack.head_tag status#stack = `BranchTag ->
909                 `Shift (pos, render_switch sw)
910             | _ -> render_switch sw
911           in
912           add_tab markup sw)
913         ~cont:add_switch ~todo:add_switch
914         status#stack;
915       switch_page_callback <-
916         Some (notebook#connect#switch_page ~callback:(fun page ->
917           let goal_switch =
918             try List.assoc page page2goal with Not_found -> assert false
919           in
920           self#script#setGoal (Some (goal_of_switch goal_switch));
921           self#render_page status ~page ~goal_switch))
922
923     method private render_page:
924      'status. #NCicCoercion.status as 'status -> page:int ->
925        goal_switch:Stack.switch -> unit
926      = fun status ~page ~goal_switch ->
927       (match goal_switch with
928       | Stack.Open goal ->
929          (match _metasenv with
930              `Old menv -> cicMathView#load_sequent menv goal
931            | `New (menv,subst) ->
932                cicMathView#nload_sequent status menv subst goal)
933       | Stack.Closed goal ->
934           let doc = Lazy.force closed_goal_mathml in
935           cicMathView#load_root ~root:doc);
936       (try
937         cicMathView#set_selection None;
938         List.assoc goal_switch goal2win ()
939       with Not_found -> assert false)
940
941     method goto_sequent: 'status. #NCicCoercion.status as 'status -> int -> unit
942      = fun status goal ->
943       let goal_switch, page =
944         try
945           List.find
946             (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
947             goal2page
948         with Not_found -> assert false
949       in
950       notebook#goto_page page;
951       self#render_page status ~page ~goal_switch
952
953   end
954
955  (** constructors *)
956 type 'widget constructor =
957  ?hadjustment:GData.adjustment ->
958  ?vadjustment:GData.adjustment ->
959  ?font_size:int ->
960  ?log_verbosity:int ->
961  ?auto_indent:bool ->
962  ?highlight_current_line:bool ->
963  ?indent_on_tab:bool ->
964  ?indent_width:int ->
965  ?insert_spaces_instead_of_tabs:bool ->
966  ?right_margin_position:int ->
967  ?show_line_marks:bool ->
968  ?show_line_numbers:bool ->
969  ?show_right_margin:bool ->
970  ?smart_home_end:SourceView2Enums.source_smart_home_end_type ->
971  ?tab_width:int ->
972  ?editable:bool ->
973  ?cursor_visible:bool ->
974  ?justification:GtkEnums.justification ->
975  ?wrap_mode:GtkEnums.wrap_mode ->
976  ?accepts_tab:bool ->
977  ?border_width:int ->
978  ?width:int ->
979  ?height:int ->
980  ?packing:(GObj.widget -> unit) ->
981  ?show:bool -> unit ->
982   'widget
983
984 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
985   SourceView.make_params [] ~cont:(
986     GtkText.View.make_params ~cont:(
987       GContainer.pack_container ~create:(fun pl ->
988         let obj = SourceView.new_ () in
989         Gobject.set_params (Gobject.try_cast obj "GtkSourceView") pl;
990         new cicMathView obj)))
991 (* MATITA 1.0
992   GtkBase.Widget.size_params
993     ~cont:(OgtkMathViewProps.pack_return (fun p ->
994       OgtkMathViewProps.set_params
995         (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
996         ~font_size ~log_verbosity))
997     []
998 *)
999
1000 let blank_uri = BuildTimeConf.blank_uri
1001 let current_proof_uri = BuildTimeConf.current_proof_uri
1002
1003 type term_source =
1004   [ `Ast of CicNotationPt.term
1005   | `Cic of Cic.term * Cic.metasenv
1006   | `NCic of NCic.term * NCic.context * NCic.metasenv * NCic.substitution
1007   | `String of string
1008   ]
1009
1010 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
1011   ()
1012 =
1013   let whelp_RE = Pcre.regexp "^\\s*whelp" in
1014   let uri_RE =
1015     Pcre.regexp
1016       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
1017   in
1018   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
1019   let metadata_RE = Pcre.regexp "^metadata:/(deps)/(forward|backward)/(.*)$" in
1020   let whelp_query_RE = Pcre.regexp
1021     "^\\s*whelp\\s+([^\\s]+)\\s+(\"|\\()(.*)(\\)|\")$" 
1022   in
1023   let is_metadata txt = Pcre.pmatch ~rex:metadata_RE txt in
1024   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
1025   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
1026   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
1027   let gui = get_gui () in
1028   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
1029   let gviz = LablGraphviz.graphviz ~packing:win#graphScrolledWin#add () in
1030   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
1031   let combo,_ = GEdit.combo_box_text ~strings:queries () in
1032   let activate_combo_query input q =
1033     let q' = String.lowercase q in
1034     let rec aux i = function
1035       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
1036       | h::_ when String.lowercase h = q' -> i
1037       | _::tl -> aux (i+1) tl
1038     in
1039     win#queryInputText#set_text input;
1040     combo#set_active (aux 0 queries);
1041   in
1042   let searchText = 
1043     GSourceView2.source_view ~auto_indent:false ~editable:false ()
1044   in
1045   let _ =
1046      win#scrolledwinContent#add (searchText :> GObj.widget);
1047      let callback () = 
1048        let text = win#entrySearch#text in
1049        let highlight start end_ =
1050          searchText#source_buffer#move_mark `INSERT ~where:start;
1051          searchText#source_buffer#move_mark `SEL_BOUND ~where:end_;
1052          searchText#scroll_mark_onscreen `INSERT
1053        in
1054        let iter = searchText#source_buffer#get_iter `SEL_BOUND in
1055        match iter#forward_search text with
1056        | None -> 
1057            (match searchText#source_buffer#start_iter#forward_search text with
1058            | None -> ()
1059            | Some (start,end_) -> highlight start end_)
1060        | Some (start,end_) -> highlight start end_
1061      in
1062      ignore(win#entrySearch#connect#activate ~callback);
1063      ignore(win#buttonSearch#connect#clicked ~callback);
1064   in
1065   let set_whelp_query txt =
1066     let query, arg = 
1067       try
1068         let q = Pcre.extract ~rex:whelp_query_RE txt in
1069         q.(1), q.(3)
1070       with Not_found -> failwith "Malformed Whelp query"
1071     in
1072     activate_combo_query arg query;
1073   in
1074   let toplevel = win#toplevel in
1075   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
1076   let fail message = 
1077     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
1078       ~parent:toplevel ()  
1079   in
1080   let tags =
1081     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
1082       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
1083   in
1084   let b = (not (Helm_registry.get_bool "matita.debug")) in
1085   let handle_error f =
1086     try
1087       f ()
1088     with exn ->
1089       if b then
1090         fail (snd (MatitaExcPp.to_string exn))
1091       else raise exn
1092   in
1093   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
1094   let load_easter_egg = lazy (
1095     win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
1096   in
1097   let load_hints () =
1098       let module Pp = GraphvizPp.Dot in
1099       let filename, oc = Filename.open_temp_file "matita" ".dot" in
1100       let fmt = Format.formatter_of_out_channel oc in
1101       let status = (MatitaScript.current ())#grafite_status in
1102       Pp.header 
1103         ~name:"Hints"
1104         ~graph_type:"graph"
1105         ~graph_attrs:["overlap", "false"]
1106         ~node_attrs:["fontsize", "9"; "width", ".4"; 
1107             "height", ".4"; "shape", "box"]
1108         ~edge_attrs:["fontsize", "10"; "len", "2"] fmt;
1109       NCicUnifHint.generate_dot_file status fmt;
1110       Pp.trailer fmt;
1111       Pp.raw "@." fmt;
1112       close_out oc;
1113       gviz#load_graph_from_file ~gviz_cmd:"neato -Tpng" filename;
1114       (*HExtlib.safe_remove filename*)
1115   in
1116   let load_coerchgraph tred () = 
1117       let module Pp = GraphvizPp.Dot in
1118       let filename, oc = Filename.open_temp_file "matita" ".dot" in
1119       let fmt = Format.formatter_of_out_channel oc in
1120       Pp.header 
1121         ~name:"Coercions"
1122         ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
1123         ~edge_attrs:["fontsize", "10"] fmt;
1124       let status = (MatitaScript.current ())#grafite_status in
1125       NCicCoercion.generate_dot_file status fmt;
1126       Pp.trailer fmt;
1127       Pp.header 
1128         ~name:"OLDCoercions"
1129         ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
1130         ~edge_attrs:["fontsize", "10"] fmt;
1131       CoercGraph.generate_dot_file fmt;
1132       Pp.trailer fmt;
1133       Pp.raw "@." fmt;
1134       close_out oc;
1135       if tred then
1136         gviz#load_graph_from_file 
1137           ~gviz_cmd:"dot -Txdot | tred |gvpack -gv | dot" filename
1138       else
1139         gviz#load_graph_from_file 
1140           ~gviz_cmd:"dot -Txdot | gvpack -gv | dot" filename;
1141       HExtlib.safe_remove filename
1142   in
1143   object (self)
1144     inherit scriptAccessor
1145     
1146     (* Whelp bar queries *)
1147
1148     val mutable gviz_graph = MetadataDeps.DepGraph.dummy
1149     val mutable gviz_uri = UriManager.uri_of_string "cic:/dummy.con";
1150
1151     val dep_contextual_menu = GMenu.menu ()
1152
1153     initializer
1154       activate_combo_query "" "locate";
1155       win#whelpBarComboVbox#add combo#coerce;
1156       let start_query () = 
1157        let query = 
1158          try
1159            String.lowercase (List.nth queries combo#active) 
1160          with Not_found -> assert false in
1161        let input = win#queryInputText#text in
1162        let statement = 
1163          if query = "locate" then
1164              "whelp " ^ query ^ " \"" ^ input ^ "\"." 
1165            else
1166              "whelp " ^ query ^ " (" ^ input ^ ")." 
1167        in
1168         (MatitaScript.current ())#advance ~statement ()
1169       in
1170       ignore(win#queryInputText#connect#activate ~callback:start_query);
1171       ignore(combo#connect#changed ~callback:start_query);
1172       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
1173       win#mathOrListNotebook#set_show_tabs false;
1174       win#browserForwardButton#misc#set_sensitive false;
1175       win#browserBackButton#misc#set_sensitive false;
1176       ignore (win#browserUri#connect#activate (handle_error' (fun () ->
1177         self#loadInput win#browserUri#text)));
1178       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
1179         self#load (`About `Current_proof))));
1180       ignore (win#browserRefreshButton#connect#clicked
1181         (handle_error' (self#refresh ~force:true)));
1182       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
1183       ignore (win#browserForwardButton#connect#clicked
1184         (handle_error' self#forward));
1185       ignore (win#toplevel#event#connect#delete (fun _ ->
1186         let my_id = Oo.id self in
1187         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
1188         false));
1189       ignore(win#whelpResultTreeview#connect#row_activated 
1190         ~callback:(fun _ _ ->
1191           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
1192       mathView#set_href_callback (Some (fun uri ->
1193         handle_error (fun () ->
1194          let uri =
1195           try
1196            `Uri (UriManager.uri_of_string uri)
1197           with
1198            UriManager.IllFormedUri _ ->
1199             `NRef (NReference.reference_of_string uri)
1200          in
1201           self#load uri)));
1202       gviz#connect_href (fun button_ev attrs ->
1203         let time = GdkEvent.Button.time button_ev in
1204         let uri = List.assoc "href" attrs in
1205         gviz_uri <- UriManager.uri_of_string uri;
1206         match GdkEvent.Button.button button_ev with
1207         | button when button = left_button -> self#load (`Uri gviz_uri)
1208         | button when button = right_button ->
1209             dep_contextual_menu#popup ~button ~time
1210         | _ -> ());
1211       connect_menu_item win#depGraphMenuItem (fun () ->
1212         match self#currentCicUri with
1213         | Some uri -> self#load (`Metadata (`Deps (`Fwd, uri)))
1214         | None -> ());
1215       connect_menu_item win#invDepGraphMenuItem (fun () ->
1216         match self#currentCicUri with
1217         | Some uri -> self#load (`Metadata (`Deps (`Back, uri)))
1218         | None -> ());
1219       connect_menu_item win#browserCloseMenuItem (fun () ->
1220         let my_id = Oo.id self in
1221         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
1222         win#toplevel#misc#hide(); win#toplevel#destroy ());
1223       (* remove hbugs *)
1224       (*
1225       connect_menu_item win#hBugsTutorsMenuItem (fun () ->
1226         self#load (`HBugs `Tutors));
1227       *)
1228       win#hBugsTutorsMenuItem#misc#hide ();
1229       connect_menu_item win#browserUrlMenuItem (fun () ->
1230         win#browserUri#misc#grab_focus ());
1231       connect_menu_item win#univMenuItem (fun () ->
1232         match self#currentCicUri with
1233         | Some uri -> self#load (`Univs uri)
1234         | None -> ());
1235
1236       (* fill dep graph contextual menu *)
1237       let go_menu_item =
1238         GMenu.image_menu_item ~label:"Browse it"
1239           ~packing:dep_contextual_menu#append () in
1240       let expand_menu_item =
1241         GMenu.image_menu_item ~label:"Expand"
1242           ~packing:dep_contextual_menu#append () in
1243       let collapse_menu_item =
1244         GMenu.image_menu_item ~label:"Collapse"
1245           ~packing:dep_contextual_menu#append () in
1246       dep_contextual_menu#append (go_menu_item :> GMenu.menu_item);
1247       dep_contextual_menu#append (expand_menu_item :> GMenu.menu_item);
1248       dep_contextual_menu#append (collapse_menu_item :> GMenu.menu_item);
1249       connect_menu_item go_menu_item (fun () -> self#load (`Uri gviz_uri));
1250       connect_menu_item expand_menu_item (fun () ->
1251         MetadataDeps.DepGraph.expand gviz_uri gviz_graph;
1252         self#redraw_gviz ~center_on:gviz_uri ());
1253       connect_menu_item collapse_menu_item (fun () ->
1254         MetadataDeps.DepGraph.collapse gviz_uri gviz_graph;
1255         self#redraw_gviz ~center_on:gviz_uri ());
1256
1257       self#_load (`About `Blank);
1258       toplevel#show ()
1259
1260     val mutable current_entry = `About `Blank 
1261
1262       (** @return None if no object uri can be built from the current entry *)
1263     method private currentCicUri =
1264       match current_entry with
1265       | `Uri uri
1266       | `Metadata (`Deps (_, uri)) -> Some uri
1267       | _ -> None
1268
1269     val model =
1270       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
1271     val model_univs =
1272       new MatitaGtkMisc.multiStringListModel ~cols:2 win#universesTreeview
1273
1274     val mutable lastDir = ""  (* last loaded "directory" *)
1275
1276     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
1277
1278     method private _getSelectedUri () =
1279       match model#easy_selection () with
1280       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
1281 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
1282       | [sel] -> lastDir ^ sel
1283       | _ -> assert false
1284
1285     (** history RATIONALE 
1286      *
1287      * All operations about history are done using _historyFoo.
1288      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
1289      *)
1290           
1291     method private _historyAdd item = 
1292       history#add item;
1293       win#browserBackButton#misc#set_sensitive true;
1294       win#browserForwardButton#misc#set_sensitive false
1295
1296     method private _historyPrev () =
1297       let item = history#previous in
1298       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
1299       win#browserForwardButton#misc#set_sensitive true;
1300       item
1301     
1302     method private _historyNext () =
1303       let item = history#next in
1304       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
1305       win#browserBackButton#misc#set_sensitive true;
1306       item
1307
1308     (** notebook RATIONALE 
1309      * 
1310      * Use only these functions to switch between the tabs
1311      *)
1312     method private _showMath = win#mathOrListNotebook#goto_page  0
1313     method private _showList = win#mathOrListNotebook#goto_page  1
1314     method private _showList2 = win#mathOrListNotebook#goto_page 5
1315     method private _showSearch = win#mathOrListNotebook#goto_page 6
1316     method private _showGviz = win#mathOrListNotebook#goto_page  3
1317     method private _showHBugs = win#mathOrListNotebook#goto_page 4
1318
1319     method private back () =
1320       try
1321         self#_load (self#_historyPrev ())
1322       with MatitaMisc.History_failure -> ()
1323
1324     method private forward () =
1325       try
1326         self#_load (self#_historyNext ())
1327       with MatitaMisc.History_failure -> ()
1328
1329       (* loads a uri which can be a cic uri or an about:* uri
1330       * @param uri string *)
1331     method private _load ?(force=false) entry =
1332       handle_error (fun () ->
1333        if entry <> current_entry || entry = `About `Current_proof || entry =
1334          `About `Coercions || entry = `About `CoercionsFull || force then
1335         begin
1336           (match entry with
1337           | `About `Current_proof -> self#home ()
1338           | `About `Blank -> self#blank ()
1339           | `About `Us -> self#egg ()
1340           | `About `CoercionsFull -> self#coerchgraph false ()
1341           | `About `Coercions -> self#coerchgraph true ()
1342           | `About `Hints -> self#hints ()
1343           | `About `TeX -> self#tex ()
1344           | `About `Grammar -> self#grammar () 
1345           | `Check term -> self#_loadCheck term
1346           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
1347           | `NCic (term, ctx, metasenv, subst) -> 
1348                self#_loadTermNCic term metasenv subst ctx
1349           | `Dir dir -> self#_loadDir dir
1350           | `HBugs `Tutors -> self#_loadHBugsTutors
1351           | `Metadata (`Deps ((`Fwd | `Back) as dir, uri)) ->
1352               self#dependencies dir uri ()
1353           | `Uri uri -> self#_loadUriManagerUri uri
1354           | `NRef nref -> self#_loadNReference nref
1355           | `Univs uri -> self#_loadUnivs uri
1356           | `Whelp (query, results) -> 
1357               set_whelp_query query;
1358               self#_loadList (List.map (fun r -> "obj",
1359                 UriManager.string_of_uri r) results));
1360           self#setEntry entry
1361         end)
1362
1363     method private blank () =
1364       self#_showMath;
1365       mathView#load_root ""
1366
1367     method private _loadCheck term =
1368       failwith "not implemented _loadCheck";
1369 (*       self#_showMath *)
1370
1371     method private egg () =
1372       win#mathOrListNotebook#goto_page 2;
1373       Lazy.force load_easter_egg
1374
1375     method private redraw_gviz ?center_on () =
1376       if Sys.command "which dot" = 0 then
1377        let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
1378        let fmt = Format.formatter_of_out_channel oc in
1379        MetadataDeps.DepGraph.render fmt gviz_graph;
1380        close_out oc;
1381        gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
1382        (match center_on with
1383        | None -> ()
1384        | Some uri -> gviz#center_on_href (UriManager.string_of_uri uri));
1385        HExtlib.safe_remove tmpfile
1386       else
1387        MatitaGtkMisc.report_error ~title:"graphviz error"
1388         ~message:("Graphviz is not installed but is necessary to render "^
1389          "the graph of dependencies amoung objects. Please install it.")
1390         ~parent:win#toplevel ()
1391
1392     method private dependencies direction uri () =
1393       let dbd = LibraryDb.instance () in
1394       let graph =
1395         match direction with
1396         | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
1397         | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
1398       gviz_graph <- graph;  (** XXX check this for memory consuption *)
1399       self#redraw_gviz ~center_on:uri ();
1400       self#_showGviz
1401
1402     method private coerchgraph tred () =
1403       load_coerchgraph tred ();
1404       self#_showGviz
1405
1406     method private hints () =
1407       load_hints ();
1408       self#_showGviz
1409
1410     method private tex () =
1411       let b = Buffer.create 1000 in
1412       Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
1413       List.iter 
1414         (fun l ->
1415            List.iter (fun sym ->
1416              Printf.bprintf b "  %s" (Glib.Utf8.from_unichar sym) 
1417            ) l;
1418            Printf.bprintf b "\n";
1419         )
1420         (List.sort 
1421           (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
1422           (Virtuals.get_all_eqclass ()));
1423       Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
1424       List.iter 
1425         (fun tag, items -> 
1426            Printf.bprintf b "  %s:\n" tag;
1427            List.iter 
1428              (fun names, symbol ->
1429                 Printf.bprintf b "  \t%s\t%s\n" 
1430                   (Glib.Utf8.from_unichar symbol)
1431                   (String.concat ", " names))
1432              (List.sort 
1433                (fun (_,a) (_,b) -> compare a b)
1434                items);
1435            Printf.bprintf b "\n")
1436         (List.sort 
1437           (fun (a,_) (b,_) -> compare a b)
1438           (Virtuals.get_all_virtuals ()));
1439       self#_loadText (Buffer.contents b)
1440
1441     method private _loadText text =
1442       searchText#source_buffer#set_text text;
1443       win#entrySearch#misc#grab_focus ();
1444       self#_showSearch
1445
1446     method private grammar () =
1447       self#_loadText (Print_grammar.ebnf_of_term ());
1448
1449     method private home () =
1450       self#_showMath;
1451       match self#script#grafite_status#proof_status with
1452       | Proof  (uri, metasenv, _subst, bo, ty, attrs) ->
1453          let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1454          let obj =
1455           Cic.CurrentProof (name, metasenv, Lazy.force bo, ty, [], attrs)
1456          in
1457           self#_loadObj obj
1458       | Incomplete_proof { proof = (uri, metasenv, _subst, bo, ty, attrs) } ->
1459          let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1460          let obj =
1461           Cic.CurrentProof (name, metasenv, Lazy.force bo, ty, [], attrs)
1462          in
1463           self#_loadObj obj
1464       | _ ->
1465         match self#script#grafite_status#ng_mode with
1466            `ProofMode ->
1467              self#_loadNObj self#script#grafite_status
1468              self#script#grafite_status#obj
1469          | _ -> self#blank ()
1470
1471       (** loads a cic uri from the environment
1472       * @param uri UriManager.uri *)
1473     method private _loadUriManagerUri uri =
1474       let uri = UriManager.strip_xpointer uri in
1475       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1476       self#_loadObj obj
1477
1478     method private _loadNReference (NReference.Ref (uri,_)) =
1479       let obj = NCicEnvironment.get_checked_obj uri in
1480       self#_loadNObj self#script#grafite_status obj
1481
1482     method private _loadUnivs uri =
1483       let uri = UriManager.strip_xpointer uri in
1484       let (_, u) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1485       let _,us = CicUniv.do_rank u in
1486       let l = 
1487         List.map 
1488           (fun u -> 
1489            [ CicUniv.string_of_universe u ; string_of_int (CicUniv.get_rank u)])
1490           us 
1491       in
1492       self#_loadList2 l
1493       
1494     method private _loadDir dir = 
1495       let content = Http_getter.ls ~local:false dir in
1496       let l =
1497         List.fast_sort
1498           Pervasives.compare
1499           (List.map
1500             (function 
1501               | Http_getter_types.Ls_section s -> "dir", s
1502               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
1503             content)
1504       in
1505       lastDir <- dir;
1506       self#_loadList l
1507
1508     method private _loadHBugsTutors =
1509       self#_showHBugs
1510
1511     method private setEntry entry =
1512       win#browserUri#set_text (MatitaTypes.string_of_entry entry);
1513       current_entry <- entry
1514
1515     method private _loadObj obj =
1516       (* showMath must be done _before_ loading the document, since if the
1517        * widget is not mapped (hidden by the notebook) the document is not
1518        * rendered *)
1519       self#_showMath;
1520       mathView#load_object obj
1521
1522     method private _loadNObj status obj =
1523       (* showMath must be done _before_ loading the document, since if the
1524        * widget is not mapped (hidden by the notebook) the document is not
1525        * rendered *)
1526       self#_showMath;
1527       mathView#load_nobject status obj
1528
1529     method private _loadTermCic term metasenv =
1530       let context = self#script#proofContext in
1531       let dummyno = CicMkImplicit.new_meta metasenv [] in
1532       let sequent = (dummyno, context, term) in
1533       mathView#load_sequent (sequent :: metasenv) dummyno;
1534       self#_showMath
1535
1536     method private _loadTermNCic term m s c =
1537       let d = 0 in
1538       let m = (0,([],c,term))::m in
1539       let status = (MatitaScript.current ())#grafite_status in
1540       mathView#nload_sequent status m s d;
1541       self#_showMath
1542
1543     method private _loadList l =
1544       model#list_store#clear ();
1545       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
1546       self#_showList
1547
1548     method private _loadList2 l =
1549       model_univs#list_store#clear ();
1550       List.iter model_univs#easy_mappend l;
1551       self#_showList2
1552     
1553     (** { public methods, all must call _load!! } *)
1554       
1555     method load entry =
1556       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
1557
1558     (**  this is what the browser does when you enter a string an hit enter *)
1559     method loadInput txt =
1560       let parse_metadata s =
1561         let subs = Pcre.extract ~rex:metadata_RE s in
1562         let uri = UriManager.uri_of_string ("cic:/" ^ subs.(3)) in
1563         match subs.(1), subs.(2) with
1564         | "deps", "forward" -> `Deps (`Fwd, uri)
1565         | "deps", "backward" -> `Deps (`Back, uri)
1566         | _ -> assert false
1567       in
1568       let txt = HExtlib.trim_blanks txt in
1569       (* (* ZACK: what the heck? *)
1570       let fix_uri txt =
1571         UriManager.string_of_uri
1572           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
1573       in
1574       *)
1575       if is_whelp txt then begin
1576         set_whelp_query txt;  
1577         (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
1578       end else begin
1579         let entry =
1580           match txt with
1581           | txt when is_uri txt ->
1582               `Uri (UriManager.uri_of_string ((*fix_uri*) txt))
1583           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
1584           | txt when is_metadata txt -> `Metadata (parse_metadata txt)
1585           | "hbugs:/tutors/" -> `HBugs `Tutors
1586           | txt ->
1587              (try
1588                MatitaTypes.entry_of_string txt
1589               with Invalid_argument _ ->
1590                raise
1591                 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
1592         in
1593         self#_load entry;
1594         self#_historyAdd entry
1595       end
1596
1597       (** {2 methods accessing underlying GtkMathView} *)
1598
1599     method updateFontSize = mathView#set_font_size !current_font_size
1600
1601       (** {2 methods used by constructor only} *)
1602
1603     method win = win
1604     method history = history
1605     method currentEntry = current_entry
1606     method refresh ~force () = self#_load ~force current_entry
1607
1608   end
1609   
1610 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
1611   MatitaGuiTypes.sequentsViewer
1612 =
1613   new sequentsViewer ~notebook ~cicMathView ()
1614
1615 let cicBrowser () =
1616   let size = BuildTimeConf.browser_history_size in
1617   let rec aux history =
1618     let browser = new cicBrowser_impl ~history () in
1619     let win = browser#win in
1620     ignore (win#browserNewButton#connect#clicked (fun () ->
1621       let history =
1622         new MatitaMisc.browser_history ~memento:history#save size
1623           (`About `Blank)
1624       in
1625       let newBrowser = aux history in
1626       newBrowser#load browser#currentEntry));
1627 (*
1628       (* attempt (failed) to close windows on CTRL-W ... *)
1629     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
1630       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
1631 *)
1632     cicBrowsers := browser :: !cicBrowsers;
1633     (browser :> MatitaGuiTypes.cicBrowser)
1634   in
1635   let history = new MatitaMisc.browser_history size (`About `Blank) in
1636   aux history
1637
1638 let default_cicMathView () = cicMathView ~show:true ()
1639 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
1640
1641 let default_sequentsViewer () =
1642   let gui = get_gui () in
1643   let cicMathView = cicMathView_instance () in
1644   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
1645 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
1646
1647 let mathViewer () = 
1648   object(self)
1649     method private get_browser reuse = 
1650       if reuse then
1651         (match !cicBrowsers with
1652         | [] -> cicBrowser ()
1653         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
1654       else
1655         (cicBrowser ())
1656           
1657     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
1658       
1659     method show_uri_list ?(reuse=false) ~entry l =
1660       (self#get_browser reuse)#load entry
1661
1662     method screenshot status sequents metasenv subst (filename as ofn) =
1663       () (*MATITA 1.0
1664        let w = GWindow.window ~title:"screenshot" () in
1665        let width = 500 in
1666        let height = 2000 in
1667        let m = GMathView.math_view 
1668           ~font_size:!current_font_size ~width ~height
1669           ~packing:w#add
1670           ~show:true ()
1671        in
1672        w#show ();
1673        let filenames = 
1674         HExtlib.list_mapi
1675          (fun (mno,_ as sequent) i ->
1676             let mathml = 
1677               ApplyTransformation.nmml_of_cic_sequent 
1678                 status metasenv subst sequent
1679             in
1680             m#load_root ~root:mathml#get_documentElement;
1681             let pixmap = m#get_buffer in
1682             let pixbuf = GdkPixbuf.create ~width ~height () in
1683             GdkPixbuf.get_from_drawable ~dest:pixbuf pixmap;
1684             let filename = 
1685               filename ^ "-raw" ^ string_of_int i ^ ".png" 
1686             in
1687             GdkPixbuf.save ~filename ~typ:"png" pixbuf;
1688             filename,mno)
1689          sequents
1690        in
1691        let items = 
1692          List.map (fun (x,mno) -> 
1693            ignore(Sys.command
1694              (Printf.sprintf
1695               ("convert "^^
1696               " '(' -gravity west -bordercolor grey -border 1 label:%d ')' "^^
1697               " '(' -trim -bordercolor white -border 5 "^^
1698                 " -bordercolor grey -border 1 %s ')' -append %s ")
1699               mno
1700               (Filename.quote x)
1701               (Filename.quote (x ^ ".label.png"))));
1702              x ^ ".label.png")
1703          filenames
1704        in
1705        let rec div2 = function 
1706          | [] -> []
1707          | [x] -> [[x]]
1708          | x::y::tl -> [x;y] :: div2 tl
1709        in
1710        let items = div2 items in
1711        ignore(Sys.command (Printf.sprintf 
1712          "convert %s -append  %s" 
1713           (String.concat ""
1714             (List.map (fun items ->
1715               Printf.sprintf " '(' %s +append ')' "
1716                 (String.concat 
1717                    (" '(' -gravity center -size 10x10 xc: ')' ") items)) items))
1718          (Filename.quote (ofn ^ ".png")))); 
1719        List.iter (fun x,_ -> Sys.remove x) filenames;
1720        List.iter Sys.remove (List.flatten items);
1721        w#destroy ();
1722     *)
1723   end
1724
1725 let refresh_all_browsers () =
1726   List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
1727
1728 let update_font_sizes () =
1729   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
1730   (cicMathView_instance ())#update_font_size
1731
1732 let get_math_views () =
1733   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
1734   :: (List.map (fun b -> b#mathView) !cicBrowsers)
1735
1736 let find_selection_owner () =
1737   let rec aux =
1738     function
1739     | [] -> raise Not_found
1740     | mv :: tl ->
1741         (match mv#get_selections with
1742         | [] -> aux tl
1743         | sel :: _ -> mv)
1744   in
1745   aux (get_math_views ())
1746
1747 let has_selection () =
1748   try ignore (find_selection_owner ()); true
1749   with Not_found -> false
1750
1751 let math_view_clipboard = ref None (* associative list target -> string *)
1752 let has_clipboard () = !math_view_clipboard <> None
1753 let empty_clipboard () = math_view_clipboard := None
1754
1755 let copy_selection () =
1756   try
1757     math_view_clipboard :=
1758       Some ((find_selection_owner ())#strings_of_selection)
1759   with Not_found -> failwith "no selection"
1760
1761 let paste_clipboard paste_kind =
1762   match !math_view_clipboard with
1763   | None -> failwith "empty clipboard"
1764   | Some cb ->
1765       (try List.assoc paste_kind cb with Not_found -> assert false)
1766