]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaMathView.ml
MAJOR SPEED UP. The previous implementation of scrolling of the slidebar to
[helm.git] / matita / 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 open CicMathView
34
35 module Stack = Continuationals.Stack
36
37 let cicBrowsers = ref []
38
39 let tab_label meta_markup =
40   let rec aux =
41     function
42     | `Closed m -> sprintf "<s>%s</s>" (aux m)
43     | `Current m -> sprintf "<b>%s</b>" (aux m)
44     | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
45     | `Meta n -> sprintf "?%d" n
46   in
47   let markup = aux meta_markup in
48   (GMisc.label ~markup ~show:true ())#coerce
49
50 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
51
52 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
53   object (self)
54     method cicMathView = cicMathView  (** clickableMathView accessor *)
55
56     val mutable pages = 0
57     val mutable switch_page_callback = None
58     val mutable page2goal = []  (* associative list: page no -> goal no *)
59     val mutable goal2page = []  (* the other way round *)
60     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
61     val mutable _metasenv = [],[]
62     val mutable scrolledWin: GBin.scrolled_window option = None
63       (* scrolled window to which the sequentViewer is currently attached *)
64     val logo = (GMisc.image
65       ~file:(MatitaMisc.image_path "matita_medium.png") ()
66       :> GObj.widget)
67             
68     val logo_with_qed = (GMisc.image
69       ~file:(MatitaMisc.image_path "matita_small.png") ()
70       :> GObj.widget)
71
72     method load_logo =
73      notebook#set_show_tabs false;
74      ignore(notebook#append_page logo)
75
76     method load_logo_with_qed =
77      notebook#set_show_tabs false;
78      ignore(notebook#append_page logo_with_qed)
79
80     method reset =
81       cicMathView#remove_selections;
82       (match scrolledWin with
83       | Some w ->
84           (* removing page from the notebook will destroy all contained widget,
85           * we do not want the cicMathView to be destroyed as well *)
86           w#remove cicMathView#coerce;
87           scrolledWin <- None
88       | None -> ());
89       (match switch_page_callback with
90       | Some id ->
91           GtkSignal.disconnect notebook#as_widget id;
92           switch_page_callback <- None
93       | None -> ());
94       for i = 0 to pages do notebook#remove_page 0 done; 
95       notebook#set_show_tabs true;
96       pages <- 0;
97       page2goal <- [];
98       goal2page <- [];
99       goal2win <- [];
100       _metasenv <- [],[]
101
102     method nload_sequents : 'status. #GrafiteTypes.status as 'status -> unit
103     = fun (status : #GrafiteTypes.status) ->
104      let _,_,metasenv,subst,_ = status#obj in
105       _metasenv <- metasenv,subst;
106       pages <- 0;
107       let win goal_switch =
108         let w =
109           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
110             ~shadow_type:`IN ~show:true () in
111         let reparent () =
112           scrolledWin <- Some w;
113           (match cicMathView#misc#parent with
114             | None -> ()
115             | Some parent ->
116                let parent =
117                 match cicMathView#misc#parent with
118                    None -> assert false
119                  | Some p -> GContainer.cast_container p
120                in
121                 parent#remove cicMathView#coerce);
122           w#add cicMathView#coerce
123         in
124         goal2win <- (goal_switch, reparent) :: goal2win;
125         w#coerce
126       in
127       assert (
128         let stack_goals = Stack.open_goals status#stack in
129         let proof_goals = List.map fst metasenv in
130         if
131           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
132           <> List.sort Pervasives.compare proof_goals
133         then begin
134           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
135           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
136           false
137         end
138         else true
139       );
140       let render_switch =
141         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
142       in
143       let page = ref 0 in
144       let added_goals = ref [] in
145         (* goals can be duplicated on the tack due to focus, but we should avoid
146          * multiple labels in the user interface *)
147       let add_tab markup goal_switch =
148         let goal = Stack.goal_of_switch goal_switch in
149         if not (List.mem goal !added_goals) then begin
150           ignore(notebook#append_page 
151             ~tab_label:(tab_label markup) (win goal_switch));
152           page2goal <- (!page, goal_switch) :: page2goal;
153           goal2page <- (goal_switch, !page) :: goal2page;
154           incr page;
155           pages <- pages + 1;
156           added_goals := goal :: !added_goals
157         end
158       in
159       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
160       Stack.iter  (** populate notebook with tabs *)
161         ~env:(fun depth tag (pos, sw) ->
162           let markup =
163             match depth, pos with
164             | 0, 0 -> `Current (render_switch sw)
165             | 0, _ -> `Shift (pos, `Current (render_switch sw))
166             | 1, pos when Stack.head_tag status#stack = `BranchTag ->
167                 `Shift (pos, render_switch sw)
168             | _ -> render_switch sw
169           in
170           add_tab markup sw)
171         ~cont:add_switch ~todo:add_switch
172         status#stack;
173       switch_page_callback <-
174         Some (notebook#connect#switch_page ~callback:(fun page ->
175           let goal_switch =
176             try List.assoc page page2goal with Not_found -> assert false
177           in
178           self#render_page status ~page ~goal_switch))
179
180     method private render_page:
181      'status. #ApplyTransformation.status as 'status -> page:int ->
182        goal_switch:Stack.switch -> unit
183      = fun status ~page ~goal_switch ->
184       (match goal_switch with
185       | Stack.Open goal ->
186          let menv,subst = _metasenv in
187           cicMathView#nload_sequent status menv subst goal
188       | Stack.Closed goal ->
189           let root = Lazy.force closed_goal_mathml in
190           cicMathView#load_root ~root);
191       (try
192         cicMathView#set_selection None;
193         List.assoc goal_switch goal2win ();
194         (match cicMathView#misc#parent with
195            None -> assert false
196          | Some p ->
197             (* The text widget dinamycally inserts the text in a separate
198                thread. We need to wait for it to terminate before we can
199                move the scrollbar to the end *)
200             while Glib.Main.pending()do ignore(Glib.Main.iteration false); done;
201             let w =
202              new GBin.scrolled_window
203               (Gobject.try_cast p#as_widget "GtkScrolledWindow") in
204             w#hadjustment#set_value 0.0;
205             w#vadjustment#set_value
206              (w#vadjustment#upper -. w#vadjustment#page_size));
207       with Not_found -> assert false)
208
209     method goto_sequent: 'status. #ApplyTransformation.status as 'status -> int -> unit
210      = fun status goal ->
211       let goal_switch, page =
212         try
213           List.find
214             (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
215             goal2page
216         with Not_found -> assert false
217       in
218       notebook#goto_page page;
219       self#render_page status ~page ~goal_switch
220   end
221
222 let blank_uri = BuildTimeConf.blank_uri
223 let current_proof_uri = BuildTimeConf.current_proof_uri
224
225 type term_source =
226   [ `Ast of NotationPt.term
227   | `NCic of NCic.term * NCic.context * NCic.metasenv * NCic.substitution
228   | `String of string
229   ]
230
231 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
232   ()
233 =
234   let uri_RE =
235     Pcre.regexp
236       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
237   in
238   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
239   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
240   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
241   let gui = MatitaMisc.get_gui () in
242   let win = new MatitaGeneratedGui.browserWin () in
243   let _ = win#browserUri#misc#grab_focus () in
244   let gviz = LablGraphviz.graphviz ~packing:win#graphScrolledWin#add () in
245   let searchText = 
246     GSourceView2.source_view ~auto_indent:false ~editable:false ()
247   in
248   let _ =
249      win#scrolledwinContent#add (searchText :> GObj.widget);
250      let callback () = 
251        let text = win#entrySearch#text in
252        let highlight start end_ =
253          searchText#source_buffer#move_mark `INSERT ~where:start;
254          searchText#source_buffer#move_mark `SEL_BOUND ~where:end_;
255          searchText#scroll_mark_onscreen `INSERT
256        in
257        let iter = searchText#source_buffer#get_iter `SEL_BOUND in
258        match iter#forward_search text with
259        | None -> 
260            (match searchText#source_buffer#start_iter#forward_search text with
261            | None -> ()
262            | Some (start,end_) -> highlight start end_)
263        | Some (start,end_) -> highlight start end_
264      in
265      ignore(win#entrySearch#connect#activate ~callback);
266      ignore(win#buttonSearch#connect#clicked ~callback);
267   in
268   let toplevel = win#toplevel in
269   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
270   let fail message = 
271     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
272       ~parent:toplevel ()  
273   in
274   let tags =
275     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
276       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
277   in
278   let b = (not (Helm_registry.get_bool "matita.debug")) in
279   let handle_error f =
280     try
281       f ()
282     with exn ->
283       if b then
284         fail (snd (MatitaExcPp.to_string exn))
285       else raise exn
286   in
287   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
288   let load_easter_egg = lazy (
289     win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
290   in
291   let load_hints () =
292       let module Pp = GraphvizPp.Dot in
293       let filename, oc = Filename.open_temp_file "matita" ".dot" in
294       let fmt = Format.formatter_of_out_channel oc in
295       let status = (get_matita_script_current ())#status in
296       Pp.header 
297         ~name:"Hints"
298         ~graph_type:"graph"
299         ~graph_attrs:["overlap", "false"]
300         ~node_attrs:["fontsize", "9"; "width", ".4"; 
301             "height", ".4"; "shape", "box"]
302         ~edge_attrs:["fontsize", "10"; "len", "2"] fmt;
303       NCicUnifHint.generate_dot_file status fmt;
304       Pp.trailer fmt;
305       Pp.raw "@." fmt;
306       close_out oc;
307       gviz#load_graph_from_file ~gviz_cmd:"neato -Tpng" filename;
308       (*HExtlib.safe_remove filename*)
309   in
310   let load_coerchgraph tred () = 
311       let module Pp = GraphvizPp.Dot in
312       let filename, oc = Filename.open_temp_file "matita" ".dot" in
313       let fmt = Format.formatter_of_out_channel oc in
314       Pp.header 
315         ~name:"Coercions"
316         ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
317         ~edge_attrs:["fontsize", "10"] fmt;
318       let status = (get_matita_script_current ())#status in
319       NCicCoercion.generate_dot_file status fmt;
320       Pp.trailer fmt;
321       Pp.raw "@." fmt;
322       close_out oc;
323       if tred then
324         gviz#load_graph_from_file 
325           ~gviz_cmd:"dot -Txdot | tred |gvpack -gv | dot" filename
326       else
327         gviz#load_graph_from_file 
328           ~gviz_cmd:"dot -Txdot | gvpack -gv | dot" filename;
329       HExtlib.safe_remove filename
330   in
331   object (self)
332     val mutable gviz_uri = NReference.reference_of_string "cic:/dummy.dec";
333
334     val dep_contextual_menu = GMenu.menu ()
335
336     initializer
337       win#mathOrListNotebook#set_show_tabs false;
338       win#browserForwardButton#misc#set_sensitive false;
339       win#browserBackButton#misc#set_sensitive false;
340       ignore (win#browserUri#connect#activate (handle_error' (fun () ->
341         self#loadInput win#browserUri#text)));
342       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
343         self#load (`About `Current_proof))));
344       ignore (win#browserRefreshButton#connect#clicked
345         (handle_error' (self#refresh ~force:true)));
346       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
347       ignore (win#browserForwardButton#connect#clicked
348         (handle_error' self#forward));
349       ignore (win#toplevel#event#connect#delete (fun _ ->
350         let my_id = Oo.id self in
351         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
352         false));
353       ignore(win#whelpResultTreeview#connect#row_activated 
354         ~callback:(fun _ _ ->
355           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
356       mathView#set_href_callback (Some (fun uri ->
357         handle_error (fun () ->
358          let uri = `NRef (NReference.reference_of_string uri) in
359           self#load uri)));
360       gviz#connect_href (fun button_ev attrs ->
361         let time = GdkEvent.Button.time button_ev in
362         let uri = List.assoc "href" attrs in
363         gviz_uri <- NReference.reference_of_string uri;
364         match GdkEvent.Button.button button_ev with
365         | button when button = MatitaMisc.left_button -> self#load (`NRef gviz_uri)
366         | button when button = MatitaMisc.right_button ->
367             dep_contextual_menu#popup ~button ~time
368         | _ -> ());
369       connect_menu_item win#browserCloseMenuItem (fun () ->
370         let my_id = Oo.id self in
371         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
372         win#toplevel#misc#hide(); win#toplevel#destroy ());
373       connect_menu_item win#browserUrlMenuItem (fun () ->
374         win#browserUri#misc#grab_focus ());
375
376       self#_load (`About `Blank);
377       toplevel#show ()
378
379     val mutable current_entry = `About `Blank 
380
381       (** @return None if no object uri can be built from the current entry *)
382     method private currentCicUri =
383       match current_entry with
384       | `NRef uri -> Some uri
385       | _ -> None
386
387     val model =
388       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
389
390     val mutable lastDir = ""  (* last loaded "directory" *)
391
392     method mathView = mathView
393
394     method private _getSelectedUri () =
395       match model#easy_selection () with
396       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
397 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
398       | [sel] -> lastDir ^ sel
399       | _ -> assert false
400
401     (** history RATIONALE 
402      *
403      * All operations about history are done using _historyFoo.
404      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
405      *)
406           
407     method private _historyAdd item = 
408       history#add item;
409       win#browserBackButton#misc#set_sensitive true;
410       win#browserForwardButton#misc#set_sensitive false
411
412     method private _historyPrev () =
413       let item = history#previous in
414       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
415       win#browserForwardButton#misc#set_sensitive true;
416       item
417     
418     method private _historyNext () =
419       let item = history#next in
420       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
421       win#browserBackButton#misc#set_sensitive true;
422       item
423
424     (** notebook RATIONALE 
425      * 
426      * Use only these functions to switch between the tabs
427      *)
428     method private _showMath = win#mathOrListNotebook#goto_page   0
429     method private _showList = win#mathOrListNotebook#goto_page   1
430     method private _showEgg  = win#mathOrListNotebook#goto_page   2
431     method private _showGviz = win#mathOrListNotebook#goto_page   3
432     method private _showSearch = win#mathOrListNotebook#goto_page 4
433
434     method private back () =
435       try
436         self#_load (self#_historyPrev ())
437       with MatitaMisc.History_failure -> ()
438
439     method private forward () =
440       try
441         self#_load (self#_historyNext ())
442       with MatitaMisc.History_failure -> ()
443
444       (* loads a uri which can be a cic uri or an about:* uri
445       * @param uri string *)
446     method private _load ?(force=false) entry =
447       handle_error (fun () ->
448        if entry <> current_entry || entry = `About `Current_proof || entry =
449          `About `Coercions || entry = `About `CoercionsFull || force then
450         begin
451           (match entry with
452           | `About `Current_proof -> self#home ()
453           | `About `Blank -> self#blank ()
454           | `About `Us -> self#egg ()
455           | `About `CoercionsFull -> self#coerchgraph false ()
456           | `About `Coercions -> self#coerchgraph true ()
457           | `About `Hints -> self#hints ()
458           | `About `TeX -> self#tex ()
459           | `About `Grammar -> self#grammar () 
460           | `Check term -> self#_loadCheck term
461           | `NCic (term, ctx, metasenv, subst) -> 
462                self#_loadTermNCic term metasenv subst ctx
463           | `Dir dir -> self#_loadDir dir
464           | `NRef nref -> self#_loadNReference nref);
465           self#setEntry entry
466         end)
467
468     method private blank () =
469       self#_showMath;
470       mathView#load_root (Lazy.force empty_mathml)
471
472     method private _loadCheck term =
473       failwith "not implemented _loadCheck";
474 (*       self#_showMath *)
475
476     method private egg () =
477       self#_showEgg;
478       Lazy.force load_easter_egg
479
480     method private redraw_gviz ?center_on () =
481       if Sys.command "which dot" = 0 then
482        let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
483        let fmt = Format.formatter_of_out_channel oc in
484        (* MATITA 1.0 MetadataDeps.DepGraph.render fmt gviz_graph;*)
485        close_out oc;
486        gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
487        (match center_on with
488        | None -> ()
489        | Some uri -> gviz#center_on_href (NReference.string_of_reference uri));
490        HExtlib.safe_remove tmpfile
491       else
492        MatitaGtkMisc.report_error ~title:"graphviz error"
493         ~message:("Graphviz is not installed but is necessary to render "^
494          "the graph of dependencies amoung objects. Please install it.")
495         ~parent:win#toplevel ()
496
497     method private dependencies direction uri () =
498       assert false (* MATITA 1.0
499       let dbd = LibraryDb.instance () in
500       let graph =
501         match direction with
502         | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
503         | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
504       gviz_graph <- graph;  (** XXX check this for memory consuption *)
505       self#redraw_gviz ~center_on:uri ();
506       self#_showGviz *)
507
508     method private coerchgraph tred () =
509       load_coerchgraph tred ();
510       self#_showGviz
511
512     method private hints () =
513       load_hints ();
514       self#_showGviz
515
516     method private tex () =
517       let b = Buffer.create 1000 in
518       Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
519       List.iter 
520         (fun l ->
521            List.iter (fun sym ->
522              Printf.bprintf b "  %s" (Glib.Utf8.from_unichar sym) 
523            ) l;
524            Printf.bprintf b "\n";
525         )
526         (List.sort 
527           (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
528           (Virtuals.get_all_eqclass ()));
529       Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
530       List.iter 
531         (fun tag, items -> 
532            Printf.bprintf b "  %s:\n" tag;
533            List.iter 
534              (fun names, symbol ->
535                 Printf.bprintf b "  \t%s\t%s\n" 
536                   (Glib.Utf8.from_unichar symbol)
537                   (String.concat ", " names))
538              (List.sort 
539                (fun (_,a) (_,b) -> compare a b)
540                items);
541            Printf.bprintf b "\n")
542         (List.sort 
543           (fun (a,_) (b,_) -> compare a b)
544           (Virtuals.get_all_virtuals ()));
545       self#_loadText (Buffer.contents b)
546
547     method private _loadText text =
548       searchText#source_buffer#set_text text;
549       win#entrySearch#misc#grab_focus ();
550       self#_showSearch
551
552     method private grammar () =
553       self#_loadText
554        (Print_grammar.ebnf_of_term (get_matita_script_current ())#status);
555
556     method private home () =
557       self#_showMath;
558       let status = (get_matita_script_current ())#status in
559        match status#ng_mode with
560           `ProofMode -> self#_loadNObj status status#obj
561         | _ -> self#blank ()
562
563     method private _loadNReference (NReference.Ref (uri,_)) =
564       let status = (get_matita_script_current ())#status in
565       let obj = NCicEnvironment.get_checked_obj status uri in
566       self#_loadNObj status obj
567
568     method private _loadDir dir = 
569       let content = Http_getter.ls ~local:false dir in
570       let l =
571         List.fast_sort
572           Pervasives.compare
573           (List.map
574             (function 
575               | Http_getter_types.Ls_section s -> "dir", s
576               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
577             content)
578       in
579       lastDir <- dir;
580       self#_loadList l
581
582     method private setEntry entry =
583       win#browserUri#set_text (MatitaTypes.string_of_entry entry);
584       current_entry <- entry
585
586     method private _loadNObj status obj =
587       (* showMath must be done _before_ loading the document, since if the
588        * widget is not mapped (hidden by the notebook) the document is not
589        * rendered *)
590       self#_showMath;
591       mathView#load_nobject status obj
592
593     method private _loadTermNCic term m s c =
594       let d = 0 in
595       let m = (0,([],c,term))::m in
596       let status = (get_matita_script_current ())#status in
597       mathView#nload_sequent status m s d;
598       self#_showMath
599
600     method private _loadList l =
601       model#list_store#clear ();
602       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
603       self#_showList
604
605     (** { public methods, all must call _load!! } *)
606       
607     method load entry =
608       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
609
610     (**  this is what the browser does when you enter a string an hit enter *)
611     method loadInput txt =
612       let txt = HExtlib.trim_blanks txt in
613       (* (* ZACK: what the heck? *)
614       let fix_uri txt =
615         UriManager.string_of_uri
616           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
617       in
618       *)
619         let entry =
620           match txt with
621           | txt when is_uri txt ->
622               `NRef (NReference.reference_of_string ((*fix_uri*) txt))
623           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
624           | txt ->
625              (try
626                MatitaTypes.entry_of_string txt
627               with Invalid_argument _ ->
628                raise
629                 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
630         in
631         self#_load entry;
632         self#_historyAdd entry
633
634       (** {2 methods used by constructor only} *)
635
636     method win = win
637     method history = history
638     method currentEntry = current_entry
639     method refresh ~force () = self#_load ~force current_entry
640
641   end
642   
643 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
644   MatitaGuiTypes.sequentsViewer
645 =
646   (new sequentsViewer ~notebook ~cicMathView ():> MatitaGuiTypes.sequentsViewer)
647
648 let new_cicBrowser () =
649   let size = BuildTimeConf.browser_history_size in
650   let rec aux history =
651     let browser = new cicBrowser_impl ~history () in
652     let win = browser#win in
653     ignore (win#browserNewButton#connect#clicked (fun () ->
654       let history =
655         new MatitaMisc.browser_history ~memento:history#save size
656           (`About `Blank)
657       in
658       let newBrowser = aux history in
659       newBrowser#load browser#currentEntry));
660 (*
661       (* attempt (failed) to close windows on CTRL-W ... *)
662     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
663       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
664 *)
665     cicBrowsers := browser :: !cicBrowsers;
666     browser
667   in
668   let history = new MatitaMisc.browser_history size (`About `Blank) in
669   aux history
670
671 (** @param reuse if set reused last opened cic browser otherwise 
672 *  opens a new one. default is false *)
673 let cicBrowser ?(reuse=false) t =
674  let browser =
675   if reuse then
676    (match !cicBrowsers with [] -> new_cicBrowser () | b :: _ -> b)
677   else
678    new_cicBrowser ()
679  in
680   match t with
681      None -> ()
682    | Some t -> browser#load t
683 ;;
684
685 let default_cicMathView () =
686  let res = cicMathView ~show:true () in
687   res#set_href_callback
688     (Some (fun uri ->
689       let uri = `NRef (NReference.reference_of_string uri) in
690        cicBrowser (Some uri)));
691   res
692
693 let cicMathView_instance =
694  MatitaMisc.singleton default_cicMathView
695
696 let default_sequentsViewer notebook =
697   let cicMathView = cicMathView_instance () in
698   sequentsViewer ~notebook ~cicMathView ()
699
700 let sequentsViewer_instance =
701  let already_used = ref false in
702   fun notebook ->
703    if !already_used then assert false
704    else
705     (already_used := true;
706      default_sequentsViewer notebook)
707
708 let refresh_all_browsers () =
709   List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
710
711 let get_math_views () =
712   (cicMathView_instance ()) :: (List.map (fun b -> b#mathView) !cicBrowsers)
713
714 let find_selection_owner () =
715   let rec aux =
716     function
717     | [] -> raise Not_found
718     | mv :: tl ->
719         (match mv#get_selections with
720         | [] -> aux tl
721         | sel :: _ -> mv)
722   in
723   aux (get_math_views ())
724
725 let has_selection () =
726   try ignore (find_selection_owner ()); true
727   with Not_found -> false
728
729 let math_view_clipboard = ref None (* associative list target -> string *)
730 let has_clipboard () = !math_view_clipboard <> None
731 let empty_clipboard () = math_view_clipboard := None
732
733 let copy_selection () =
734   try
735     math_view_clipboard :=
736       Some ((find_selection_owner ())#strings_of_selection)
737   with Not_found -> failwith "no selection"
738
739 let paste_clipboard paste_kind =
740   match !math_view_clipboard with
741   | None -> failwith "empty clipboard"
742   | Some cb ->
743       (try List.assoc paste_kind cb with Not_found -> assert false)
744