]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
added "are you sure you want to quit with usaved script?"
[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 "yellow" ]
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 class gui () =
63     (* creation order _is_ relevant for windows placement *)
64   let main = new mainWin () in
65   let about = new aboutWin () in
66   let fileSel = new fileSelectionWin () in
67   let keyBindingBoxes = (* event boxes which should receive global key events *)
68     [ main#mainWinEventBox ]
69   in
70   let console = new console ~buffer:main#logTextView#buffer () in
71   let (source_view: GSourceView.source_view) =
72     GSourceView.source_view
73       ~auto_indent:true
74       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
75       ~margin:80 ~show_margin:true
76       ~smart_home_end:true
77       ~packing:main#scriptScrolledWin#add
78       ()
79   in
80   let default_font_size =
81     Helm_registry.get_opt_default Helm_registry.int
82       ~default:BuildTimeConf.default_font_size "matita.font_size"
83   in
84   let source_buffer = source_view#source_buffer in
85   object (self)
86     val mutable chosen_file = None
87     val mutable _ok_not_exists = false
88     val mutable script_fname = None
89     val mutable font_size = default_font_size
90    
91     initializer
92         (* glade's check widgets *)
93       List.iter (fun w -> w#check_widgets ())
94         (let c w = (w :> <check_widgets: unit -> unit>) in
95          [ c about; c fileSel; c main ]);
96         (* key bindings *)
97       List.iter (* global key bindings *)
98         (fun (key, callback) -> self#addKeyBinding key callback)
99 (*
100         [ GdkKeysyms._F3,
101             toggle_win ~check:main#showProofMenuItem proof#proofWin;
102           GdkKeysyms._F4,
103             toggle_win ~check:main#showCheckMenuItem check#checkWin;
104 *)
105         [ ];
106         (* about win *)
107       ignore (about#aboutWin#event#connect#delete (fun _ -> true));
108       ignore (main#aboutMenuItem#connect#activate (fun _ ->
109         about#aboutWin#show ()));
110       connect_button about#aboutDismissButton (fun _ ->
111         about#aboutWin#misc#hide ());
112       about#aboutLabel#set_label (Pcre.replace ~pat:"@VERSION@"
113         ~templ:BuildTimeConf.version about#aboutLabel#label);
114         (* file selection win *)
115       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
116       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
117         let return r =
118           chosen_file <- r;
119           fileSel#fileSelectionWin#misc#hide ();
120           GMain.Main.quit ()
121         in
122         match event with
123         | `OK ->
124             let fname = fileSel#fileSelectionWin#filename in
125             if Sys.file_exists fname then
126               (if is_regular fname then return (Some fname))
127             else
128               (if _ok_not_exists then return (Some fname))
129         | `CANCEL -> return None
130         | `HELP -> ()
131         | `DELETE_EVENT -> return None));
132         (* menus *)
133       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
134       main#helpMenu#set_right_justified true;
135         (* console *)
136       let adj = main#logScrolledWin#vadjustment in
137       ignore (adj#connect#changed
138                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
139       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
140         (* toolbar *)
141       let module A = TacticAst in
142       let hole = CicAst.UserInput in
143       let loc = CicAst.dummy_floc in
144       let tac ast _ =
145         if (MatitaScript.instance ())#onGoingProof () then
146           (MatitaScript.instance ())#advance
147             ~statement:("\n" ^ TacticAstPp.pp_tactical (A.Tactic (loc, ast))) ()
148       in
149       let tac_w_term ast _ =
150         if (MatitaScript.instance ())#onGoingProof () then
151           let buf = source_buffer in
152           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
153             ("\n" ^ TacticAstPp.pp_tactic ast)
154       in
155       let tbar = self#main in
156       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
157       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
158       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
159       connect_button tbar#elimButton (tac_w_term (A.Elim (loc, hole, None)));
160       connect_button tbar#elimTypeButton (tac_w_term (A.ElimType (loc, hole)));
161       connect_button tbar#splitButton (tac (A.Split loc));
162       connect_button tbar#leftButton (tac (A.Left loc));
163       connect_button tbar#rightButton (tac (A.Right loc));
164       connect_button tbar#existsButton (tac (A.Exists loc));
165       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
166       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
167       connect_button tbar#transitivityButton
168         (tac_w_term (A.Transitivity (loc, hole)));
169       connect_button tbar#assumptionButton (tac (A.Assumption loc));
170       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
171       connect_button tbar#autoButton (tac (A.Auto (loc,None,None)));
172       MatitaGtkMisc.toggle_widget_visibility
173        ~widget:(self#main#tacticsButtonsHandlebox :> GObj.widget)
174        ~check:self#main#tacticsBarMenuItem;
175       let module Hr = Helm_registry in
176       if
177         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
178       then 
179         self#main#tacticsBarMenuItem#set_active false;
180       MatitaGtkMisc.toggle_callback 
181         ~callback:(function 
182           | true -> self#main#toplevel#fullscreen () 
183           | false -> self#main#toplevel#unfullscreen ())
184         ~check:self#main#fullscreenMenuItem;
185       self#main#fullscreenMenuItem#set_active false;
186         (* log *)
187       MatitaLog.set_log_callback self#console#log_callback;
188       GtkSignal.user_handler :=
189         (fun exn ->
190            MatitaLog.error
191              (sprintf "Uncaught exception: %s" (Printexc.to_string exn)));
192         (* script *)
193       let _ =
194         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
195         | None ->
196             MatitaLog.warn (sprintf "can't load language file %s"
197               BuildTimeConf.lang_file)
198         | Some matita_lang ->
199             source_buffer#set_language matita_lang;
200             source_buffer#set_highlight true
201       in
202       let s () = MatitaScript.instance () in
203       let disableSave () =
204         script_fname <- None;
205         self#main#saveMenuItem#misc#set_sensitive false
206       in
207       let loadScript () =
208         let script = s () in
209         match self#chooseFile () with
210         | Some f -> 
211               script#reset (); 
212               script#assignFileName f;
213               script#loadFromFile (); 
214               console#message ("'"^f^"' loaded.\n");
215               self#_enableSaveTo f
216         | None -> ()
217       in
218       let saveAsScript () =
219         let script = s () in
220         match self#chooseFile ~ok_not_exists:true () with
221         | Some f -> 
222               script#assignFileName f;
223               script#saveToFile (); 
224               console#message ("'"^f^"' saved.\n");
225               self#_enableSaveTo f
226         | None -> ()
227       in
228       let saveScript () =
229         match script_fname with
230         | None -> saveAsScript ()
231         | Some f -> 
232               (s ())#assignFileName f;
233               (s ())#saveToFile ();
234               console#message ("'"^f^"' saved.\n");
235       in
236       let newScript () = (s ())#reset (); disableSave () in
237       let cursor () =
238         source_buffer#place_cursor
239           (source_buffer#get_iter_at_mark (`NAME "locked"))
240       in
241       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
242       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
243       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
244       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
245       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
246       let connect_key sym f =
247         connect_key self#main#mainWinEventBox#event
248           ~modifiers:[`CONTROL] ~stop:true sym f;
249         connect_key self#sourceView#event
250           ~modifiers:[`CONTROL] ~stop:true sym f
251       in
252         (* quit *)
253       self#setQuitCallback (fun () -> 
254         if 
255           MatitaGtkMisc.ask_confirmation 
256             ~parent:main#toplevel
257             ~title:"Unsaved work!" 
258             ~message:("Your work is <b>unsaved</b>!\n\n"^
259                  "<i>Do you want to save the script before exiting?</i>")
260             ()
261         then 
262           (saveScript ();prerr_endline "SAVE";GMain.Main.quit ())
263         else
264           GMain.Main.quit ());
265       connect_button self#main#scriptAdvanceButton advance;
266       connect_button self#main#scriptRetractButton retract;
267       connect_button self#main#scriptTopButton top;
268       connect_button self#main#scriptBottomButton bottom;
269       connect_key GdkKeysyms._Down advance;
270       connect_key GdkKeysyms._Up retract;
271       connect_key GdkKeysyms._Home top;
272       connect_key GdkKeysyms._End bottom;
273       connect_button self#main#scriptJumpButton jump;
274       connect_menu_item self#main#openMenuItem   loadScript;
275       connect_menu_item self#main#saveMenuItem   saveScript;
276       connect_menu_item self#main#saveAsMenuItem saveAsScript;
277       connect_menu_item self#main#newMenuItem    newScript;
278       connect_key GdkKeysyms._period
279         (fun () ->
280           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
281             ".\n";
282           advance ());
283       connect_key GdkKeysyms._Return
284         (fun () ->
285           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
286             "\n";
287           advance ());
288          (* script monospace font stuff *)  
289       self#updateFontSize ();
290         (* debug menu *)
291       self#main#debugMenu#misc#hide ();
292         (* status bar *)
293       self#main#hintLowImage#set_file (image_path "matita-bulb-low.png");
294       self#main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
295       self#main#hintHighImage#set_file (image_path "matita-bulb-high.png");
296         (* focus *)
297       self#sourceView#misc#grab_focus ();
298         (* main win dimension *)
299       let width = Gdk.Screen.width () in
300       let height = Gdk.Screen.height () in
301       let main_w = width * 90 / 100 in 
302       let main_h = height * 80 / 100 in
303       let script_w = main_w * 6 / 10 in
304       self#main#toplevel#resize ~width:main_w ~height:main_h;
305       self#main#hpaneScriptSequent#set_position script_w  
306     
307     method loadScript file =       
308       let script = MatitaScript.instance () in
309       script#reset (); 
310       script#assignFileName file;
311       script#loadFromFile (); 
312       console#message ("'"^file^"' loaded.");
313       self#_enableSaveTo file
314       
315     method setStar name b =
316       let l = main#scriptLabel in
317       if b then
318         l#set_text (name ^  " *")
319       else
320         l#set_text (name)
321         
322     method private _enableSaveTo file =
323       script_fname <- Some file;
324       self#main#saveMenuItem#misc#set_sensitive true
325         
326
327     method console = console
328     method sourceView: GSourceView.source_view = (source_view: GSourceView.source_view)
329     method about = about
330     method fileSel = fileSel
331     method main = main
332
333     method newBrowserWin () =
334       object (self)
335         inherit browserWin ()
336         val combo = GEdit.combo_box_entry ()
337         initializer
338           self#check_widgets ();
339           let combo_widget = combo#coerce in
340           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
341           combo#entry#misc#grab_focus ()
342         method browserUri = combo
343       end
344
345     method newUriDialog () =
346       let dialog = new uriChoiceDialog () in
347       dialog#check_widgets ();
348       dialog
349
350     method newInterpDialog () =
351       let dialog = new interpChoiceDialog () in
352       dialog#check_widgets ();
353       dialog
354
355     method newConfirmationDialog () =
356       let dialog = new confirmationDialog () in
357       dialog#check_widgets ();
358       dialog
359
360     method newEmptyDialog () =
361       let dialog = new emptyDialog () in
362       dialog#check_widgets ();
363       dialog
364
365     method private addKeyBinding key callback =
366       List.iter (fun evbox -> add_key_binding key callback evbox)
367         keyBindingBoxes
368
369     method setQuitCallback callback =
370       ignore (main#quitMenuItem#connect#activate callback);
371       ignore (main#toplevel#event#connect#delete 
372         (fun _ -> callback ();true));
373       self#addKeyBinding GdkKeysyms._q callback
374
375     method chooseFile ?(ok_not_exists = false) () =
376       _ok_not_exists <- ok_not_exists;
377       fileSel#fileSelectionWin#show ();
378       GtkThread.main ();
379       chosen_file
380
381     method askText ?(title = "") ?(msg = "") () =
382       let dialog = new textDialog () in
383       dialog#textDialog#set_title title;
384       dialog#textDialogLabel#set_label msg;
385       let text = ref None in
386       let return v =
387         text := v;
388         dialog#textDialog#destroy ();
389         GMain.Main.quit ()
390       in
391       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
392       connect_button dialog#textDialogCancelButton (fun _ -> return None);
393       connect_button dialog#textDialogOkButton (fun _ ->
394         let text = dialog#textDialogTextView#buffer#get_text () in
395         return (Some text));
396       dialog#textDialog#show ();
397       GtkThread.main ();
398       !text
399
400     method private updateFontSize () =
401       self#sourceView#misc#modify_font_by_name
402         (sprintf "%s %d" BuildTimeConf.script_font font_size)
403
404     method increaseFontSize () =
405       font_size <- font_size + 1;
406       self#updateFontSize ()
407
408     method decreaseFontSize () =
409       font_size <- font_size - 1;
410       self#updateFontSize ()
411
412     method resetFontSize () =
413       font_size <- default_font_size;
414       self#updateFontSize ()
415
416   end
417
418 let gui () = 
419   let g = new gui () in
420   gui_instance := Some g;
421   g
422   
423 let instance = singleton gui
424
425 let non p x = not (p x)
426
427 (* this is a shit and should be changed :-{ *)
428 let interactive_uri_choice
429   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
430   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
431   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
432   ?copy_cb ()
433   ~id uris
434 =
435   let gui = instance () in
436   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
437   if (selection_mode <> `SINGLE) &&
438     (Helm_registry.get_bool "matita.auto_disambiguation")
439   then
440     Lazy.force nonvars_uris
441   else begin
442     let dialog = gui#newUriDialog () in
443     if hide_uri_entry then
444       dialog#uriEntryHBox#misc#hide ();
445     if hide_try then
446       begin
447       dialog#uriChoiceSelectedButton#misc#hide ();
448       dialog#uriChoiceConstantsButton#misc#hide ();
449       end;
450     dialog#okLabel#set_label ok_label;  
451     dialog#uriChoiceTreeView#selection#set_mode
452       (selection_mode :> Gtk.Tags.selection_mode);
453     let model = new stringListModel dialog#uriChoiceTreeView in
454     let choices = ref None in
455     let nonvars = ref false in
456     (match copy_cb with
457     | None -> ()
458     | Some cb ->
459         dialog#copyButton#misc#show ();
460         connect_button dialog#copyButton 
461         (fun _ ->
462           match model#easy_selection () with
463           | [u] -> (cb u)
464           | _ -> ()));
465     dialog#uriChoiceDialog#set_title title;
466     dialog#uriChoiceLabel#set_text msg;
467     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
468     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
469     let return v =
470       choices := v;
471       dialog#uriChoiceDialog#destroy ();
472       GMain.Main.quit ()
473     in
474     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
475     connect_button dialog#uriChoiceConstantsButton (fun _ ->
476       return (Some (Lazy.force nonvars_uris)));
477     if ok_action = `AUTO then
478       connect_button dialog#uriChoiceAutoButton (fun _ ->
479         Helm_registry.set_bool "matita.auto_disambiguation" true;
480         return (Some (Lazy.force nonvars_uris)))
481     else
482       connect_button dialog#uriChoiceAutoButton (fun _ ->
483         match model#easy_selection () with
484         | [] -> ()
485         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
486     connect_button dialog#uriChoiceSelectedButton (fun _ ->
487       match model#easy_selection () with
488       | [] -> ()
489       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
490     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
491     dialog#uriChoiceDialog#show ();
492     GtkThread.main ();
493     (match !choices with 
494     | None -> raise MatitaTypes.Cancel
495     | Some uris -> uris)
496   end
497
498 class interpModel =
499   let cols = new GTree.column_list in
500   let id_col = cols#add Gobject.Data.string in
501   let dsc_col = cols#add Gobject.Data.string in
502   let interp_no_col = cols#add Gobject.Data.int in
503   let tree_store = GTree.tree_store cols in
504   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
505   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
506   let id_view_col = GTree.view_column ~renderer:id_renderer () in
507   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
508   fun tree_view choices ->
509     object
510       initializer
511         tree_view#set_model (Some (tree_store :> GTree.model));
512         ignore (tree_view#append_column id_view_col);
513         ignore (tree_view#append_column dsc_view_col);
514         let name_of_interp =
515           (* try to find a reasonable name for an interpretation *)
516           let idx = ref 0 in
517           fun interp ->
518             try
519               List.assoc "0" interp
520             with Not_found ->
521               incr idx; string_of_int !idx
522         in
523         tree_store#clear ();
524         let idx = ref ~-1 in
525         List.iter
526           (fun interp ->
527             incr idx;
528             let interp_row = tree_store#append () in
529             tree_store#set ~row:interp_row ~column:id_col
530               (name_of_interp interp);
531             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
532             List.iter
533               (fun (id, dsc) ->
534                 let row = tree_store#append ~parent:interp_row () in
535                 tree_store#set ~row ~column:id_col id;
536                 tree_store#set ~row ~column:dsc_col dsc;
537                 tree_store#set ~row ~column:interp_no_col !idx)
538               interp)
539           choices
540
541       method get_interp_no tree_path =
542         let iter = tree_store#get_iter tree_path in
543         tree_store#get ~row:iter ~column:interp_no_col
544     end
545
546 let interactive_interp_choice () choices =
547   let gui = instance () in
548   assert (choices <> []);
549   let dialog = gui#newInterpDialog () in
550   let model = new interpModel dialog#interpChoiceTreeView choices in
551   let interp_len = List.length (List.hd choices) in
552   dialog#interpChoiceDialog#set_title "Interpretation choice";
553   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
554   let interp_no = ref None in
555   let return _ =
556     dialog#interpChoiceDialog#destroy ();
557     GMain.Main.quit ()
558   in
559   let fail _ = interp_no := None; return () in
560   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
561   connect_button dialog#interpChoiceOkButton (fun _ ->
562     match !interp_no with None -> () | Some _ -> return ());
563   connect_button dialog#interpChoiceCancelButton fail;
564   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
565     interp_no := Some (model#get_interp_no path);
566     return ()));
567   let selection = dialog#interpChoiceTreeView#selection in
568   ignore (selection#connect#changed (fun _ ->
569     match selection#get_selected_rows with
570     | [path] ->
571         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
572         interp_no := Some (model#get_interp_no path)
573     | _ -> assert false));
574   dialog#interpChoiceDialog#show ();
575   GtkThread.main ();
576   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
577