]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaGui.ml
- Disambiguation error exception enriched with more information
[helm.git] / 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 gui_instance = ref None
37
38 class type browserWin =
39   (* this class exists only because GEdit.combo_box_entry is not supported by
40    * lablgladecc :-(((( *)
41 object
42   inherit MatitaGeneratedGui.browserWin
43   method browserUri: GEdit.combo_box_entry
44 end
45
46 class console ~(buffer: GText.buffer) () =
47   object (self)
48     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
49     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
50     val message_tag = buffer#create_tag []
51     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
52     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
53     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
54     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
55     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
56     method clear () =
57       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
58     method log_callback (tag: HLog.log_tag) s =
59       match tag with
60       | `Debug -> self#debug (s ^ "\n")
61       | `Error -> self#error (s ^ "\n")
62       | `Message -> self#message (s ^ "\n")
63       | `Warning -> self#warning (s ^ "\n")
64   end
65         
66 let clean_current_baseuri grafite_status = 
67     try  
68       let baseuri = GrafiteTypes.get_string_option grafite_status "baseuri" in
69       LibraryClean.clean_baseuris [baseuri]
70     with GrafiteTypes.Option_error _ -> ()
71
72 let ask_and_save_moo_if_needed parent fname lexicon_status grafite_status = 
73   let baseuri =
74    try Some (GrafiteTypes.get_string_option grafite_status "baseuri")
75    with GrafiteTypes.Option_error _ -> None
76   in
77   if (MatitaScript.current ())#eos &&
78      grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof &&
79      baseuri <> None
80   then
81    begin
82     let baseuri = match baseuri with Some b -> b | None -> assert false in
83     let moo_fname = 
84      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
85       ~writable:true in
86     let save () =
87       let metadata_fname =
88        LibraryMisc.metadata_file_of_baseuri 
89          ~must_exist:false ~baseuri ~writable:true in
90       let lexicon_fname =
91        LibraryMisc.lexicon_file_of_baseuri 
92          ~must_exist:false ~baseuri ~writable:true
93       in
94        GrafiteMarshal.save_moo moo_fname
95         grafite_status.GrafiteTypes.moo_content_rev;
96        LibraryNoDb.save_metadata metadata_fname
97         lexicon_status.LexiconEngine.metadata;
98        LexiconMarshal.save_lexicon lexicon_fname
99         lexicon_status.LexiconEngine.lexicon_content_rev
100     in
101      begin
102        let rc = 
103          MatitaGtkMisc.ask_confirmation
104          ~title:"A .moo can be generated"
105          ~message:(Printf.sprintf 
106            "%s can be generated for %s.\n<i>Should I generate it?</i>"
107            (Filename.basename moo_fname) (Filename.basename fname))
108          ~parent ()
109        in
110        let b = 
111          match rc with 
112          | `YES -> true 
113          | `NO -> false 
114          | `CANCEL -> raise MatitaTypes.Cancel 
115        in
116        if b then
117            save ()
118        else
119          clean_current_baseuri grafite_status
120      end
121    end
122   else
123     clean_current_baseuri grafite_status 
124     
125 let ask_unsaved parent =
126   MatitaGtkMisc.ask_confirmation 
127     ~parent ~title:"Unsaved work!" 
128     ~message:("Your work is <b>unsaved</b>!\n\n"^
129          "<i>Do you want to save the script before continuing?</i>")
130     ()
131
132 class interpErrorModel =
133   let cols = new GTree.column_list in
134   let id_col = cols#add Gobject.Data.string in
135   let dsc_col = cols#add Gobject.Data.string in
136   let interp_no_col = cols#add Gobject.Data.int in
137   let tree_store = GTree.tree_store cols in
138   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
139   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
140   let id_view_col = GTree.view_column ~renderer:id_renderer () in
141   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
142   fun tree_view choices ->
143     object
144       initializer
145         tree_view#set_model (Some (tree_store :> GTree.model));
146         ignore (tree_view#append_column id_view_col);
147         ignore (tree_view#append_column dsc_view_col);
148         let name_of_interp =
149           (* try to find a reasonable name for an interpretation *)
150           let idx = ref 0 in
151           fun interp ->
152             try
153              let _,_,y = List.find (fun (_,x,y) -> x="0") interp in y
154             with Not_found ->
155               incr idx; string_of_int !idx
156         in
157         tree_store#clear ();
158         let idx = ref ~-1 in
159         List.iter
160           (fun pass,env,_,_,_ ->
161             incr idx;
162             let interp_row = tree_store#append () in
163             tree_store#set ~row:interp_row ~column:id_col
164               ("Pass " ^ string_of_int pass ^
165                "; Interpretation " ^ name_of_interp env);
166             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
167             List.iter
168               (fun (_, id, dsc) ->
169                 let row = tree_store#append ~parent:interp_row () in
170                 tree_store#set ~row ~column:id_col id;
171                 tree_store#set ~row ~column:dsc_col dsc;
172                 tree_store#set ~row ~column:interp_no_col !idx)
173               env)
174           choices
175
176       method get_interp_no tree_path =
177         let iter = tree_store#get_iter tree_path in
178         tree_store#get ~row:iter ~column:interp_no_col
179     end
180
181
182 let rec interactive_error_interp ?(all_passes=false) source_buffer notify_exn
183  offset errorll
184
185   let errorll' =
186    if all_passes then errorll else List.rev (List.tl (List.tl (List.rev errorll))) in
187   let choices =
188    let pass = ref 0 in
189    List.flatten
190     (List.map
191       (fun l ->
192         incr pass;
193         List.map (fun (env,diff,offset,msg) -> !pass, env, diff, offset, msg) l
194       ) errorll') in
195   let choices_eq (_,e1,_,_,_) (_,e2,_,_,_) = e1 = e2 in
196   let choices_compare (_,e1,_,_,_) (_,e2,_,_,_) = compare e1 e2 in
197   (* Here we are doing a stable sort and list_uniq returns the latter
198      "equal" element. I.e. we are showing the error corresponding to the
199      most advanced disambiguation pass *)
200   let choices =
201    HExtlib.list_uniq ~eq:choices_eq
202     (List.stable_sort choices_compare choices)
203   in
204    match choices with
205       [] -> assert false
206     | [_,env,diff,loffset,msg] ->
207         notify_exn
208          (GrafiteDisambiguator.DisambiguationError
209            (offset,[[env,diff,loffset,msg]]));
210     | _::_ ->
211        let dialog = new disambiguationErrors () in
212        dialog#check_widgets ();
213        if all_passes then
214         dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
215        let model = new interpErrorModel dialog#treeview choices in
216        dialog#disambiguationErrors#set_title "Interpretation choice";
217        dialog#disambiguationErrorsLabel#set_label "Choose an interpretation:";
218        ignore (dialog#treeview#connect#cursor_changed (fun _ ->
219         let tree_path =
220          match fst (dialog#treeview#get_cursor ()) with
221             None -> assert false
222          | Some tp -> tp in
223         let idx = model#get_interp_no tree_path in
224         let _,env,diff,loffset,msg = List.nth choices idx in
225         let script = MatitaScript.current () in
226         let error_tag = script#error_tag in
227          source_buffer#remove_tag error_tag
228            ~start:source_buffer#start_iter
229            ~stop:source_buffer#end_iter;
230          notify_exn
231           (GrafiteDisambiguator.DisambiguationError
232             (offset,[[env,diff,loffset,msg]]))
233          ));
234        let return _ =
235          dialog#disambiguationErrors#destroy ();
236          GMain.Main.quit ()
237        in
238        let fail _ = return () in
239        ignore (dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
240        connect_button dialog#disambiguationErrorsOkButton (fun _ -> return ());
241        connect_button dialog#disambiguationErrorsMoreErrors
242         (fun _ -> return () ;
243           interactive_error_interp ~all_passes:true source_buffer notify_exn offset
244            errorll);
245        connect_button dialog#disambiguationErrorsCancelButton fail;
246        dialog#disambiguationErrors#show ();
247        GtkThread.main ()
248
249
250 (** Selection handling
251  * Two clipboards are used: "clipboard" and "primary".
252  * "primary" is used by X, when you hit the middle button mouse is content is
253  *    pasted between applications. In Matita this selection always contain the
254  *    textual version of the selected term.
255  * "clipboard" is used inside Matita only and support ATM two different targets:
256  *    "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
257  *    be added
258  *)
259
260 class gui () =
261     (* creation order _is_ relevant for windows placement *)
262   let main = new mainWin () in
263   let fileSel = new fileSelectionWin () in
264   let findRepl = new findReplWin () in
265   let develList = new develListWin () in
266   let newDevel = new newDevelWin () in
267   let keyBindingBoxes = (* event boxes which should receive global key events *)
268     [ main#mainWinEventBox ]
269   in
270   let console = new console ~buffer:main#logTextView#buffer () in
271   let (source_view: GSourceView.source_view) =
272     GSourceView.source_view
273       ~auto_indent:true
274       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
275       ~margin:80 ~show_margin:true
276       ~smart_home_end:true
277       ~packing:main#scriptScrolledWin#add
278       ()
279   in
280   let default_font_size =
281     Helm_registry.get_opt_default Helm_registry.int
282       ~default:BuildTimeConf.default_font_size "matita.font_size"
283   in
284   let source_buffer = source_view#source_buffer in
285   object (self)
286     val mutable chosen_file = None
287     val mutable _ok_not_exists = false
288     val mutable _only_directory = false
289     val mutable script_fname = None
290     val mutable font_size = default_font_size
291     val mutable next_devel_must_contain = None
292     val mutable next_ligatures = []
293     val clipboard = GData.clipboard Gdk.Atom.clipboard
294     val primary = GData.clipboard Gdk.Atom.primary
295    
296     initializer
297         (* glade's check widgets *)
298       List.iter (fun w -> w#check_widgets ())
299         (let c w = (w :> <check_widgets: unit -> unit>) in
300         [ c fileSel; c main; c findRepl]);
301         (* key bindings *)
302       List.iter (* global key bindings *)
303         (fun (key, callback) -> self#addKeyBinding key callback)
304 (*
305         [ GdkKeysyms._F3,
306             toggle_win ~check:main#showProofMenuItem proof#proofWin;
307           GdkKeysyms._F4,
308             toggle_win ~check:main#showCheckMenuItem check#checkWin;
309 *)
310         [ ];
311         (* about win *)
312       let parse_txt_file file =
313        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
314        let l_rev = ref [] in
315        try
316         while true do
317          l_rev := input_line ch :: !l_rev;
318         done;
319         assert false
320        with
321         End_of_file ->
322          close_in ch;
323          List.rev !l_rev in 
324       let about_dialog =
325        GWindow.about_dialog
326         ~authors:(parse_txt_file "AUTHORS")
327         (*~comments:"comments"*)
328         ~copyright:"Copyright (C) 2005, the HELM team"
329         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
330         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
331         ~name:"Matita"
332         ~version:BuildTimeConf.version
333         ~website:"http://helm.cs.unibo.it"
334         ()
335       in
336       connect_menu_item main#contentsMenuItem (fun () ->
337         let cmd =
338           sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
339         in
340         ignore (Sys.command cmd));
341       connect_menu_item main#aboutMenuItem about_dialog#present;
342         (* findRepl win *)
343       let show_find_Repl () = 
344         findRepl#toplevel#misc#show ();
345         findRepl#toplevel#misc#grab_focus ()
346       in
347       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
348       let find_forward _ = 
349           let highlight start end_ =
350             source_buffer#move_mark `INSERT ~where:start;
351             source_buffer#move_mark `SEL_BOUND ~where:end_;
352             source_view#scroll_mark_onscreen `INSERT
353           in
354           let text = findRepl#findEntry#text in
355           let iter = source_buffer#get_iter `SEL_BOUND in
356           match iter#forward_search text with
357           | None -> 
358               (match source_buffer#start_iter#forward_search text with
359               | None -> ()
360               | Some (start,end_) -> highlight start end_)
361           | Some (start,end_) -> highlight start end_ 
362       in
363       let replace _ =
364         let text = findRepl#replaceEntry#text in
365         let ins = source_buffer#get_iter `INSERT in
366         let sel = source_buffer#get_iter `SEL_BOUND in
367         if ins#compare sel < 0 then 
368           begin
369             ignore(source_buffer#delete_selection ());
370             source_buffer#insert text
371           end
372       in
373       connect_button findRepl#findButton find_forward;
374       connect_button findRepl#findReplButton replace;
375       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
376       ignore(findRepl#toplevel#event#connect#delete 
377         ~callback:(fun _ -> hide_find_Repl ();true));
378       let safe_undo =
379        fun () ->
380         (* phase 1: we save the actual status of the marks and we undo *)
381         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
382         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
383         let locked_iter_offset = locked_iter#offset in
384         let mark2 =
385          `MARK
386            (source_view#buffer#create_mark ~name:"lock_point"
387              ~left_gravity:true locked_iter) in
388         source_view#source_buffer#undo ();
389         (* phase 2: we save the cursor position and we redo, restoring
390            the previous status of all the marks *)
391         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
392         let mark =
393          `MARK
394            (source_view#buffer#create_mark ~name:"undo_point"
395              ~left_gravity:true cursor_iter)
396         in
397          source_view#source_buffer#redo ();
398          let mark_iter = source_view#buffer#get_iter_at_mark mark in
399          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
400          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
401           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
402           source_view#buffer#delete_mark mark;
403           source_view#buffer#delete_mark mark2;
404           (* phase 3: if after the undo the cursor was in the locked area,
405              then we move it there again and we perform a goto *)
406           if mark_iter#offset < locked_iter_offset then
407            begin
408             source_view#buffer#move_mark `INSERT ~where:mark_iter;
409             (MatitaScript.current ())#goto `Cursor ();
410            end;
411           (* phase 4: we perform again the undo. This time we are sure that
412              the text to undo is not locked *)
413           source_view#source_buffer#undo ();
414           source_view#misc#grab_focus () in
415       let safe_redo =
416        fun () ->
417         (* phase 1: we save the actual status of the marks, we redo and
418            we undo *)
419         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
420         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
421         let locked_iter_offset = locked_iter#offset in
422         let mark2 =
423          `MARK
424            (source_view#buffer#create_mark ~name:"lock_point"
425              ~left_gravity:true locked_iter) in
426         source_view#source_buffer#redo ();
427         source_view#source_buffer#undo ();
428         (* phase 2: we save the cursor position and we restore
429            the previous status of all the marks *)
430         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
431         let mark =
432          `MARK
433            (source_view#buffer#create_mark ~name:"undo_point"
434              ~left_gravity:true cursor_iter)
435         in
436          let mark_iter = source_view#buffer#get_iter_at_mark mark in
437          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
438          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
439           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
440           source_view#buffer#delete_mark mark;
441           source_view#buffer#delete_mark mark2;
442           (* phase 3: if after the undo the cursor is in the locked area,
443              then we move it there again and we perform a goto *)
444           if mark_iter#offset < locked_iter_offset then
445            begin
446             source_view#buffer#move_mark `INSERT ~where:mark_iter;
447             (MatitaScript.current ())#goto `Cursor ();
448            end;
449           (* phase 4: we perform again the redo. This time we are sure that
450              the text to redo is not locked *)
451           source_view#source_buffer#redo ();
452           source_view#misc#grab_focus ()
453       in
454       connect_menu_item main#undoMenuItem safe_undo;
455       ignore(source_view#source_buffer#connect#can_undo
456         ~callback:main#undoMenuItem#misc#set_sensitive);
457       connect_menu_item main#redoMenuItem safe_redo;
458       ignore(source_view#source_buffer#connect#can_redo
459         ~callback:main#redoMenuItem#misc#set_sensitive);
460       ignore(source_view#connect#after#populate_popup
461        ~callback:(fun pre_menu ->
462          let menu = new GMenu.menu pre_menu in
463          let menuItems = menu#children in
464          let undoMenuItem, redoMenuItem =
465           match menuItems with
466              [undo;redo;sep1;cut;copy;paste;delete;sep2;
467               selectall;sep3;inputmethod;insertunicodecharacter] ->
468                 List.iter menu#remove [ copy; cut; delete; paste ];
469                 undo,redo
470            | _ -> assert false in
471          let add_menu_item =
472            let i = ref 2 in (* last occupied position *)
473            fun ?label ?stock () ->
474              incr i;
475              GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
476               ()
477          in
478          let copy = add_menu_item ~stock:`COPY () in
479          let cut = add_menu_item ~stock:`CUT () in
480          let delete = add_menu_item ~stock:`DELETE () in
481          let paste = add_menu_item ~stock:`PASTE () in
482          let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
483          copy#misc#set_sensitive self#canCopy;
484          cut#misc#set_sensitive self#canCut;
485          delete#misc#set_sensitive self#canDelete;
486          paste#misc#set_sensitive self#canPaste;
487          paste_pattern#misc#set_sensitive self#canPastePattern;
488          connect_menu_item copy self#copy;
489          connect_menu_item cut self#cut;
490          connect_menu_item delete self#delete;
491          connect_menu_item paste self#paste;
492          connect_menu_item paste_pattern self#pastePattern;
493          let new_undoMenuItem =
494           GMenu.image_menu_item
495            ~image:(GMisc.image ~stock:`UNDO ())
496            ~use_mnemonic:true
497            ~label:"_Undo"
498            ~packing:(menu#insert ~pos:0) () in
499          new_undoMenuItem#misc#set_sensitive
500           (undoMenuItem#misc#get_flag `SENSITIVE);
501          menu#remove (undoMenuItem :> GMenu.menu_item);
502          connect_menu_item new_undoMenuItem safe_undo;
503          let new_redoMenuItem =
504           GMenu.image_menu_item
505            ~image:(GMisc.image ~stock:`REDO ())
506            ~use_mnemonic:true
507            ~label:"_Redo"
508            ~packing:(menu#insert ~pos:1) () in
509          new_redoMenuItem#misc#set_sensitive
510           (redoMenuItem#misc#get_flag `SENSITIVE);
511           menu#remove (redoMenuItem :> GMenu.menu_item);
512           connect_menu_item new_redoMenuItem safe_redo));
513
514       connect_menu_item main#editMenu (fun () ->
515         main#copyMenuItem#misc#set_sensitive self#canCopy;
516         main#cutMenuItem#misc#set_sensitive self#canCut;
517         main#deleteMenuItem#misc#set_sensitive self#canDelete;
518         main#pasteMenuItem#misc#set_sensitive self#canPaste;
519         main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
520       connect_menu_item main#copyMenuItem self#copy;
521       connect_menu_item main#cutMenuItem self#cut;
522       connect_menu_item main#deleteMenuItem self#delete;
523       connect_menu_item main#pasteMenuItem self#paste;
524       connect_menu_item main#pastePatternMenuItem self#pastePattern;
525       connect_menu_item main#selectAllMenuItem (fun () ->
526         source_buffer#move_mark `INSERT source_buffer#start_iter;
527         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
528       connect_menu_item main#findReplMenuItem show_find_Repl;
529       connect_menu_item main#externalEditorMenuItem self#externalEditor;
530       connect_menu_item main#ligatureButton self#nextLigature;
531       ignore (findRepl#findEntry#connect#activate find_forward);
532         (* interface lockers *)
533       let lock_world _ =
534         main#buttonsToolbar#misc#set_sensitive false;
535         develList#buttonsHbox#misc#set_sensitive false;
536         main#scriptMenu#misc#set_sensitive false;
537         source_view#set_editable false
538       in
539       let unlock_world _ =
540         main#buttonsToolbar#misc#set_sensitive true;
541         develList#buttonsHbox#misc#set_sensitive true;
542         main#scriptMenu#misc#set_sensitive true;
543         source_view#set_editable true;
544         (*The next line seems sufficient to avoid some unknown race condition *)
545         GtkThread.sync (fun () -> ()) ()
546       in
547       let worker_thread = ref None in
548       let notify_exn exn =
549        let floc, msg = MatitaExcPp.to_string exn in
550         begin
551          match floc with
552             None -> ()
553           | Some floc ->
554              let (x, y) = HExtlib.loc_of_floc floc in
555              let script = MatitaScript.current () in
556              let locked_mark = script#locked_mark in
557              let error_tag = script#error_tag in
558              let baseoffset =
559               (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
560              let x' = baseoffset + x in
561              let y' = baseoffset + y in
562              let x_iter = source_buffer#get_iter (`OFFSET x') in
563              let y_iter = source_buffer#get_iter (`OFFSET y') in
564              source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
565              let id = ref None in
566              id := Some (source_buffer#connect#changed ~callback:(fun () ->
567                source_buffer#remove_tag error_tag
568                  ~start:source_buffer#start_iter
569                  ~stop:source_buffer#end_iter;
570                match !id with
571                | None -> assert false (* a race condition occurred *)
572                | Some id ->
573                    (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
574              source_buffer#place_cursor
575               (source_buffer#get_iter (`OFFSET x'));
576         end;
577         HLog.error msg in
578       let locker f () =
579        let thread_main =
580         fun () -> 
581           lock_world ();
582           try
583            f ();
584            unlock_world ()
585           with
586            | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
587               interactive_error_interp source_buffer notify_exn offset errorll ;
588               unlock_world ()
589            | exc ->
590               notify_exn exc;
591               unlock_world ()
592        in
593         worker_thread := Some (Thread.create thread_main ()) in
594       let kill_worker =
595        (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
596        let interrupt = ref None in
597        let old_callback = ref (function _ -> ()) in
598        let force_interrupt n =
599          (* This function is called just before the thread's timeslice ends *)
600          !old_callback n;
601          if Some(Thread.id(Thread.self())) = !interrupt then
602           (interrupt := None; raise Sys.Break) in
603        let _ =
604         match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
605            Sys.Signal_handle f -> old_callback := f
606          | Sys.Signal_ignore
607          | Sys.Signal_default -> assert false
608        in
609         fun () ->
610          match !worker_thread with
611             None -> assert false
612           | Some t -> interrupt := Some (Thread.id t) in
613       let keep_focus f =
614         fun () ->
615          try
616           f (); source_view#misc#grab_focus ()
617          with
618           exc -> source_view#misc#grab_focus (); raise exc in
619         (* developments win *)
620       let model = 
621         new MatitaGtkMisc.multiStringListModel 
622           ~cols:2 develList#developmentsTreeview
623       in
624       let refresh_devels_win () =
625         model#list_store#clear ();
626         List.iter 
627           (fun (name, root) -> model#easy_mappend [name;root]) 
628           (MatitamakeLib.list_known_developments ())
629       in
630       let get_devel_selected () = 
631         match model#easy_mselection () with
632         | [[name;_]] -> MatitamakeLib.development_for_name name
633         | _ -> None
634       in
635       let refresh () = 
636         while Glib.Main.pending () do 
637           ignore(Glib.Main.iteration false); 
638         done
639       in
640       connect_button develList#newButton
641         (fun () -> 
642           next_devel_must_contain <- None;
643           newDevel#toplevel#misc#show());
644       connect_button develList#deleteButton
645         (locker (fun () -> 
646           (match get_devel_selected () with
647           | None -> ()
648           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
649           refresh_devels_win ()));
650       connect_button develList#buildButton 
651         (locker (fun () -> 
652           match get_devel_selected () with
653           | None -> ()
654           | Some d -> 
655               let build = locker 
656                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
657               in
658               ignore(build ())));
659       connect_button develList#cleanButton 
660         (locker (fun () -> 
661           match get_devel_selected () with
662           | None -> ()
663           | Some d -> 
664               let clean = locker 
665                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
666               in
667               ignore(clean ())));
668       connect_button develList#publishButton 
669         (locker (fun () -> 
670           match get_devel_selected () with
671           | None -> ()
672           | Some d -> 
673               let publish = locker (fun () ->
674                 MatitamakeLib.publish_development_in_bg refresh d) in
675               ignore(publish ())));
676       connect_button develList#graphButton (fun () -> 
677         match get_devel_selected () with
678         | None -> ()
679         | Some d ->
680             (match MatitamakeLib.dot_for_development d with
681             | None -> ()
682             | Some _ ->
683                 let browser = MatitaMathView.cicBrowser () in
684                 browser#load (`Development
685                   (MatitamakeLib.name_for_development d))));
686       connect_button develList#closeButton 
687         (fun () -> develList#toplevel#misc#hide());
688       ignore(develList#toplevel#event#connect#delete 
689         (fun _ -> develList#toplevel#misc#hide();true));
690       connect_menu_item main#developmentsMenuItem
691         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
692       
693         (* add development win *)
694       let check_if_root_contains root =
695         match next_devel_must_contain with
696         | None -> true
697         | Some path -> 
698             let is_prefix_of d1 d2 =
699               let len1 = String.length d1 in
700               let len2 = String.length d2 in
701               if len2 < len1 then 
702                 false
703               else
704                 let pref = String.sub d2 0 len1 in
705                 pref = d1
706             in
707             is_prefix_of root path
708       in
709       connect_button newDevel#addButton 
710        (fun () -> 
711           let name = newDevel#nameEntry#text in
712           let root = newDevel#rootEntry#text in
713           if check_if_root_contains root then
714             begin
715               ignore (MatitamakeLib.initialize_development name root);
716               refresh_devels_win ();
717               newDevel#nameEntry#set_text "";
718               newDevel#rootEntry#set_text "";
719               newDevel#toplevel#misc#hide()
720             end
721           else
722             HLog.error ("The selected root does not contain " ^ 
723               match next_devel_must_contain with 
724               | Some x -> x 
725               | _ -> assert false));
726       connect_button newDevel#chooseRootButton 
727        (fun () ->
728          let path = self#chooseDir () in
729          match path with
730          | Some path -> newDevel#rootEntry#set_text path
731          | None -> ());
732       connect_button newDevel#cancelButton 
733        (fun () -> newDevel#toplevel#misc#hide ());
734       ignore(newDevel#toplevel#event#connect#delete 
735         (fun _ -> newDevel#toplevel#misc#hide();true));
736       
737         (* file selection win *)
738       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
739       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
740         let return r =
741           chosen_file <- r;
742           fileSel#fileSelectionWin#misc#hide ();
743           GMain.Main.quit ()
744         in
745         match event with
746         | `OK ->
747             let fname = fileSel#fileSelectionWin#filename in
748             if Sys.file_exists fname then
749               begin
750                 if HExtlib.is_regular fname && not (_only_directory) then 
751                   return (Some fname) 
752                 else if _only_directory && HExtlib.is_dir fname then 
753                   return (Some fname)
754               end
755             else
756               begin
757                 if _ok_not_exists then 
758                   return (Some fname)
759               end
760         | `CANCEL -> return None
761         | `HELP -> ()
762         | `DELETE_EVENT -> return None));
763         (* menus *)
764       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
765         (* console *)
766       let adj = main#logScrolledWin#vadjustment in
767         ignore (adj#connect#changed
768                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
769       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
770         (* toolbar *)
771       let module A = GrafiteAst in
772       let hole = CicNotationPt.UserInput in
773       let loc = HExtlib.dummy_floc in
774       let tac ast _ =
775         if (MatitaScript.current ())#onGoingProof () then
776           (MatitaScript.current ())#advance
777             ~statement:("\n"
778               ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
779                 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
780             ()
781       in
782       let tac_w_term ast _ =
783         if (MatitaScript.current ())#onGoingProof () then
784           let buf = source_buffer in
785           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
786             ("\n"
787             ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
788               ~lazy_term_pp:CicNotationPp.pp_term ast)
789       in
790       let tbar = main in
791       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
792       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
793       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
794       connect_button tbar#elimButton (tac_w_term
795         (A.Elim (loc, hole, None, None, [])));
796       connect_button tbar#elimTypeButton (tac_w_term
797         (A.ElimType (loc, hole, None, None, [])));
798       connect_button tbar#splitButton (tac (A.Split loc));
799       connect_button tbar#leftButton (tac (A.Left loc));
800       connect_button tbar#rightButton (tac (A.Right loc));
801       connect_button tbar#existsButton (tac (A.Exists loc));
802       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
803       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
804       connect_button tbar#transitivityButton
805         (tac_w_term (A.Transitivity (loc, hole)));
806       connect_button tbar#assumptionButton (tac (A.Assumption loc));
807       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
808       connect_button tbar#autoButton (tac (A.Auto (loc,[])));
809       MatitaGtkMisc.toggle_widget_visibility
810        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
811        ~check:main#tacticsBarMenuItem;
812       let module Hr = Helm_registry in
813       if
814         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
815       then 
816         main#tacticsBarMenuItem#set_active false;
817       MatitaGtkMisc.toggle_callback 
818         ~callback:(function 
819           | true -> main#toplevel#fullscreen () 
820           | false -> main#toplevel#unfullscreen ())
821         ~check:main#fullscreenMenuItem;
822       main#fullscreenMenuItem#set_active false;
823         (* log *)
824       HLog.set_log_callback self#console#log_callback;
825       GtkSignal.user_handler :=
826         (function 
827         | MatitaScript.ActionCancelled s -> HLog.error s
828         | exn ->
829           if not (Helm_registry.get_bool "matita.debug") then
830            notify_exn exn
831           else raise exn);
832         (* script *)
833       ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
834       let _ =
835         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
836         | None ->
837             HLog.warn (sprintf "can't load language file %s"
838               BuildTimeConf.lang_file)
839         | Some matita_lang ->
840             source_buffer#set_language matita_lang;
841             source_buffer#set_highlight true
842       in
843       let s () = MatitaScript.current () in
844       let disableSave () =
845         script_fname <- None;
846         main#saveMenuItem#misc#set_sensitive false
847       in
848       let saveAsScript () =
849         let script = s () in
850         match self#chooseFile ~ok_not_exists:true () with
851         | Some f -> 
852               script#assignFileName f;
853               script#saveToFile (); 
854               console#message ("'"^f^"' saved.\n");
855               self#_enableSaveTo f
856         | None -> ()
857       in
858       let saveScript () =
859         match script_fname with
860         | None -> saveAsScript ()
861         | Some f -> 
862               (s ())#assignFileName f;
863               (s ())#saveToFile ();
864               console#message ("'"^f^"' saved.\n");
865       in
866       let abandon_script () =
867         let lexicon_status = (s ())#lexicon_status in
868         let grafite_status = (s ())#grafite_status in
869         if source_view#buffer#modified then
870           (match ask_unsaved main#toplevel with
871           | `YES -> saveScript ()
872           | `NO -> ()
873           | `CANCEL -> raise MatitaTypes.Cancel);
874         (match script_fname with
875         | None -> ()
876         | Some fname ->
877            ask_and_save_moo_if_needed main#toplevel fname
878             lexicon_status grafite_status);
879       in
880       let loadScript () =
881         let script = s () in 
882         try 
883           match self#chooseFile () with
884           | Some f -> 
885               abandon_script ();
886               script#reset (); 
887               script#assignFileName f;
888               source_view#source_buffer#begin_not_undoable_action ();
889               script#loadFromFile f; 
890               source_view#source_buffer#end_not_undoable_action ();
891               console#message ("'"^f^"' loaded.\n");
892               self#_enableSaveTo f
893           | None -> ()
894         with MatitaTypes.Cancel -> ()
895       in
896       let newScript () = 
897         abandon_script ();
898         source_view#source_buffer#begin_not_undoable_action ();
899         (s ())#reset (); 
900         (s ())#template (); 
901         source_view#source_buffer#end_not_undoable_action ();
902         disableSave ();
903         script_fname <- None
904       in
905       let cursor () =
906         source_buffer#place_cursor
907           (source_buffer#get_iter_at_mark (`NAME "locked")) in
908       let advance _ = (MatitaScript.current ())#advance (); cursor () in
909       let retract _ = (MatitaScript.current ())#retract (); cursor () in
910       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
911       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
912       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
913       let advance = locker (keep_focus advance) in
914       let retract = locker (keep_focus retract) in
915       let top = locker (keep_focus top) in
916       let bottom = locker (keep_focus bottom) in
917       let jump = locker (keep_focus jump) in
918         (* quit *)
919       self#setQuitCallback (fun () -> 
920         let lexicon_status = (MatitaScript.current ())#lexicon_status in
921         let grafite_status = (MatitaScript.current ())#grafite_status in
922         if source_view#buffer#modified then
923           begin
924             let rc = ask_unsaved main#toplevel in 
925             try
926               match rc with
927               | `YES -> saveScript ();
928                         if not source_view#buffer#modified then
929                           begin
930                             (match script_fname with
931                             | None -> ()
932                             | Some fname -> 
933                                ask_and_save_moo_if_needed main#toplevel
934                                 fname lexicon_status grafite_status);
935                           GMain.Main.quit ()
936                           end
937               | `NO -> GMain.Main.quit ()
938               | `CANCEL -> raise MatitaTypes.Cancel
939             with MatitaTypes.Cancel -> ()
940           end 
941         else 
942           begin  
943             (match script_fname with
944             | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
945             | Some fname ->
946                 try
947                   ask_and_save_moo_if_needed main#toplevel fname lexicon_status
948                    grafite_status;
949                   GMain.Main.quit ()
950                 with MatitaTypes.Cancel -> ())
951           end);
952       connect_button main#scriptAdvanceButton advance;
953       connect_button main#scriptRetractButton retract;
954       connect_button main#scriptTopButton top;
955       connect_button main#scriptBottomButton bottom;
956       connect_button main#scriptJumpButton jump;
957       connect_button main#scriptAbortButton kill_worker;
958       connect_menu_item main#scriptAdvanceMenuItem advance;
959       connect_menu_item main#scriptRetractMenuItem retract;
960       connect_menu_item main#scriptTopMenuItem top;
961       connect_menu_item main#scriptBottomMenuItem bottom;
962       connect_menu_item main#scriptJumpMenuItem jump;
963       connect_menu_item main#openMenuItem   loadScript;
964       connect_menu_item main#saveMenuItem   saveScript;
965       connect_menu_item main#saveAsMenuItem saveAsScript;
966       connect_menu_item main#newMenuItem    newScript;
967          (* script monospace font stuff *)  
968       self#updateFontSize ();
969         (* debug menu *)
970       main#debugMenu#misc#hide ();
971         (* status bar *)
972       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
973       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
974       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
975         (* focus *)
976       self#sourceView#misc#grab_focus ();
977         (* main win dimension *)
978       let width = Gdk.Screen.width () in
979       let height = Gdk.Screen.height () in
980       let main_w = width * 90 / 100 in 
981       let main_h = height * 80 / 100 in
982       let script_w = main_w * 6 / 10 in
983       main#toplevel#resize ~width:main_w ~height:main_h;
984       main#hpaneScriptSequent#set_position script_w;
985         (* source_view *)
986       ignore(source_view#connect#after#paste_clipboard 
987         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
988       (* clean_locked is set to true only "during" a PRIMARY paste
989          operation (i.e. by clicking with the second mouse button) *)
990       let clean_locked = ref false in
991       ignore(source_view#event#connect#button_press
992         ~callback:
993           (fun button ->
994             if GdkEvent.Button.button button = 2 then
995              clean_locked := true;
996             false
997           ));
998       ignore(source_view#event#connect#button_release
999         ~callback:(fun button -> clean_locked := false; false));
1000       ignore(source_view#buffer#connect#after#apply_tag
1001        ~callback:(
1002          fun tag ~start:_ ~stop:_ ->
1003           if !clean_locked &&
1004              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1005           then
1006            begin
1007             clean_locked := false;
1008             (MatitaScript.current ())#clean_dirty_lock;
1009             clean_locked := true
1010            end));
1011       (* math view handling *)
1012       connect_menu_item main#newCicBrowserMenuItem (fun () ->
1013         ignore (MatitaMathView.cicBrowser ()));
1014       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1015         self#increaseFontSize ();
1016         MatitaMathView.increase_font_size ();
1017         MatitaMathView.update_font_sizes ());
1018       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1019         self#decreaseFontSize ();
1020         MatitaMathView.decrease_font_size ();
1021         MatitaMathView.update_font_sizes ());
1022       connect_menu_item main#normalFontSizeMenuItem (fun () ->
1023         self#resetFontSize ();
1024         MatitaMathView.reset_font_size ();
1025         MatitaMathView.update_font_sizes ());
1026       MatitaMathView.reset_font_size ();
1027
1028       (** selections / clipboards handling *)
1029
1030     method markupSelected = MatitaMathView.has_selection ()
1031     method private textSelected =
1032       (source_buffer#get_iter_at_mark `INSERT)#compare
1033         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1034     method private somethingSelected = self#markupSelected || self#textSelected
1035     method private markupStored = MatitaMathView.has_clipboard ()
1036     method private textStored = clipboard#text <> None
1037     method private somethingStored = self#markupStored || self#textStored
1038
1039     method canCopy = self#somethingSelected
1040     method canCut = self#textSelected
1041     method canDelete = self#textSelected
1042     method canPaste = self#somethingStored
1043     method canPastePattern = self#markupStored
1044
1045     method copy () =
1046       if self#textSelected
1047       then begin
1048         MatitaMathView.empty_clipboard ();
1049         source_view#buffer#copy_clipboard clipboard;
1050       end else
1051         MatitaMathView.copy_selection ()
1052     method cut () =
1053       source_view#buffer#cut_clipboard clipboard;
1054       MatitaMathView.empty_clipboard ()
1055     method delete () = ignore (source_view#buffer#delete_selection ())
1056     method paste () =
1057       if MatitaMathView.has_clipboard ()
1058       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1059       else source_view#buffer#paste_clipboard clipboard;
1060       (MatitaScript.current ())#clean_dirty_lock
1061     method pastePattern () =
1062       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1063     
1064     method private nextLigature () =
1065       let iter = source_buffer#get_iter_at_mark `INSERT in
1066       let write_ligature len s =
1067         assert(Glib.Utf8.validate s);
1068         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1069         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1070       in
1071       let get_ligature word =
1072         let len = String.length word in
1073         let aux_tex () =
1074           try
1075             for i = len - 1 downto 0 do
1076               if HExtlib.is_alpha word.[i] then ()
1077               else
1078                 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1079             done;
1080             None
1081           with Found i ->
1082             if i = ~-1 then None else Some (String.sub word i (len - i))
1083         in
1084         let aux_ligature () =
1085           try
1086             for i = len - 1 downto 0 do
1087               if CicNotationLexer.is_ligature_char word.[i] then ()
1088               else raise (Found (i+1))
1089             done;
1090             raise (Found 0)
1091           with
1092           | Found i ->
1093               (try
1094                 Some (String.sub word i (len - i))
1095               with Invalid_argument _ -> None)
1096         in
1097         match aux_tex () with
1098         | Some macro -> macro
1099         | None -> (match aux_ligature () with Some l -> l | None -> word)
1100       in
1101       (match next_ligatures with
1102       | [] -> (* find ligatures and fill next_ligatures, then try again *)
1103           let last_word =
1104             iter#get_slice
1105               ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1106           in
1107           let ligature = get_ligature last_word in
1108           (match CicNotationLexer.lookup_ligatures ligature with
1109           | [] -> ()
1110           | hd :: tl ->
1111               write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1112               next_ligatures <- tl @ [ hd ])
1113       | hd :: tl ->
1114           write_ligature 1 hd;
1115           next_ligatures <- tl @ [ hd ])
1116
1117     method private externalEditor () =
1118       let cmd = Helm_registry.get "matita.external_editor" in
1119 (* ZACK uncomment to enable interactive ask of external editor command *)
1120 (*      let cmd =
1121          let msg =
1122           "External editor command:
1123 %f  will be substitute for the script name,
1124 %p  for the cursor position in bytes,
1125 %l  for the execution point in bytes."
1126         in
1127         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1128           ~default:(Helm_registry.get "matita.external_editor") ()
1129       in *)
1130       let fname = (MatitaScript.current ())#filename in
1131       let slice mark =
1132         source_buffer#start_iter#get_slice
1133           ~stop:(source_buffer#get_iter_at_mark mark)
1134       in
1135       let script = MatitaScript.current () in
1136       let locked = `MARK script#locked_mark in
1137       let string_pos mark = string_of_int (String.length (slice mark)) in
1138       let cursor_pos = string_pos `INSERT in
1139       let locked_pos = string_pos locked in
1140       let cmd =
1141         Pcre.replace ~pat:"%f" ~templ:fname
1142           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1143             (Pcre.replace ~pat:"%l" ~templ:locked_pos
1144               cmd))
1145       in
1146       let locked_before = slice locked in
1147       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1148       ignore (Unix.system cmd);
1149       source_buffer#set_text (HExtlib.input_file fname);
1150       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1151       source_buffer#move_mark locked locked_iter;
1152       source_buffer#apply_tag script#locked_tag
1153         ~start:source_buffer#start_iter ~stop:locked_iter;
1154       let locked_after = slice locked in
1155       let line = ref 0 in
1156       let col = ref 0 in
1157       try
1158         for i = 0 to String.length locked_before - 1 do
1159           if locked_before.[i] <> locked_after.[i] then begin
1160             source_buffer#place_cursor
1161               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1162             script#goto `Cursor ();
1163             raise Exit
1164           end else if locked_before.[i] = '\n' then begin
1165             incr line;
1166             col := 0
1167           end
1168         done
1169       with
1170       | Exit -> ()
1171       | Invalid_argument _ -> script#goto `Bottom ()
1172
1173     method loadScript file =       
1174       let script = MatitaScript.current () in
1175       script#reset (); 
1176       if Pcre.pmatch ~pat:"\\.p$" file then
1177         begin
1178           let tptppath = 
1179             Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1180               "matita.tptppath"
1181           in
1182           let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1183           let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1184           script#assignFileName filename;
1185           source_view#source_buffer#begin_not_undoable_action ();
1186           script#loadFromString data;
1187           source_view#source_buffer#end_not_undoable_action ();
1188           console#message ("'"^filename^"' loaded.");
1189           self#_enableSaveTo filename
1190         end
1191       else
1192         begin
1193           script#assignFileName file;
1194           let content =
1195            if Sys.file_exists file then file
1196            else BuildTimeConf.script_template
1197           in
1198            source_view#source_buffer#begin_not_undoable_action ();
1199            script#loadFromFile content;
1200            source_view#source_buffer#end_not_undoable_action ();
1201            console#message ("'"^file^"' loaded.");
1202            self#_enableSaveTo file
1203         end
1204       
1205     method setStar name b =
1206       let l = main#scriptLabel in
1207       if b then
1208         l#set_text (name ^  " *")
1209       else
1210         l#set_text (name)
1211         
1212     method private _enableSaveTo file =
1213       script_fname <- Some file;
1214       self#main#saveMenuItem#misc#set_sensitive true
1215         
1216     method console = console
1217     method sourceView: GSourceView.source_view =
1218       (source_view: GSourceView.source_view)
1219     method fileSel = fileSel
1220     method findRepl = findRepl
1221     method main = main
1222     method develList = develList
1223     method newDevel = newDevel
1224
1225     method newBrowserWin () =
1226       object (self)
1227         inherit browserWin ()
1228         val combo = GEdit.combo_box_entry ()
1229         initializer
1230           self#check_widgets ();
1231           let combo_widget = combo#coerce in
1232           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1233           combo#entry#misc#grab_focus ()
1234         method browserUri = combo
1235       end
1236
1237     method newUriDialog () =
1238       let dialog = new uriChoiceDialog () in
1239       dialog#check_widgets ();
1240       dialog
1241
1242     method newConfirmationDialog () =
1243       let dialog = new confirmationDialog () in
1244       dialog#check_widgets ();
1245       dialog
1246
1247     method newEmptyDialog () =
1248       let dialog = new emptyDialog () in
1249       dialog#check_widgets ();
1250       dialog
1251
1252     method private addKeyBinding key callback =
1253       List.iter (fun evbox -> add_key_binding key callback evbox)
1254         keyBindingBoxes
1255
1256     method setQuitCallback callback =
1257       connect_menu_item main#quitMenuItem callback;
1258       ignore (main#toplevel#event#connect#delete 
1259         (fun _ -> callback ();true));
1260       self#addKeyBinding GdkKeysyms._q callback
1261
1262     method chooseFile ?(ok_not_exists = false) () =
1263       _ok_not_exists <- ok_not_exists;
1264       _only_directory <- false;
1265       fileSel#fileSelectionWin#show ();
1266       GtkThread.main ();
1267       chosen_file
1268
1269     method private chooseDir ?(ok_not_exists = false) () =
1270       _ok_not_exists <- ok_not_exists;
1271       _only_directory <- true;
1272       fileSel#fileSelectionWin#show ();
1273       GtkThread.main ();
1274       (* we should check that this is a directory *)
1275       chosen_file
1276   
1277     method createDevelopment ~containing =
1278       next_devel_must_contain <- containing;
1279       newDevel#toplevel#misc#show()
1280
1281     method askText ?(title = "") ?(msg = "") () =
1282       let dialog = new textDialog () in
1283       dialog#textDialog#set_title title;
1284       dialog#textDialogLabel#set_label msg;
1285       let text = ref None in
1286       let return v =
1287         text := v;
1288         dialog#textDialog#destroy ();
1289         GMain.Main.quit ()
1290       in
1291       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1292       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1293       connect_button dialog#textDialogOkButton (fun _ ->
1294         let text = dialog#textDialogTextView#buffer#get_text () in
1295         return (Some text));
1296       dialog#textDialog#show ();
1297       GtkThread.main ();
1298       !text
1299
1300     method private updateFontSize () =
1301       self#sourceView#misc#modify_font_by_name
1302         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1303
1304     method increaseFontSize () =
1305       font_size <- font_size + 1;
1306       self#updateFontSize ()
1307
1308     method decreaseFontSize () =
1309       font_size <- font_size - 1;
1310       self#updateFontSize ()
1311
1312     method resetFontSize () =
1313       font_size <- default_font_size;
1314       self#updateFontSize ()
1315
1316   end
1317
1318 let gui () = 
1319   let g = new gui () in
1320   gui_instance := Some g;
1321   MatitaMathView.set_gui g;
1322   g
1323   
1324 let instance = singleton gui
1325
1326 let non p x = not (p x)
1327
1328 (* this is a shit and should be changed :-{ *)
1329 let interactive_uri_choice
1330   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1331   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1332   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1333   ?copy_cb ()
1334   ~id uris
1335 =
1336   let gui = instance () in
1337   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1338   if (selection_mode <> `SINGLE) &&
1339     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1340   then
1341     Lazy.force nonvars_uris
1342   else begin
1343     let dialog = gui#newUriDialog () in
1344     if hide_uri_entry then
1345       dialog#uriEntryHBox#misc#hide ();
1346     if hide_try then
1347       begin
1348       dialog#uriChoiceSelectedButton#misc#hide ();
1349       dialog#uriChoiceConstantsButton#misc#hide ();
1350       end;
1351     dialog#okLabel#set_label ok_label;  
1352     dialog#uriChoiceTreeView#selection#set_mode
1353       (selection_mode :> Gtk.Tags.selection_mode);
1354     let model = new stringListModel dialog#uriChoiceTreeView in
1355     let choices = ref None in
1356     (match copy_cb with
1357     | None -> ()
1358     | Some cb ->
1359         dialog#copyButton#misc#show ();
1360         connect_button dialog#copyButton 
1361         (fun _ ->
1362           match model#easy_selection () with
1363           | [u] -> (cb u)
1364           | _ -> ()));
1365     dialog#uriChoiceDialog#set_title title;
1366     dialog#uriChoiceLabel#set_text msg;
1367     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1368     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1369     let return v =
1370       choices := v;
1371       dialog#uriChoiceDialog#destroy ();
1372       GMain.Main.quit ()
1373     in
1374     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1375     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1376       return (Some (Lazy.force nonvars_uris)));
1377     if ok_action = `AUTO then
1378       connect_button dialog#uriChoiceAutoButton (fun _ ->
1379         Helm_registry.set_bool "matita.auto_disambiguation" true;
1380         return (Some (Lazy.force nonvars_uris)))
1381     else
1382       connect_button dialog#uriChoiceAutoButton (fun _ ->
1383         match model#easy_selection () with
1384         | [] -> ()
1385         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1386     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1387       match model#easy_selection () with
1388       | [] -> ()
1389       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1390     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1391     dialog#uriChoiceDialog#show ();
1392     GtkThread.main ();
1393     (match !choices with 
1394     | None -> raise MatitaTypes.Cancel
1395     | Some uris -> uris)
1396   end
1397
1398 class interpModel =
1399   let cols = new GTree.column_list in
1400   let id_col = cols#add Gobject.Data.string in
1401   let dsc_col = cols#add Gobject.Data.string in
1402   let interp_no_col = cols#add Gobject.Data.int in
1403   let tree_store = GTree.tree_store cols in
1404   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1405   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1406   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1407   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1408   fun tree_view choices ->
1409     object
1410       initializer
1411         tree_view#set_model (Some (tree_store :> GTree.model));
1412         ignore (tree_view#append_column id_view_col);
1413         ignore (tree_view#append_column dsc_view_col);
1414         let name_of_interp =
1415           (* try to find a reasonable name for an interpretation *)
1416           let idx = ref 0 in
1417           fun interp ->
1418             try
1419               List.assoc "0" interp
1420             with Not_found ->
1421               incr idx; string_of_int !idx
1422         in
1423         tree_store#clear ();
1424         let idx = ref ~-1 in
1425         List.iter
1426           (fun interp ->
1427             incr idx;
1428             let interp_row = tree_store#append () in
1429             tree_store#set ~row:interp_row ~column:id_col
1430               (name_of_interp interp);
1431             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1432             List.iter
1433               (fun (id, dsc) ->
1434                 let row = tree_store#append ~parent:interp_row () in
1435                 tree_store#set ~row ~column:id_col id;
1436                 tree_store#set ~row ~column:dsc_col dsc;
1437                 tree_store#set ~row ~column:interp_no_col !idx)
1438               interp)
1439           choices
1440
1441       method get_interp_no tree_path =
1442         let iter = tree_store#get_iter tree_path in
1443         tree_store#get ~row:iter ~column:interp_no_col
1444     end
1445
1446 let interactive_string_choice 
1447   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1448 =
1449   let gui = instance () in
1450     let dialog = gui#newUriDialog () in
1451     dialog#uriEntryHBox#misc#hide ();
1452     dialog#uriChoiceSelectedButton#misc#hide ();
1453     dialog#uriChoiceAutoButton#misc#hide ();
1454     dialog#uriChoiceConstantsButton#misc#hide ();
1455     dialog#uriChoiceTreeView#selection#set_mode
1456       (`SINGLE :> Gtk.Tags.selection_mode);
1457     let model = new stringListModel dialog#uriChoiceTreeView in
1458     let choices = ref None in
1459     dialog#uriChoiceDialog#set_title title; 
1460     let hack_len = MatitaGtkMisc.utf8_string_length text in
1461     let rec colorize acc_len = function
1462       | [] -> 
1463           let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1464           fst(MatitaGtkMisc.utf8_parsed_text text floc)
1465       | he::tl -> 
1466           let start, stop =  HExtlib.loc_of_floc he in
1467           let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1468           let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1469           let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1470           str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1471     in
1472 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1473                 Printf.eprintf "(%d,%d)" start stop) locs; *)
1474     let locs = 
1475       List.sort 
1476         (fun loc1 loc2 -> 
1477           fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1478         locs 
1479     in
1480 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1481     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1482                 Printf.eprintf "(%d,%d)" start stop) locs;
1483     prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1484     dialog#uriChoiceLabel#set_use_markup true;
1485     let txt = colorize 0 locs in
1486     let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1487       (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1488     in
1489     dialog#uriChoiceLabel#set_label txt;
1490     List.iter model#easy_append uris;
1491     let return v =
1492       choices := v;
1493       dialog#uriChoiceDialog#destroy ();
1494       GMain.Main.quit ()
1495     in
1496     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1497     connect_button dialog#uriChoiceForwardButton (fun _ ->
1498       match model#easy_selection () with
1499       | [] -> ()
1500       | uris -> return (Some uris));
1501     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1502     dialog#uriChoiceDialog#show ();
1503     GtkThread.main ();
1504     (match !choices with 
1505     | None -> raise MatitaTypes.Cancel
1506     | Some uris -> uris)
1507
1508 let interactive_interp_choice () text prefix_len choices =
1509 (*  List.iter (fun (l,_,_) -> 
1510    List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1511    Printf.eprintf "(%d,%d)" start stop) l; prerr_endline "")
1512    ((List.hd choices)); *)
1513  let filter_choices filter =
1514   let rec is_compatible filter =
1515    function
1516       [] -> true
1517     | (_,id,dsc)::tl ->
1518        try
1519         if List.assoc id filter = dsc then
1520          is_compatible filter tl
1521         else
1522          false
1523        with
1524         Not_found -> true
1525   in
1526    List.filter (fun (_,interp) -> is_compatible filter interp)
1527  in
1528  let rec get_choices id =
1529   function
1530      [] -> []
1531    | (_,he)::tl ->
1532       let _,_,dsc = List.find (fun (_,id',_) -> id = id') he in
1533        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices id tl))
1534  in
1535  let example_interp =
1536   match choices with
1537      [] -> assert false
1538    | he::_ -> he in
1539  let ask_user id locs choices =
1540   interactive_string_choice
1541    text prefix_len
1542    ~title:"Ambiguous input"
1543    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1544  in
1545  let rec classify ids filter partial_interpretations =
1546   match ids with
1547      [] -> List.map fst partial_interpretations
1548    | (locs,id,_)::tl ->
1549       let choices = get_choices id partial_interpretations in
1550       let chosen_dsc =
1551        match choices with
1552           [dsc] -> dsc
1553         | _ ->
1554           match ask_user id locs choices with
1555              [x] -> x
1556            | _ -> assert false
1557       in
1558       let filter = (id,chosen_dsc)::filter in
1559       let compatible_interps = filter_choices filter partial_interpretations in
1560        classify tl filter compatible_interps in
1561  let enumerated_choices =
1562   let idx = ref ~-1 in
1563   List.map (fun interp -> incr idx; !idx,interp) choices
1564  in
1565   classify example_interp [] enumerated_choices
1566
1567 let _ =
1568   (* disambiguator callbacks *)
1569   GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1570   GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1571   (* gtk initialization *)
1572   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1573   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1574   ignore (GMain.Main.init ())
1575