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 let all_disambiguation_passes = ref false
36 (* this is a shit and should be changed :-{ *)
37 let interactive_uri_choice
38 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
39 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
40 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
44 if (selection_mode <> `SINGLE) &&
45 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
49 let dialog = new uriChoiceDialog () in
50 if hide_uri_entry then
51 dialog#uriEntryHBox#misc#hide ();
54 dialog#uriChoiceSelectedButton#misc#hide ();
55 dialog#uriChoiceConstantsButton#misc#hide ();
57 dialog#okLabel#set_label ok_label;
58 dialog#uriChoiceTreeView#selection#set_mode
59 (selection_mode :> Gtk.Tags.selection_mode);
60 let model = new stringListModel dialog#uriChoiceTreeView in
61 let choices = ref None in
65 dialog#copyButton#misc#show ();
66 connect_button dialog#copyButton
68 match model#easy_selection () with
71 dialog#uriChoiceDialog#set_title title;
72 dialog#uriChoiceLabel#set_text msg;
73 List.iter model#easy_append (List.map NReference.string_of_reference uris);
74 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
77 dialog#uriChoiceDialog#destroy ();
80 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
81 connect_button dialog#uriChoiceConstantsButton (fun _ ->
83 if ok_action = `AUTO then
84 connect_button dialog#uriChoiceAutoButton (fun _ ->
85 Helm_registry.set_bool "matita.auto_disambiguation" true;
88 connect_button dialog#uriChoiceAutoButton (fun _ ->
89 match model#easy_selection () with
91 | uris -> return (Some (List.map NReference.reference_of_string uris)));
92 connect_button dialog#uriChoiceSelectedButton (fun _ ->
93 match model#easy_selection () with
95 | uris -> return (Some (List.map NReference.reference_of_string uris)));
96 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
97 dialog#uriChoiceDialog#show ();
98 (* CSC: old Gtk2 code. Use #run instead. Look for similar code handling
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_moo0 ~do_clean script status =
132 let baseuri = status#baseuri in
133 match script#bos, script#eos with
136 GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
138 | _ -> if do_clean then clean_current_baseuri status
141 let save_moo status =
142 let script = MatitaScript.current () in
143 save_moo0 ~do_clean:true script status
146 let ask_unsaved parent filename =
147 MatitaGtkMisc.ask_confirmation
148 ~parent ~title:"Unsaved work!"
149 ~message:("Script <b>" ^ filename ^ "</b> is modified.!\n\n"^
150 "<i>Do you want to save the script before continuing?</i>")
153 class interpErrorModel =
154 let cols = new GTree.column_list in
155 let id_col = cols#add Gobject.Data.string in
156 let dsc_col = cols#add Gobject.Data.string in
157 let interp_no_col = cols#add Gobject.Data.caml in
158 let tree_store = GTree.tree_store cols in
159 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
160 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
161 let id_view_col = GTree.view_column ~renderer:id_renderer () in
162 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
163 fun (tree_view: GTree.view) choices ->
166 tree_view#set_model (Some (tree_store :> GTree.model));
167 ignore (tree_view#append_column id_view_col);
168 ignore (tree_view#append_column dsc_view_col);
170 let idx1 = ref ~-1 in
175 if List.length choices = 1 then
178 (let loc_row = tree_store#append () in
181 [passes,_envs_and_diffs,_,_] ->
182 tree_store#set ~row:loc_row ~column:id_col
183 ("Error location " ^ string_of_int (!idx1+1) ^
184 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
186 String.concat " " (List.map string_of_int passes) ^
188 tree_store#set ~row:loc_row ~column:interp_no_col
191 tree_store#set ~row:loc_row ~column:id_col
192 ("Error location " ^ string_of_int (!idx1+1));
193 tree_store#set ~row:loc_row ~column:interp_no_col
197 let idx2 = ref ~-1 in
199 (fun (passes,envs_and_diffs,_,_) ->
202 if List.length lll = 1 then
205 let msg_row = tree_store#append ?parent:loc_row () in
206 (tree_store#set ~row:msg_row ~column:id_col
207 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
208 string_of_int (!idx2+1) ^
210 String.concat " " (List.map string_of_int passes) ^
212 tree_store#set ~row:msg_row ~column:interp_no_col
213 (!idx1,Some !idx2,None);
215 let idx3 = ref ~-1 in
217 (fun (passes,env,_) ->
220 match envs_and_diffs with
222 let interp_row = tree_store#append ?parent:msg_row () in
223 tree_store#set ~row:interp_row ~column:id_col
224 ("Interpretation " ^ string_of_int (!idx3+1) ^
226 String.concat " " (List.map string_of_int passes) ^
228 tree_store#set ~row:interp_row ~column:interp_no_col
229 (!idx1,Some !idx2,Some !idx3);
236 let row = tree_store#append ?parent:interp_row () in
237 tree_store#set ~row ~column:id_col id;
238 tree_store#set ~row ~column:dsc_col dsc;
239 tree_store#set ~row ~column:interp_no_col
240 (!idx1,Some !idx2,Some !idx3)
244 if List.length lll > 1 then
246 (fun p -> tree_view#expand_row (tree_store#get_path p))
250 method get_interp_no tree_path =
251 let iter = tree_store#get_iter tree_path in
252 tree_store#get ~row:iter ~column:interp_no_col
255 exception UseLibrary;;
257 let interactive_error_interp ~all_passes
258 (source_buffer:GSourceView3.source_buffer) notify_exn offset errorll filename
260 (* hook to save a script for each disambiguation error *)
263 source_buffer#get_text ~start:source_buffer#start_iter
264 ~stop:source_buffer#end_iter () in
265 let md5 = Digest.to_hex (Digest.string text) in
267 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
268 let ch = open_out filename in
269 output_string ch text;
272 assert (List.flatten errorll <> []);
274 let remove_non_significant =
275 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
276 let annotated_errorll () =
279 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
281 if all_passes then annotated_errorll () else
282 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
283 (* We remove passes 1,2 and 5,6 *)
286 ::(3,remove_non_significant (safe_list_nth errorll 2))
287 ::(4,remove_non_significant (safe_list_nth errorll 3))
290 if List.flatten (List.map snd res) <> [] then res
292 (* all errors (if any) are not significant: we keep them *)
295 ::(3,(safe_list_nth errorll 2))
296 ::(4,(safe_list_nth errorll 3))
299 if List.flatten (List.map snd res) <> [] then
302 "All disambiguation errors are not significant. Showing them anyway." ;
308 "No errors in phases 2 and 3. Showing all errors in all phases" ;
312 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
315 | [loffset,[_,envs_and_diffs,msg,significant]] ->
316 let _,env,diff = List.hd envs_and_diffs in
318 (MultiPassDisambiguator.DisambiguationError
319 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
321 GtkThread.sync (fun _ ->
322 let dialog = new disambiguationErrors () in
323 dialog#toplevel#add_button "Fix this interpretation" `OK;
324 dialog#toplevel#add_button "Close" `DELETE_EVENT;
325 if not all_passes then
326 dialog#toplevel#add_button "More errors" `HELP; (* HELP means MORE *)
327 let model = new interpErrorModel dialog#treeview choices in
328 dialog#disambiguationErrors#set_title "Disambiguation error";
329 dialog#disambiguationErrorsLabel#set_label
330 "Click on an error to see the corresponding message:";
331 ignore (dialog#treeview#connect#cursor_changed
334 match fst (dialog#treeview#get_cursor ()) with
337 let idx1,idx2,idx3 = model#get_interp_no tree_path in
338 let loffset,lll = List.nth choices idx1 in
339 let _,envs_and_diffs,msg,significant =
341 Some idx2 -> List.nth lll idx2
343 [],[],lazy "Multiple error messages. Please select one.",true
347 Some idx3 -> List.nth envs_and_diffs idx3
348 | None -> [],[],[] (* dymmy value, used *) in
349 let script = MatitaScript.current () in
350 let error_tag = script#error_tag in
351 source_buffer#remove_tag error_tag
352 ~start:source_buffer#start_iter
353 ~stop:source_buffer#end_iter;
355 (MultiPassDisambiguator.DisambiguationError
356 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
358 (match GtkThread.sync dialog#toplevel#run () with
361 match fst (dialog#treeview#get_cursor ()) with
364 let idx1,idx2,idx3 = model#get_interp_no tree_path in
367 Some idx2, Some idx3 ->
368 let _,lll = List.nth choices idx1 in
369 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
370 let _,_,diff = List.nth envs_and_diffs idx3 in
372 | _,_ -> assert false
381 | DisambiguateTypes.Id id ->
382 GrafiteAst.Ident_alias (id, desc)
383 | DisambiguateTypes.Symbol (symb, i)->
384 GrafiteAst.Symbol_alias (symb, i, desc)
385 | DisambiguateTypes.Num i ->
386 GrafiteAst.Number_alias (i, desc)
388 GrafiteAstPp.pp_alias alias)
393 (source_buffer#get_iter_at_mark
394 (`NAME "beginning_of_statement")) newtxt
395 | `HELP (* HELP MEANS MORE *) ->
396 dialog#toplevel#destroy () ;
398 | `DELETE_EVENT -> ()
399 | _ -> assert false) ;
400 dialog#toplevel#destroy ()
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 findRepl = new findReplWin () in
409 let keyBindingBoxes = (* event boxes which should receive global key events *)
410 [ main#mainWinEventBox ]
412 let console = new console ~buffer:main#logTextView#buffer () in
414 val mutable chosen_file = None
415 val mutable _ok_not_exists = false
416 val mutable _only_directory = false
417 val mutable current_page = -1
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#event#connect#delete (fun _ -> true));
461 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
462 connect_menu_item main#contentsMenuItem (fun () ->
463 if 0 = Sys.command "which gnome-help" then
465 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
467 ignore (Sys.command cmd)
469 MatitaGtkMisc.report_error ~title:"help system error"
471 "The program gnome-help is not installed\n\n"^
472 "To browse the user manal it is necessary to install "^
473 "the gnome help syste (also known as yelp)")
474 ~parent:main#toplevel ());
475 connect_menu_item main#aboutMenuItem about_dialog#present;
477 let show_find_Repl () =
478 findRepl#toplevel#misc#show ();
479 findRepl#toplevel#misc#grab_focus ()
481 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
483 let source_view = (s ())#source_view in
484 let highlight start end_ =
485 source_view#source_buffer#move_mark `INSERT ~where:start;
486 source_view#source_buffer#move_mark `SEL_BOUND ~where:end_;
487 source_view#scroll_mark_onscreen `INSERT
489 let text = findRepl#findEntry#text in
490 let iter = source_view#source_buffer#get_iter `SEL_BOUND in
491 match iter#forward_search text with
493 (match source_view#source_buffer#start_iter#forward_search text with
495 | Some (start,end_) -> highlight start end_)
496 | Some (start,end_) -> highlight start end_
499 let source_view = (s ())#source_view in
500 let text = findRepl#replaceEntry#text in
501 let ins = source_view#source_buffer#get_iter `INSERT in
502 let sel = source_view#source_buffer#get_iter `SEL_BOUND in
503 if ins#compare sel < 0 then
505 ignore(source_view#source_buffer#delete_selection ());
506 source_view#source_buffer#insert text
509 connect_button findRepl#findButton find_forward;
510 connect_button findRepl#findReplButton replace;
511 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
512 ignore(findRepl#toplevel#event#connect#delete
513 ~callback:(fun _ -> hide_find_Repl ();true));
514 connect_menu_item main#undoMenuItem
515 (fun () -> (MatitaScript.current ())#safe_undo);
516 main#undoMenuItem#misc#set_sensitive false;
517 connect_menu_item main#redoMenuItem
518 (fun () -> (MatitaScript.current ())#safe_redo);
519 main#redoMenuItem#misc#set_sensitive false;
520 connect_menu_item main#editMenu (fun () ->
521 main#copyMenuItem#misc#set_sensitive
522 (MatitaScript.current ())#canCopy;
523 main#cutMenuItem#misc#set_sensitive
524 (MatitaScript.current ())#canCut;
525 main#deleteMenuItem#misc#set_sensitive
526 (MatitaScript.current ())#canDelete;
527 main#pasteMenuItem#misc#set_sensitive
528 (MatitaScript.current ())#canPaste;
529 main#pastePatternMenuItem#misc#set_sensitive
530 (MatitaScript.current ())#canPastePattern);
531 connect_menu_item main#copyMenuItem
532 (fun () -> (MatitaScript.current ())#copy ());
533 connect_menu_item main#cutMenuItem
534 (fun () -> (MatitaScript.current ())#cut ());
535 connect_menu_item main#deleteMenuItem
536 (fun () -> (MatitaScript.current ())#delete ());
537 connect_menu_item main#pasteMenuItem
538 (fun () -> (MatitaScript.current ())#paste ());
539 connect_menu_item main#pastePatternMenuItem
540 (fun () -> (MatitaScript.current ())#pastePattern ());
541 connect_menu_item main#selectAllMenuItem (fun () ->
542 let source_view = (s ())#source_view in
543 source_view#source_buffer#move_mark `INSERT source_view#source_buffer#start_iter;
544 source_view#source_buffer#move_mark `SEL_BOUND source_view#source_buffer#end_iter);
545 connect_menu_item main#findReplMenuItem show_find_Repl;
546 connect_menu_item main#externalEditorMenuItem self#externalEditor;
547 connect_menu_item main#ligatureButton
548 (fun () -> (MatitaScript.current ())#nextSimilarSymbol);
549 ignore (findRepl#findEntry#connect#activate find_forward);
550 (* interface lockers *)
552 let source_view = (s ())#source_view in
553 main#buttonsToolbar#misc#set_sensitive false;
554 main#scriptMenu#misc#set_sensitive false;
555 source_view#set_editable false
558 let source_view = (s ())#source_view in
559 main#buttonsToolbar#misc#set_sensitive true;
560 main#scriptMenu#misc#set_sensitive true;
561 source_view#set_editable true
563 let worker_thread = ref None in
564 let notify_exn (source_view : GSourceView3.source_view) exn =
565 let floc, msg = MatitaExcPp.to_string exn in
570 let (x, y) = HExtlib.loc_of_floc floc in
571 let script = MatitaScript.current () in
572 let locked_mark = script#locked_mark in
573 let error_tag = script#error_tag in
575 (source_view#source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
576 let x' = baseoffset + x in
577 let y' = baseoffset + y in
578 let x_iter = source_view#source_buffer#get_iter (`OFFSET x') in
579 let y_iter = source_view#source_buffer#get_iter (`OFFSET y') in
580 source_view#source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
582 id := Some (source_view#source_buffer#connect#changed ~callback:(fun () ->
583 source_view#source_buffer#remove_tag error_tag
584 ~start:source_view#source_buffer#start_iter
585 ~stop:source_view#source_buffer#end_iter;
587 | None -> assert false (* a race condition occurred *)
589 source_view#source_buffer#misc#disconnect id));
590 source_view#source_buffer#place_cursor
591 (source_view#source_buffer#get_iter (`OFFSET x'));
594 let locker f script =
595 let source_view = script#source_view in
599 let saved_use_library= !MultiPassDisambiguator.use_library in
601 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
603 MultiPassDisambiguator.use_library := saved_use_library;
606 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
608 interactive_error_interp
609 ~all_passes:!all_disambiguation_passes source_view#source_buffer
610 (notify_exn source_view) offset errorll (s())#filename
613 MultiPassDisambiguator.use_library := true;
616 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
617 interactive_error_interp ~all_passes:true source_view#source_buffer
618 (notify_exn source_view) offset errorll (s())#filename
620 notify_exn source_view exc);
621 | exc -> notify_exn source_view exc);
622 MultiPassDisambiguator.use_library := saved_use_library;
625 (try notify_exn source_view exc
626 with Sys.Break as e -> notify_exn source_view e);
630 worker_thread := Some (Thread.create thread_main ())
633 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
634 let interrupt = ref None in
635 let old_callback = ref (function _ -> ()) in
636 let force_interrupt n =
637 (* This function is called just before the thread's timeslice ends *)
639 if Some(Thread.id(Thread.self())) = !interrupt then
640 (interrupt := None; raise Sys.Break) in
642 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
643 Sys.Signal_handle f -> old_callback := f
645 | Sys.Signal_default -> assert false
648 match !worker_thread with
650 | Some t -> interrupt := Some (Thread.id t) in
651 let keep_focus f (script: MatitaScript.script) =
653 f script; script#source_view#misc#grab_focus ()
655 exc -> script#source_view#misc#grab_focus (); raise exc in
658 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
660 let adj = main#logScrolledWin#vadjustment in
661 ignore (adj#connect#changed
662 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
663 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
664 (* natural deduction palette *)
665 main#tacticsButtonsHandlebox#misc#hide ();
666 MatitaGtkMisc.toggle_callback
668 if b then main#tacticsButtonsHandlebox#misc#show ()
669 else main#tacticsButtonsHandlebox#misc#hide ())
670 ~check:main#menuitemPalette;
671 connect_button main#butImpl_intro
672 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⇒#i […] (…));\n");
673 connect_button main#butAnd_intro
674 (fun () -> (s ())#source_view#source_buffer#insert
675 "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
676 connect_button main#butOr_intro_left
677 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_l (…));\n");
678 connect_button main#butOr_intro_right
679 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_r (…));\n");
680 connect_button main#butNot_intro
681 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (¬#i […] (…));\n");
682 connect_button main#butTop_intro
683 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊤#i);\n");
684 connect_button main#butImpl_elim
685 (fun () -> (s ())#source_view#source_buffer#insert
686 "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
687 connect_button main#butAnd_elim_left
688 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_l (…));\n");
689 connect_button main#butAnd_elim_right
690 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_r (…));\n");
691 connect_button main#butOr_elim
692 (fun () -> (s ())#source_view#source_buffer#insert
693 "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
694 connect_button main#butNot_elim
695 (fun () -> (s ())#source_view#source_buffer#insert
696 "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
697 connect_button main#butBot_elim
698 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊥#e (…));\n");
699 connect_button main#butRAA
700 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (RAA […] (…));\n");
701 connect_button main#butUseLemma
702 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (lem #premises name …);\n");
703 connect_button main#butDischarge
704 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (discharge […]);\n");
706 connect_button main#butForall_intro
707 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#i {…} (…));\n");
708 connect_button main#butForall_elim
709 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#e {…} (…));\n");
710 connect_button main#butExists_intro
711 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∃#i {…} (…));\n");
712 connect_button main#butExists_elim
713 (fun () -> (s ())#source_view#source_buffer#insert
714 "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
717 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
719 | true -> main#toplevel#fullscreen ()
720 | false -> main#toplevel#unfullscreen ());
721 main#fullscreenMenuItem#set_active false;
722 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
723 ~callback:(function b ->
725 let _status = Interpretations.toggle_active_interpretations s#status b
727 assert false (* MATITA 1.0 ???
728 s#set_grafite_status status*)
730 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
731 ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
732 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
733 ~callback:(fun enabled ->
734 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
735 main#unicodeAsTexMenuItem#set_active
736 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
738 HLog.set_log_callback (fun tag msg -> GtkThread.async (self#console#log_callback tag) msg);
739 GtkSignal.user_handler :=
741 | MatitaScript.ActionCancelled s -> HLog.error s
743 if not (Helm_registry.get_bool "matita.debug") then
744 (* MatitaScript.current is problably wrong, but what else
746 notify_exn (MatitaScript.current ())#source_view exn
750 match self#chooseFile () with
751 | Some f -> self#loadScript f
753 with MatitaTypes.Cancel -> ()
756 let source_view = (s ())#source_view in
757 source_view#source_buffer#place_cursor
758 (source_view#source_buffer#get_iter_at_mark (`NAME "locked")) in
759 let advance (script: MatitaScript.script) = script#advance (); cursor () in
760 let retract (script: MatitaScript.script) = script#retract (); cursor () in
761 let top (script: MatitaScript.script) = script#goto `Top (); cursor () in
762 let bottom (script: MatitaScript.script) = script#goto `Bottom (); cursor () in
763 let jump (script: MatitaScript.script) = script#goto `Cursor (); cursor () in
764 let advance () = locker (keep_focus advance) (MatitaScript.current ()) in
765 let retract () = locker (keep_focus retract) (MatitaScript.current ()) in
766 let top () = locker (keep_focus top) (MatitaScript.current ()) in
767 let bottom () = locker (keep_focus bottom) (MatitaScript.current ()) in
768 let jump () = locker (keep_focus jump) (MatitaScript.current ()) in
770 self#setQuitCallback (fun () ->
771 let cancel = ref false in
772 MatitaScript.iter_scripts
775 if not (self#closeScript0 script) then
779 connect_button main#scriptAdvanceButton advance;
780 connect_button main#scriptRetractButton retract;
781 connect_button main#scriptTopButton top;
782 connect_button main#scriptBottomButton bottom;
783 connect_button main#scriptJumpButton jump;
784 connect_button main#scriptAbortButton kill_worker;
785 connect_menu_item main#scriptAdvanceMenuItem advance;
786 connect_menu_item main#scriptRetractMenuItem retract;
787 connect_menu_item main#scriptTopMenuItem top;
788 connect_menu_item main#scriptBottomMenuItem bottom;
789 connect_menu_item main#scriptJumpMenuItem jump;
790 connect_menu_item main#openMenuItem loadScript;
791 connect_menu_item main#saveMenuItem
792 (fun () -> self#saveScript (MatitaScript.current ()));
793 connect_menu_item main#saveAsMenuItem
794 (fun () -> self#saveAsScript (MatitaScript.current ()));
795 connect_menu_item main#newMenuItem self#newScript;
796 connect_menu_item main#closeMenuItem self#closeCurrentScript;
797 connect_menu_item main#showCoercionsGraphMenuItem
798 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Coercions)));
799 connect_menu_item main#showHintsDbMenuItem
800 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Hints)));
801 connect_menu_item main#showTermGrammarMenuItem
802 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Grammar)));
803 connect_menu_item main#showUnicodeTable
804 (fun _ -> MatitaMathView.cicBrowser (Some (`About `TeX)));
806 main#debugMenu#misc#hide ();
808 main#hintNotebook#misc#hide ();
810 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
811 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
812 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
814 (* main win dimension *)
815 let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
816 let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
817 (* hack for xinerama, no proper support of monitors from lablgtk *)
818 let width = if width > 1600 then width / 2 else width in
819 let height = if height > 1200 then height / 2 else height in
820 let main_w = width * 90 / 100 in
821 let main_h = height * 80 / 100 in
822 let script_w = main_w * 6 / 10 in
823 main#toplevel#resize ~width:main_w ~height:main_h;
824 main#hpaneScriptSequent#set_position script_w;
825 (* math view handling *)
826 connect_menu_item main#newCicBrowserMenuItem (fun () ->
827 ignore(MatitaMathView.cicBrowser None));
828 connect_menu_item main#increaseFontSizeMenuItem
829 MatitaMisc.increase_font_size;
830 connect_menu_item main#decreaseFontSizeMenuItem
831 MatitaMisc.decrease_font_size;
832 connect_menu_item main#normalFontSizeMenuItem
833 MatitaMisc.reset_font_size;
834 ignore (main#scriptNotebook#connect#switch_page (fun page ->
836 current_page <- page;
837 let script = MatitaScript.at_page page in
839 main#undoMenuItem#misc#set_sensitive
840 script#source_view#source_buffer#can_undo ;
841 main#redoMenuItem#misc#set_sensitive
842 script#source_view#source_buffer#can_redo ;
843 main#saveMenuItem#misc#set_sensitive script#has_name))
845 method private externalEditor () =
846 let script = MatitaScript.current () in
847 let source_view = script#source_view in
848 let cmd = Helm_registry.get "matita.external_editor" in
849 (* ZACK uncomment to enable interactive ask of external editor command *)
852 "External editor command:
853 %f will be substitute for the script name,
854 %p for the cursor position in bytes,
855 %l for the execution point in bytes."
857 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
858 ~default:(Helm_registry.get "matita.external_editor") ()
860 let fname = script#filename in
862 source_view#source_buffer#start_iter#get_slice
863 ~stop:(source_view#source_buffer#get_iter_at_mark mark)
865 let locked = `MARK script#locked_mark in
866 let string_pos mark = string_of_int (String.length (slice mark)) in
867 let cursor_pos = string_pos `INSERT in
868 let locked_pos = string_pos locked in
870 Pcre.replace ~pat:"%f" ~templ:fname
871 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
872 (Pcre.replace ~pat:"%l" ~templ:locked_pos
875 let locked_before = slice locked in
876 let locked_offset = (source_view#source_buffer#get_iter_at_mark locked)#offset in
877 ignore (Unix.system cmd);
878 source_view#source_buffer#set_text (HExtlib.input_file fname);
879 let locked_iter = source_view#source_buffer#get_iter (`OFFSET locked_offset) in
880 source_view#source_buffer#move_mark locked locked_iter;
881 source_view#source_buffer#apply_tag script#locked_tag
882 ~start:source_view#source_buffer#start_iter ~stop:locked_iter;
883 let locked_after = slice locked in
887 for i = 0 to String.length locked_before - 1 do
888 if locked_before.[i] <> locked_after.[i] then begin
889 source_view#source_buffer#place_cursor
890 ~where:(source_view#source_buffer#get_iter (`LINEBYTE (!line, !col)));
891 script#goto `Cursor ();
893 end else if locked_before.[i] = '\n' then begin
900 | Invalid_argument _ -> script#goto `Bottom ()
902 method private saveAsScript script =
903 match self#chooseFile ~ok_not_exists:true () with
906 script#assignFileName (Some f);
907 script#saveToFile ();
908 console#message ("'"^f^"' saved.\n");
912 method private saveScript script =
913 if script#has_name then
914 (script#saveToFile ();
915 console#message ("'"^script#filename^"' saved.\n"))
916 else self#saveAsScript script
918 (* returns false if closure is aborted by the user *)
919 method private closeScript0 script =
920 if script#source_view#buffer#modified then
922 ask_unsaved main#toplevel (Filename.basename script#filename)
925 self#saveScript script;
926 save_moo script#status;
929 | `DELETE_EVENT -> false
931 (save_moo script#status; true)
933 method private closeScript page script =
934 if self#closeScript0 script then
936 MatitaScript.destroy page;
937 ignore (main#scriptNotebook#remove_page page)
940 method private closeCurrentScript () =
941 let page = main#scriptNotebook#current_page in
942 let script = MatitaScript.at_page page in
943 self#closeScript page script
945 method private save_page () =
946 if current_page >= 0 then
947 let old_script = MatitaScript.at_page current_page in
948 save_moo0 ~do_clean:false old_script old_script#status
950 method newScript () =
952 let scrolledWindow = GBin.scrolled_window () in
953 let hbox = GPack.hbox () in
954 let tab_label = GMisc.label ~text:"foo" ~packing:hbox#pack () in
956 GMisc.label ~text:"" ~packing:(hbox#pack ~expand:true ~fill:true) () in
958 GButton.button ~relief:`NONE ~packing:hbox#pack () in
959 let image = GMisc.image ~stock:`CLOSE ~icon_size:`MENU () in
960 closebutton#set_image image#coerce;
961 let script = MatitaScript.script ~parent:scrolledWindow ~tab_label () in
962 ignore (main#scriptNotebook#prepend_page ~tab_label:hbox#coerce
963 scrolledWindow#coerce);
964 ignore (closebutton#connect#clicked (fun () ->
966 (main#scriptNotebook#page_num scrolledWindow#coerce) script));
967 main#scriptNotebook#goto_page 0;
968 sequents_viewer#reset;
969 sequents_viewer#load_logo;
970 let browser_observer _ = MatitaMathView.refresh_all_browsers () in
971 let sequents_observer status =
972 sequents_viewer#reset;
973 match status#ng_mode with
975 sequents_viewer#nload_sequents status;
978 Continuationals.Stack.find_goal status#stack
980 sequents_viewer#goto_sequent status goal
981 with Failure _ -> ());
982 | `CommandMode -> sequents_viewer#load_logo
984 script#addObserver sequents_observer;
985 script#addObserver browser_observer
987 method loadScript file =
988 let page = main#scriptNotebook#current_page in
989 let script = MatitaScript.at_page page in
990 if script#source_view#buffer#modified || script#has_name then
992 let script = MatitaScript.current () in
993 let source_view = script#source_view in
995 script#assignFileName (Some file);
996 let file = script#filename in
998 if Sys.file_exists file then file
999 else BuildTimeConf.script_template
1001 source_view#source_buffer#begin_not_undoable_action ();
1002 script#loadFromFile content;
1003 source_view#source_buffer#end_not_undoable_action ();
1004 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1005 source_view#buffer#place_cursor source_view#buffer#start_iter;
1006 console#message ("'"^file^"' loaded.");
1007 self#_enableSaveTo file
1009 method private _enableSaveTo _file =
1010 self#main#saveMenuItem#misc#set_sensitive true
1012 method private console = console
1013 method private findRepl = findRepl
1016 method private addKeyBinding key ?modifiers callback =
1017 (* List.iter (fun evbox -> add_key_binding key callback evbox) *)
1018 List.iter (fun evbox -> connect_key evbox#event key ?modifiers callback)
1021 method private setQuitCallback callback =
1022 connect_menu_item main#quitMenuItem callback;
1023 ignore (main#toplevel#event#connect#delete
1024 (fun _ -> callback ();true));
1025 self#addKeyBinding GdkKeysyms._q callback
1027 method private chooseFileOrDir ok_not_exists only_directory =
1028 let fileSel = GWindow.file_chooser_dialog
1030 ~title:"Select file"
1035 fileSel#add_select_button_stock `OPEN `OK;
1036 fileSel#add_button_stock `CANCEL `CANCEL;
1037 ignore (fileSel#set_current_folder(Sys.getcwd ())) ;
1040 match fileSel#run () with
1042 (match fileSel#filename with
1045 if Sys.file_exists fname then
1047 if HExtlib.is_regular fname && not (only_directory) then
1049 else if only_directory && HExtlib.is_dir fname then
1054 else if ok_not_exists then Some fname else aux ())
1056 | `DELETE_EVENT -> None in
1058 fileSel#destroy () ;
1061 method private chooseFile ?(ok_not_exists = false) () =
1062 self#chooseFileOrDir ok_not_exists false
1064 method private chooseDir ?(ok_not_exists = false) () =
1065 (* we should check that this is a directory *)
1066 self#chooseFileOrDir ok_not_exists true
1071 let g = new gui () in
1072 let rg = (g :> MatitaGuiTypes.gui) in
1073 MatitaMisc.set_gui rg;
1077 let instance = singleton gui
1079 let non p x = not (p x)
1082 let cols = new GTree.column_list in
1083 let id_col = cols#add Gobject.Data.string in
1084 let dsc_col = cols#add Gobject.Data.string in
1085 let interp_no_col = cols#add Gobject.Data.int in
1086 let tree_store = GTree.tree_store cols in
1087 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1088 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1089 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1090 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1091 fun tree_view choices ->
1094 tree_view#set_model (Some (tree_store :> GTree.model));
1095 ignore (tree_view#append_column id_view_col);
1096 ignore (tree_view#append_column dsc_view_col);
1097 let name_of_interp =
1098 (* try to find a reasonable name for an interpretation *)
1102 List.assoc "0" interp
1104 incr idx; string_of_int !idx
1106 tree_store#clear ();
1107 let idx = ref ~-1 in
1111 let interp_row = tree_store#append () in
1112 tree_store#set ~row:interp_row ~column:id_col
1113 (name_of_interp interp);
1114 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1117 let row = tree_store#append ~parent:interp_row () in
1118 tree_store#set ~row ~column:id_col id;
1119 tree_store#set ~row ~column:dsc_col dsc;
1120 tree_store#set ~row ~column:interp_no_col !idx)
1124 method get_interp_no tree_path =
1125 let iter = tree_store#get_iter tree_path in
1126 tree_store#get ~row:iter ~column:interp_no_col
1130 let interactive_string_choice
1131 text prefix_len ?(title = "") ?msg:(_ = "") () ~id:_ locs uris
1133 GtkThread.sync (fun _ ->
1134 let dialog = new uriChoiceDialog () in
1135 dialog#uriEntryHBox#misc#hide ();
1136 dialog#uriChoiceSelectedButton#misc#hide ();
1137 dialog#uriChoiceAutoButton#misc#hide ();
1138 dialog#uriChoiceConstantsButton#misc#hide ();
1139 dialog#uriChoiceTreeView#selection#set_mode
1140 (`SINGLE :> Gtk.Tags.selection_mode);
1141 let model = new stringListModel dialog#uriChoiceTreeView in
1142 let choices = ref [] in
1143 dialog#uriChoiceDialog#set_title title;
1144 let hack_len = MatitaGtkMisc.utf8_string_length text in
1145 let rec colorize acc_len = function
1147 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1148 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1150 let start, stop = HExtlib.loc_of_floc he in
1151 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1152 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1153 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1154 escape_pango_markup str1 ^ "<b>" ^
1155 escape_pango_markup str2 ^ "</b>" ^
1158 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1159 Printf.eprintf "(%d,%d)" start stop) locs; *)
1163 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1166 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1167 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1168 Printf.eprintf "(%d,%d)" start stop) locs;
1169 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1170 dialog#uriChoiceLabel#set_use_markup true;
1171 let txt = colorize 0 locs in
1172 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1173 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1175 dialog#uriChoiceLabel#set_label txt;
1176 List.iter model#easy_append uris;
1177 connect_button dialog#uriChoiceForwardButton (fun _ ->
1178 match model#easy_selection () with
1180 | uris -> choices := uris; dialog#toplevel#response `OK);
1181 connect_button dialog#uriChoiceAbortButton (fun _ -> dialog#toplevel#response `DELETE_EVENT);
1182 dialog#uriChoiceDialog#show ();
1184 match dialog#toplevel#run () with
1185 | `DELETE_EVENT -> dialog#toplevel#destroy() ; raise MatitaTypes.Cancel
1187 | _ -> assert false in
1188 dialog#toplevel#destroy () ;
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 *)