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