1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://cs.unibo.it/helm/.
34 module Stack = Continuationals.Stack
36 (** inherit from this class if you want to access current script *)
37 class scriptAccessor =
39 method private script = MatitaScript.current ()
42 let cicBrowsers = ref []
43 let gui_instance = ref None
44 let set_gui gui = gui_instance := Some gui
46 match !gui_instance with
47 | None -> assert false
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 ()
58 (* is there any lablgtk2 constant corresponding to the various mouse
64 let near (x1, y1) (x2, y2) =
65 let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
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"
73 let domImpl = Gdome.domImplementation ()
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)
81 let empty_boxml = lazy (
82 domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns)
83 ~qualifiedName:(Gdome.domString "box") ~doctype:None)
85 (** shown for goals closed by side effects *)
86 let closed_goal_mathml = lazy (
87 domImpl#createDocumentFromURI ~uri:BuildTimeConf.closed_xml ())
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 =
93 (* (prerr_endline (sprintf "id %s = %s" id
95 CicPp.ppterm (Hashtbl.find ids_to_terms id)
96 with Not_found -> "NONE"))); *)
97 if List.mem id ids then Some id
100 (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
103 | Some id' -> aux id')
107 let return_father id ids =
108 match find_parent id ids with
109 | None -> assert false
110 | Some parent_id -> parent_id
112 let mk_ids terms = List.map CicUtil.id_of_annterm terms in
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
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 *)
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
138 let text = new Gdome.text_of_node node in
139 text#get_data#to_string
140 with GdomeInit.DOMCastException _ -> "")
142 let name_of_hypothesis = function
143 | Some (Cic.Name s, _) -> s
146 let id_of_node (node: Gdome.element) =
148 node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds in
150 List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
151 with Failure _ -> assert false
154 | SelTerm of Cic.term * string option (* term, parent hypothesis (if any) *)
155 | SelHyp of string * Cic.context (* hypothesis, context *)
157 let hrefs_of_elt elt =
158 let localName = href_ds in
159 if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
161 (elt#getAttributeNS ~namespaceURI:xlink_ns ~localName)#to_string in
162 Some (HExtlib.split text)
166 class clickableMathView obj =
167 let text_width = 80 in
169 inherit GMathViewAux.multi_selection_math_view obj
171 val mutable href_callback: (string -> unit) option = None
172 method set_href_callback f = href_callback <- f
174 val mutable _cic_info = None
175 method private set_cic_info info = _cic_info <- info
176 method private cic_info = _cic_info
178 val normal_cursor = Gdk.Cursor.create `LEFT_PTR
179 val href_cursor = Gdk.Cursor.create `HAND1
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)
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> *)
197 method private selection_get_cb ctxt ~info ~time =
199 match ctxt#target with
200 | "PATTERN" -> self#text_of_selection `Pattern
201 | "TERM" | _ -> self#text_of_selection `Term
205 | Some s -> ctxt#return s
207 method private text_of_selection fmt =
208 match self#get_selections with
210 | node :: _ -> Some (self#string_of_node ~paste_kind:fmt node)
212 method private selection_clear_cb sel_event =
213 self#remove_selections;
214 (GData.clipboard Gdk.Atom.clipboard)#clear ();
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);
227 method private element_over_cb (elt_opt, _, _, _) =
228 let win () = self#misc#window in
230 Gdk.Window.set_cursor (win ()) normal_cursor;
231 HExtlib.iter_option (fun (ctxt, msg) -> ctxt#remove msg)
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 *)
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 ()
249 method private tactic_text_pattern_of_node node =
250 let id = id_of_node node in
251 let cic_info, unsh_sequent = self#get_cic_info id in
252 match self#get_term_by_id cic_info id with
253 | SelTerm (t, father_hyp) ->
254 let sequent = self#sequent_of_id ~paste_kind:`Pattern id in
255 let text = self#string_of_cic_sequent sequent in
256 (match father_hyp with
257 | None -> None, [], Some text
258 | Some hyp_name -> None, [ hyp_name, text ], None)
259 | SelHyp (hyp_name, _ctxt) -> None, [ hyp_name, "%" ], None
261 method private tactic_text_of_node node =
262 let id = id_of_node node in
263 let cic_info, unsh_sequent = self#get_cic_info id in
264 match self#get_term_by_id cic_info id with
265 | SelTerm (t, father_hyp) ->
266 let sequent = self#sequent_of_id ~paste_kind:`Term id in
267 let text = self#string_of_cic_sequent sequent in
269 | SelHyp (hyp_name, _ctxt) -> hyp_name
271 (** @return a pattern structure which contains pretty printed terms *)
272 method private tactic_text_pattern_of_selection =
273 match self#get_selections with
274 | [] -> assert false (* this method is invoked only if there's a sel. *)
275 | node :: _ -> self#tactic_text_pattern_of_node node
277 method private popup_contextual_menu time =
278 let menu = GMenu.menu () in
279 let add_menu_item ?(menu = menu) ?stock ?label () =
280 GMenu.image_menu_item ?stock ?label ~packing:menu#append () in
281 let check = add_menu_item ~label:"Check" () in
282 let reductions_menu_item = GMenu.menu_item ~label:"βδιζ-reduce" () in
283 let tactics_menu_item = GMenu.menu_item ~label:"Apply tactic" () in
284 menu#append reductions_menu_item;
285 menu#append tactics_menu_item;
286 let reductions = GMenu.menu () in
287 let tactics = GMenu.menu () in
288 reductions_menu_item#set_submenu reductions;
289 tactics_menu_item#set_submenu tactics;
290 let normalize = add_menu_item ~menu:reductions ~label:"Normalize" () in
291 let reduce = add_menu_item ~menu:reductions ~label:"Reduce" () in
292 let simplify = add_menu_item ~menu:reductions ~label:"Simplify" () in
293 let whd = add_menu_item ~menu:reductions ~label:"Weak head" () in
294 menu#append (GMenu.separator_item ());
295 let copy = add_menu_item ~stock:`COPY () in
296 let gui = get_gui () in
297 List.iter (fun item -> item#misc#set_sensitive gui#canCopy)
298 [ copy; check; normalize; reduce; simplify; whd ];
299 let reduction_action kind () =
300 let pat = self#tactic_text_pattern_of_selection in
302 let loc = HExtlib.dummy_floc in
304 GrafiteAstPp.pp_executable ~term_pp:(fun s -> s)
305 ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
306 (GrafiteAst.Tactical (loc,
307 GrafiteAst.Tactic (loc, GrafiteAst.Reduce (loc, kind, pat)),
308 Some (GrafiteAst.Semicolon loc))) in
309 (MatitaScript.current ())#advance ~statement () in
310 connect_menu_item copy gui#copy;
311 connect_menu_item normalize (reduction_action `Normalize);
312 connect_menu_item reduce (reduction_action `Reduce);
313 connect_menu_item simplify (reduction_action `Simpl);
314 connect_menu_item whd (reduction_action `Whd);
315 menu#popup ~button:right_button ~time
317 method private button_release_cb gdk_button =
318 if GdkEvent.Button.button gdk_button = left_button then begin
319 let button_release_x = GdkEvent.Button.x gdk_button in
320 let button_release_y = GdkEvent.Button.y gdk_button in
321 if selection_changed then
323 else (* selection _not_ changed *)
324 if near (button_press_x, button_press_y)
325 (button_release_x, button_release_y)
327 let x = int_of_float button_press_x in
328 let y = int_of_float button_press_y in
329 (match self#get_element_at x y with
332 (match hrefs_of_elt elt with
333 | Some hrefs -> self#invoke_href_callback hrefs gdk_button
334 | None -> ignore (self#action_toggle elt)))
338 method private invoke_href_callback hrefs gdk_button =
339 let button = GdkEvent.Button.button gdk_button in
340 if button = left_button then
341 let time = GdkEvent.Button.time gdk_button in
342 match href_callback with
348 let menu = GMenu.menu () in
352 GMenu.menu_item ~label:uri ~packing:menu#append () in
353 connect_menu_item menu_item
354 (fun () -> try f uri with Not_found -> assert false))
356 menu#popup ~button ~time)
358 method private choose_selection_cb gdome_elt =
359 let set_selection elt =
360 let misc = self#coerce#misc in
361 self#set_selection (Some elt);
362 misc#add_selection_target ~target:"STRING" Gdk.Atom.primary;
363 ignore (misc#grab_selection Gdk.Atom.primary);
366 if (elt#getAttributeNS ~namespaceURI:helm_ns
367 ~localName:xref_ds)#to_string <> ""
372 (match elt#get_parentNode with
373 | None -> assert false
374 | Some p -> aux (new Gdome.element_of_node p))
375 with GdomeInit.DOMCastException _ -> ()
377 (match gdome_elt with
378 | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
379 ~localName:href_ds)#to_string <> "" ->
381 | Some elt -> aux elt
382 | None -> self#set_selection None);
383 selection_changed <- true
385 method update_font_size = self#set_font_size !current_font_size
387 (** find a term by id from stored CIC infos @return either `Hyp if the id
388 * correspond to an hypothesis or `Term (cic, hyp) if the id correspond to a
389 * term. In the latter case hyp is either None (if the term is a subterm of
390 * the sequent conclusion) or Some hyp_name if the term belongs to an
392 method private get_term_by_id cic_info id =
393 let unsh_item, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, _, _ =
395 let rec find_father_hyp id =
396 if Hashtbl.mem ids_to_hypotheses id
397 then Some (name_of_hypothesis (Hashtbl.find ids_to_hypotheses id))
400 try Hashtbl.find ids_to_father_ids id
401 with Not_found -> assert false in
403 | Some id -> find_father_hyp id
407 let term = Hashtbl.find ids_to_terms id in
408 let father_hyp = find_father_hyp id in
409 SelTerm (term, father_hyp)
412 let hyp = Hashtbl.find ids_to_hypotheses id in
414 match unsh_item with Some seq -> seq | None -> assert false in
415 let context' = MatitaMisc.list_tl_at hyp context in
416 SelHyp (name_of_hypothesis hyp, context')
417 with Not_found -> assert false
419 method private find_obj_conclusion id =
420 match self#cic_info with
422 | Some (_, _, _, _, _, None) -> assert false
423 | Some (_, ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
425 find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
427 (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
429 method private string_of_node ~(paste_kind:paste_kind) node =
430 if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
432 match paste_kind with
434 let tactic_text_pattern = self#tactic_text_pattern_of_node node in
435 GrafiteAstPp.pp_tactic_pattern
436 ~term_pp:(fun s -> s) ~lazy_term_pp:(fun _ -> assert false)
438 | `Term -> self#tactic_text_of_node node
439 else string_of_dom_node node
441 method private string_of_cic_sequent cic_sequent =
442 let script = MatitaScript.current () in
444 if script#onGoingProof () then script#proofMetasenv else [] in
446 let _, (acic_sequent, _, _, ids_to_inner_sorts, _) =
447 Cic2acic.asequent_of_sequent metasenv cic_sequent in
448 let _, _, _, annterm = acic_sequent in
449 let ast, ids_to_uris =
450 TermAcicContent.ast_of_acic ids_to_inner_sorts annterm in
451 let pped_ast = TermContentPres.pp_ast ast in
452 let markup = CicNotationPres.render ids_to_uris pped_ast in
453 BoxPp.render_to_string text_width markup
455 ApplyTransformation.txt_of_cic_sequent_conclusion
456 text_width metasenv cic_sequent
458 method private pattern_of term context unsh_sequent =
459 let context_len = List.length context in
460 let _, unsh_context, conclusion = unsh_sequent in
463 List.nth unsh_context (List.length unsh_context - context_len - 1)
465 | None -> assert false (* can't select a restricted hypothesis *)
466 | Some (name, Cic.Decl ty) ->
467 ProofEngineHelpers.pattern_of ~term:ty [term]
468 | Some (name, Cic.Def (bo, _)) ->
469 ProofEngineHelpers.pattern_of ~term:bo [term])
470 with Failure _ | Invalid_argument _ ->
471 ProofEngineHelpers.pattern_of ~term:conclusion [term]
473 method private get_cic_info id =
474 match self#cic_info with
475 | Some ((Some unsh_sequent, _, _, _, _, _) as info) -> info, unsh_sequent
476 | Some ((None, _, _, _, _, _) as info) ->
477 let t = self#find_obj_conclusion id in
478 info, (~-1, [], t) (* dummy sequent for obj *)
479 | None -> assert false
481 method private sequent_of_id ~(paste_kind:paste_kind) id =
482 let cic_info, unsh_sequent = self#get_cic_info id in
484 match self#get_term_by_id cic_info id with
485 | SelTerm (t, _father_hyp) ->
487 ProofEngineHelpers.locate_in_conjecture t unsh_sequent in
488 (match occurrences with
490 (match paste_kind with
491 | `Term -> ~-1, context, t
492 | `Pattern -> ~-1, [], self#pattern_of t context unsh_sequent)
494 HLog.error (sprintf "found %d occurrences while 1 was expected"
495 (List.length occurrences));
496 assert false) (* since it uses physical equality *)
497 | SelHyp (_name, context) -> ~-1, context, Cic.Rel 1 in
500 method private string_of_selection ~(paste_kind:paste_kind) =
501 match self#get_selections with
503 | node :: _ -> Some (self#string_of_node ~paste_kind node)
505 method has_selection = self#get_selections <> []
507 (** @return an associative list format -> string with all possible selection
508 * formats. Rationale: in order to convert the selection to TERM or PATTERN
509 * format we need the sequent, the metasenv, ... keeping all of them in a
510 * closure would be more expensive than keeping their already converted
512 method strings_of_selection =
514 let misc = self#coerce#misc in
516 (fun target -> misc#add_selection_target ~target Gdk.Atom.clipboard)
517 [ "TERM"; "PATTERN"; "STRING" ];
518 ignore (misc#grab_selection Gdk.Atom.clipboard);
521 paste_kind, HExtlib.unopt (self#string_of_selection ~paste_kind))
523 with Failure _ -> failwith "no selection"
527 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
528 GtkBase.Widget.size_params
529 ~cont:(OgtkMathViewProps.pack_return (fun p ->
530 OgtkMathViewProps.set_params
531 (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
532 ~font_size:None ~log_verbosity:None))
535 class cicMathView obj =
537 inherit clickableMathView obj
539 val mutable current_mathml = None
541 method load_sequent metasenv metano =
542 let sequent = CicUtil.lookup_meta metano metasenv in
543 let (mathml, unsh_sequent,
544 (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ )))
546 ApplyTransformation.mml_of_cic_sequent metasenv sequent
549 (Some (Some unsh_sequent,
550 ids_to_terms, ids_to_hypotheses, ids_to_father_ids,
551 Hashtbl.create 1, None));
552 if BuildTimeConf.debug then begin
553 let name = "sequent_viewer.xml" in
554 HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
555 ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
557 self#load_root ~root:mathml#get_documentElement
559 method load_object obj =
560 let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
562 (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
564 ApplyTransformation.mml_of_cic_object obj
567 (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
568 (match current_mathml with
569 | Some current_mathml when use_diff ->
571 XmlDiff.update_dom ~from:current_mathml mathml;
574 if BuildTimeConf.debug then begin
575 let name = "cic_browser.xml" in
576 HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
577 ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
579 self#load_root ~root:mathml#get_documentElement;
580 current_mathml <- Some mathml);
583 let tab_label meta_markup =
586 | `Closed m -> sprintf "<s>%s</s>" (aux m)
587 | `Current m -> sprintf "<b>%s</b>" (aux m)
588 | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
589 | `Meta n -> sprintf "?%d" n
591 let markup = aux meta_markup in
592 (GMisc.label ~markup ~show:true ())#coerce
594 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
596 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
598 inherit scriptAccessor
600 method cicMathView = cicMathView (** clickableMathView accessor *)
602 val mutable pages = 0
603 val mutable switch_page_callback = None
604 val mutable page2goal = [] (* associative list: page no -> goal no *)
605 val mutable goal2page = [] (* the other way round *)
606 val mutable goal2win = [] (* associative list: goal no -> scrolled win *)
607 val mutable _metasenv = []
608 val mutable scrolledWin: GBin.scrolled_window option = None
609 (* scrolled window to which the sequentViewer is currently attached *)
610 val logo = (GMisc.image
611 ~file:(MatitaMisc.image_path "matita_medium.png") ()
614 val logo_with_qed = (GMisc.image
615 ~file:(MatitaMisc.image_path "matita_small.png") ()
619 notebook#set_show_tabs false;
620 notebook#append_page logo
622 method load_logo_with_qed =
623 notebook#set_show_tabs false;
624 notebook#append_page logo_with_qed
627 cicMathView#remove_selections;
628 (match scrolledWin with
630 (* removing page from the notebook will destroy all contained widget,
631 * we do not want the cicMathView to be destroyed as well *)
632 w#remove cicMathView#coerce;
635 (match switch_page_callback with
637 GtkSignal.disconnect notebook#as_widget id;
638 switch_page_callback <- None
640 for i = 0 to pages do notebook#remove_page 0 done;
641 notebook#set_show_tabs true;
647 self#script#setGoal None
649 method load_sequents { proof = (_,metasenv,_,_) as proof; stack = stack } =
650 _metasenv <- metasenv;
652 let win goal_switch =
654 GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
655 ~shadow_type:`IN ~show:true ()
658 scrolledWin <- Some w;
659 match cicMathView#misc#parent with
660 | None -> w#add cicMathView#coerce
663 match cicMathView#misc#parent with
665 | Some p -> GContainer.cast_container p
667 parent#remove cicMathView#coerce;
668 w#add cicMathView#coerce
670 goal2win <- (goal_switch, reparent) :: goal2win;
674 let stack_goals = Stack.open_goals stack in
675 let proof_goals = ProofEngineTypes.goals_of_proof proof in
677 HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
678 <> List.sort Pervasives.compare proof_goals
680 prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
681 prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
687 function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
690 let added_goals = ref [] in
691 (* goals can be duplicated on the tack due to focus, but we should avoid
692 * multiple labels in the user interface *)
693 let add_tab markup goal_switch =
694 let goal = Stack.goal_of_switch goal_switch in
695 if not (List.mem goal !added_goals) then begin
696 notebook#append_page ~tab_label:(tab_label markup) (win goal_switch);
697 page2goal <- (!page, goal_switch) :: page2goal;
698 goal2page <- (goal_switch, !page) :: goal2page;
701 added_goals := goal :: !added_goals
704 let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
705 Stack.iter (** populate notebook with tabs *)
706 ~env:(fun depth tag (pos, sw) ->
708 match depth, pos with
709 | 0, 0 -> `Current (render_switch sw)
710 | 0, _ -> `Shift (pos, `Current (render_switch sw))
711 | 1, pos when Stack.head_tag stack = `BranchTag ->
712 `Shift (pos, render_switch sw)
713 | _ -> render_switch sw
716 ~cont:add_switch ~todo:add_switch
718 switch_page_callback <-
719 Some (notebook#connect#switch_page ~callback:(fun page ->
721 try List.assoc page page2goal with Not_found -> assert false
723 self#script#setGoal (Some (goal_of_switch goal_switch));
724 self#render_page ~page ~goal_switch))
726 method private render_page ~page ~goal_switch =
727 (match goal_switch with
728 | Stack.Open goal -> cicMathView#load_sequent _metasenv goal
729 | Stack.Closed goal ->
730 let doc = Lazy.force closed_goal_mathml in
731 cicMathView#load_root ~root:doc#get_documentElement);
733 cicMathView#set_selection None;
734 List.assoc goal_switch goal2win ()
735 with Not_found -> assert false)
737 method goto_sequent goal =
738 let goal_switch, page =
741 (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
743 with Not_found -> assert false
745 notebook#goto_page page;
746 self#render_page page goal_switch
752 type 'widget constructor =
753 ?hadjustment:GData.adjustment ->
754 ?vadjustment:GData.adjustment ->
756 ?log_verbosity:int ->
759 ?packing:(GObj.widget -> unit) ->
764 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
765 GtkBase.Widget.size_params
766 ~cont:(OgtkMathViewProps.pack_return (fun p ->
767 OgtkMathViewProps.set_params
768 (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
769 ~font_size ~log_verbosity))
772 let blank_uri = BuildTimeConf.blank_uri
773 let current_proof_uri = BuildTimeConf.current_proof_uri
776 [ `Ast of CicNotationPt.term
777 | `Cic of Cic.term * Cic.metasenv
781 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
784 let whelp_RE = Pcre.regexp "^\\s*whelp" in
787 "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
789 let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
790 let metadata_RE = Pcre.regexp "^metadata:/(deps)/(forward|backward)/(.*)$" in
791 let whelp_query_RE = Pcre.regexp
792 "^\\s*whelp\\s+([^\\s]+)\\s+(\"|\\()(.*)(\\)|\")$"
794 let is_metadata txt = Pcre.pmatch ~rex:metadata_RE txt in
795 let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
796 let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
797 let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
798 let gui = get_gui () in
799 let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
800 let gviz = LablGraphviz.gDot ~packing:win#graphScrolledWin#add () in
801 let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
802 let combo,_ = GEdit.combo_box_text ~strings:queries () in
803 let activate_combo_query input q =
804 let q' = String.lowercase q in
805 let rec aux i = function
806 | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
807 | h::_ when String.lowercase h = q' -> i
808 | _::tl -> aux (i+1) tl
810 win#queryInputText#set_text input;
811 combo#set_active (aux 0 queries);
813 let set_whelp_query txt =
816 let q = Pcre.extract ~rex:whelp_query_RE txt in
818 with Not_found -> failwith "Malformed Whelp query"
820 activate_combo_query arg query;
822 let toplevel = win#toplevel in
823 let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
825 MatitaGtkMisc.report_error ~title:"Cic browser" ~message
829 [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
830 "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
832 let b = (not (Helm_registry.get_bool "matita.debug")) in
838 fail (snd (MatitaExcPp.to_string exn))
841 let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
842 let load_easter_egg = lazy (
843 win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
845 let load_coerchgraph () =
846 let str = CoercGraph.generate_dot_file () in
847 let filename, oc = Filename.open_temp_file "matita" ".dot" in
848 output_string oc str;
850 gviz#load_graph_from_file filename;
851 HExtlib.safe_remove filename
854 inherit scriptAccessor
856 (* Whelp bar queries *)
858 val mutable gviz_graph = MetadataDeps.DepGraph.dummy
859 val mutable gviz_uri = UriManager.uri_of_string "cic:/dummy.con";
861 val dep_contextual_menu = GMenu.menu ()
864 activate_combo_query "" "locate";
865 win#whelpBarComboVbox#add combo#coerce;
869 String.lowercase (List.nth queries combo#active)
870 with Not_found -> assert false in
871 let input = win#queryInputText#text in
873 if query = "locate" then
874 "whelp " ^ query ^ " \"" ^ input ^ "\"."
876 "whelp " ^ query ^ " (" ^ input ^ ")."
878 (MatitaScript.current ())#advance ~statement ()
880 ignore(win#queryInputText#connect#activate ~callback:start_query);
881 ignore(combo#connect#changed ~callback:start_query);
882 win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
883 win#mathOrListNotebook#set_show_tabs false;
884 win#browserForwardButton#misc#set_sensitive false;
885 win#browserBackButton#misc#set_sensitive false;
886 ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
887 self#loadInput win#browserUri#entry#text)));
888 ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
889 self#load (`About `Current_proof))));
890 ignore (win#browserRefreshButton#connect#clicked
891 (handle_error' (self#refresh ~force:true)));
892 ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
893 ignore (win#browserForwardButton#connect#clicked
894 (handle_error' self#forward));
895 ignore (win#toplevel#event#connect#delete (fun _ ->
896 let my_id = Oo.id self in
897 cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
898 if !cicBrowsers = [] &&
899 Helm_registry.get "matita.mode" = "cicbrowser"
903 ignore(win#whelpResultTreeview#connect#row_activated
904 ~callback:(fun _ _ ->
905 handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
906 mathView#set_href_callback (Some (fun uri ->
907 handle_error (fun () ->
908 self#load (`Uri (UriManager.uri_of_string uri)))));
909 gviz#connect_href (fun button_ev attrs ->
910 let time = GdkEvent.Button.time button_ev in
911 let uri = List.assoc "href" attrs in
912 gviz_uri <- UriManager.uri_of_string uri;
913 match GdkEvent.Button.button button_ev with
914 | button when button = left_button -> self#load (`Uri gviz_uri)
915 | button when button = right_button ->
916 dep_contextual_menu#popup ~button ~time
918 connect_menu_item win#depGraphMenuItem (fun () ->
919 match self#currentCicUri with
920 | Some uri -> self#load (`Metadata (`Deps (`Fwd, uri)))
922 connect_menu_item win#invDepGraphMenuItem (fun () ->
923 match self#currentCicUri with
924 | Some uri -> self#load (`Metadata (`Deps (`Back, uri)))
927 (* fill dep graph contextual menu *)
929 GMenu.image_menu_item ~label:"Browse it"
930 ~packing:dep_contextual_menu#append () in
931 let expand_menu_item =
932 GMenu.image_menu_item ~label:"Expand"
933 ~packing:dep_contextual_menu#append () in
934 let collapse_menu_item =
935 GMenu.image_menu_item ~label:"Collapse"
936 ~packing:dep_contextual_menu#append () in
937 dep_contextual_menu#append (go_menu_item :> GMenu.menu_item);
938 dep_contextual_menu#append (expand_menu_item :> GMenu.menu_item);
939 dep_contextual_menu#append (collapse_menu_item :> GMenu.menu_item);
940 connect_menu_item go_menu_item (fun () -> self#load (`Uri gviz_uri));
941 connect_menu_item expand_menu_item (fun () ->
942 MetadataDeps.DepGraph.expand gviz_uri gviz_graph;
943 self#redraw_gviz ~center_on:gviz_uri ());
944 connect_menu_item collapse_menu_item (fun () ->
945 MetadataDeps.DepGraph.collapse gviz_uri gviz_graph;
946 self#redraw_gviz ~center_on:gviz_uri ());
948 self#_load (`About `Blank);
951 val mutable current_entry = `About `Blank
953 (** @return None if no object uri can be built from the current entry *)
954 method private currentCicUri =
955 match current_entry with
957 | `Metadata (`Deps (_, uri)) -> Some uri
961 new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
963 val mutable lastDir = "" (* last loaded "directory" *)
965 method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
967 method private _getSelectedUri () =
968 match model#easy_selection () with
969 | [sel] when is_uri sel -> sel (* absolute URI selected *)
970 (* | [sel] -> win#browserUri#entry#text ^ sel |+ relative URI selected +| *)
971 | [sel] -> lastDir ^ sel
974 (** history RATIONALE
976 * All operations about history are done using _historyFoo.
977 * Only toplevel functions (ATM load and loadInput) call _historyAdd.
980 method private _historyAdd item =
982 win#browserBackButton#misc#set_sensitive true;
983 win#browserForwardButton#misc#set_sensitive false
985 method private _historyPrev () =
986 let item = history#previous in
987 if history#is_begin then win#browserBackButton#misc#set_sensitive false;
988 win#browserForwardButton#misc#set_sensitive true;
991 method private _historyNext () =
992 let item = history#next in
993 if history#is_end then win#browserForwardButton#misc#set_sensitive false;
994 win#browserBackButton#misc#set_sensitive true;
997 (** notebook RATIONALE
999 * Use only these functions to switch between the tabs
1001 method private _showMath = win#mathOrListNotebook#goto_page 0
1002 method private _showList = win#mathOrListNotebook#goto_page 1
1004 method private back () =
1006 self#_load (self#_historyPrev ())
1007 with MatitaMisc.History_failure -> ()
1009 method private forward () =
1011 self#_load (self#_historyNext ())
1012 with MatitaMisc.History_failure -> ()
1014 (* loads a uri which can be a cic uri or an about:* uri
1015 * @param uri string *)
1016 method private _load ?(force=false) entry =
1017 handle_error (fun () ->
1018 if entry <> current_entry || entry = `About `Current_proof || entry =
1019 `About `Coercions || force then
1022 | `About `Current_proof -> self#home ()
1023 | `About `Blank -> self#blank ()
1024 | `About `Us -> self#egg ()
1025 | `About `Coercions -> self#coerchgraph ()
1026 | `Check term -> self#_loadCheck term
1027 | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
1028 | `Dir dir -> self#_loadDir dir
1029 | `Metadata (`Deps ((`Fwd | `Back) as dir, uri)) ->
1030 self#dependencies dir uri ()
1031 | `Uri uri -> self#_loadUriManagerUri uri
1032 | `Whelp (query, results) ->
1033 set_whelp_query query;
1034 self#_loadList (List.map (fun r -> "obj",
1035 UriManager.string_of_uri r) results));
1039 method private blank () =
1041 mathView#load_root (Lazy.force empty_mathml)#get_documentElement
1043 method private _loadCheck term =
1044 failwith "not implemented _loadCheck";
1045 (* self#_showMath *)
1047 method private egg () =
1048 win#mathOrListNotebook#goto_page 2;
1049 Lazy.force load_easter_egg
1051 method private redraw_gviz ?center_on () =
1052 let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
1053 let fmt = Format.formatter_of_out_channel oc in
1054 MetadataDeps.DepGraph.render fmt gviz_graph;
1056 gviz#load_graph_from_file tmpfile;
1057 (match center_on with
1059 | Some uri -> gviz#center_on_href (UriManager.string_of_uri uri));
1060 HExtlib.safe_remove tmpfile
1062 method private dependencies direction uri () =
1063 let dbd = LibraryDb.instance () in
1065 match direction with
1066 | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
1067 | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
1068 gviz_graph <- graph; (** XXX check this for memory consuption *)
1069 self#redraw_gviz ~center_on:uri ();
1070 win#mathOrListNotebook#goto_page 3
1072 method private coerchgraph () =
1073 load_coerchgraph ();
1074 win#mathOrListNotebook#goto_page 3
1076 method private home () =
1078 match self#script#grafite_status.proof_status with
1079 | Proof (uri, metasenv, bo, ty) ->
1080 let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1081 let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
1083 | Incomplete_proof { proof = (uri, metasenv, bo, ty) } ->
1084 let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1085 let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
1087 | _ -> self#blank ()
1089 (** loads a cic uri from the environment
1090 * @param uri UriManager.uri *)
1091 method private _loadUriManagerUri uri =
1092 let uri = UriManager.strip_xpointer uri in
1093 let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1096 method private _loadDir dir =
1097 let content = Http_getter.ls dir in
1103 | Http_getter_types.Ls_section s -> "dir", s
1104 | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
1110 method private setEntry entry =
1111 win#browserUri#entry#set_text (MatitaTypes.string_of_entry entry);
1112 current_entry <- entry
1114 method private _loadObj obj =
1115 (* showMath must be done _before_ loading the document, since if the
1116 * widget is not mapped (hidden by the notebook) the document is not
1119 mathView#load_object obj
1121 method private _loadTermCic term metasenv =
1122 let context = self#script#proofContext in
1123 let dummyno = CicMkImplicit.new_meta metasenv [] in
1124 let sequent = (dummyno, context, term) in
1125 mathView#load_sequent (sequent :: metasenv) dummyno;
1128 method private _loadList l =
1129 model#list_store#clear ();
1130 List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
1133 (** { public methods, all must call _load!! } *)
1136 handle_error (fun () -> self#_load entry; self#_historyAdd entry)
1138 (** this is what the browser does when you enter a string an hit enter *)
1139 method loadInput txt =
1140 let parse_metadata s =
1141 let subs = Pcre.extract ~rex:metadata_RE s in
1142 let uri = UriManager.uri_of_string ("cic:/" ^ subs.(3)) in
1143 match subs.(1), subs.(2) with
1144 | "deps", "forward" -> `Deps (`Fwd, uri)
1145 | "deps", "backward" -> `Deps (`Back, uri)
1148 let txt = HExtlib.trim_blanks txt in
1149 (* (* ZACK: what the heck? *)
1151 UriManager.string_of_uri
1152 (UriManager.strip_xpointer (UriManager.uri_of_string txt))
1155 if is_whelp txt then begin
1156 set_whelp_query txt;
1157 (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
1161 | txt when is_uri txt ->
1162 `Uri (UriManager.uri_of_string ((*fix_uri*) txt))
1163 | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
1164 | txt when is_metadata txt -> `Metadata (parse_metadata txt)
1167 MatitaTypes.entry_of_string txt
1168 with Invalid_argument _ ->
1170 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
1173 self#_historyAdd entry
1176 (** {2 methods accessing underlying GtkMathView} *)
1178 method updateFontSize = mathView#set_font_size !current_font_size
1180 (** {2 methods used by constructor only} *)
1183 method history = history
1184 method currentEntry = current_entry
1185 method refresh ~force () = self#_load ~force current_entry
1189 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
1190 MatitaGuiTypes.sequentsViewer
1192 new sequentsViewer ~notebook ~cicMathView ()
1195 let size = BuildTimeConf.browser_history_size in
1196 let rec aux history =
1197 let browser = new cicBrowser_impl ~history () in
1198 let win = browser#win in
1199 ignore (win#browserNewButton#connect#clicked (fun () ->
1201 new MatitaMisc.browser_history ~memento:history#save size
1204 let newBrowser = aux history in
1205 newBrowser#load browser#currentEntry));
1207 (* attempt (failed) to close windows on CTRL-W ... *)
1208 MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
1209 GdkKeysyms._W (fun () -> win#toplevel#destroy ());
1211 cicBrowsers := browser :: !cicBrowsers;
1212 (browser :> MatitaGuiTypes.cicBrowser)
1214 let history = new MatitaMisc.browser_history size (`About `Blank) in
1217 let default_cicMathView () = cicMathView ~show:true ()
1218 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
1220 let default_sequentsViewer () =
1221 let gui = get_gui () in
1222 let cicMathView = cicMathView_instance () in
1223 sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
1224 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
1228 method private get_browser reuse =
1230 (match !cicBrowsers with
1231 | [] -> cicBrowser ()
1232 | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
1236 method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
1238 method show_uri_list ?(reuse=false) ~entry l =
1239 (self#get_browser reuse)#load entry
1242 let refresh_all_browsers () =
1243 List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
1245 let update_font_sizes () =
1246 List.iter (fun b -> b#updateFontSize) !cicBrowsers;
1247 (cicMathView_instance ())#update_font_size
1249 let get_math_views () =
1250 ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
1251 :: (List.map (fun b -> b#mathView) !cicBrowsers)
1253 let find_selection_owner () =
1256 | [] -> raise Not_found
1258 (match mv#get_selections with
1262 aux (get_math_views ())
1264 let has_selection () =
1265 try ignore (find_selection_owner ()); true
1266 with Not_found -> false
1268 let math_view_clipboard = ref None (* associative list target -> string *)
1269 let has_clipboard () = !math_view_clipboard <> None
1270 let empty_clipboard () = math_view_clipboard := None
1272 let copy_selection () =
1274 math_view_clipboard :=
1275 Some ((find_selection_owner ())#strings_of_selection)
1276 with Not_found -> failwith "no selection"
1278 let paste_clipboard paste_kind =
1279 match !math_view_clipboard with
1280 | None -> failwith "empty clipboard"
1282 (try List.assoc paste_kind cb with Not_found -> assert false)