1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 open MatitaGeneratedGui
34 exception Found of int
36 let all_disambiguation_passes = ref false
38 (* this is a shit and should be changed :-{ *)
39 let interactive_uri_choice
40 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
41 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
42 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
46 if (selection_mode <> `SINGLE) &&
47 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
51 let dialog = new uriChoiceDialog () in
52 if hide_uri_entry then
53 dialog#uriEntryHBox#misc#hide ();
56 dialog#uriChoiceSelectedButton#misc#hide ();
57 dialog#uriChoiceConstantsButton#misc#hide ();
59 dialog#okLabel#set_label ok_label;
60 dialog#uriChoiceTreeView#selection#set_mode
61 (selection_mode :> Gtk.Tags.selection_mode);
62 let model = new stringListModel dialog#uriChoiceTreeView in
63 let choices = ref None in
67 dialog#copyButton#misc#show ();
68 connect_button dialog#copyButton
70 match model#easy_selection () with
73 dialog#uriChoiceDialog#set_title title;
74 dialog#uriChoiceLabel#set_text msg;
75 List.iter model#easy_append (List.map NReference.string_of_reference uris);
76 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
79 dialog#uriChoiceDialog#destroy ();
82 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
83 connect_button dialog#uriChoiceConstantsButton (fun _ ->
85 if ok_action = `AUTO then
86 connect_button dialog#uriChoiceAutoButton (fun _ ->
87 Helm_registry.set_bool "matita.auto_disambiguation" true;
90 connect_button dialog#uriChoiceAutoButton (fun _ ->
91 match model#easy_selection () with
93 | uris -> return (Some (List.map NReference.reference_of_string uris)));
94 connect_button dialog#uriChoiceSelectedButton (fun _ ->
95 match model#easy_selection () with
97 | uris -> return (Some (List.map NReference.reference_of_string uris)));
98 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
99 dialog#uriChoiceDialog#show ();
102 | None -> raise MatitaTypes.Cancel
107 class console ~(buffer: GText.buffer) () =
109 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
110 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
111 val message_tag = buffer#create_tag []
112 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
113 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
114 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
115 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
116 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
118 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
119 method log_callback (tag: HLog.log_tag) s =
120 let s = Pcre.replace ~pat:"
\e\\[0;3.m([^
\e]+)
\e\\[0m" ~templ:"$1" s in
122 | `Debug -> self#debug (s ^ "\n")
123 | `Error -> self#error (s ^ "\n")
124 | `Message -> self#message (s ^ "\n")
125 | `Warning -> self#warning (s ^ "\n")
128 let clean_current_baseuri status =
129 LibraryClean.clean_baseuris [status#baseuri]
131 let save_moo status =
132 let script = MatitaScript.current () in
133 let baseuri = status#baseuri in
134 match script#bos, script#eos with
137 GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
139 | _ -> clean_current_baseuri status
142 let ask_unsaved parent filename =
143 MatitaGtkMisc.ask_confirmation
144 ~parent ~title:"Unsaved work!"
145 ~message:("Script <b>" ^ filename ^ "</b> is modified.!\n\n"^
146 "<i>Do you want to save the script before continuing?</i>")
149 class interpErrorModel =
150 let cols = new GTree.column_list in
151 let id_col = cols#add Gobject.Data.string in
152 let dsc_col = cols#add Gobject.Data.string in
153 let interp_no_col = cols#add Gobject.Data.caml in
154 let tree_store = GTree.tree_store cols in
155 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
156 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
157 let id_view_col = GTree.view_column ~renderer:id_renderer () in
158 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
159 fun (tree_view: GTree.view) choices ->
162 tree_view#set_model (Some (tree_store :> GTree.model));
163 ignore (tree_view#append_column id_view_col);
164 ignore (tree_view#append_column dsc_view_col);
166 let idx1 = ref ~-1 in
171 if List.length choices = 1 then
174 (let loc_row = tree_store#append () in
177 [passes,envs_and_diffs,_,_] ->
178 tree_store#set ~row:loc_row ~column:id_col
179 ("Error location " ^ string_of_int (!idx1+1) ^
180 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
182 String.concat " " (List.map string_of_int passes) ^
184 tree_store#set ~row:loc_row ~column:interp_no_col
187 tree_store#set ~row:loc_row ~column:id_col
188 ("Error location " ^ string_of_int (!idx1+1));
189 tree_store#set ~row:loc_row ~column:interp_no_col
193 let idx2 = ref ~-1 in
195 (fun passes,envs_and_diffs,_,_ ->
198 if List.length lll = 1 then
201 let msg_row = tree_store#append ?parent:loc_row () in
202 (tree_store#set ~row:msg_row ~column:id_col
203 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
204 string_of_int (!idx2+1) ^
206 String.concat " " (List.map string_of_int passes) ^
208 tree_store#set ~row:msg_row ~column:interp_no_col
209 (!idx1,Some !idx2,None);
211 let idx3 = ref ~-1 in
213 (fun (passes,env,_) ->
216 match envs_and_diffs with
218 let interp_row = tree_store#append ?parent:msg_row () in
219 tree_store#set ~row:interp_row ~column:id_col
220 ("Interpretation " ^ string_of_int (!idx3+1) ^
222 String.concat " " (List.map string_of_int passes) ^
224 tree_store#set ~row:interp_row ~column:interp_no_col
225 (!idx1,Some !idx2,Some !idx3);
232 let row = tree_store#append ?parent:interp_row () in
233 tree_store#set ~row ~column:id_col id;
234 tree_store#set ~row ~column:dsc_col dsc;
235 tree_store#set ~row ~column:interp_no_col
236 (!idx1,Some !idx2,Some !idx3)
240 if List.length lll > 1 then
242 (fun p -> tree_view#expand_row (tree_store#get_path p))
246 method get_interp_no tree_path =
247 let iter = tree_store#get_iter tree_path in
248 tree_store#get ~row:iter ~column:interp_no_col
251 exception UseLibrary;;
253 let interactive_error_interp ~all_passes
254 (source_buffer:GSourceView2.source_buffer) notify_exn offset errorll filename
256 (* hook to save a script for each disambiguation error *)
259 source_buffer#get_text ~start:source_buffer#start_iter
260 ~stop:source_buffer#end_iter () in
261 let md5 = Digest.to_hex (Digest.string text) in
263 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
264 let ch = open_out filename in
265 output_string ch text;
268 assert (List.flatten errorll <> []);
270 let remove_non_significant =
271 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
272 let annotated_errorll () =
275 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
277 if all_passes then annotated_errorll () else
278 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
279 (* We remove passes 1,2 and 5,6 *)
282 ::(3,remove_non_significant (safe_list_nth errorll 2))
283 ::(4,remove_non_significant (safe_list_nth errorll 3))
286 if List.flatten (List.map snd res) <> [] then res
288 (* all errors (if any) are not significant: we keep them *)
291 ::(3,(safe_list_nth errorll 2))
292 ::(4,(safe_list_nth errorll 3))
295 if List.flatten (List.map snd res) <> [] then
298 "All disambiguation errors are not significant. Showing them anyway." ;
304 "No errors in phases 2 and 3. Showing all errors in all phases" ;
308 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
311 | [loffset,[_,envs_and_diffs,msg,significant]] ->
312 let _,env,diff = List.hd envs_and_diffs in
314 (MultiPassDisambiguator.DisambiguationError
315 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
317 let dialog = new disambiguationErrors () in
319 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
320 let model = new interpErrorModel dialog#treeview choices in
321 dialog#disambiguationErrors#set_title "Disambiguation error";
322 dialog#disambiguationErrorsLabel#set_label
323 "Click on an error to see the corresponding message:";
324 ignore (dialog#treeview#connect#cursor_changed
327 match fst (dialog#treeview#get_cursor ()) with
330 let idx1,idx2,idx3 = model#get_interp_no tree_path in
331 let loffset,lll = List.nth choices idx1 in
332 let _,envs_and_diffs,msg,significant =
334 Some idx2 -> List.nth lll idx2
336 [],[],lazy "Multiple error messages. Please select one.",true
340 Some idx3 -> List.nth envs_and_diffs idx3
341 | None -> [],[],[] (* dymmy value, used *) in
342 let script = MatitaScript.current () in
343 let error_tag = script#error_tag in
344 source_buffer#remove_tag error_tag
345 ~start:source_buffer#start_iter
346 ~stop:source_buffer#end_iter;
348 (MultiPassDisambiguator.DisambiguationError
349 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
352 dialog#disambiguationErrors#destroy ();
355 let fail _ = return () in
356 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
357 connect_button dialog#disambiguationErrorsOkButton
360 match fst (dialog#treeview#get_cursor ()) with
363 let idx1,idx2,idx3 = model#get_interp_no tree_path in
366 Some idx2, Some idx3 ->
367 let _,lll = List.nth choices idx1 in
368 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
369 let _,_,diff = List.nth envs_and_diffs idx3 in
371 | _,_ -> assert false
380 | DisambiguateTypes.Id id ->
381 GrafiteAst.Ident_alias (id, desc)
382 | DisambiguateTypes.Symbol (symb, i)->
383 GrafiteAst.Symbol_alias (symb, i, desc)
384 | DisambiguateTypes.Num i ->
385 GrafiteAst.Number_alias (i, desc)
387 GrafiteAstPp.pp_alias alias)
392 (source_buffer#get_iter_at_mark
393 (`NAME "beginning_of_statement")) newtxt ;
396 connect_button dialog#disambiguationErrorsMoreErrors
397 (fun _ -> return () ; raise UseLibrary);
398 connect_button dialog#disambiguationErrorsCancelButton fail;
399 dialog#disambiguationErrors#show ();
404 (* creation order _is_ relevant for windows placement *)
405 let main = new mainWin () in
406 let sequents_viewer =
407 MatitaMathView.sequentsViewer_instance main#sequentsNotebook in
408 let fileSel = new fileSelectionWin () in
409 let findRepl = new findReplWin () in
410 let keyBindingBoxes = (* event boxes which should receive global key events *)
411 [ main#mainWinEventBox ]
413 let console = new console ~buffer:main#logTextView#buffer () in
415 val mutable chosen_file = None
416 val mutable _ok_not_exists = false
417 val mutable _only_directory = false
420 let s () = MatitaScript.current () in
422 List.iter (* global key bindings *)
423 (fun (key, modifiers, callback) ->
424 self#addKeyBinding key ~modifiers callback)
427 toggle_win ~check:main#showProofMenuItem proof#proofWin;
429 toggle_win ~check:main#showCheckMenuItem check#checkWin;
432 GdkKeysyms._Page_Down, [`CONTROL], main#scriptNotebook#next_page;
433 GdkKeysyms._Page_Up, [`CONTROL], main#scriptNotebook#previous_page
436 let parse_txt_file file =
437 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
438 let l_rev = ref [] in
441 l_rev := input_line ch :: !l_rev;
450 ~authors:(parse_txt_file "AUTHORS")
451 (*~comments:"comments"*)
452 ~copyright:"Copyright (C) 2005, the HELM team"
453 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
454 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
456 ~version:BuildTimeConf.version
457 ~website:"http://matita.cs.unibo.it"
460 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
461 connect_menu_item main#contentsMenuItem (fun () ->
462 if 0 = Sys.command "which gnome-help" then
464 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
466 ignore (Sys.command cmd)
468 MatitaGtkMisc.report_error ~title:"help system error"
470 "The program gnome-help is not installed\n\n"^
471 "To browse the user manal it is necessary to install "^
472 "the gnome help syste (also known as yelp)")
473 ~parent:main#toplevel ());
474 connect_menu_item main#aboutMenuItem about_dialog#present;
476 let show_find_Repl () =
477 findRepl#toplevel#misc#show ();
478 findRepl#toplevel#misc#grab_focus ()
480 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
482 let source_view = (s ())#source_view in
483 let highlight start end_ =
484 source_view#source_buffer#move_mark `INSERT ~where:start;
485 source_view#source_buffer#move_mark `SEL_BOUND ~where:end_;
486 source_view#scroll_mark_onscreen `INSERT
488 let text = findRepl#findEntry#text in
489 let iter = source_view#source_buffer#get_iter `SEL_BOUND in
490 match iter#forward_search text with
492 (match source_view#source_buffer#start_iter#forward_search text with
494 | Some (start,end_) -> highlight start end_)
495 | Some (start,end_) -> highlight start end_
498 let source_view = (s ())#source_view in
499 let text = findRepl#replaceEntry#text in
500 let ins = source_view#source_buffer#get_iter `INSERT in
501 let sel = source_view#source_buffer#get_iter `SEL_BOUND in
502 if ins#compare sel < 0 then
504 ignore(source_view#source_buffer#delete_selection ());
505 source_view#source_buffer#insert text
508 connect_button findRepl#findButton find_forward;
509 connect_button findRepl#findReplButton replace;
510 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
511 ignore(findRepl#toplevel#event#connect#delete
512 ~callback:(fun _ -> hide_find_Repl ();true));
513 connect_menu_item main#undoMenuItem
514 (fun () -> (MatitaScript.current ())#safe_undo);
516 ignore(source_view#source_buffer#connect#can_undo
517 ~callback:main#undoMenuItem#misc#set_sensitive);
518 *) main#undoMenuItem#misc#set_sensitive true;
519 connect_menu_item main#redoMenuItem
520 (fun () -> (MatitaScript.current ())#safe_redo);
522 ignore(source_view#source_buffer#connect#can_redo
523 ~callback:main#redoMenuItem#misc#set_sensitive);
524 *) main#redoMenuItem#misc#set_sensitive true;
525 connect_menu_item main#editMenu (fun () ->
526 main#copyMenuItem#misc#set_sensitive
527 (MatitaScript.current ())#canCopy;
528 main#cutMenuItem#misc#set_sensitive
529 (MatitaScript.current ())#canCut;
530 main#deleteMenuItem#misc#set_sensitive
531 (MatitaScript.current ())#canDelete;
532 main#pasteMenuItem#misc#set_sensitive
533 (MatitaScript.current ())#canPaste;
534 main#pastePatternMenuItem#misc#set_sensitive
535 (MatitaScript.current ())#canPastePattern);
536 connect_menu_item main#copyMenuItem
537 (fun () -> (MatitaScript.current ())#copy ());
538 connect_menu_item main#cutMenuItem
539 (fun () -> (MatitaScript.current ())#cut ());
540 connect_menu_item main#deleteMenuItem
541 (fun () -> (MatitaScript.current ())#delete ());
542 connect_menu_item main#pasteMenuItem
543 (fun () -> (MatitaScript.current ())#paste ());
544 connect_menu_item main#pastePatternMenuItem
545 (fun () -> (MatitaScript.current ())#pastePattern ());
546 connect_menu_item main#selectAllMenuItem (fun () ->
547 let source_view = (s ())#source_view in
548 source_view#source_buffer#move_mark `INSERT source_view#source_buffer#start_iter;
549 source_view#source_buffer#move_mark `SEL_BOUND source_view#source_buffer#end_iter);
550 connect_menu_item main#findReplMenuItem show_find_Repl;
551 connect_menu_item main#externalEditorMenuItem self#externalEditor;
552 connect_menu_item main#ligatureButton
553 (fun () -> (MatitaScript.current ())#nextSimilarSymbol);
554 ignore (findRepl#findEntry#connect#activate find_forward);
555 (* interface lockers *)
557 let source_view = (s ())#source_view in
558 main#buttonsToolbar#misc#set_sensitive false;
559 main#scriptMenu#misc#set_sensitive false;
560 source_view#set_editable false
563 let source_view = (s ())#source_view in
564 main#buttonsToolbar#misc#set_sensitive true;
565 main#scriptMenu#misc#set_sensitive true;
566 source_view#set_editable true;
567 (*The next line seems sufficient to avoid some unknown race condition *)
568 GtkThread.sync (fun () -> ()) ()
570 let worker_thread = ref None in
571 let notify_exn (source_view : GSourceView2.source_view) exn =
572 let floc, msg = MatitaExcPp.to_string exn in
577 let (x, y) = HExtlib.loc_of_floc floc in
578 let script = MatitaScript.current () in
579 let locked_mark = script#locked_mark in
580 let error_tag = script#error_tag in
582 (source_view#source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
583 let x' = baseoffset + x in
584 let y' = baseoffset + y in
585 let x_iter = source_view#source_buffer#get_iter (`OFFSET x') in
586 let y_iter = source_view#source_buffer#get_iter (`OFFSET y') in
587 source_view#source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
589 id := Some (source_view#source_buffer#connect#changed ~callback:(fun () ->
590 source_view#source_buffer#remove_tag error_tag
591 ~start:source_view#source_buffer#start_iter
592 ~stop:source_view#source_buffer#end_iter;
594 | None -> assert false (* a race condition occurred *)
596 source_view#source_buffer#misc#disconnect id));
597 source_view#source_buffer#place_cursor
598 (source_view#source_buffer#get_iter (`OFFSET x'));
601 let locker f script =
602 let source_view = script#source_view in
606 let saved_use_library= !MultiPassDisambiguator.use_library in
608 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
610 MultiPassDisambiguator.use_library := saved_use_library;
613 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
615 interactive_error_interp
616 ~all_passes:!all_disambiguation_passes source_view#source_buffer
617 (notify_exn source_view) offset errorll (s())#filename
620 MultiPassDisambiguator.use_library := true;
623 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
624 interactive_error_interp ~all_passes:true source_view#source_buffer
625 (notify_exn source_view) offset errorll (s())#filename
627 notify_exn source_view exc);
628 | exc -> notify_exn source_view exc);
629 MultiPassDisambiguator.use_library := saved_use_library;
632 (try notify_exn source_view exc
633 with Sys.Break as e -> notify_exn source_view e);
637 worker_thread := Some (Thread.create thread_main ())
640 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
641 let interrupt = ref None in
642 let old_callback = ref (function _ -> ()) in
643 let force_interrupt n =
644 (* This function is called just before the thread's timeslice ends *)
646 if Some(Thread.id(Thread.self())) = !interrupt then
647 (interrupt := None; raise Sys.Break) in
649 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
650 Sys.Signal_handle f -> old_callback := f
652 | Sys.Signal_default -> assert false
655 match !worker_thread with
657 | Some t -> interrupt := Some (Thread.id t) in
658 let keep_focus f (script: MatitaScript.script) =
660 f script; script#source_view#misc#grab_focus ()
662 exc -> script#source_view#misc#grab_focus (); raise exc in
664 (* file selection win *)
665 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
666 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
669 fileSel#fileSelectionWin#misc#hide ();
674 let fname = fileSel#fileSelectionWin#filename in
675 if Sys.file_exists fname then
677 if HExtlib.is_regular fname && not (_only_directory) then
679 else if _only_directory && HExtlib.is_dir fname then
684 if _ok_not_exists then
687 | `CANCEL -> return None
689 | `DELETE_EVENT -> return None));
691 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
693 let adj = main#logScrolledWin#vadjustment in
694 ignore (adj#connect#changed
695 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
696 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
697 (* natural deduction palette *)
698 main#tacticsButtonsHandlebox#misc#hide ();
699 MatitaGtkMisc.toggle_callback
701 if b then main#tacticsButtonsHandlebox#misc#show ()
702 else main#tacticsButtonsHandlebox#misc#hide ())
703 ~check:main#menuitemPalette;
704 connect_button main#butImpl_intro
705 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⇒#i […] (…));\n");
706 connect_button main#butAnd_intro
707 (fun () -> (s ())#source_view#source_buffer#insert
708 "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
709 connect_button main#butOr_intro_left
710 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_l (…));\n");
711 connect_button main#butOr_intro_right
712 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_r (…));\n");
713 connect_button main#butNot_intro
714 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (¬#i […] (…));\n");
715 connect_button main#butTop_intro
716 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊤#i);\n");
717 connect_button main#butImpl_elim
718 (fun () -> (s ())#source_view#source_buffer#insert
719 "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
720 connect_button main#butAnd_elim_left
721 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_l (…));\n");
722 connect_button main#butAnd_elim_right
723 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_r (…));\n");
724 connect_button main#butOr_elim
725 (fun () -> (s ())#source_view#source_buffer#insert
726 "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
727 connect_button main#butNot_elim
728 (fun () -> (s ())#source_view#source_buffer#insert
729 "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
730 connect_button main#butBot_elim
731 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊥#e (…));\n");
732 connect_button main#butRAA
733 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (RAA […] (…));\n");
734 connect_button main#butUseLemma
735 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (lem #premises name …);\n");
736 connect_button main#butDischarge
737 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (discharge […]);\n");
739 connect_button main#butForall_intro
740 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#i {…} (…));\n");
741 connect_button main#butForall_elim
742 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#e {…} (…));\n");
743 connect_button main#butExists_intro
744 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∃#i {…} (…));\n");
745 connect_button main#butExists_elim
746 (fun () -> (s ())#source_view#source_buffer#insert
747 "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
750 let module Hr = Helm_registry in
751 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
753 | true -> main#toplevel#fullscreen ()
754 | false -> main#toplevel#unfullscreen ());
755 main#fullscreenMenuItem#set_active false;
756 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
757 ~callback:(function b ->
759 let _status = Interpretations.toggle_active_interpretations s#status b
761 assert false (* MATITA 1.0 ???
762 s#set_grafite_status status*)
764 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
765 ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
766 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
767 ~callback:(fun enabled ->
768 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
769 main#unicodeAsTexMenuItem#set_active
770 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
772 HLog.set_log_callback self#console#log_callback;
773 GtkSignal.user_handler :=
775 | MatitaScript.ActionCancelled s -> HLog.error s
777 if not (Helm_registry.get_bool "matita.debug") then
778 (* MatitaScript.current is problably wrong, but what else
780 notify_exn (MatitaScript.current ())#source_view exn
784 match self#chooseFile () with
785 | Some f -> self#loadScript f
787 with MatitaTypes.Cancel -> ()
790 let source_view = (s ())#source_view in
791 source_view#source_buffer#place_cursor
792 (source_view#source_buffer#get_iter_at_mark (`NAME "locked")) in
793 let advance (script: MatitaScript.script) = script#advance (); cursor () in
794 let retract (script: MatitaScript.script) = script#retract (); cursor () in
795 let top (script: MatitaScript.script) = script#goto `Top (); cursor () in
796 let bottom (script: MatitaScript.script) = script#goto `Bottom (); cursor () in
797 let jump (script: MatitaScript.script) = script#goto `Cursor (); cursor () in
798 let advance () = locker (keep_focus advance) (MatitaScript.current ()) in
799 let retract () = locker (keep_focus retract) (MatitaScript.current ()) in
800 let top () = locker (keep_focus top) (MatitaScript.current ()) in
801 let bottom () = locker (keep_focus bottom) (MatitaScript.current ()) in
802 let jump () = locker (keep_focus jump) (MatitaScript.current ()) in
804 self#setQuitCallback (fun () ->
805 let cancel = ref false in
806 MatitaScript.iter_scripts
809 if not (self#closeScript0 script) then
813 connect_button main#scriptAdvanceButton advance;
814 connect_button main#scriptRetractButton retract;
815 connect_button main#scriptTopButton top;
816 connect_button main#scriptBottomButton bottom;
817 connect_button main#scriptJumpButton jump;
818 connect_button main#scriptAbortButton kill_worker;
819 connect_menu_item main#scriptAdvanceMenuItem advance;
820 connect_menu_item main#scriptRetractMenuItem retract;
821 connect_menu_item main#scriptTopMenuItem top;
822 connect_menu_item main#scriptBottomMenuItem bottom;
823 connect_menu_item main#scriptJumpMenuItem jump;
824 connect_menu_item main#openMenuItem loadScript;
825 connect_menu_item main#saveMenuItem
826 (fun () -> self#saveScript (MatitaScript.current ()));
827 connect_menu_item main#saveAsMenuItem
828 (fun () -> self#saveAsScript (MatitaScript.current ()));
829 connect_menu_item main#newMenuItem self#newScript;
830 connect_menu_item main#closeMenuItem self#closeCurrentScript;
831 connect_menu_item main#showCoercionsGraphMenuItem
832 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Coercions)));
833 connect_menu_item main#showHintsDbMenuItem
834 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Hints)));
835 connect_menu_item main#showTermGrammarMenuItem
836 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Grammar)));
837 connect_menu_item main#showUnicodeTable
838 (fun _ -> MatitaMathView.cicBrowser (Some (`About `TeX)));
840 main#debugMenu#misc#hide ();
842 main#hintNotebook#misc#hide ();
844 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
845 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
846 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
848 (* main win dimension *)
849 let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
850 let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
851 (* hack for xinerama, no proper support of monitors from lablgtk *)
852 let width = if width > 1600 then width / 2 else width in
853 let height = if height > 1200 then height / 2 else height in
854 let main_w = width * 90 / 100 in
855 let main_h = height * 80 / 100 in
856 let script_w = main_w * 6 / 10 in
857 main#toplevel#resize ~width:main_w ~height:main_h;
858 main#hpaneScriptSequent#set_position script_w;
859 (* math view handling *)
860 connect_menu_item main#newCicBrowserMenuItem (fun () ->
861 ignore(MatitaMathView.cicBrowser None));
862 connect_menu_item main#increaseFontSizeMenuItem
863 MatitaMisc.increase_font_size;
864 connect_menu_item main#decreaseFontSizeMenuItem
865 MatitaMisc.decrease_font_size;
866 connect_menu_item main#normalFontSizeMenuItem
867 MatitaMisc.reset_font_size;
868 ignore (main#scriptNotebook#connect#switch_page
870 let script = MatitaScript.at_page page in
872 main#saveMenuItem#misc#set_sensitive script#has_name))
874 method private externalEditor () =
875 let script = MatitaScript.current () in
876 let source_view = script#source_view in
877 let cmd = Helm_registry.get "matita.external_editor" in
878 (* ZACK uncomment to enable interactive ask of external editor command *)
881 "External editor command:
882 %f will be substitute for the script name,
883 %p for the cursor position in bytes,
884 %l for the execution point in bytes."
886 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
887 ~default:(Helm_registry.get "matita.external_editor") ()
889 let fname = script#filename in
891 source_view#source_buffer#start_iter#get_slice
892 ~stop:(source_view#source_buffer#get_iter_at_mark mark)
894 let locked = `MARK script#locked_mark in
895 let string_pos mark = string_of_int (String.length (slice mark)) in
896 let cursor_pos = string_pos `INSERT in
897 let locked_pos = string_pos locked in
899 Pcre.replace ~pat:"%f" ~templ:fname
900 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
901 (Pcre.replace ~pat:"%l" ~templ:locked_pos
904 let locked_before = slice locked in
905 let locked_offset = (source_view#source_buffer#get_iter_at_mark locked)#offset in
906 ignore (Unix.system cmd);
907 source_view#source_buffer#set_text (HExtlib.input_file fname);
908 let locked_iter = source_view#source_buffer#get_iter (`OFFSET locked_offset) in
909 source_view#source_buffer#move_mark locked locked_iter;
910 source_view#source_buffer#apply_tag script#locked_tag
911 ~start:source_view#source_buffer#start_iter ~stop:locked_iter;
912 let locked_after = slice locked in
916 for i = 0 to String.length locked_before - 1 do
917 if locked_before.[i] <> locked_after.[i] then begin
918 source_view#source_buffer#place_cursor
919 ~where:(source_view#source_buffer#get_iter (`LINEBYTE (!line, !col)));
920 script#goto `Cursor ();
922 end else if locked_before.[i] = '\n' then begin
929 | Invalid_argument _ -> script#goto `Bottom ()
931 method private saveAsScript script =
932 match self#chooseFile ~ok_not_exists:true () with
935 script#assignFileName (Some f);
936 script#saveToFile ();
937 console#message ("'"^f^"' saved.\n");
941 method private saveScript script =
942 if script#has_name then
943 (script#saveToFile ();
944 console#message ("'"^script#filename^"' saved.\n"))
945 else self#saveAsScript script
947 (* returns false if closure is aborted by the user *)
948 method private closeScript0 script =
949 if script#source_view#buffer#modified then
951 ask_unsaved main#toplevel (Filename.basename script#filename)
954 self#saveScript script;
955 save_moo script#status;
960 (save_moo script#status; true)
962 method private closeScript page script =
963 if self#closeScript0 script then
965 MatitaScript.destroy page;
966 ignore (main#scriptNotebook#remove_page page)
969 method private closeCurrentScript () =
970 let page = main#scriptNotebook#current_page in
971 let script = MatitaScript.at_page page in
972 self#closeScript page script
974 method newScript () =
975 let scrolledWindow = GBin.scrolled_window () in
976 let hbox = GPack.hbox () in
977 let tab_label = GMisc.label ~text:"foo" ~packing:hbox#pack () in
979 GMisc.label ~text:"" ~packing:(hbox#pack ~expand:true ~fill:true) () in
981 GButton.button ~relief:`NONE ~packing:hbox#pack () in
982 let image = GMisc.image ~stock:`CLOSE ~icon_size:`MENU () in
983 closebutton#set_image image#coerce;
984 let script = MatitaScript.script ~parent:scrolledWindow ~tab_label () in
985 ignore (main#scriptNotebook#prepend_page ~tab_label:hbox#coerce
986 scrolledWindow#coerce);
987 ignore (closebutton#connect#clicked (fun () ->
989 (main#scriptNotebook#page_num scrolledWindow#coerce) script));
990 main#scriptNotebook#goto_page 0;
991 sequents_viewer#reset;
992 sequents_viewer#load_logo;
993 let browser_observer _ = MatitaMathView.refresh_all_browsers () in
994 let sequents_observer status =
995 sequents_viewer#reset;
996 match status#ng_mode with
998 sequents_viewer#nload_sequents status;
1001 Continuationals.Stack.find_goal status#stack
1003 sequents_viewer#goto_sequent status goal
1004 with Failure _ -> ());
1005 | `CommandMode -> sequents_viewer#load_logo
1007 script#addObserver sequents_observer;
1008 script#addObserver browser_observer
1010 method loadScript file =
1011 let page = main#scriptNotebook#current_page in
1012 let script = MatitaScript.at_page page in
1013 if script#source_view#buffer#modified || script#has_name then
1015 let script = MatitaScript.current () in
1016 let source_view = script#source_view in
1018 script#assignFileName (Some file);
1019 let file = script#filename in
1021 if Sys.file_exists file then file
1022 else BuildTimeConf.script_template
1024 source_view#source_buffer#begin_not_undoable_action ();
1025 script#loadFromFile content;
1026 source_view#source_buffer#end_not_undoable_action ();
1027 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1028 source_view#buffer#place_cursor source_view#buffer#start_iter;
1029 console#message ("'"^file^"' loaded.");
1030 self#_enableSaveTo file
1032 method private _enableSaveTo file =
1033 self#main#saveMenuItem#misc#set_sensitive true
1035 method private console = console
1036 method private fileSel = fileSel
1037 method private findRepl = findRepl
1040 method private addKeyBinding key ?modifiers callback =
1041 (* List.iter (fun evbox -> add_key_binding key callback evbox) *)
1042 List.iter (fun evbox -> connect_key evbox#event key ?modifiers callback)
1045 method private setQuitCallback callback =
1046 connect_menu_item main#quitMenuItem callback;
1047 ignore (main#toplevel#event#connect#delete
1048 (fun _ -> callback ();true));
1049 self#addKeyBinding GdkKeysyms._q callback
1051 method private chooseFile ?(ok_not_exists = false) () =
1052 _ok_not_exists <- ok_not_exists;
1053 _only_directory <- false;
1054 fileSel#fileSelectionWin#show ();
1058 method private chooseDir ?(ok_not_exists = false) () =
1059 _ok_not_exists <- ok_not_exists;
1060 _only_directory <- true;
1061 fileSel#fileSelectionWin#show ();
1063 (* we should check that this is a directory *)
1069 let g = new gui () in
1070 let rg = (g :> MatitaGuiTypes.gui) in
1071 MatitaMisc.set_gui rg;
1075 let instance = singleton gui
1077 let non p x = not (p x)
1080 let cols = new GTree.column_list in
1081 let id_col = cols#add Gobject.Data.string in
1082 let dsc_col = cols#add Gobject.Data.string in
1083 let interp_no_col = cols#add Gobject.Data.int in
1084 let tree_store = GTree.tree_store cols in
1085 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1086 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1087 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1088 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1089 fun tree_view choices ->
1092 tree_view#set_model (Some (tree_store :> GTree.model));
1093 ignore (tree_view#append_column id_view_col);
1094 ignore (tree_view#append_column dsc_view_col);
1095 let name_of_interp =
1096 (* try to find a reasonable name for an interpretation *)
1100 List.assoc "0" interp
1102 incr idx; string_of_int !idx
1104 tree_store#clear ();
1105 let idx = ref ~-1 in
1109 let interp_row = tree_store#append () in
1110 tree_store#set ~row:interp_row ~column:id_col
1111 (name_of_interp interp);
1112 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1115 let row = tree_store#append ~parent:interp_row () in
1116 tree_store#set ~row ~column:id_col id;
1117 tree_store#set ~row ~column:dsc_col dsc;
1118 tree_store#set ~row ~column:interp_no_col !idx)
1122 method get_interp_no tree_path =
1123 let iter = tree_store#get_iter tree_path in
1124 tree_store#get ~row:iter ~column:interp_no_col
1128 let interactive_string_choice
1129 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1131 let dialog = new uriChoiceDialog () in
1132 dialog#uriEntryHBox#misc#hide ();
1133 dialog#uriChoiceSelectedButton#misc#hide ();
1134 dialog#uriChoiceAutoButton#misc#hide ();
1135 dialog#uriChoiceConstantsButton#misc#hide ();
1136 dialog#uriChoiceTreeView#selection#set_mode
1137 (`SINGLE :> Gtk.Tags.selection_mode);
1138 let model = new stringListModel dialog#uriChoiceTreeView in
1139 let choices = ref None in
1140 dialog#uriChoiceDialog#set_title title;
1141 let hack_len = MatitaGtkMisc.utf8_string_length text in
1142 let rec colorize acc_len = function
1144 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1145 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1147 let start, stop = HExtlib.loc_of_floc he in
1148 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1149 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1150 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1151 escape_pango_markup str1 ^ "<b>" ^
1152 escape_pango_markup str2 ^ "</b>" ^
1155 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1156 Printf.eprintf "(%d,%d)" start stop) locs; *)
1160 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1163 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1164 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1165 Printf.eprintf "(%d,%d)" start stop) locs;
1166 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1167 dialog#uriChoiceLabel#set_use_markup true;
1168 let txt = colorize 0 locs in
1169 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1170 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1172 dialog#uriChoiceLabel#set_label txt;
1173 List.iter model#easy_append uris;
1176 dialog#uriChoiceDialog#destroy ();
1179 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1180 connect_button dialog#uriChoiceForwardButton (fun _ ->
1181 match model#easy_selection () with
1183 | uris -> return (Some uris));
1184 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1185 dialog#uriChoiceDialog#show ();
1187 (match !choices with
1188 | None -> raise MatitaTypes.Cancel
1189 | Some uris -> uris)
1191 let interactive_interp_choice () text prefix_len choices =
1192 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1193 let filter_choices filter =
1194 let rec is_compatible filter =
1197 | ([],_,_)::tl -> is_compatible filter tl
1198 | (loc::tlloc,id,dsc)::tl ->
1200 if List.assoc (loc,id) filter = dsc then
1201 is_compatible filter ((tlloc,id,dsc)::tl)
1207 List.filter (fun (_,interp) -> is_compatible filter interp)
1209 let rec get_choices loc id =
1214 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1216 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1218 let example_interp =
1222 let ask_user id locs choices =
1223 interactive_string_choice
1225 ~title:"Ambiguous input"
1226 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1228 let rec classify ids filter partial_interpretations =
1230 [] -> List.map fst partial_interpretations
1231 | ([],_,_)::tl -> classify tl filter partial_interpretations
1232 | (loc::tlloc,id,dsc)::tl ->
1233 let choices = get_choices loc id partial_interpretations in
1236 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1239 match ask_user id [loc] choices with
1243 let filter = ((loc,id),chosen_dsc)::filter in
1244 let compatible_interps = filter_choices filter partial_interpretations in
1245 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1247 let enumerated_choices =
1248 let idx = ref ~-1 in
1249 List.map (fun interp -> incr idx; !idx,interp) choices
1251 classify example_interp [] enumerated_choices
1254 (* disambiguator callbacks *)
1255 Disambiguate.set_choose_uris_callback
1256 (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1257 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1258 Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1259 (* gtk initialization *)
1260 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1261 ignore (GMain.Main.init ())