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