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