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