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