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