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