]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaGui.ml
0bea9c43f6a1531c5bb6d927544e8ecc2e873372
[helm.git] / matita / matita / matitaGui.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://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29
30 open MatitaGeneratedGui
31 open MatitaGtkMisc
32 open MatitaMisc
33
34 exception Found of int
35
36 let all_disambiguation_passes = ref false
37
38 let gui_instance = ref None
39
40 (* this is a shit and should be changed :-{ *)
41 let interactive_uri_choice
42   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
43   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
44   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
45   ?copy_cb ()
46   ~id uris
47 =
48   if (selection_mode <> `SINGLE) &&
49     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
50   then
51     uris
52   else begin
53     let dialog = new uriChoiceDialog () in
54     if hide_uri_entry then
55       dialog#uriEntryHBox#misc#hide ();
56     if hide_try then
57       begin
58       dialog#uriChoiceSelectedButton#misc#hide ();
59       dialog#uriChoiceConstantsButton#misc#hide ();
60       end;
61     dialog#okLabel#set_label ok_label;  
62     dialog#uriChoiceTreeView#selection#set_mode
63       (selection_mode :> Gtk.Tags.selection_mode);
64     let model = new stringListModel dialog#uriChoiceTreeView in
65     let choices = ref None in
66     (match copy_cb with
67     | None -> ()
68     | Some cb ->
69         dialog#copyButton#misc#show ();
70         connect_button dialog#copyButton 
71         (fun _ ->
72           match model#easy_selection () with
73           | [u] -> (cb u)
74           | _ -> ()));
75     dialog#uriChoiceDialog#set_title title;
76     dialog#uriChoiceLabel#set_text msg;
77     List.iter model#easy_append (List.map NReference.string_of_reference uris);
78     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
79     let return v =
80       choices := v;
81       dialog#uriChoiceDialog#destroy ();
82       GMain.Main.quit ()
83     in
84     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
85     connect_button dialog#uriChoiceConstantsButton (fun _ ->
86       return (Some uris));
87     if ok_action = `AUTO then
88       connect_button dialog#uriChoiceAutoButton (fun _ ->
89         Helm_registry.set_bool "matita.auto_disambiguation" true;
90         return (Some uris))
91     else
92       connect_button dialog#uriChoiceAutoButton (fun _ ->
93         match model#easy_selection () with
94         | [] -> ()
95         | uris -> return (Some (List.map NReference.reference_of_string uris)));
96     connect_button dialog#uriChoiceSelectedButton (fun _ ->
97       match model#easy_selection () with
98       | [] -> ()
99       | uris -> return (Some (List.map NReference.reference_of_string uris)));
100     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
101     dialog#uriChoiceDialog#show ();
102     GtkThread.main ();
103     (match !choices with 
104     | None -> raise MatitaTypes.Cancel
105     | Some uris -> uris)
106   end
107
108
109 class type browserWin =
110   (* this class exists only because GEdit.combo_box_entry is not supported by
111    * lablgladecc :-(((( *)
112 object
113   inherit MatitaGeneratedGui.browserWin
114   method browserUri: GEdit.entry
115 end
116
117 class console ~(buffer: GText.buffer) () =
118   object (self)
119     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
120     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
121     val message_tag = buffer#create_tag []
122     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
123     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
124     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
125     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
126     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
127     method clear () =
128       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
129     method log_callback (tag: HLog.log_tag) s =
130       let s = Pcre.replace ~pat:"\e\\[0;3.m([^\e]+)\e\\[0m" ~templ:"$1" s in
131       match tag with
132       | `Debug -> self#debug (s ^ "\n")
133       | `Error -> self#error (s ^ "\n")
134       | `Message -> self#message (s ^ "\n")
135       | `Warning -> self#warning (s ^ "\n")
136   end
137         
138 let clean_current_baseuri status = 
139   LibraryClean.clean_baseuris [status#baseuri]
140
141 let save_moo status = 
142   let script = MatitaScript.current () in
143   let baseuri = status#baseuri in
144   match script#bos, script#eos with
145   | true, _ -> ()
146   | _, true ->
147      GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
148       status
149   | _ -> clean_current_baseuri status 
150 ;;
151     
152 let ask_unsaved parent filename =
153   MatitaGtkMisc.ask_confirmation 
154     ~parent ~title:"Unsaved work!" 
155     ~message:("Script <b>" ^ filename ^ "</b> is modified.!\n\n"^
156          "<i>Do you want to save the script before continuing?</i>")
157     ()
158
159 class interpErrorModel =
160   let cols = new GTree.column_list in
161   let id_col = cols#add Gobject.Data.string in
162   let dsc_col = cols#add Gobject.Data.string in
163   let interp_no_col = cols#add Gobject.Data.caml in
164   let tree_store = GTree.tree_store cols in
165   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
166   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
167   let id_view_col = GTree.view_column ~renderer:id_renderer () in
168   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
169   fun (tree_view: GTree.view) choices ->
170     object
171       initializer
172         tree_view#set_model (Some (tree_store :> GTree.model));
173         ignore (tree_view#append_column id_view_col);
174         ignore (tree_view#append_column dsc_view_col);
175         tree_store#clear ();
176         let idx1 = ref ~-1 in
177         List.iter
178           (fun _,lll ->
179             incr idx1;
180             let loc_row =
181              if List.length choices = 1 then
182               None
183              else
184               (let loc_row = tree_store#append () in
185                 begin
186                  match lll with
187                     [passes,envs_and_diffs,_,_] ->
188                       tree_store#set ~row:loc_row ~column:id_col
189                        ("Error location " ^ string_of_int (!idx1+1) ^
190                         ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
191                         " (in passes " ^
192                         String.concat " " (List.map string_of_int passes) ^
193                         ")");
194                       tree_store#set ~row:loc_row ~column:interp_no_col
195                        (!idx1,Some 0,None);
196                   | _ ->
197                     tree_store#set ~row:loc_row ~column:id_col
198                      ("Error location " ^ string_of_int (!idx1+1));
199                     tree_store#set ~row:loc_row ~column:interp_no_col
200                      (!idx1,None,None);
201                 end ;
202                 Some loc_row) in
203             let idx2 = ref ~-1 in
204              List.iter
205               (fun passes,envs_and_diffs,_,_ ->
206                 incr idx2;
207                 let msg_row =
208                  if List.length lll = 1 then
209                   loc_row
210                  else
211                   let msg_row = tree_store#append ?parent:loc_row () in
212                    (tree_store#set ~row:msg_row ~column:id_col
213                      ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
214                       string_of_int (!idx2+1) ^
215                       " (in passes " ^
216                       String.concat " " (List.map string_of_int passes) ^
217                       ")");
218                     tree_store#set ~row:msg_row ~column:interp_no_col
219                      (!idx1,Some !idx2,None);
220                     Some msg_row) in
221                 let idx3 = ref ~-1 in
222                 List.iter
223                  (fun (passes,env,_) ->
224                    incr idx3;
225                    let interp_row =
226                     match envs_and_diffs with
227                        _::_::_ ->
228                         let interp_row = tree_store#append ?parent:msg_row () in
229                         tree_store#set ~row:interp_row ~column:id_col
230                           ("Interpretation " ^ string_of_int (!idx3+1) ^
231                            " (in passes " ^
232                            String.concat " " (List.map string_of_int passes) ^
233                            ")");
234                         tree_store#set ~row:interp_row ~column:interp_no_col
235                          (!idx1,Some !idx2,Some !idx3);
236                         Some interp_row
237                      | [_] -> msg_row
238                      | [] -> assert false
239                    in
240                     List.iter
241                      (fun (_, id, dsc) ->
242                        let row = tree_store#append ?parent:interp_row () in
243                        tree_store#set ~row ~column:id_col id;
244                        tree_store#set ~row ~column:dsc_col dsc;
245                        tree_store#set ~row ~column:interp_no_col
246                         (!idx1,Some !idx2,Some !idx3)
247                      ) env
248                  ) envs_and_diffs
249               ) lll ;
250              if List.length lll > 1 then
251               HExtlib.iter_option
252                (fun p -> tree_view#expand_row (tree_store#get_path p))
253                loc_row
254           ) choices
255
256       method get_interp_no tree_path =
257         let iter = tree_store#get_iter tree_path in
258         tree_store#get ~row:iter ~column:interp_no_col
259     end
260
261 exception UseLibrary;;
262
263 let interactive_error_interp ~all_passes
264   (source_buffer:GSourceView2.source_buffer) notify_exn offset errorll filename
265
266   (* hook to save a script for each disambiguation error *)
267   if false then
268    (let text =
269      source_buffer#get_text ~start:source_buffer#start_iter
270       ~stop:source_buffer#end_iter () in
271     let md5 = Digest.to_hex (Digest.string text) in
272     let filename =
273      Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma"  in
274     let ch = open_out filename in
275      output_string ch text;
276     close_out ch
277    );
278   assert (List.flatten errorll <> []);
279   let errorll' =
280    let remove_non_significant =
281      List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
282    let annotated_errorll () =
283     List.rev
284      (snd
285        (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
286          errorll)) in
287    if all_passes then annotated_errorll () else
288      let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
289     (* We remove passes 1,2 and 5,6 *)
290      let res =
291       (1,[])::(2,[])
292       ::(3,remove_non_significant (safe_list_nth errorll 2))
293       ::(4,remove_non_significant (safe_list_nth errorll 3))
294       ::(5,[])::(6,[])::[]
295      in
296       if List.flatten (List.map snd res) <> [] then res
297       else
298        (* all errors (if any) are not significant: we keep them *)
299        let res =
300         (1,[])::(2,[])
301         ::(3,(safe_list_nth errorll 2))
302         ::(4,(safe_list_nth errorll 3))
303         ::(5,[])::(6,[])::[]
304        in
305         if List.flatten (List.map snd res) <> [] then
306          begin
307           HLog.warn
308            "All disambiguation errors are not significant. Showing them anyway." ;
309           res
310          end
311         else
312          begin
313           HLog.warn
314            "No errors in phases 2 and 3. Showing all errors in all phases" ;
315           annotated_errorll ()
316          end
317    in
318   let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
319    match choices with
320       [] -> assert false
321     | [loffset,[_,envs_and_diffs,msg,significant]] ->
322         let _,env,diff = List.hd envs_and_diffs in
323          notify_exn
324           (MultiPassDisambiguator.DisambiguationError
325             (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
326     | _::_ ->
327        let dialog = new disambiguationErrors () in
328        if all_passes then
329         dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
330        let model = new interpErrorModel dialog#treeview choices in
331        dialog#disambiguationErrors#set_title "Disambiguation error";
332        dialog#disambiguationErrorsLabel#set_label
333         "Click on an error to see the corresponding message:";
334        ignore (dialog#treeview#connect#cursor_changed
335         (fun _ ->
336           let tree_path =
337            match fst (dialog#treeview#get_cursor ()) with
338               None -> assert false
339            | Some tp -> tp in
340           let idx1,idx2,idx3 = model#get_interp_no tree_path in
341           let loffset,lll = List.nth choices idx1 in
342           let _,envs_and_diffs,msg,significant =
343            match idx2 with
344               Some idx2 -> List.nth lll idx2
345             | None ->
346                 [],[],lazy "Multiple error messages. Please select one.",true
347           in
348           let _,env,diff =
349            match idx3 with
350               Some idx3 -> List.nth envs_and_diffs idx3
351             | None -> [],[],[] (* dymmy value, used *) in
352           let script = MatitaScript.current () in
353           let error_tag = script#error_tag in
354            source_buffer#remove_tag error_tag
355              ~start:source_buffer#start_iter
356              ~stop:source_buffer#end_iter;
357            notify_exn
358             (MultiPassDisambiguator.DisambiguationError
359               (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
360            ));
361        let return _ =
362          dialog#disambiguationErrors#destroy ();
363          GMain.Main.quit ()
364        in
365        let fail _ = return () in
366        ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
367        connect_button dialog#disambiguationErrorsOkButton
368         (fun _ ->
369           let tree_path =
370            match fst (dialog#treeview#get_cursor ()) with
371               None -> assert false
372            | Some tp -> tp in
373           let idx1,idx2,idx3 = model#get_interp_no tree_path in
374           let diff =
375            match idx2,idx3 with
376               Some idx2, Some idx3 ->
377                let _,lll = List.nth choices idx1 in
378                let _,envs_and_diffs,_,_ = List.nth lll idx2 in
379                let _,_,diff = List.nth envs_and_diffs idx3 in
380                 diff
381             | _,_ -> assert false
382           in
383            let newtxt =
384             String.concat "\n"
385              ("" ::
386                List.map
387                 (fun k,desc -> 
388                   let alias =
389                    match k with
390                    | DisambiguateTypes.Id id ->
391                        GrafiteAst.Ident_alias (id, desc)
392                    | DisambiguateTypes.Symbol (symb, i)-> 
393                        GrafiteAst.Symbol_alias (symb, i, desc)
394                    | DisambiguateTypes.Num i ->
395                        GrafiteAst.Number_alias (i, desc)
396                   in
397                    GrafiteAstPp.pp_alias alias)
398                 diff) ^ "\n"
399            in
400             source_buffer#insert
401              ~iter:
402                (source_buffer#get_iter_at_mark
403                 (`NAME "beginning_of_statement")) newtxt ;
404             return ()
405         );
406        connect_button dialog#disambiguationErrorsMoreErrors
407         (fun _ -> return () ; raise UseLibrary);
408        connect_button dialog#disambiguationErrorsCancelButton fail;
409        dialog#disambiguationErrors#show ();
410        GtkThread.main ()
411
412
413 class gui () =
414     (* creation order _is_ relevant for windows placement *)
415   let main = new mainWin () in
416   let sequents_viewer =
417    MatitaMathView.sequentsViewer_instance main#sequentsNotebook in
418   let fileSel = new fileSelectionWin () in
419   let findRepl = new findReplWin () in
420   let keyBindingBoxes = (* event boxes which should receive global key events *)
421     [ main#mainWinEventBox ]
422   in
423   let console = new console ~buffer:main#logTextView#buffer () in
424   object (self)
425     val mutable chosen_file = None
426     val mutable _ok_not_exists = false
427     val mutable _only_directory = false
428       
429     initializer
430       let s () = MatitaScript.current () in
431         (* key bindings *)
432       List.iter (* global key bindings *)
433         (fun (key, callback) -> self#addKeyBinding key callback)
434 (*
435         [ GdkKeysyms._F3,
436             toggle_win ~check:main#showProofMenuItem proof#proofWin;
437           GdkKeysyms._F4,
438             toggle_win ~check:main#showCheckMenuItem check#checkWin;
439 *)
440         [ ];
441         (* about win *)
442       let parse_txt_file file =
443        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
444        let l_rev = ref [] in
445        try
446         while true do
447          l_rev := input_line ch :: !l_rev;
448         done;
449         assert false
450        with
451         End_of_file ->
452          close_in ch;
453          List.rev !l_rev in 
454       let about_dialog =
455        GWindow.about_dialog
456         ~authors:(parse_txt_file "AUTHORS")
457         (*~comments:"comments"*)
458         ~copyright:"Copyright (C) 2005, the HELM team"
459         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
460         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
461         ~name:"Matita"
462         ~version:BuildTimeConf.version
463         ~website:"http://matita.cs.unibo.it"
464         ()
465       in
466       ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
467       connect_menu_item main#contentsMenuItem (fun () ->
468         if 0 = Sys.command "which gnome-help" then
469           let cmd =
470             sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
471           in
472            ignore (Sys.command cmd)
473         else
474           MatitaGtkMisc.report_error ~title:"help system error"
475            ~message:(
476               "The program gnome-help is not installed\n\n"^
477               "To browse the user manal it is necessary to install "^
478               "the gnome help syste (also known as yelp)") 
479            ~parent:main#toplevel ());
480       connect_menu_item main#aboutMenuItem about_dialog#present;
481         (* findRepl win *)
482       let show_find_Repl () = 
483         findRepl#toplevel#misc#show ();
484         findRepl#toplevel#misc#grab_focus ()
485       in
486       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
487       let find_forward _ = 
488           let source_view = (s ())#source_view in
489           let highlight start end_ =
490             source_view#source_buffer#move_mark `INSERT ~where:start;
491             source_view#source_buffer#move_mark `SEL_BOUND ~where:end_;
492             source_view#scroll_mark_onscreen `INSERT
493           in
494           let text = findRepl#findEntry#text in
495           let iter = source_view#source_buffer#get_iter `SEL_BOUND in
496           match iter#forward_search text with
497           | None -> 
498               (match source_view#source_buffer#start_iter#forward_search text with
499               | None -> ()
500               | Some (start,end_) -> highlight start end_)
501           | Some (start,end_) -> highlight start end_ 
502       in
503       let replace _ =
504         let source_view = (s ())#source_view in
505         let text = findRepl#replaceEntry#text in
506         let ins = source_view#source_buffer#get_iter `INSERT in
507         let sel = source_view#source_buffer#get_iter `SEL_BOUND in
508         if ins#compare sel < 0 then 
509           begin
510             ignore(source_view#source_buffer#delete_selection ());
511             source_view#source_buffer#insert text
512           end
513       in
514       connect_button findRepl#findButton find_forward;
515       connect_button findRepl#findReplButton replace;
516       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
517       ignore(findRepl#toplevel#event#connect#delete 
518         ~callback:(fun _ -> hide_find_Repl ();true));
519       connect_menu_item main#undoMenuItem
520        (fun () -> (MatitaScript.current ())#safe_undo);
521 (*CSC: XXX
522       ignore(source_view#source_buffer#connect#can_undo
523         ~callback:main#undoMenuItem#misc#set_sensitive);
524 *) main#undoMenuItem#misc#set_sensitive true;
525       connect_menu_item main#redoMenuItem
526        (fun () -> (MatitaScript.current ())#safe_redo);
527 (*CSC: XXX
528       ignore(source_view#source_buffer#connect#can_redo
529         ~callback:main#redoMenuItem#misc#set_sensitive);
530 *) main#redoMenuItem#misc#set_sensitive true;
531       connect_menu_item main#editMenu (fun () ->
532         main#copyMenuItem#misc#set_sensitive
533          (MatitaScript.current ())#canCopy;
534         main#cutMenuItem#misc#set_sensitive
535          (MatitaScript.current ())#canCut;
536         main#deleteMenuItem#misc#set_sensitive
537          (MatitaScript.current ())#canDelete;
538         main#pasteMenuItem#misc#set_sensitive
539          (MatitaScript.current ())#canPaste;
540         main#pastePatternMenuItem#misc#set_sensitive
541          (MatitaScript.current ())#canPastePattern);
542       connect_menu_item main#copyMenuItem
543          (fun () -> (MatitaScript.current ())#copy ());
544       connect_menu_item main#cutMenuItem
545          (fun () -> (MatitaScript.current ())#cut ());
546       connect_menu_item main#deleteMenuItem
547          (fun () -> (MatitaScript.current ())#delete ());
548       connect_menu_item main#pasteMenuItem
549          (fun () -> (MatitaScript.current ())#paste ());
550       connect_menu_item main#pastePatternMenuItem
551          (fun () -> (MatitaScript.current ())#pastePattern ());
552       connect_menu_item main#selectAllMenuItem (fun () ->
553        let source_view = (s ())#source_view in
554         source_view#source_buffer#move_mark `INSERT source_view#source_buffer#start_iter;
555         source_view#source_buffer#move_mark `SEL_BOUND source_view#source_buffer#end_iter);
556       connect_menu_item main#findReplMenuItem show_find_Repl;
557       connect_menu_item main#externalEditorMenuItem self#externalEditor;
558       connect_menu_item main#ligatureButton
559        (fun () -> (MatitaScript.current ())#nextSimilarSymbol);
560       ignore (findRepl#findEntry#connect#activate find_forward);
561         (* interface lockers *)
562       let lock_world _ =
563        let source_view = (s ())#source_view in
564         main#buttonsToolbar#misc#set_sensitive false;
565         main#scriptMenu#misc#set_sensitive false;
566         source_view#set_editable false
567       in
568       let unlock_world _ =
569        let source_view = (s ())#source_view in
570         main#buttonsToolbar#misc#set_sensitive true;
571         main#scriptMenu#misc#set_sensitive true;
572         source_view#set_editable true;
573         (*The next line seems sufficient to avoid some unknown race condition *)
574         GtkThread.sync (fun () -> ()) ()
575       in
576       let worker_thread = ref None in
577       let notify_exn (source_view : GSourceView2.source_view) exn =
578        let floc, msg = MatitaExcPp.to_string exn in
579         begin
580          match floc with
581             None -> ()
582           | Some floc ->
583              let (x, y) = HExtlib.loc_of_floc floc in
584              let script = MatitaScript.current () in
585              let locked_mark = script#locked_mark in
586              let error_tag = script#error_tag in
587              let baseoffset =
588               (source_view#source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
589              let x' = baseoffset + x in
590              let y' = baseoffset + y in
591              let x_iter = source_view#source_buffer#get_iter (`OFFSET x') in
592              let y_iter = source_view#source_buffer#get_iter (`OFFSET y') in
593              source_view#source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
594              let id = ref None in
595              id := Some (source_view#source_buffer#connect#changed ~callback:(fun () ->
596                source_view#source_buffer#remove_tag error_tag
597                  ~start:source_view#source_buffer#start_iter
598                  ~stop:source_view#source_buffer#end_iter;
599                match !id with
600                | None -> assert false (* a race condition occurred *)
601                | Some id ->
602                    (new GObj.gobject_ops source_view#source_buffer#as_buffer)#disconnect id));
603              source_view#source_buffer#place_cursor
604               (source_view#source_buffer#get_iter (`OFFSET x'));
605         end;
606         HLog.error msg in
607       let locker f script =
608        let source_view = script#source_view in
609        let thread_main =
610         fun () -> 
611           lock_world ();
612           let saved_use_library= !MultiPassDisambiguator.use_library in
613           try
614            MultiPassDisambiguator.use_library := !all_disambiguation_passes;
615            f script;
616            MultiPassDisambiguator.use_library := saved_use_library;
617            unlock_world ()
618           with
619            | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
620               (try
621                 interactive_error_interp 
622                  ~all_passes:!all_disambiguation_passes source_view#source_buffer
623                  (notify_exn source_view) offset errorll (s())#filename
624                with
625                 | UseLibrary ->
626                    MultiPassDisambiguator.use_library := true;
627                    (try f script
628                     with
629                     | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
630                        interactive_error_interp ~all_passes:true source_view#source_buffer
631                         (notify_exn source_view) offset errorll (s())#filename
632                     | exc ->
633                        notify_exn source_view exc);
634                 | exc -> notify_exn source_view exc);
635               MultiPassDisambiguator.use_library := saved_use_library;
636               unlock_world ()
637            | exc ->
638               (try notify_exn source_view exc
639                with Sys.Break as e -> notify_exn source_view e);
640               unlock_world ()
641        in
642        (*thread_main ();*)
643        worker_thread := Some (Thread.create thread_main ())
644       in
645       let kill_worker =
646        (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
647        let interrupt = ref None in
648        let old_callback = ref (function _ -> ()) in
649        let force_interrupt n =
650          (* This function is called just before the thread's timeslice ends *)
651          !old_callback n;
652          if Some(Thread.id(Thread.self())) = !interrupt then
653           (interrupt := None; raise Sys.Break) in
654        let _ =
655         match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
656            Sys.Signal_handle f -> old_callback := f
657          | Sys.Signal_ignore
658          | Sys.Signal_default -> assert false
659        in
660         fun () ->
661          match !worker_thread with
662             None -> assert false
663           | Some t -> interrupt := Some (Thread.id t) in
664       let keep_focus f (script: MatitaScript.script) =
665          try
666           f script; script#source_view#misc#grab_focus ()
667          with
668           exc -> script#source_view#misc#grab_focus (); raise exc in
669       
670         (* file selection win *)
671       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
672       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
673         let return r =
674           chosen_file <- r;
675           fileSel#fileSelectionWin#misc#hide ();
676           GMain.Main.quit ()
677         in
678         match event with
679         | `OK ->
680             let fname = fileSel#fileSelectionWin#filename in
681             if Sys.file_exists fname then
682               begin
683                 if HExtlib.is_regular fname && not (_only_directory) then 
684                   return (Some fname) 
685                 else if _only_directory && HExtlib.is_dir fname then 
686                   return (Some fname)
687               end
688             else
689               begin
690                 if _ok_not_exists then 
691                   return (Some fname)
692               end
693         | `CANCEL -> return None
694         | `HELP -> ()
695         | `DELETE_EVENT -> return None));
696         (* menus *)
697       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
698         (* console *)
699       let adj = main#logScrolledWin#vadjustment in
700         ignore (adj#connect#changed
701                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
702       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
703         (* natural deduction palette *)
704       main#tacticsButtonsHandlebox#misc#hide ();
705       MatitaGtkMisc.toggle_callback
706         ~callback:(fun b -> 
707           if b then main#tacticsButtonsHandlebox#misc#show ()
708           else main#tacticsButtonsHandlebox#misc#hide ())
709         ~check:main#menuitemPalette;
710       connect_button main#butImpl_intro
711         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⇒#i […] (…));\n");
712       connect_button main#butAnd_intro
713         (fun () -> (s ())#source_view#source_buffer#insert 
714           "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
715       connect_button main#butOr_intro_left
716         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_l (…));\n");
717       connect_button main#butOr_intro_right
718         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_r (…));\n");
719       connect_button main#butNot_intro
720         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (¬#i […] (…));\n");
721       connect_button main#butTop_intro
722         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊤#i);\n");
723       connect_button main#butImpl_elim
724         (fun () -> (s ())#source_view#source_buffer#insert 
725           "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
726       connect_button main#butAnd_elim_left
727         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_l (…));\n");
728       connect_button main#butAnd_elim_right
729         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_r (…));\n");
730       connect_button main#butOr_elim
731         (fun () -> (s ())#source_view#source_buffer#insert 
732           "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
733       connect_button main#butNot_elim
734         (fun () -> (s ())#source_view#source_buffer#insert 
735           "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
736       connect_button main#butBot_elim
737         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊥#e (…));\n");
738       connect_button main#butRAA
739         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (RAA […] (…));\n");
740       connect_button main#butUseLemma
741         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (lem #premises name â€¦);\n");
742       connect_button main#butDischarge
743         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (discharge […]);\n");
744       
745       connect_button main#butForall_intro
746         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#i {…} (…));\n");
747       connect_button main#butForall_elim
748         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#e {…} (…));\n");
749       connect_button main#butExists_intro
750         (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∃#i {…} (…));\n");
751       connect_button main#butExists_elim
752         (fun () -> (s ())#source_view#source_buffer#insert 
753           "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
754
755     
756       let module Hr = Helm_registry in
757       MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
758         ~callback:(function 
759           | true -> main#toplevel#fullscreen () 
760           | false -> main#toplevel#unfullscreen ());
761       main#fullscreenMenuItem#set_active false;
762       MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
763         ~callback:(function b ->
764           let s = s () in
765           let status = Interpretations.toggle_active_interpretations s#status b
766           in
767            assert false (* MATITA 1.0 ???
768            s#set_grafite_status status*)
769          );
770       MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
771         ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
772       MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
773         ~callback:(fun enabled ->
774           Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
775       main#unicodeAsTexMenuItem#set_active
776         (Helm_registry.get_bool "matita.paste_unicode_as_tex");
777         (* log *)
778       HLog.set_log_callback self#console#log_callback;
779       GtkSignal.user_handler :=
780         (function 
781         | MatitaScript.ActionCancelled s -> HLog.error s
782         | exn ->
783           if not (Helm_registry.get_bool "matita.debug") then
784            (* MatitaScript.current is problably wrong, but what else
785               can we do? *)
786            notify_exn (MatitaScript.current ())#source_view exn
787           else raise exn);
788       let loadScript () =
789         try 
790           match self#chooseFile () with
791           | Some f -> self#loadScript f
792           | None -> ()
793         with MatitaTypes.Cancel -> ()
794       in
795       let cursor () =
796        let source_view = (s ())#source_view in
797         source_view#source_buffer#place_cursor
798           (source_view#source_buffer#get_iter_at_mark (`NAME "locked")) in
799       let advance (script: MatitaScript.script) = script#advance (); cursor () in
800       let retract (script: MatitaScript.script) = script#retract (); cursor () in
801       let top (script: MatitaScript.script) = script#goto `Top (); cursor () in
802       let bottom (script: MatitaScript.script) = script#goto `Bottom (); cursor () in
803       let jump (script: MatitaScript.script) = script#goto `Cursor (); cursor () in
804       let advance () = locker (keep_focus advance) (MatitaScript.current ()) in
805       let retract () = locker (keep_focus retract) (MatitaScript.current ()) in
806       let top () = locker (keep_focus top) (MatitaScript.current ()) in
807       let bottom () = locker (keep_focus bottom) (MatitaScript.current ()) in
808       let jump () = locker (keep_focus jump) (MatitaScript.current ()) in
809         (* quit *)
810       self#setQuitCallback (fun () -> 
811        let cancel = ref false in
812         MatitaScript.iter_scripts
813          (fun script ->
814            if not !cancel then
815             if not (self#closeScript0 script) then
816              cancel := true);
817         if not !cancel then
818          GMain.Main.quit ());
819       connect_button main#scriptAdvanceButton advance;
820       connect_button main#scriptRetractButton retract;
821       connect_button main#scriptTopButton top;
822       connect_button main#scriptBottomButton bottom;
823       connect_button main#scriptJumpButton jump;
824       connect_button main#scriptAbortButton kill_worker;
825       connect_menu_item main#scriptAdvanceMenuItem advance;
826       connect_menu_item main#scriptRetractMenuItem retract;
827       connect_menu_item main#scriptTopMenuItem top;
828       connect_menu_item main#scriptBottomMenuItem bottom;
829       connect_menu_item main#scriptJumpMenuItem jump;
830       connect_menu_item main#openMenuItem   loadScript;
831       connect_menu_item main#saveMenuItem 
832        (fun () -> self#saveScript (MatitaScript.current ()));
833       connect_menu_item main#saveAsMenuItem
834        (fun () -> self#saveAsScript (MatitaScript.current ()));
835       connect_menu_item main#newMenuItem self#newScript;
836       connect_menu_item main#closeMenuItem self#closeCurrentScript;
837       connect_menu_item main#showCoercionsGraphMenuItem 
838         (fun _ -> 
839           let c = MatitaMathView.cicBrowser () in
840           c#load (`About `Coercions));
841       connect_menu_item main#showHintsDbMenuItem 
842         (fun _ -> 
843           let c = MatitaMathView.cicBrowser () in
844           c#load (`About `Hints));
845       connect_menu_item main#showTermGrammarMenuItem 
846         (fun _ -> 
847           let c = MatitaMathView.cicBrowser () in
848           c#load (`About `Grammar));
849       connect_menu_item main#showUnicodeTable
850         (fun _ -> 
851           let c = MatitaMathView.cicBrowser () in
852           c#load (`About `TeX));
853         (* debug menu *)
854       main#debugMenu#misc#hide ();
855         (* HBUGS *)
856       main#hintNotebook#misc#hide ();
857       (*
858       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
859       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
860       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
861       *)
862         (* main win dimension *)
863       let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
864       let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
865       (* hack for xinerama, no proper support of monitors from lablgtk *)
866       let width = if width > 1600 then width / 2 else width in
867       let height = if height > 1200 then height / 2 else height in
868       let main_w = width * 90 / 100 in 
869       let main_h = height * 80 / 100 in
870       let script_w = main_w * 6 / 10 in
871       main#toplevel#resize ~width:main_w ~height:main_h;
872       main#hpaneScriptSequent#set_position script_w;
873       (* math view handling *)
874       connect_menu_item main#newCicBrowserMenuItem (fun () ->
875         ignore(MatitaMathView.cicBrowser ()));
876       connect_menu_item main#increaseFontSizeMenuItem
877         MatitaMisc.increase_font_size;
878       connect_menu_item main#decreaseFontSizeMenuItem
879         MatitaMisc.decrease_font_size;
880       connect_menu_item main#normalFontSizeMenuItem
881         MatitaMisc.reset_font_size;
882       ignore (main#scriptNotebook#connect#switch_page
883        (fun page ->
884          let script = MatitaScript.at_page page in
885           script#activate;
886           main#saveMenuItem#misc#set_sensitive script#has_name));
887
888     method private externalEditor () =
889      let script = MatitaScript.current () in
890      let source_view = script#source_view in
891       let cmd = Helm_registry.get "matita.external_editor" in
892 (* ZACK uncomment to enable interactive ask of external editor command *)
893 (*      let cmd =
894          let msg =
895           "External editor command:
896 %f  will be substitute for the script name,
897 %p  for the cursor position in bytes,
898 %l  for the execution point in bytes."
899         in
900         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
901           ~default:(Helm_registry.get "matita.external_editor") ()
902       in *)
903       let fname = script#filename in
904       let slice mark =
905         source_view#source_buffer#start_iter#get_slice
906           ~stop:(source_view#source_buffer#get_iter_at_mark mark)
907       in
908       let locked = `MARK script#locked_mark in
909       let string_pos mark = string_of_int (String.length (slice mark)) in
910       let cursor_pos = string_pos `INSERT in
911       let locked_pos = string_pos locked in
912       let cmd =
913         Pcre.replace ~pat:"%f" ~templ:fname
914           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
915             (Pcre.replace ~pat:"%l" ~templ:locked_pos
916               cmd))
917       in
918       let locked_before = slice locked in
919       let locked_offset = (source_view#source_buffer#get_iter_at_mark locked)#offset in
920       ignore (Unix.system cmd);
921       source_view#source_buffer#set_text (HExtlib.input_file fname);
922       let locked_iter = source_view#source_buffer#get_iter (`OFFSET locked_offset) in
923       source_view#source_buffer#move_mark locked locked_iter;
924       source_view#source_buffer#apply_tag script#locked_tag
925         ~start:source_view#source_buffer#start_iter ~stop:locked_iter;
926       let locked_after = slice locked in
927       let line = ref 0 in
928       let col = ref 0 in
929       try
930         for i = 0 to String.length locked_before - 1 do
931           if locked_before.[i] <> locked_after.[i] then begin
932             source_view#source_buffer#place_cursor
933               ~where:(source_view#source_buffer#get_iter (`LINEBYTE (!line, !col)));
934             script#goto `Cursor ();
935             raise Exit
936           end else if locked_before.[i] = '\n' then begin
937             incr line;
938             col := 0
939           end
940         done
941       with
942       | Exit -> ()
943       | Invalid_argument _ -> script#goto `Bottom ()
944
945     method private saveAsScript script = 
946      match self#chooseFile ~ok_not_exists:true () with
947      | Some f -> 
948            HExtlib.touch f;
949            script#assignFileName (Some f);
950            script#saveToFile (); 
951            console#message ("'"^f^"' saved.\n");
952            self#_enableSaveTo f
953      | None -> ()
954
955     method private saveScript script = 
956      if script#has_name then 
957        (script#saveToFile (); 
958         console#message ("'"^script#filename^"' saved.\n"))
959      else self#saveAsScript script
960     
961     (* returns false if closure is aborted by the user *)
962     method private closeScript0 script = 
963       if script#source_view#buffer#modified then
964         match
965          ask_unsaved main#toplevel (Filename.basename script#filename)
966         with
967         | `YES -> 
968              self#saveScript script;
969              save_moo script#status;
970              true
971         | `NO -> true
972         | `CANCEL -> false
973       else 
974        (save_moo script#status; true)
975
976     method private closeScript page script = 
977      if self#closeScript0 script then
978       begin
979        MatitaScript.destroy page;
980        ignore (main#scriptNotebook#remove_page page)
981       end
982
983     method private closeCurrentScript () = 
984      let page = main#scriptNotebook#current_page in
985      let script = MatitaScript.at_page page in 
986       self#closeScript page script
987
988     method newScript () = 
989        let scrolledWindow = GBin.scrolled_window () in
990        let hbox = GPack.hbox () in
991        let tab_label = GMisc.label ~text:"foo"
992         ~packing:hbox#pack () in
993        let _ =
994         GMisc.label ~text:"" ~packing:(hbox#pack ~expand:true ~fill:true) () in
995        let closebutton =
996         GButton.button ~relief:`NONE ~packing:hbox#pack () in
997        let image =
998         GMisc.image ~stock:`CLOSE ~icon_size:`MENU () in
999        closebutton#set_image image#coerce;
1000        let script = MatitaScript.script ~parent:scrolledWindow ~tab_label () in
1001         ignore (main#scriptNotebook#prepend_page ~tab_label:hbox#coerce
1002          scrolledWindow#coerce);
1003         ignore (closebutton#connect#clicked (fun () ->
1004            self#closeScript (main#scriptNotebook#page_num hbox#coerce) script));
1005         main#scriptNotebook#goto_page 0;
1006         sequents_viewer#reset;
1007         sequents_viewer#load_logo;
1008         let browser_observer _ = MatitaMathView.refresh_all_browsers () in
1009         let sequents_observer status =
1010           sequents_viewer#reset;
1011           match status#ng_mode with
1012              `ProofMode ->
1013               sequents_viewer#nload_sequents status;
1014               (try
1015                 let goal =
1016                  Continuationals.Stack.find_goal status#stack
1017                 in
1018                  sequents_viewer#goto_sequent status goal
1019               with Failure _ -> ());
1020            | `CommandMode -> sequents_viewer#load_logo
1021         in
1022         script#addObserver sequents_observer;
1023         script#addObserver browser_observer
1024
1025     method loadScript file =       
1026      let page = main#scriptNotebook#current_page in
1027      let script = MatitaScript.at_page page in
1028       if script#source_view#buffer#modified || script#has_name then
1029        self#newScript ();
1030      let script = MatitaScript.current () in
1031      let source_view = script#source_view in
1032       script#reset (); 
1033       script#assignFileName (Some file);
1034       let file = script#filename in
1035       let content =
1036        if Sys.file_exists file then file
1037        else BuildTimeConf.script_template
1038       in
1039       source_view#source_buffer#begin_not_undoable_action ();
1040       script#loadFromFile content;
1041       source_view#source_buffer#end_not_undoable_action ();
1042       source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1043       source_view#buffer#place_cursor source_view#buffer#start_iter;
1044       console#message ("'"^file^"' loaded.");
1045       self#_enableSaveTo file
1046
1047     method private _enableSaveTo file =
1048       self#main#saveMenuItem#misc#set_sensitive true
1049         
1050     method private console = console
1051     method private fileSel = fileSel
1052     method private findRepl = findRepl
1053     method main = main
1054
1055     method newBrowserWin () =
1056       object (self)
1057         inherit browserWin ()
1058         val combo = GEdit.entry ()
1059         initializer
1060           let combo_widget = combo#coerce in
1061           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1062           combo#misc#grab_focus ()
1063         method browserUri = combo
1064       end
1065
1066     method private addKeyBinding key callback =
1067       List.iter (fun evbox -> add_key_binding key callback evbox)
1068         keyBindingBoxes
1069
1070     method private setQuitCallback callback =
1071       connect_menu_item main#quitMenuItem callback;
1072       ignore (main#toplevel#event#connect#delete 
1073         (fun _ -> callback ();true));
1074       self#addKeyBinding GdkKeysyms._q callback
1075
1076     method private chooseFile ?(ok_not_exists = false) () =
1077       _ok_not_exists <- ok_not_exists;
1078       _only_directory <- false;
1079       fileSel#fileSelectionWin#show ();
1080       GtkThread.main ();
1081       chosen_file
1082
1083     method private chooseDir ?(ok_not_exists = false) () =
1084       _ok_not_exists <- ok_not_exists;
1085       _only_directory <- true;
1086       fileSel#fileSelectionWin#show ();
1087       GtkThread.main ();
1088       (* we should check that this is a directory *)
1089       chosen_file
1090   
1091   end
1092
1093 let gui () = 
1094   let g = new gui () in
1095   gui_instance := Some g;
1096   MatitaMisc.set_gui g;
1097   g
1098   
1099 let instance = singleton gui
1100
1101 let non p x = not (p x)
1102
1103 class interpModel =
1104   let cols = new GTree.column_list in
1105   let id_col = cols#add Gobject.Data.string in
1106   let dsc_col = cols#add Gobject.Data.string in
1107   let interp_no_col = cols#add Gobject.Data.int in
1108   let tree_store = GTree.tree_store cols in
1109   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1110   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1111   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1112   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1113   fun tree_view choices ->
1114     object
1115       initializer
1116         tree_view#set_model (Some (tree_store :> GTree.model));
1117         ignore (tree_view#append_column id_view_col);
1118         ignore (tree_view#append_column dsc_view_col);
1119         let name_of_interp =
1120           (* try to find a reasonable name for an interpretation *)
1121           let idx = ref 0 in
1122           fun interp ->
1123             try
1124               List.assoc "0" interp
1125             with Not_found ->
1126               incr idx; string_of_int !idx
1127         in
1128         tree_store#clear ();
1129         let idx = ref ~-1 in
1130         List.iter
1131           (fun interp ->
1132             incr idx;
1133             let interp_row = tree_store#append () in
1134             tree_store#set ~row:interp_row ~column:id_col
1135               (name_of_interp interp);
1136             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1137             List.iter
1138               (fun (id, dsc) ->
1139                 let row = tree_store#append ~parent:interp_row () in
1140                 tree_store#set ~row ~column:id_col id;
1141                 tree_store#set ~row ~column:dsc_col dsc;
1142                 tree_store#set ~row ~column:interp_no_col !idx)
1143               interp)
1144           choices
1145
1146       method get_interp_no tree_path =
1147         let iter = tree_store#get_iter tree_path in
1148         tree_store#get ~row:iter ~column:interp_no_col
1149     end
1150
1151
1152 let interactive_string_choice 
1153   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1154
1155  let dialog = new uriChoiceDialog () in
1156  dialog#uriEntryHBox#misc#hide ();
1157  dialog#uriChoiceSelectedButton#misc#hide ();
1158  dialog#uriChoiceAutoButton#misc#hide ();
1159  dialog#uriChoiceConstantsButton#misc#hide ();
1160  dialog#uriChoiceTreeView#selection#set_mode
1161    (`SINGLE :> Gtk.Tags.selection_mode);
1162  let model = new stringListModel dialog#uriChoiceTreeView in
1163  let choices = ref None in
1164  dialog#uriChoiceDialog#set_title title; 
1165  let hack_len = MatitaGtkMisc.utf8_string_length text in
1166  let rec colorize acc_len = function
1167    | [] -> 
1168        let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1169        escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1170    | he::tl -> 
1171        let start, stop =  HExtlib.loc_of_floc he in
1172        let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1173        let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1174        let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1175        escape_pango_markup str1 ^ "<b>" ^ 
1176        escape_pango_markup str2 ^ "</b>" ^ 
1177        colorize stop tl
1178  in
1179 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1180               Printf.eprintf "(%d,%d)" start stop) locs; *)
1181   let locs = 
1182     List.sort 
1183       (fun loc1 loc2 -> 
1184         fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1185       locs 
1186   in
1187 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1188   List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1189               Printf.eprintf "(%d,%d)" start stop) locs;
1190   prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1191   dialog#uriChoiceLabel#set_use_markup true;
1192   let txt = colorize 0 locs in
1193   let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1194     (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1195   in
1196   dialog#uriChoiceLabel#set_label txt;
1197   List.iter model#easy_append uris;
1198   let return v =
1199     choices := v;
1200     dialog#uriChoiceDialog#destroy ();
1201     GMain.Main.quit ()
1202   in
1203   ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1204   connect_button dialog#uriChoiceForwardButton (fun _ ->
1205     match model#easy_selection () with
1206     | [] -> ()
1207     | uris -> return (Some uris));
1208   connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1209   dialog#uriChoiceDialog#show ();
1210   GtkThread.main ();
1211   (match !choices with 
1212   | None -> raise MatitaTypes.Cancel
1213   | Some uris -> uris)
1214
1215 let interactive_interp_choice () text prefix_len choices =
1216 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1217  let filter_choices filter =
1218   let rec is_compatible filter =
1219    function
1220       [] -> true
1221     | ([],_,_)::tl -> is_compatible filter tl
1222     | (loc::tlloc,id,dsc)::tl ->
1223        try
1224         if List.assoc (loc,id) filter = dsc then
1225          is_compatible filter ((tlloc,id,dsc)::tl)
1226         else
1227          false
1228        with
1229         Not_found -> true
1230   in
1231    List.filter (fun (_,interp) -> is_compatible filter interp)
1232  in
1233  let rec get_choices loc id =
1234   function
1235      [] -> []
1236    | (_,he)::tl ->
1237       let _,_,dsc =
1238        List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1239       in
1240        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1241  in
1242  let example_interp =
1243   match choices with
1244      [] -> assert false
1245    | he::_ -> he in
1246  let ask_user id locs choices =
1247   interactive_string_choice
1248    text prefix_len
1249    ~title:"Ambiguous input"
1250    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1251  in
1252  let rec classify ids filter partial_interpretations =
1253   match ids with
1254      [] -> List.map fst partial_interpretations
1255    | ([],_,_)::tl -> classify tl filter partial_interpretations
1256    | (loc::tlloc,id,dsc)::tl ->
1257       let choices = get_choices loc id partial_interpretations in
1258       let chosen_dsc =
1259        match choices with
1260           [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1261         | [dsc] -> dsc
1262         | _ ->
1263           match ask_user id [loc] choices with
1264              [x] -> x
1265            | _ -> assert false
1266       in
1267        let filter = ((loc,id),chosen_dsc)::filter in
1268        let compatible_interps = filter_choices filter partial_interpretations in
1269         classify ((tlloc,id,dsc)::tl) filter compatible_interps
1270  in
1271  let enumerated_choices =
1272   let idx = ref ~-1 in
1273   List.map (fun interp -> incr idx; !idx,interp) choices
1274  in
1275   classify example_interp [] enumerated_choices
1276
1277 let _ =
1278   (* disambiguator callbacks *)
1279   Disambiguate.set_choose_uris_callback
1280    (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1281      interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1282   Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1283   (* gtk initialization *)
1284   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1285   ignore (GMain.Main.init ())
1286