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