]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
blocked undo of authomatic text (template)
[helm.git] / helm / 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 open Printf
27
28 open MatitaGeneratedGui
29 open MatitaGtkMisc
30 open MatitaMisc
31
32 let gui_instance = ref None ;;
33
34 class type browserWin =
35   (* this class exists only because GEdit.combo_box_entry is not supported by
36    * lablgladecc :-(((( *)
37 object
38   inherit MatitaGeneratedGui.browserWin
39   method browserUri: GEdit.combo_box_entry
40 end
41
42 class console ~(buffer: GText.buffer) () =
43   object (self)
44     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
45     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
46     val message_tag = buffer#create_tag []
47     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
48     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
49     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
50     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
51     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
52     method clear () =
53       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
54     method log_callback (tag: MatitaLog.log_tag) s =
55       match tag with
56       | `Debug -> self#debug (s ^ "\n")
57       | `Error -> self#error (s ^ "\n")
58       | `Message -> self#message (s ^ "\n")
59       | `Warning -> self#warning (s ^ "\n")
60   end
61         
62 let clean_current_baseuri status = 
63     try  
64       let baseuri = MatitaTypes.get_string_option status "baseuri" in
65       MatitacleanLib.clean_baseuris [baseuri]
66     with MatitaTypes.Option_error _ -> ()
67
68 let ask_and_save_moo_if_needed parent fname status = 
69   let save () =
70     MatitacLib.dump_moo_to_file fname status.MatitaTypes.moo_content_rev in
71   if (MatitaScript.instance ())#eos &&
72      status.MatitaTypes.proof_status = MatitaTypes.No_proof
73   then
74     begin
75       let mooname = 
76         MatitaMisc.obj_file_of_script fname
77       in
78       let rc = 
79         MatitaGtkMisc.ask_confirmation
80         ~title:"A .moo can be generated"
81         ~message:(Printf.sprintf 
82           "%s can be generated for %s.\n<i>Should I generate it?</i>"
83           mooname fname)
84         ~parent ()
85       in
86       let b = 
87         match rc with 
88         | `YES -> true 
89         | `NO -> false 
90         | `CANCEL -> raise MatitaTypes.Cancel 
91       in
92       if b then
93         save ()
94       else
95         clean_current_baseuri status
96     end
97   else
98     clean_current_baseuri status 
99     
100 let ask_unsaved parent =
101   MatitaGtkMisc.ask_confirmation 
102     ~parent ~title:"Unsaved work!" 
103     ~message:("Your work is <b>unsaved</b>!\n\n"^
104          "<i>Do you want to save the script before exiting?</i>")
105     ()
106
107 class gui () =
108     (* creation order _is_ relevant for windows placement *)
109   let main = new mainWin () in
110   let about = new aboutWin () in
111   let fileSel = new fileSelectionWin () in
112   let findRepl = new findReplWin () in
113   let develList = new develListWin () in
114   let newDevel = new newDevelopmentWin () in
115   let keyBindingBoxes = (* event boxes which should receive global key events *)
116     [ main#mainWinEventBox ]
117   in
118   let console = new console ~buffer:main#logTextView#buffer () in
119   let (source_view: GSourceView.source_view) =
120     GSourceView.source_view
121       ~auto_indent:true
122       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
123       ~margin:80 ~show_margin:true
124       ~smart_home_end:true
125       ~packing:main#scriptScrolledWin#add
126       ()
127   in
128   let default_font_size =
129     Helm_registry.get_opt_default Helm_registry.int
130       ~default:BuildTimeConf.default_font_size "matita.font_size"
131   in
132   let source_buffer = source_view#source_buffer in
133   object (self)
134     val mutable chosen_file = None
135     val mutable _ok_not_exists = false
136     val mutable _only_directory = false
137     val mutable script_fname = None
138     val mutable font_size = default_font_size
139     val mutable next_devel_must_contain = None
140    
141     initializer
142         (* glade's check widgets *)
143       List.iter (fun w -> w#check_widgets ())
144         (let c w = (w :> <check_widgets: unit -> unit>) in
145         [ c about; c fileSel; c main; c findRepl]);
146         (* key bindings *)
147       List.iter (* global key bindings *)
148         (fun (key, callback) -> self#addKeyBinding key callback)
149 (*
150         [ GdkKeysyms._F3,
151             toggle_win ~check:main#showProofMenuItem proof#proofWin;
152           GdkKeysyms._F4,
153             toggle_win ~check:main#showCheckMenuItem check#checkWin;
154 *)
155         [ ];
156         (* about win *)
157       ignore (about#aboutWin#event#connect#delete (fun _ -> true));
158       ignore (main#aboutMenuItem#connect#activate (fun _ ->
159         about#aboutWin#show ()));
160       connect_button about#aboutDismissButton (fun _ ->
161         about#aboutWin#misc#hide ());
162       about#aboutLabel#set_label (Pcre.replace ~pat:"@VERSION@"
163         ~templ:BuildTimeConf.version about#aboutLabel#label);
164         (* findRepl win *)
165       let show_find_Repl () = 
166         findRepl#toplevel#misc#show ();
167         findRepl#toplevel#misc#grab_focus ()
168       in
169       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
170       let find_forward _ = 
171           let highlight start end_ =
172             source_buffer#move_mark `INSERT ~where:start;
173             source_buffer#move_mark `SEL_BOUND ~where:end_;
174             source_view#scroll_mark_onscreen `INSERT
175           in
176           let text = findRepl#findEntry#text in
177           let iter = source_buffer#get_iter `SEL_BOUND in
178           match iter#forward_search text with
179           | None -> 
180               (match source_buffer#start_iter#forward_search text with
181               | None -> ()
182               | Some (start,end_) -> highlight start end_)
183           | Some (start,end_) -> highlight start end_ 
184       in
185       let replace _ =
186         let text = findRepl#replaceEntry#text in
187         let ins = source_buffer#get_iter `INSERT in
188         let sel = source_buffer#get_iter `SEL_BOUND in
189         if ins#compare sel < 0 then 
190           begin
191             ignore(source_buffer#delete_selection ());
192             source_buffer#insert text
193           end
194       in
195       connect_button findRepl#findButton find_forward;
196       connect_button findRepl#findReplButton replace;
197       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
198       ignore(findRepl#toplevel#event#connect#delete 
199         ~callback:(fun _ -> hide_find_Repl ();true));
200       ignore(self#main#findReplMenuItem#connect#activate
201         ~callback:show_find_Repl);
202       ignore (findRepl#findEntry#connect#activate ~callback:find_forward);
203         (* developments win *)
204       let model = 
205         new MatitaGtkMisc.multiStringListModel 
206           ~cols:2 develList#developmentsTreeview
207       in
208       let refresh_devels_win () =
209         model#list_store#clear ();
210         List.iter 
211           (fun (name, root) -> model#easy_mappend [name;root]) 
212           (MatitamakeLib.list_known_developments ())
213       in
214       let get_devel_selected () = 
215         match model#easy_mselection () with
216         | [[name;_]] -> MatitamakeLib.development_for_name name
217         | _ -> assert false 
218       in
219       connect_button develList#newButton
220         (fun () -> 
221           next_devel_must_contain <- None;
222           newDevel#toplevel#misc#show());
223       connect_button develList#deleteButton
224         (fun () -> 
225           (match get_devel_selected () with
226           | None -> ()
227           | Some d -> MatitamakeLib.destroy_development d);
228           refresh_devels_win ());
229       let refresh () = 
230         while Glib.Main.pending () do 
231           ignore(Glib.Main.iteration false); 
232         done
233       in
234       connect_button develList#buildButton 
235         (fun () -> 
236           match get_devel_selected () with
237           | None -> ()
238           | Some d -> ignore(MatitamakeLib.build_development_in_bg refresh d));
239       connect_button develList#cleanButton 
240         (fun () -> 
241           match get_devel_selected () with
242           | None -> ()
243           | Some d -> ignore(MatitamakeLib.clean_development_in_bg refresh d));
244       connect_button develList#closeButton 
245         (fun () -> develList#toplevel#misc#hide());
246       ignore(develList#toplevel#event#connect#delete 
247         (fun _ -> develList#toplevel#misc#hide();true));
248       let selected_devel = ref None in
249       connect_menu_item self#main#developmentsMenuItem
250         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
251       
252         (* add development win *)
253       let check_if_root_contains root =
254         match next_devel_must_contain with
255         | None -> true
256         | Some path -> 
257             let is_prefix_of d1 d2 =
258               let len1 = String.length d1 in
259               let len2 = String.length d2 in
260               if len2 < len1 then 
261                 false
262               else
263                 let pref = String.sub d2 0 len1 in
264                 pref = d1
265             in
266             is_prefix_of root path
267       in
268       connect_button newDevel#addButton 
269        (fun () -> 
270           let name = newDevel#nameEntry#text in
271           let root = newDevel#rootEntry#text in
272           if check_if_root_contains root then
273             begin
274               ignore (MatitamakeLib.initialize_development name root);
275               refresh_devels_win ();
276               newDevel#nameEntry#set_text "";
277               newDevel#rootEntry#set_text "";
278               newDevel#toplevel#misc#hide()
279             end
280           else
281             MatitaLog.error ("The selected root does not contain " ^ 
282               match next_devel_must_contain with 
283               | Some x -> x 
284               | _ -> assert false));
285       connect_button newDevel#chooseRootButton 
286        (fun () ->
287          let path = self#chooseDir () in
288          match path with
289          | Some path -> newDevel#rootEntry#set_text path
290          | None -> ());
291       connect_button newDevel#cancelButton 
292        (fun () -> newDevel#toplevel#misc#hide ());
293       ignore(newDevel#toplevel#event#connect#delete 
294         (fun _ -> newDevel#toplevel#misc#hide();true));
295       
296         (* file selection win *)
297       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
298       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
299         let return r =
300           chosen_file <- r;
301           fileSel#fileSelectionWin#misc#hide ();
302           GMain.Main.quit ()
303         in
304         match event with
305         | `OK ->
306             let fname = fileSel#fileSelectionWin#filename in
307             if Sys.file_exists fname then
308               begin
309                 if is_regular fname && not(_only_directory) then 
310                   return (Some fname) 
311                 else if _only_directory && is_dir fname then 
312                   return (Some fname)
313               end
314             else
315               begin
316                 if _ok_not_exists then 
317                   return (Some fname)
318               end
319         | `CANCEL -> return None
320         | `HELP -> ()
321         | `DELETE_EVENT -> return None));
322         (* menus *)
323       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
324       main#helpMenu#set_right_justified true;
325         (* console *)
326       let adj = main#logScrolledWin#vadjustment in
327         ignore (adj#connect#changed
328                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
329       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
330         (* toolbar *)
331       let module A = GrafiteAst in
332       let hole = CicNotationPt.UserInput in
333       let loc = Disambiguate.dummy_floc in
334       let tac ast _ =
335         if (MatitaScript.instance ())#onGoingProof () then
336           (MatitaScript.instance ())#advance
337             ~statement:("\n" ^ GrafiteAstPp.pp_tactical (A.Tactic (loc, ast)))
338             ()
339       in
340       let tac_w_term ast _ =
341         if (MatitaScript.instance ())#onGoingProof () then
342           let buf = source_buffer in
343           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
344             ("\n" ^ GrafiteAstPp.pp_tactic ast)
345       in
346       let tbar = self#main in
347       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
348       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
349       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
350       connect_button tbar#elimButton (tac_w_term (A.Elim (loc, hole, None, None, [])));
351       connect_button tbar#elimTypeButton (tac_w_term (A.ElimType (loc, hole, None, None, [])));
352       connect_button tbar#splitButton (tac (A.Split loc));
353       connect_button tbar#leftButton (tac (A.Left loc));
354       connect_button tbar#rightButton (tac (A.Right loc));
355       connect_button tbar#existsButton (tac (A.Exists loc));
356       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
357       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
358       connect_button tbar#transitivityButton
359         (tac_w_term (A.Transitivity (loc, hole)));
360       connect_button tbar#assumptionButton (tac (A.Assumption loc));
361       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
362       connect_button tbar#autoButton (tac (A.Auto (loc,None,None)));
363       MatitaGtkMisc.toggle_widget_visibility
364        ~widget:(self#main#tacticsButtonsHandlebox :> GObj.widget)
365        ~check:self#main#tacticsBarMenuItem;
366       let module Hr = Helm_registry in
367       if
368         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
369       then 
370         self#main#tacticsBarMenuItem#set_active false;
371       MatitaGtkMisc.toggle_callback 
372         ~callback:(function 
373           | true -> self#main#toplevel#fullscreen () 
374           | false -> self#main#toplevel#unfullscreen ())
375         ~check:self#main#fullscreenMenuItem;
376       self#main#fullscreenMenuItem#set_active false;
377         (* log *)
378       MatitaLog.set_log_callback self#console#log_callback;
379       GtkSignal.user_handler :=
380         (fun exn -> MatitaLog.error (MatitaExcPp.to_string exn));
381         (* script *)
382       let _ =
383         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
384         | None ->
385             MatitaLog.warn (sprintf "can't load language file %s"
386               BuildTimeConf.lang_file)
387         | Some matita_lang ->
388             source_buffer#set_language matita_lang;
389             source_buffer#set_highlight true
390       in
391       let s () = MatitaScript.instance () in
392       let disableSave () =
393         script_fname <- None;
394         self#main#saveMenuItem#misc#set_sensitive false
395       in
396       let saveAsScript () =
397         let script = s () in
398         match self#chooseFile ~ok_not_exists:true () with
399         | Some f -> 
400               script#assignFileName f;
401               script#saveToFile (); 
402               console#message ("'"^f^"' saved.\n");
403               self#_enableSaveTo f
404         | None -> ()
405       in
406       let saveScript () =
407         match script_fname with
408         | None -> saveAsScript ()
409         | Some f -> 
410               (s ())#assignFileName f;
411               (s ())#saveToFile ();
412               console#message ("'"^f^"' saved.\n");
413       in
414       let loadScript () =
415         let script = s () in 
416         let status = script#status in
417         try 
418           if source_view#buffer#modified then
419             begin
420               match ask_unsaved main#toplevel with
421               | `YES -> saveScript ()
422               | `NO -> ()
423               | `CANCEL -> raise MatitaTypes.Cancel
424             end;
425           (match script_fname with
426           | None -> ()
427           | Some fname -> 
428               ask_and_save_moo_if_needed main#toplevel fname status);
429           match self#chooseFile () with
430           | Some f -> 
431                 script#reset (); 
432                 script#assignFileName f;
433                 source_view#source_buffer#begin_not_undoable_action ();
434                 script#loadFromFile (); 
435                 source_view#source_buffer#end_not_undoable_action ();
436                 console#message ("'"^f^"' loaded.\n");
437                 self#_enableSaveTo f
438           | None -> ()
439         with MatitaTypes.Cancel -> ()
440       in
441       let newScript () = 
442         source_view#source_buffer#begin_not_undoable_action ();
443         (s ())#reset (); 
444         (s ())#template (); 
445         source_view#source_buffer#end_not_undoable_action ();
446         disableSave ();
447         script_fname <- None
448       in
449       let cursor () =
450         source_buffer#place_cursor
451           (source_buffer#get_iter_at_mark (`NAME "locked"))
452       in
453       let lock_world _ =
454         main#buttonsToolbar#misc#set_sensitive false;
455         source_view#set_editable false
456       in
457       let unlock_world _ =
458         main#buttonsToolbar#misc#set_sensitive true;
459         source_view#set_editable true
460       in
461       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
462       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
463       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
464       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
465       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
466       let locker f = 
467         fun () -> 
468           lock_world ();
469           try f ();unlock_world () with exc -> unlock_world (); raise exc
470       in
471       let advance = locker advance in
472       let retract = locker retract in
473       let top = locker top in
474       let bottom = locker bottom in
475       let jump = locker jump in
476       let connect_key sym f =
477         connect_key self#main#mainWinEventBox#event
478           ~modifiers:[`CONTROL] ~stop:true sym f;
479         connect_key self#sourceView#event
480           ~modifiers:[`CONTROL] ~stop:true sym f
481       in
482         (* quit *)
483       self#setQuitCallback (fun () -> 
484         let status = (MatitaScript.instance ())#status in
485         if source_view#buffer#modified then
486           begin
487             let rc = ask_unsaved main#toplevel in 
488             try
489               match rc with
490               | `YES -> saveScript ();
491                         if not source_view#buffer#modified then
492                           begin
493                             (match script_fname with
494                             | None -> ()
495                             | Some fname -> 
496                                ask_and_save_moo_if_needed 
497                                  main#toplevel fname status);
498                           GMain.Main.quit ()
499                           end
500               | `NO -> GMain.Main.quit ()
501               | `CANCEL -> raise MatitaTypes.Cancel
502             with MatitaTypes.Cancel -> ()
503           end 
504         else 
505           begin  
506             (match script_fname with
507             | None -> clean_current_baseuri status; GMain.Main.quit ()
508             | Some fname ->
509                 try
510                   ask_and_save_moo_if_needed main#toplevel fname status;
511                   GMain.Main.quit ()
512                 with MatitaTypes.Cancel -> ())
513           end);
514       connect_button self#main#scriptAdvanceButton advance;
515       connect_button self#main#scriptRetractButton retract;
516       connect_button self#main#scriptTopButton top;
517       connect_button self#main#scriptBottomButton bottom;
518       connect_key GdkKeysyms._Down advance;
519       connect_key GdkKeysyms._Up retract;
520       connect_key GdkKeysyms._Home top;
521       connect_key GdkKeysyms._End bottom;
522       connect_button self#main#scriptJumpButton jump;
523       connect_menu_item self#main#openMenuItem   loadScript;
524       connect_menu_item self#main#saveMenuItem   saveScript;
525       connect_menu_item self#main#saveAsMenuItem saveAsScript;
526       connect_menu_item self#main#newMenuItem    newScript;
527       connect_key GdkKeysyms._period
528         (fun () ->
529           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
530             ".\n";
531           advance ());
532       connect_key GdkKeysyms._Return
533         (fun () ->
534           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
535             "\n";
536           advance ());
537          (* script monospace font stuff *)  
538       self#updateFontSize ();
539         (* debug menu *)
540       self#main#debugMenu#misc#hide ();
541         (* status bar *)
542       self#main#hintLowImage#set_file (image_path "matita-bulb-low.png");
543       self#main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
544       self#main#hintHighImage#set_file (image_path "matita-bulb-high.png");
545         (* focus *)
546       self#sourceView#misc#grab_focus ();
547         (* main win dimension *)
548       let width = Gdk.Screen.width () in
549       let height = Gdk.Screen.height () in
550       let main_w = width * 90 / 100 in 
551       let main_h = height * 80 / 100 in
552       let script_w = main_w * 6 / 10 in
553       self#main#toplevel#resize ~width:main_w ~height:main_h;
554       self#main#hpaneScriptSequent#set_position script_w;
555         (* source_view *)
556       ignore(source_view#connect#after#paste_clipboard 
557         ~callback:(fun () -> (MatitaScript.instance ())#clean_dirty_lock))
558     
559     method loadScript file =       
560       let script = MatitaScript.instance () in
561       script#reset (); 
562       script#assignFileName file;
563       if not (Sys.file_exists file) then
564         begin
565           let oc = open_out file in
566           let template = MatitaMisc.input_file BuildTimeConf.script_template in 
567           output_string oc template;
568           close_out oc
569         end;
570       source_view#source_buffer#begin_not_undoable_action ();
571       script#loadFromFile ();
572       source_view#source_buffer#end_not_undoable_action ();
573       console#message ("'"^file^"' loaded.");
574       self#_enableSaveTo file
575       
576     method setStar name b =
577       let l = main#scriptLabel in
578       if b then
579         l#set_text (name ^  " *")
580       else
581         l#set_text (name)
582         
583     method private _enableSaveTo file =
584       script_fname <- Some file;
585       self#main#saveMenuItem#misc#set_sensitive true
586         
587
588     method console = console
589     method sourceView: GSourceView.source_view = (source_view: GSourceView.source_view)
590     method about = about
591     method fileSel = fileSel
592     method findRepl = findRepl
593     method main = main
594     method develList = develList
595     method newDevel = newDevel
596
597     method newBrowserWin () =
598       object (self)
599         inherit browserWin ()
600         val combo = GEdit.combo_box_entry ()
601         initializer
602           self#check_widgets ();
603           let combo_widget = combo#coerce in
604           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
605           combo#entry#misc#grab_focus ()
606         method browserUri = combo
607       end
608
609     method newUriDialog () =
610       let dialog = new uriChoiceDialog () in
611       dialog#check_widgets ();
612       dialog
613
614     method newInterpDialog () =
615       let dialog = new interpChoiceDialog () in
616       dialog#check_widgets ();
617       dialog
618
619     method newConfirmationDialog () =
620       let dialog = new confirmationDialog () in
621       dialog#check_widgets ();
622       dialog
623
624     method newEmptyDialog () =
625       let dialog = new emptyDialog () in
626       dialog#check_widgets ();
627       dialog
628
629     method private addKeyBinding key callback =
630       List.iter (fun evbox -> add_key_binding key callback evbox)
631         keyBindingBoxes
632
633     method setQuitCallback callback =
634       ignore (main#quitMenuItem#connect#activate callback);
635       ignore (main#toplevel#event#connect#delete 
636         (fun _ -> callback ();true));
637       self#addKeyBinding GdkKeysyms._q callback
638
639     method chooseFile ?(ok_not_exists = false) () =
640       _ok_not_exists <- ok_not_exists;
641       _only_directory <- false;
642       fileSel#fileSelectionWin#show ();
643       GtkThread.main ();
644       chosen_file
645
646     method private chooseDir ?(ok_not_exists = false) () =
647       _ok_not_exists <- ok_not_exists;
648       _only_directory <- true;
649       fileSel#fileSelectionWin#show ();
650       GtkThread.main ();
651       (* we should check that this is a directory *)
652       chosen_file
653   
654     method createDevelopment ~containing =
655       next_devel_must_contain <- containing;
656       newDevel#toplevel#misc#show()
657
658     method askText ?(title = "") ?(msg = "") () =
659       let dialog = new textDialog () in
660       dialog#textDialog#set_title title;
661       dialog#textDialogLabel#set_label msg;
662       let text = ref None in
663       let return v =
664         text := v;
665         dialog#textDialog#destroy ();
666         GMain.Main.quit ()
667       in
668       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
669       connect_button dialog#textDialogCancelButton (fun _ -> return None);
670       connect_button dialog#textDialogOkButton (fun _ ->
671         let text = dialog#textDialogTextView#buffer#get_text () in
672         return (Some text));
673       dialog#textDialog#show ();
674       GtkThread.main ();
675       !text
676
677     method private updateFontSize () =
678       self#sourceView#misc#modify_font_by_name
679         (sprintf "%s %d" BuildTimeConf.script_font font_size)
680
681     method increaseFontSize () =
682       font_size <- font_size + 1;
683       self#updateFontSize ()
684
685     method decreaseFontSize () =
686       font_size <- font_size - 1;
687       self#updateFontSize ()
688
689     method resetFontSize () =
690       font_size <- default_font_size;
691       self#updateFontSize ()
692
693   end
694
695 let gui () = 
696   let g = new gui () in
697   gui_instance := Some g;
698   g
699   
700 let instance = singleton gui
701
702 let non p x = not (p x)
703
704 (* this is a shit and should be changed :-{ *)
705 let interactive_uri_choice
706   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
707   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
708   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
709   ?copy_cb ()
710   ~id uris
711 =
712   let gui = instance () in
713   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
714   if (selection_mode <> `SINGLE) &&
715     (Helm_registry.get_bool "matita.auto_disambiguation")
716   then
717     Lazy.force nonvars_uris
718   else begin
719     let dialog = gui#newUriDialog () in
720     if hide_uri_entry then
721       dialog#uriEntryHBox#misc#hide ();
722     if hide_try then
723       begin
724       dialog#uriChoiceSelectedButton#misc#hide ();
725       dialog#uriChoiceConstantsButton#misc#hide ();
726       end;
727     dialog#okLabel#set_label ok_label;  
728     dialog#uriChoiceTreeView#selection#set_mode
729       (selection_mode :> Gtk.Tags.selection_mode);
730     let model = new stringListModel dialog#uriChoiceTreeView in
731     let choices = ref None in
732     let nonvars = ref false in
733     (match copy_cb with
734     | None -> ()
735     | Some cb ->
736         dialog#copyButton#misc#show ();
737         connect_button dialog#copyButton 
738         (fun _ ->
739           match model#easy_selection () with
740           | [u] -> (cb u)
741           | _ -> ()));
742     dialog#uriChoiceDialog#set_title title;
743     dialog#uriChoiceLabel#set_text msg;
744     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
745     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
746     let return v =
747       choices := v;
748       dialog#uriChoiceDialog#destroy ();
749       GMain.Main.quit ()
750     in
751     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
752     connect_button dialog#uriChoiceConstantsButton (fun _ ->
753       return (Some (Lazy.force nonvars_uris)));
754     if ok_action = `AUTO then
755       connect_button dialog#uriChoiceAutoButton (fun _ ->
756         Helm_registry.set_bool "matita.auto_disambiguation" true;
757         return (Some (Lazy.force nonvars_uris)))
758     else
759       connect_button dialog#uriChoiceAutoButton (fun _ ->
760         match model#easy_selection () with
761         | [] -> ()
762         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
763     connect_button dialog#uriChoiceSelectedButton (fun _ ->
764       match model#easy_selection () with
765       | [] -> ()
766       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
767     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
768     dialog#uriChoiceDialog#show ();
769     GtkThread.main ();
770     (match !choices with 
771     | None -> raise MatitaTypes.Cancel
772     | Some uris -> uris)
773   end
774
775 class interpModel =
776   let cols = new GTree.column_list in
777   let id_col = cols#add Gobject.Data.string in
778   let dsc_col = cols#add Gobject.Data.string in
779   let interp_no_col = cols#add Gobject.Data.int in
780   let tree_store = GTree.tree_store cols in
781   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
782   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
783   let id_view_col = GTree.view_column ~renderer:id_renderer () in
784   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
785   fun tree_view choices ->
786     object
787       initializer
788         tree_view#set_model (Some (tree_store :> GTree.model));
789         ignore (tree_view#append_column id_view_col);
790         ignore (tree_view#append_column dsc_view_col);
791         let name_of_interp =
792           (* try to find a reasonable name for an interpretation *)
793           let idx = ref 0 in
794           fun interp ->
795             try
796               List.assoc "0" interp
797             with Not_found ->
798               incr idx; string_of_int !idx
799         in
800         tree_store#clear ();
801         let idx = ref ~-1 in
802         List.iter
803           (fun interp ->
804             incr idx;
805             let interp_row = tree_store#append () in
806             tree_store#set ~row:interp_row ~column:id_col
807               (name_of_interp interp);
808             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
809             List.iter
810               (fun (id, dsc) ->
811                 let row = tree_store#append ~parent:interp_row () in
812                 tree_store#set ~row ~column:id_col id;
813                 tree_store#set ~row ~column:dsc_col dsc;
814                 tree_store#set ~row ~column:interp_no_col !idx)
815               interp)
816           choices
817
818       method get_interp_no tree_path =
819         let iter = tree_store#get_iter tree_path in
820         tree_store#get ~row:iter ~column:interp_no_col
821     end
822
823 let interactive_interp_choice () choices =
824   let gui = instance () in
825   assert (choices <> []);
826   let dialog = gui#newInterpDialog () in
827   let model = new interpModel dialog#interpChoiceTreeView choices in
828   let interp_len = List.length (List.hd choices) in
829   dialog#interpChoiceDialog#set_title "Interpretation choice";
830   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
831   let interp_no = ref None in
832   let return _ =
833     dialog#interpChoiceDialog#destroy ();
834     GMain.Main.quit ()
835   in
836   let fail _ = interp_no := None; return () in
837   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
838   connect_button dialog#interpChoiceOkButton (fun _ ->
839     match !interp_no with None -> () | Some _ -> return ());
840   connect_button dialog#interpChoiceCancelButton fail;
841   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
842     interp_no := Some (model#get_interp_no path);
843     return ()));
844   let selection = dialog#interpChoiceTreeView#selection in
845   ignore (selection#connect#changed (fun _ ->
846     match selection#get_selected_rows with
847     | [path] ->
848         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
849         interp_no := Some (model#get_interp_no path)
850     | _ -> assert false));
851   dialog#interpChoiceDialog#show ();
852   GtkThread.main ();
853   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
854