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