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/.
31 let rec aux = function
42 let add_trailing_slash =
43 let rex = Pcre.regexp "/$" in
45 if Pcre.pmatch ~rex s then s
49 let rex = Pcre.regexp "^\\s*([^\\s]*)\\s*$" in
51 (Pcre.extract ~rex s).(1)
53 (** inherit from this class if you want to access current script *)
54 class scriptAccessor =
56 method private script = MatitaScript.instance ()
59 class clickableMathView obj =
60 let href = Gdome.domString "href" in
61 let xref = Gdome.domString "xref" in
63 inherit GMathViewAux.multi_selection_math_view obj
65 val mutable href_callback: (string -> unit) option = None
66 method set_href_callback f = href_callback <- f
69 ignore (self#connect#selection_changed self#choose_selection);
70 ignore (self#connect#click (fun (gdome_elt, _, _, _) ->
72 | Some elt (* element is an hyperlink, use href_callback on it *)
73 when elt#hasAttributeNS ~namespaceURI:Misc.xlink_ns ~localName:href ->
74 (match href_callback with
78 elt#getAttributeNS ~namespaceURI:Misc.xlink_ns ~localName:href
81 | Some elt -> ignore (self#action_toggle elt)
83 method private choose_selection gdome_elt =
85 if elt#hasAttributeNS ~namespaceURI:Misc.helm_ns ~localName:xref then
86 self#set_selection (Some elt)
89 (match elt#get_parentNode with
90 | None -> assert false
91 | Some p -> aux (new Gdome.element_of_node p))
92 with GdomeInit.DOMCastException _ -> ()
93 (* debug_print "trying to select above the document root" *)
97 | None -> self#set_selection None
100 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
101 GtkBase.Widget.size_params
102 ~cont:(OgtkMathViewProps.pack_return (fun p ->
103 OgtkMathViewProps.set_params
104 (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
105 ~font_size:None ~log_verbosity:None))
108 class sequentViewer obj =
111 inherit clickableMathView obj
113 val mutable current_infos = None
115 method get_selected_terms =
116 let selections = self#get_selections in
120 ((node : Gdome.element)#getAttributeNS
121 ~namespaceURI:Misc.helm_ns
122 ~localName:(Gdome.domString "xref"))#to_string
124 if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
126 match current_infos with
127 | Some (ids_to_terms,_,_) ->
128 (try Hashtbl.find ids_to_terms xpath with _ -> raise Exit)
129 | None -> assert false) (* "ERROR: No current term!!!" *)
132 method get_selected_hypotheses =
133 let selections = self#get_selections in
137 ((node : Gdome.element)#getAttributeNS
138 ~namespaceURI:Misc.helm_ns
139 ~localName:(Gdome.domString "xref"))#to_string
141 if xpath = "" then assert false (* "ERROR: No xref found!!!" *)
143 match current_infos with
144 | Some (_,_,ids_to_hypotheses) ->
145 (try Hashtbl.find ids_to_hypotheses xpath with _ -> raise Exit)
146 | None -> assert false) (* "ERROR: No current term!!!" *)
149 method load_sequent metasenv metano =
150 let sequent = CicUtil.lookup_meta metano metasenv in
151 let (mathml,(_,(ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_))) =
152 ApplyTransformation.mml_of_cic_sequent metasenv sequent
154 current_infos <- Some (ids_to_terms, ids_to_father_ids, ids_to_hypotheses);
156 debug_print "load_sequent: dumping MathML to ./prova";
157 ignore (Misc.domImpl#saveDocumentToFile ~name:"./prova" ~doc:mathml ());
159 self#load_root ~root:mathml#get_documentElement
162 class sequentsViewer ~(notebook:GPack.notebook)
163 ~(sequentViewer:sequentViewer) ()
166 inherit scriptAccessor
168 val mutable pages = 0
169 val mutable switch_page_callback = None
170 val mutable page2goal = [] (* associative list: page no -> goal no *)
171 val mutable goal2page = [] (* the other way round *)
172 val mutable goal2win = [] (* associative list: goal no -> scrolled win *)
173 val mutable _metasenv = []
174 val mutable scrolledWin: GBin.scrolled_window option = None
175 (* scrolled window to which the sequentViewer is currently attached *)
177 method private tab_label metano =
178 (GMisc.label ~text:(sprintf "?%d" metano) ~show:true ())#coerce
181 (match scrolledWin with
183 (* removing page from the notebook will destroy all contained widget,
184 * we do not want the sequentViewer to be destroyed as well *)
185 w#remove sequentViewer#coerce;
188 for i = 1 to pages do notebook#remove_page 0 done;
194 self#script#setGoal ~-1;
195 (match switch_page_callback with
197 GtkSignal.disconnect notebook#as_widget id;
198 switch_page_callback <- None
201 method load_sequents (status: ProofEngineTypes.status) =
202 let ((_, metasenv, _, _), goal) = status in
203 let sequents_no = List.length metasenv in
204 _metasenv <- metasenv;
205 pages <- sequents_no;
206 self#script#setGoal goal;
209 GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
210 ~shadow_type:`IN ~show:true ()
213 scrolledWin <- Some w;
214 match sequentViewer#misc#parent with
215 | None -> w#add sequentViewer#coerce
216 | Some _ -> sequentViewer#misc#reparent w#coerce
218 goal2win <- (metano, reparent) :: goal2win;
223 (fun (metano, _, _) ->
224 page2goal <- (!page, metano) :: page2goal;
225 goal2page <- (metano, !page) :: goal2page;
227 notebook#append_page ~tab_label:(self#tab_label metano) (win metano))
229 switch_page_callback <-
230 Some (notebook#connect#switch_page ~callback:(fun page ->
233 List.assoc page page2goal
234 with Not_found -> assert false
236 self#script#setGoal goal;
237 self#render_page ~page ~goal))
239 method private render_page ~page ~goal =
240 sequentViewer#load_sequent _metasenv goal;
242 List.assoc goal goal2win ();
243 sequentViewer#set_selection None
244 with Not_found -> assert false
246 method goto_sequent goal =
249 List.assoc goal goal2page
250 with Not_found -> assert false
252 notebook#goto_page page;
253 self#render_page page goal
259 type 'widget constructor =
260 ?hadjustment:GData.adjustment ->
261 ?vadjustment:GData.adjustment ->
263 ?log_verbosity:int ->
266 ?packing:(GObj.widget -> unit) ->
271 let sequentViewer ?hadjustment ?vadjustment ?font_size ?log_verbosity =
272 GtkBase.Widget.size_params
273 ~cont:(OgtkMathViewProps.pack_return (fun p ->
274 OgtkMathViewProps.set_params
275 (new sequentViewer (GtkMathViewProps.MathView_GMetaDOM.create p))
276 ~font_size ~log_verbosity))
279 let blank_uri = BuildTimeConf.blank_uri
280 let current_proof_uri = BuildTimeConf.current_proof_uri
283 [ `Ast of DisambiguateTypes.term
284 | `Cic of Cic.term * Cic.metasenv
288 exception Browser_failure of string
290 let cicBrowsers = ref []
292 class type cicBrowser =
294 method load: MatitaTypes.mathViewer_entry -> unit
295 (* method loadList: string list -> MatitaTypes.mathViewer_entry-> unit *)
296 method loadInput: string -> unit
299 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
302 let term_RE = Pcre.regexp "^term:(.*)" in
303 let whelp_RE = Pcre.regexp "^\\s*whelp" in
306 "^cic:/(\\w+/)*\\w+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
308 let dir_RE = Pcre.regexp "^cic:((/(\\w+/)*\\w+(/)?)|/|)$" in
309 let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
310 let trailing_slash_RE = Pcre.regexp "/$" in
311 let has_xpointer_RE = Pcre.regexp "#xpointer\\(\\d+/\\d+(/\\d+)?\\)$" in
312 let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
313 let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
314 let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
315 let gui = MatitaGui.instance () in
316 let win = gui#newBrowserWin () in
317 let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
318 let combo,_ = GEdit.combo_box_text ~strings:queries () in
319 let activate_combo_query input q =
320 let q' = String.lowercase q in
321 let rec aux i = function
322 | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
323 | h::_ when String.lowercase h = q' -> i
324 | _::tl -> aux (i+1) tl
326 combo#set_active (aux 0 queries);
327 win#queryInputText#set_text input
329 let set_whelp_query txt =
332 let q = Pcre.extract ~rex:whelp_query_RE txt in
334 with Invalid_argument _ -> failwith "Malformed Whelp query"
336 activate_combo_query arg query
338 let toplevel = win#toplevel in
339 let mathView = sequentViewer ~packing:win#scrolledBrowser#add () in
341 ignore (MatitaGtkMisc.ask_confirmation ~gui:(MatitaGui.instance ())
342 ~title:"Cic browser" ~msg ~cancel:false ());
345 [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
346 "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
352 fail (sprintf "Uncaught exception:\n%s" (Printexc.to_string exn))
354 let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
356 inherit scriptAccessor
358 (* Whelp bar queries *)
361 activate_combo_query "" "locate";
362 win#whelpBarComboVbox#add combo#coerce;
364 let query = String.lowercase (List.nth queries combo#active) in
365 let input = win#queryInputText#text in
366 let statement = "whelp " ^ query ^ " " ^ input ^ "." in
367 (MatitaScript.instance ())#advance ~statement ()
369 ignore(win#queryInputText#connect#activate ~callback:start_query);
370 ignore(combo#connect#changed ~callback:start_query);
371 win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
372 win#mathOrListNotebook#set_show_tabs false;
374 win#browserForwardButton#misc#set_sensitive false;
375 win#browserBackButton#misc#set_sensitive false;
376 ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
377 self#loadInput win#browserUri#entry#text)));
378 ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
379 self#load (`About `Current_proof))));
380 ignore (win#browserRefreshButton#connect#clicked
381 (handle_error' self#refresh));
382 ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
383 ignore (win#browserForwardButton#connect#clicked
384 (handle_error' self#forward));
385 ignore (win#toplevel#event#connect#delete (fun _ ->
386 let my_id = Oo.id self in
387 cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
388 if !cicBrowsers = [] &&
389 Helm_registry.get "matita.mode" = "cicbrowser"
393 ignore(win#whelpResultTreeview#connect#row_activated
394 ~callback:(fun _ _ -> self#loadInput (self#_getSelectedUri ())));
395 mathView#set_href_callback (Some (fun uri ->
396 handle_error (fun () -> self#load (`Uri uri))));
397 self#_load (`About `Blank);
400 val mutable current_entry = `About `Blank
401 val mutable current_infos = None
402 val mutable current_mathml = None
405 new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
407 method private _getSelectedUri () =
408 match model#easy_selection () with
409 | [sel] when is_uri sel -> sel (* absolute URI selected *)
410 | [sel] -> win#browserUri#entry#text ^ sel (* relative URI selected *)
413 (** history RATIONALE
415 * All operations about history are done using _historyFoo.
416 * Only toplevel functions (ATM load and loadInput) call _historyAdd.
419 method private _historyAdd item =
421 win#browserBackButton#misc#set_sensitive true;
422 win#browserForwardButton#misc#set_sensitive false
424 method private _historyPrev () =
425 let item = history#previous in
426 if history#is_begin then win#browserBackButton#misc#set_sensitive false;
427 win#browserForwardButton#misc#set_sensitive true;
430 method private _historyNext () =
431 let item = history#next in
432 if history#is_end then win#browserForwardButton#misc#set_sensitive false;
433 win#browserBackButton#misc#set_sensitive true;
436 (** notebook RATIONALE
438 * Use only these functions to switch between the tabs
440 method private _showList = win#mathOrListNotebook#goto_page 1
441 method private _showMath = win#mathOrListNotebook#goto_page 0
443 method private back () =
445 self#_load (self#_historyPrev ())
446 with MatitaMisc.History_failure -> ()
448 method private forward () =
450 self#_load (self#_historyNext ())
451 with MatitaMisc.History_failure -> ()
453 (* loads a uri which can be a cic uri or an about:* uri
454 * @param uri string *)
455 method private _load entry =
457 if entry <> current_entry || entry = `About `Current_proof then begin
459 | `About `Current_proof -> self#home ()
460 | `About `Blank -> self#blank ()
461 | `About `Us -> () (* TODO implement easter egg here :-] *)
462 | `Check term -> self#_loadCheck term
463 | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
464 | `Dir dir -> self#_loadDir dir
465 | `Uri uri -> self#_loadUriManagerUri (UriManager.uri_of_string uri)
466 | `Whelp (query, results) ->
467 set_whelp_query query;
468 self#_loadList (List.map (fun r -> "obj", r) results));
472 | UriManager.IllFormedUri uri -> fail (sprintf "invalid uri: %s" uri)
473 | CicEnvironment.Object_not_found uri ->
474 fail (sprintf "object not found: %s" (UriManager.string_of_uri uri))
475 | Browser_failure msg -> fail msg
477 method private blank () =
479 mathView#load_root (MatitaMisc.empty_mathml ())#get_documentElement
481 method private _loadCheck term =
482 failwith "not implemented _loadCheck";
485 method private home () =
487 match self#script#status.proof_status with
488 | Proof (uri, metasenv, bo, ty) ->
489 let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
490 let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
492 | Incomplete_proof ((uri, metasenv, bo, ty), _) ->
493 let name = UriManager.name_of_uri (MatitaMisc.unopt uri) in
494 let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
498 (** loads a cic uri from the environment
499 * @param uri UriManager.uri *)
500 method private _loadUriManagerUri uri =
501 let uri = UriManager.strip_xpointer uri in
502 let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
505 method private _loadDir dir =
506 let content = Http_getter.ls dir in
510 | Http_getter_types.Ls_section s -> "dir", s
511 | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
514 if l = [] then raise (Browser_failure "no such directory");
517 method private setEntry entry =
518 win#browserUri#entry#set_text (string_of_entry entry);
519 current_entry <- entry
521 method private _loadObj obj =
523 (* this must be _before_ loading the document, since
524 * if the widget is not mapped (hidden by the notebook)
525 * the document is not rendered *)
526 let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
527 let (mathml, (_,(ids_to_terms, ids_to_father_ids, ids_to_conjectures,
528 ids_to_hypotheses,_,_))) =
529 ApplyTransformation.mml_of_cic_object obj
531 current_infos <- Some (ids_to_terms, ids_to_father_ids,
532 ids_to_conjectures, ids_to_hypotheses);
533 (match current_mathml with
534 | Some current_mathml when use_diff ->
536 XmlDiff.update_dom ~from:current_mathml mathml;
539 mathView#load_root ~root:mathml#get_documentElement;
540 current_mathml <- Some mathml);
542 method private _loadTermCic term metasenv =
543 let context = self#script#proofContext in
544 let dummyno = CicMkImplicit.new_meta metasenv [] in
545 let sequent = (dummyno, context, term) in
546 mathView#load_sequent (sequent :: metasenv) dummyno;
549 method private _loadList l =
550 model#list_store#clear ();
551 List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
554 (** { public methods, all must call _load!! } *)
557 handle_error (fun () -> self#_load entry; self#_historyAdd entry)
559 (** this is what the browser does when you enter a string an hit enter *)
560 method loadInput txt =
561 let txt = strip_blanks txt in
563 UriManager.string_of_uri
564 (UriManager.strip_xpointer (UriManager.uri_of_string txt))
566 if is_whelp txt then begin
568 (MatitaScript.instance ())#advance ~statement:(txt ^ ".") ()
572 | txt when is_uri txt -> `Uri (fix_uri txt)
573 | txt when is_dir txt -> `Dir (add_trailing_slash txt)
577 with Invalid_argument _ ->
578 raise (Browser_failure (sprintf "unsupported uri: %s" txt)))
581 self#_historyAdd entry
584 (** {2 methods used by constructor only} *)
587 method history = history
588 method currentEntry = current_entry
590 if current_entry = `About `Current_proof then
591 self#_load (`About `Current_proof)
595 let sequentsViewer ~(notebook:GPack.notebook)
596 ~(sequentViewer:sequentViewer) ()
598 new sequentsViewer ~notebook ~sequentViewer ()
601 let size = BuildTimeConf.browser_history_size in
602 let rec aux history =
603 let browser = new cicBrowser_impl ~history () in
604 let win = browser#win in
605 ignore (win#browserNewButton#connect#clicked (fun () ->
607 new MatitaMisc.browser_history ~memento:history#save size
610 let newBrowser = aux history in
611 newBrowser#load browser#currentEntry));
613 (* attempt (failed) to close windows on CTRL-W ... *)
614 MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
615 GdkKeysyms._W (fun () -> win#toplevel#destroy ());
617 cicBrowsers := browser :: !cicBrowsers;
618 (browser :> cicBrowser)
620 let history = new MatitaMisc.browser_history size (`About `Blank) in
623 let refresh_all_browsers () = List.iter (fun b -> b#refresh ()) !cicBrowsers
625 let default_sequentViewer () = sequentViewer ~show:true ()
626 let sequentViewer_instance = MatitaMisc.singleton default_sequentViewer
628 let default_sequentsViewer () =
629 let gui = MatitaGui.instance () in
630 let sequentViewer = sequentViewer_instance () in
631 sequentsViewer ~notebook:gui#main#sequentsNotebook ~sequentViewer ()
632 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
636 method private get_browser reuse =
638 (match !cicBrowsers with
639 | [] -> cicBrowser ()
640 | b :: _ -> (b :> cicBrowser))
644 method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
646 method show_uri_list ?(reuse=false) ~entry l =
647 (self#get_browser reuse)#load entry