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 let gui_instance = ref None
40 class type browserWin =
41 (* this class exists only because GEdit.combo_box_entry is not supported by
42 * lablgladecc :-(((( *)
44 inherit MatitaGeneratedGui.browserWin
45 method browserUri: GEdit.entry
48 class console ~(buffer: GText.buffer) () =
50 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
51 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
52 val message_tag = buffer#create_tag []
53 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
54 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
55 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
56 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
57 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
59 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
60 method log_callback (tag: HLog.log_tag) s =
61 let s = Pcre.replace ~pat:"
\e\\[0;3.m([^
\e]+)
\e\\[0m" ~templ:"$1" s in
63 | `Debug -> self#debug (s ^ "\n")
64 | `Error -> self#error (s ^ "\n")
65 | `Message -> self#message (s ^ "\n")
66 | `Warning -> self#warning (s ^ "\n")
69 let clean_current_baseuri grafite_status =
70 LibraryClean.clean_baseuris [GrafiteTypes.get_baseuri grafite_status]
72 let save_moo lexicon_status grafite_status =
73 let script = MatitaScript.current () in
74 let baseuri = GrafiteTypes.get_baseuri grafite_status in
76 grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof
78 match script#bos, script#eos, no_pstatus with
82 LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
85 LibraryMisc.lexicon_file_of_baseuri
86 ~must_exist:false ~baseuri ~writable:true
88 GrafiteMarshal.save_moo moo_fname
89 grafite_status.GrafiteTypes.moo_content_rev;
90 LexiconMarshal.save_lexicon lexicon_fname
91 lexicon_status.LexiconEngine.lexicon_content_rev
92 | _ -> clean_current_baseuri grafite_status
95 let ask_unsaved parent =
96 MatitaGtkMisc.ask_confirmation
97 ~parent ~title:"Unsaved work!"
98 ~message:("Your work is <b>unsaved</b>!\n\n"^
99 "<i>Do you want to save the script before continuing?</i>")
102 class interpErrorModel =
103 let cols = new GTree.column_list in
104 let id_col = cols#add Gobject.Data.string in
105 let dsc_col = cols#add Gobject.Data.string in
106 let interp_no_col = cols#add Gobject.Data.caml in
107 let tree_store = GTree.tree_store cols in
108 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
109 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
110 let id_view_col = GTree.view_column ~renderer:id_renderer () in
111 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
112 fun (tree_view: GTree.view) choices ->
115 tree_view#set_model (Some (tree_store :> GTree.model));
116 ignore (tree_view#append_column id_view_col);
117 ignore (tree_view#append_column dsc_view_col);
119 let idx1 = ref ~-1 in
124 if List.length choices = 1 then
127 (let loc_row = tree_store#append () in
130 [passes,envs_and_diffs,_,_] ->
131 tree_store#set ~row:loc_row ~column:id_col
132 ("Error location " ^ string_of_int (!idx1+1) ^
133 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
135 String.concat " " (List.map string_of_int passes) ^
137 tree_store#set ~row:loc_row ~column:interp_no_col
140 tree_store#set ~row:loc_row ~column:id_col
141 ("Error location " ^ string_of_int (!idx1+1));
142 tree_store#set ~row:loc_row ~column:interp_no_col
146 let idx2 = ref ~-1 in
148 (fun passes,envs_and_diffs,_,_ ->
151 if List.length lll = 1 then
154 let msg_row = tree_store#append ?parent:loc_row () in
155 (tree_store#set ~row:msg_row ~column:id_col
156 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
157 string_of_int (!idx2+1) ^
159 String.concat " " (List.map string_of_int passes) ^
161 tree_store#set ~row:msg_row ~column:interp_no_col
162 (!idx1,Some !idx2,None);
164 let idx3 = ref ~-1 in
166 (fun (passes,env,_) ->
169 match envs_and_diffs with
171 let interp_row = tree_store#append ?parent:msg_row () in
172 tree_store#set ~row:interp_row ~column:id_col
173 ("Interpretation " ^ string_of_int (!idx3+1) ^
175 String.concat " " (List.map string_of_int passes) ^
177 tree_store#set ~row:interp_row ~column:interp_no_col
178 (!idx1,Some !idx2,Some !idx3);
185 let row = tree_store#append ?parent:interp_row () in
186 tree_store#set ~row ~column:id_col id;
187 tree_store#set ~row ~column:dsc_col dsc;
188 tree_store#set ~row ~column:interp_no_col
189 (!idx1,Some !idx2,Some !idx3)
193 if List.length lll > 1 then
195 (fun p -> tree_view#expand_row (tree_store#get_path p))
199 method get_interp_no tree_path =
200 let iter = tree_store#get_iter tree_path in
201 tree_store#get ~row:iter ~column:interp_no_col
204 exception UseLibrary;;
206 let rec interactive_error_interp ~all_passes
207 (source_buffer:GSourceView.source_buffer) notify_exn offset errorll filename
209 (* hook to save a script for each disambiguation error *)
212 source_buffer#get_text ~start:source_buffer#start_iter
213 ~stop:source_buffer#end_iter () in
214 let md5 = Digest.to_hex (Digest.string text) in
216 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
217 let ch = open_out filename in
218 output_string ch text;
221 assert (List.flatten errorll <> []);
223 let remove_non_significant =
224 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
225 let annotated_errorll () =
228 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
230 if all_passes then annotated_errorll () else
231 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
232 (* We remove passes 1,2 and 5,6 *)
235 ::(3,remove_non_significant (safe_list_nth errorll 2))
236 ::(4,remove_non_significant (safe_list_nth errorll 3))
239 if List.flatten (List.map snd res) <> [] then res
241 (* all errors (if any) are not significant: we keep them *)
244 ::(3,(safe_list_nth errorll 2))
245 ::(4,(safe_list_nth errorll 3))
248 if List.flatten (List.map snd res) <> [] then
251 "All disambiguation errors are not significant. Showing them anyway." ;
257 "No errors in phases 2 and 3. Showing all errors in all phases" ;
261 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
264 | [loffset,[_,envs_and_diffs,msg,significant]] ->
265 let _,env,diff = List.hd envs_and_diffs in
267 (MultiPassDisambiguator.DisambiguationError
268 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
270 let dialog = new disambiguationErrors () in
271 dialog#check_widgets ();
273 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
274 let model = new interpErrorModel dialog#treeview choices in
275 dialog#disambiguationErrors#set_title "Disambiguation error";
276 dialog#disambiguationErrorsLabel#set_label
277 "Click on an error to see the corresponding message:";
278 ignore (dialog#treeview#connect#cursor_changed
281 match fst (dialog#treeview#get_cursor ()) with
284 let idx1,idx2,idx3 = model#get_interp_no tree_path in
285 let loffset,lll = List.nth choices idx1 in
286 let _,envs_and_diffs,msg,significant =
288 Some idx2 -> List.nth lll idx2
290 [],[],lazy "Multiple error messages. Please select one.",true
294 Some idx3 -> List.nth envs_and_diffs idx3
295 | None -> [],[],[] (* dymmy value, used *) in
296 let script = MatitaScript.current () in
297 let error_tag = script#error_tag in
298 source_buffer#remove_tag error_tag
299 ~start:source_buffer#start_iter
300 ~stop:source_buffer#end_iter;
302 (MultiPassDisambiguator.DisambiguationError
303 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
306 dialog#disambiguationErrors#destroy ();
309 let fail _ = return () in
310 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
311 connect_button dialog#disambiguationErrorsOkButton
314 match fst (dialog#treeview#get_cursor ()) with
317 let idx1,idx2,idx3 = model#get_interp_no tree_path in
320 Some idx2, Some idx3 ->
321 let _,lll = List.nth choices idx1 in
322 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
323 let _,_,diff = List.nth envs_and_diffs idx3 in
325 | _,_ -> assert false
334 | DisambiguateTypes.Id id ->
335 LexiconAst.Ident_alias (id, desc)
336 | DisambiguateTypes.Symbol (symb, i)->
337 LexiconAst.Symbol_alias (symb, i, desc)
338 | DisambiguateTypes.Num i ->
339 LexiconAst.Number_alias (i, desc)
341 LexiconAstPp.pp_alias alias)
346 (source_buffer#get_iter_at_mark
347 (`NAME "beginning_of_statement")) newtxt ;
350 connect_button dialog#disambiguationErrorsMoreErrors
351 (fun _ -> return () ; raise UseLibrary);
352 connect_button dialog#disambiguationErrorsCancelButton fail;
353 dialog#disambiguationErrors#show ();
357 (** Selection handling
358 * Two clipboards are used: "clipboard" and "primary".
359 * "primary" is used by X, when you hit the middle button mouse is content is
360 * pasted between applications. In Matita this selection always contain the
361 * textual version of the selected term.
362 * "clipboard" is used inside Matita only and support ATM two different targets:
363 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
368 (* creation order _is_ relevant for windows placement *)
369 let main = new mainWin () in
370 let fileSel = new fileSelectionWin () in
371 let findRepl = new findReplWin () in
372 let keyBindingBoxes = (* event boxes which should receive global key events *)
373 [ main#mainWinEventBox ]
375 let console = new console ~buffer:main#logTextView#buffer () in
376 let (source_view: GSourceView.source_view) =
377 GSourceView.source_view
379 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
380 ~margin:80 ~show_margin:true
382 ~packing:main#scriptScrolledWin#add
385 let default_font_size =
386 Helm_registry.get_opt_default Helm_registry.int
387 ~default:BuildTimeConf.default_font_size "matita.font_size"
389 let similarsymbols_tag_name = "similarsymbolos" in
390 let similarsymbols_tag = `NAME similarsymbols_tag_name in
391 let source_buffer = source_view#source_buffer in
393 val mutable chosen_file = None
394 val mutable _ok_not_exists = false
395 val mutable _only_directory = false
396 val mutable font_size = default_font_size
397 val mutable similarsymbols = []
398 val mutable similarsymbols_orig = []
399 val clipboard = GData.clipboard Gdk.Atom.clipboard
400 val primary = GData.clipboard Gdk.Atom.primary
402 method private reset_similarsymbols =
403 similarsymbols <- [];
404 similarsymbols_orig <- [];
405 try source_buffer#delete_mark similarsymbols_tag
406 with GText.No_such_mark _ -> ()
409 let s () = MatitaScript.current () in
410 (* glade's check widgets *)
411 List.iter (fun w -> w#check_widgets ())
412 (let c w = (w :> <check_widgets: unit -> unit>) in
413 [ c fileSel; c main; c findRepl]);
415 List.iter (* global key bindings *)
416 (fun (key, callback) -> self#addKeyBinding key callback)
419 toggle_win ~check:main#showProofMenuItem proof#proofWin;
421 toggle_win ~check:main#showCheckMenuItem check#checkWin;
425 let parse_txt_file file =
426 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
427 let l_rev = ref [] in
430 l_rev := input_line ch :: !l_rev;
439 ~authors:(parse_txt_file "AUTHORS")
440 (*~comments:"comments"*)
441 ~copyright:"Copyright (C) 2005, the HELM team"
442 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
443 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
445 ~version:BuildTimeConf.version
446 ~website:"http://matita.cs.unibo.it"
449 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
450 connect_menu_item main#contentsMenuItem (fun () ->
451 if 0 = Sys.command "which gnome-help" then
453 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
455 ignore (Sys.command cmd)
457 MatitaGtkMisc.report_error ~title:"help system error"
459 "The program gnome-help is not installed\n\n"^
460 "To browse the user manal it is necessary to install "^
461 "the gnome help syste (also known as yelp)")
462 ~parent:main#toplevel ());
463 connect_menu_item main#aboutMenuItem about_dialog#present;
465 let show_find_Repl () =
466 findRepl#toplevel#misc#show ();
467 findRepl#toplevel#misc#grab_focus ()
469 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
471 let highlight start end_ =
472 source_buffer#move_mark `INSERT ~where:start;
473 source_buffer#move_mark `SEL_BOUND ~where:end_;
474 source_view#scroll_mark_onscreen `INSERT
476 let text = findRepl#findEntry#text in
477 let iter = source_buffer#get_iter `SEL_BOUND in
478 match iter#forward_search text with
480 (match source_buffer#start_iter#forward_search text with
482 | Some (start,end_) -> highlight start end_)
483 | Some (start,end_) -> highlight start end_
486 let text = findRepl#replaceEntry#text in
487 let ins = source_buffer#get_iter `INSERT in
488 let sel = source_buffer#get_iter `SEL_BOUND in
489 if ins#compare sel < 0 then
491 ignore(source_buffer#delete_selection ());
492 source_buffer#insert text
495 connect_button findRepl#findButton find_forward;
496 connect_button findRepl#findReplButton replace;
497 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
498 ignore(findRepl#toplevel#event#connect#delete
499 ~callback:(fun _ -> hide_find_Repl ();true));
502 (* phase 1: we save the actual status of the marks and we undo *)
503 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
504 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
505 let locked_iter_offset = locked_iter#offset in
508 (source_view#buffer#create_mark ~name:"lock_point"
509 ~left_gravity:true locked_iter) in
510 source_view#source_buffer#undo ();
511 (* phase 2: we save the cursor position and we redo, restoring
512 the previous status of all the marks *)
513 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
516 (source_view#buffer#create_mark ~name:"undo_point"
517 ~left_gravity:true cursor_iter)
519 source_view#source_buffer#redo ();
520 let mark_iter = source_view#buffer#get_iter_at_mark mark in
521 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
522 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
523 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
524 source_view#buffer#delete_mark mark;
525 source_view#buffer#delete_mark mark2;
526 (* phase 3: if after the undo the cursor was in the locked area,
527 then we move it there again and we perform a goto *)
528 if mark_iter#offset < locked_iter_offset then
530 source_view#buffer#move_mark `INSERT ~where:mark_iter;
531 (MatitaScript.current ())#goto `Cursor ();
533 (* phase 4: we perform again the undo. This time we are sure that
534 the text to undo is not locked *)
535 source_view#source_buffer#undo ();
536 source_view#misc#grab_focus () in
539 (* phase 1: we save the actual status of the marks, we redo and
541 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
542 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
543 let locked_iter_offset = locked_iter#offset in
546 (source_view#buffer#create_mark ~name:"lock_point"
547 ~left_gravity:true locked_iter) in
548 source_view#source_buffer#redo ();
549 source_view#source_buffer#undo ();
550 (* phase 2: we save the cursor position and we restore
551 the previous status of all the marks *)
552 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
555 (source_view#buffer#create_mark ~name:"undo_point"
556 ~left_gravity:true cursor_iter)
558 let mark_iter = source_view#buffer#get_iter_at_mark mark in
559 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
560 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
561 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
562 source_view#buffer#delete_mark mark;
563 source_view#buffer#delete_mark mark2;
564 (* phase 3: if after the undo the cursor is in the locked area,
565 then we move it there again and we perform a goto *)
566 if mark_iter#offset < locked_iter_offset then
568 source_view#buffer#move_mark `INSERT ~where:mark_iter;
569 (MatitaScript.current ())#goto `Cursor ();
571 (* phase 4: we perform again the redo. This time we are sure that
572 the text to redo is not locked *)
573 source_view#source_buffer#redo ();
574 source_view#misc#grab_focus ()
576 connect_menu_item main#undoMenuItem safe_undo;
577 ignore(source_view#source_buffer#connect#can_undo
578 ~callback:main#undoMenuItem#misc#set_sensitive);
579 connect_menu_item main#redoMenuItem safe_redo;
580 ignore(source_view#source_buffer#connect#can_redo
581 ~callback:main#redoMenuItem#misc#set_sensitive);
582 ignore(source_view#connect#after#populate_popup
583 ~callback:(fun pre_menu ->
584 let menu = new GMenu.menu pre_menu in
585 let menuItems = menu#children in
586 let undoMenuItem, redoMenuItem =
588 [undo;redo;sep1;cut;copy;paste;delete;sep2;
589 selectall;sep3;inputmethod;insertunicodecharacter] ->
590 List.iter menu#remove [ copy; cut; delete; paste ];
592 | _ -> assert false in
594 let i = ref 2 in (* last occupied position *)
595 fun ?label ?stock () ->
597 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
600 let copy = add_menu_item ~stock:`COPY () in
601 let cut = add_menu_item ~stock:`CUT () in
602 let delete = add_menu_item ~stock:`DELETE () in
603 let paste = add_menu_item ~stock:`PASTE () in
604 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
605 copy#misc#set_sensitive self#canCopy;
606 cut#misc#set_sensitive self#canCut;
607 delete#misc#set_sensitive self#canDelete;
608 paste#misc#set_sensitive self#canPaste;
609 paste_pattern#misc#set_sensitive self#canPastePattern;
610 connect_menu_item copy self#copy;
611 connect_menu_item cut self#cut;
612 connect_menu_item delete self#delete;
613 connect_menu_item paste self#paste;
614 connect_menu_item paste_pattern self#pastePattern;
615 let new_undoMenuItem =
616 GMenu.image_menu_item
617 ~image:(GMisc.image ~stock:`UNDO ())
620 ~packing:(menu#insert ~pos:0) () in
621 new_undoMenuItem#misc#set_sensitive
622 (undoMenuItem#misc#get_flag `SENSITIVE);
623 menu#remove (undoMenuItem :> GMenu.menu_item);
624 connect_menu_item new_undoMenuItem safe_undo;
625 let new_redoMenuItem =
626 GMenu.image_menu_item
627 ~image:(GMisc.image ~stock:`REDO ())
630 ~packing:(menu#insert ~pos:1) () in
631 new_redoMenuItem#misc#set_sensitive
632 (redoMenuItem#misc#get_flag `SENSITIVE);
633 menu#remove (redoMenuItem :> GMenu.menu_item);
634 connect_menu_item new_redoMenuItem safe_redo));
636 connect_menu_item main#editMenu (fun () ->
637 main#copyMenuItem#misc#set_sensitive self#canCopy;
638 main#cutMenuItem#misc#set_sensitive self#canCut;
639 main#deleteMenuItem#misc#set_sensitive self#canDelete;
640 main#pasteMenuItem#misc#set_sensitive self#canPaste;
641 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
642 connect_menu_item main#copyMenuItem self#copy;
643 connect_menu_item main#cutMenuItem self#cut;
644 connect_menu_item main#deleteMenuItem self#delete;
645 connect_menu_item main#pasteMenuItem self#paste;
646 connect_menu_item main#pastePatternMenuItem self#pastePattern;
647 connect_menu_item main#selectAllMenuItem (fun () ->
648 source_buffer#move_mark `INSERT source_buffer#start_iter;
649 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
650 connect_menu_item main#findReplMenuItem show_find_Repl;
651 connect_menu_item main#externalEditorMenuItem self#externalEditor;
652 connect_menu_item main#ligatureButton self#nextSimilarSymbol;
653 ignore(source_buffer#connect#after#insert_text
654 ~callback:(fun iter str ->
655 if main#menuitemAutoAltL#active && (str = " " || str = "\n") then
656 ignore(self#expand_virtual_if_any iter str)));
657 ignore (findRepl#findEntry#connect#activate find_forward);
658 (* interface lockers *)
660 main#buttonsToolbar#misc#set_sensitive false;
661 main#scriptMenu#misc#set_sensitive false;
662 source_view#set_editable false
665 main#buttonsToolbar#misc#set_sensitive true;
666 main#scriptMenu#misc#set_sensitive true;
667 source_view#set_editable true;
668 (*The next line seems sufficient to avoid some unknown race condition *)
669 GtkThread.sync (fun () -> ()) ()
671 let worker_thread = ref None in
673 let floc, msg = MatitaExcPp.to_string exn in
678 let (x, y) = HExtlib.loc_of_floc floc in
679 let script = MatitaScript.current () in
680 let locked_mark = script#locked_mark in
681 let error_tag = script#error_tag in
683 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
684 let x' = baseoffset + x in
685 let y' = baseoffset + y in
686 let x_iter = source_buffer#get_iter (`OFFSET x') in
687 let y_iter = source_buffer#get_iter (`OFFSET y') in
688 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
690 id := Some (source_buffer#connect#changed ~callback:(fun () ->
691 source_buffer#remove_tag error_tag
692 ~start:source_buffer#start_iter
693 ~stop:source_buffer#end_iter;
695 | None -> assert false (* a race condition occurred *)
697 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
698 source_buffer#place_cursor
699 (source_buffer#get_iter (`OFFSET x'));
706 let saved_use_library= !MultiPassDisambiguator.use_library in
708 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
710 MultiPassDisambiguator.use_library := saved_use_library;
713 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
715 interactive_error_interp
716 ~all_passes:!all_disambiguation_passes source_buffer
717 notify_exn offset errorll (s())#filename
720 MultiPassDisambiguator.use_library := true;
723 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
724 interactive_error_interp ~all_passes:true source_buffer
725 notify_exn offset errorll (s())#filename
728 | exc -> notify_exn exc);
729 MultiPassDisambiguator.use_library := saved_use_library;
732 (try notify_exn exc with Sys.Break as e -> notify_exn e);
736 worker_thread := Some (Thread.create thread_main ())
739 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
740 let interrupt = ref None in
741 let old_callback = ref (function _ -> ()) in
742 let force_interrupt n =
743 (* This function is called just before the thread's timeslice ends *)
745 if Some(Thread.id(Thread.self())) = !interrupt then
746 (interrupt := None; raise Sys.Break) in
748 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
749 Sys.Signal_handle f -> old_callback := f
751 | Sys.Signal_default -> assert false
754 match !worker_thread with
756 | Some t -> interrupt := Some (Thread.id t) in
760 f (); source_view#misc#grab_focus ()
762 exc -> source_view#misc#grab_focus (); raise exc in
764 (* file selection win *)
765 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
766 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
769 fileSel#fileSelectionWin#misc#hide ();
774 let fname = fileSel#fileSelectionWin#filename in
775 if Sys.file_exists fname then
777 if HExtlib.is_regular fname && not (_only_directory) then
779 else if _only_directory && HExtlib.is_dir fname then
784 if _ok_not_exists then
787 | `CANCEL -> return None
789 | `DELETE_EVENT -> return None));
791 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
793 let adj = main#logScrolledWin#vadjustment in
794 ignore (adj#connect#changed
795 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
796 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
797 (* natural deduction palette *)
798 main#tacticsButtonsHandlebox#misc#hide ();
799 MatitaGtkMisc.toggle_callback
801 if b then main#tacticsButtonsHandlebox#misc#show ()
802 else main#tacticsButtonsHandlebox#misc#hide ())
803 ~check:main#menuitemPalette;
804 connect_button main#butImpl_intro
805 (fun () -> source_buffer#insert "apply rule (⇒_i […] (…));\n");
806 connect_button main#butAnd_intro
807 (fun () -> source_buffer#insert
808 "apply rule (∧_i (…) (…));\n\t[\n\t|\n\t]\n");
809 connect_button main#butOr_intro_left
810 (fun () -> source_buffer#insert "apply rule (∨_i_l (…));\n");
811 connect_button main#butOr_intro_right
812 (fun () -> source_buffer#insert "apply rule (∨_i_r (…));\n");
813 connect_button main#butNot_intro
814 (fun () -> source_buffer#insert "apply rule (¬_i […] (…));\n");
815 connect_button main#butTop_intro
816 (fun () -> source_buffer#insert "apply rule (⊤_i);\n");
817 connect_button main#butImpl_elim
818 (fun () -> source_buffer#insert
819 "apply rule (⇒_e (…) (…));\n\t[\n\t|\n\t]\n");
820 connect_button main#butAnd_elim_left
821 (fun () -> source_buffer#insert "apply rule (∧_e_l (…));\n");
822 connect_button main#butAnd_elim_right
823 (fun () -> source_buffer#insert "apply rule (∧_e_r (…));\n");
824 connect_button main#butOr_elim
825 (fun () -> source_buffer#insert
826 "apply rule (∨_e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
827 connect_button main#butNot_elim
828 (fun () -> source_buffer#insert
829 "apply rule (¬_e (…) (…));\n\t[\n\t|\n\t]\n");
830 connect_button main#butBot_elim
831 (fun () -> source_buffer#insert "apply rule (⊥_e (…));\n");
832 connect_button main#butRAA
833 (fun () -> source_buffer#insert "apply rule (RAA […] (…));\n");
834 connect_button main#butUseLemma
835 (fun () -> source_buffer#insert "apply rule (lem #premises name …);\n");
836 connect_button main#butDischarge
837 (fun () -> source_buffer#insert "apply rule (discharge […]);\n");
839 connect_button main#butForall_intro
840 (fun () -> source_buffer#insert "apply rule (∀_i {…} (…));\n");
841 connect_button main#butForall_elim
842 (fun () -> source_buffer#insert "apply rule (∀_e {…} (…));\n");
843 connect_button main#butExists_intro
844 (fun () -> source_buffer#insert "apply rule (∃_i {…} (…));\n");
845 connect_button main#butExists_elim
846 (fun () -> source_buffer#insert
847 "apply rule (∃_e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
851 main#scriptNotebook#remove_page 1;
852 main#scriptNotebook#set_show_tabs false;
853 (* / TO BE REMOVED *)
854 let module Hr = Helm_registry in
855 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
857 | true -> main#toplevel#fullscreen ()
858 | false -> main#toplevel#unfullscreen ());
859 main#fullscreenMenuItem#set_active false;
860 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
863 CicNotation.set_active_notations
864 (List.map fst (CicNotation.get_all_notations ()))
866 CicNotation.set_active_notations []);
867 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
868 ~callback:(fun enabled -> Acic2content.hide_coercions := enabled);
869 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
870 ~callback:(fun enabled ->
871 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
872 main#unicodeAsTexMenuItem#set_active
873 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
875 HLog.set_log_callback self#console#log_callback;
876 GtkSignal.user_handler :=
878 | MatitaScript.ActionCancelled s -> HLog.error s
880 if not (Helm_registry.get_bool "matita.debug") then
885 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
887 HLog.warn (sprintf "can't load language file %s"
888 BuildTimeConf.lang_file)
889 | Some matita_lang ->
890 source_buffer#set_language matita_lang;
891 source_buffer#set_highlight true
894 (s())#assignFileName None;
895 main#saveMenuItem#misc#set_sensitive false
897 let saveAsScript () =
899 match self#chooseFile ~ok_not_exists:true () with
902 script#assignFileName (Some f);
903 script#saveToFile ();
904 console#message ("'"^f^"' saved.\n");
910 if script#has_name then
911 (script#saveToFile ();
912 console#message ("'"^script#filename^"' saved.\n"))
915 let abandon_script () =
916 let lexicon_status = (s ())#lexicon_status in
917 let grafite_status = (s ())#grafite_status in
918 if source_view#buffer#modified then
919 (match ask_unsaved main#toplevel with
920 | `YES -> saveScript ()
922 | `CANCEL -> raise MatitaTypes.Cancel);
923 save_moo lexicon_status grafite_status
928 match self#chooseFile () with
932 script#assignFileName (Some f);
933 source_view#source_buffer#begin_not_undoable_action ();
934 script#loadFromFile f;
935 source_view#source_buffer#end_not_undoable_action ();
936 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
937 source_view#buffer#place_cursor source_view#buffer#start_iter;
938 console#message ("'"^f^"' loaded.\n");
941 with MatitaTypes.Cancel -> ()
945 source_view#source_buffer#begin_not_undoable_action ();
948 source_view#source_buffer#end_not_undoable_action ();
950 (s ())#assignFileName None
953 source_buffer#place_cursor
954 (source_buffer#get_iter_at_mark (`NAME "locked")) in
955 let advance _ = (MatitaScript.current ())#advance (); cursor () in
956 let retract _ = (MatitaScript.current ())#retract (); cursor () in
957 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
958 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
959 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
960 let advance = locker (keep_focus advance) in
961 let retract = locker (keep_focus retract) in
962 let top = locker (keep_focus top) in
963 let bottom = locker (keep_focus bottom) in
964 let jump = locker (keep_focus jump) in
966 self#setQuitCallback (fun () ->
967 let script = MatitaScript.current () in
968 if source_view#buffer#modified then
969 match ask_unsaved main#toplevel with
972 save_moo script#lexicon_status script#grafite_status;
974 | `NO -> GMain.Main.quit ()
977 (save_moo script#lexicon_status script#grafite_status;
978 GMain.Main.quit ()));
979 connect_button main#scriptAdvanceButton advance;
980 connect_button main#scriptRetractButton retract;
981 connect_button main#scriptTopButton top;
982 connect_button main#scriptBottomButton bottom;
983 connect_button main#scriptJumpButton jump;
984 connect_button main#scriptAbortButton kill_worker;
985 connect_menu_item main#scriptAdvanceMenuItem advance;
986 connect_menu_item main#scriptRetractMenuItem retract;
987 connect_menu_item main#scriptTopMenuItem top;
988 connect_menu_item main#scriptBottomMenuItem bottom;
989 connect_menu_item main#scriptJumpMenuItem jump;
990 connect_menu_item main#openMenuItem loadScript;
991 connect_menu_item main#saveMenuItem saveScript;
992 connect_menu_item main#saveAsMenuItem saveAsScript;
993 connect_menu_item main#newMenuItem newScript;
994 connect_menu_item main#showCoercionsGraphMenuItem
996 let c = MatitaMathView.cicBrowser () in
997 c#load (`About `Coercions));
998 connect_menu_item main#showAutoGuiMenuItem
999 (fun _ -> MatitaAutoGui.auto_dialog Auto.get_auto_status);
1000 connect_menu_item main#showTermGrammarMenuItem
1002 let c = MatitaMathView.cicBrowser () in
1003 c#load (`About `Grammar));
1004 connect_menu_item main#showUnicodeTable
1006 let c = MatitaMathView.cicBrowser () in
1007 c#load (`About `TeX));
1008 (* script monospace font stuff *)
1009 self#updateFontSize ();
1011 main#debugMenu#misc#hide ();
1013 main#hintNotebook#misc#hide ();
1015 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1016 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1017 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1020 self#sourceView#misc#grab_focus ();
1021 (* main win dimension *)
1022 let width = Gdk.Screen.width () in
1023 let height = Gdk.Screen.height () in
1024 let main_w = width * 90 / 100 in
1025 let main_h = height * 80 / 100 in
1026 let script_w = main_w * 6 / 10 in
1027 main#toplevel#resize ~width:main_w ~height:main_h;
1028 main#hpaneScriptSequent#set_position script_w;
1030 ignore(source_view#connect#after#paste_clipboard
1031 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1032 (* clean_locked is set to true only "during" a PRIMARY paste
1033 operation (i.e. by clicking with the second mouse button) *)
1034 let clean_locked = ref false in
1035 ignore(source_view#event#connect#button_press
1038 if GdkEvent.Button.button button = 2 then
1039 clean_locked := true;
1042 ignore(source_view#event#connect#button_release
1043 ~callback:(fun button -> clean_locked := false; false));
1044 ignore(source_view#buffer#connect#after#apply_tag
1046 fun tag ~start:_ ~stop:_ ->
1048 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1051 clean_locked := false;
1052 (MatitaScript.current ())#clean_dirty_lock;
1053 clean_locked := true
1055 (* math view handling *)
1056 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1057 ignore(MatitaMathView.cicBrowser ()));
1058 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1059 self#increaseFontSize ();
1060 MatitaMathView.increase_font_size ();
1061 MatitaMathView.update_font_sizes ());
1062 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1063 self#decreaseFontSize ();
1064 MatitaMathView.decrease_font_size ();
1065 MatitaMathView.update_font_sizes ());
1066 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1067 self#resetFontSize ();
1068 MatitaMathView.reset_font_size ();
1069 MatitaMathView.update_font_sizes ());
1070 MatitaMathView.reset_font_size ();
1072 (** selections / clipboards handling *)
1074 method markupSelected = MatitaMathView.has_selection ()
1075 method private textSelected =
1076 (source_buffer#get_iter_at_mark `INSERT)#compare
1077 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1078 method private somethingSelected = self#markupSelected || self#textSelected
1079 method private markupStored = MatitaMathView.has_clipboard ()
1080 method private textStored = clipboard#text <> None
1081 method private somethingStored = self#markupStored || self#textStored
1083 method canCopy = self#somethingSelected
1084 method canCut = self#textSelected
1085 method canDelete = self#textSelected
1086 method canPaste = self#somethingStored
1087 method canPastePattern = self#markupStored
1090 if self#textSelected
1092 MatitaMathView.empty_clipboard ();
1093 source_view#buffer#copy_clipboard clipboard;
1095 MatitaMathView.copy_selection ()
1097 source_view#buffer#cut_clipboard clipboard;
1098 MatitaMathView.empty_clipboard ()
1099 method delete () = ignore (source_view#buffer#delete_selection ())
1101 if MatitaMathView.has_clipboard ()
1102 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1103 else source_view#buffer#paste_clipboard clipboard;
1104 (MatitaScript.current ())#clean_dirty_lock
1105 method pastePattern () =
1106 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1108 method private expand_virtual_if_any iter tok =
1110 let len = MatitaGtkMisc.utf8_string_length tok in
1112 let prev = iter#copy#backward_chars len in
1113 prev#get_slice ~stop:(prev#copy#backward_find_char
1114 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
1116 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
1117 self#reset_similarsymbols;
1118 let s = Glib.Utf8.from_unichar symb in
1119 let iter = source_buffer#get_iter_at_mark `INSERT in
1120 assert(Glib.Utf8.validate s);
1121 source_buffer#delete ~start:iter
1122 ~stop:(iter#copy#backward_chars
1123 (MatitaGtkMisc.utf8_string_length inplaceof + len));
1124 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
1125 (if inplaceof.[0] = '\\' then s else (s ^ tok));
1127 with Virtuals.Not_a_virtual -> false
1129 val similar_memory = Hashtbl.create 97
1130 val mutable old_used_memory = false
1132 method private nextSimilarSymbol () =
1133 let write_similarsymbol s =
1134 let s = Glib.Utf8.from_unichar s in
1135 let iter = source_buffer#get_iter_at_mark `INSERT in
1136 assert(Glib.Utf8.validate s);
1137 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
1138 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s;
1139 (try source_buffer#delete_mark similarsymbols_tag
1140 with GText.No_such_mark _ -> ());
1141 ignore(source_buffer#create_mark ~name:similarsymbols_tag_name
1142 (source_buffer#get_iter_at_mark `INSERT));
1144 let new_similarsymbol =
1146 let iter_ins = source_buffer#get_iter_at_mark `INSERT in
1147 let iter_lig = source_buffer#get_iter_at_mark similarsymbols_tag in
1148 not (iter_ins#equal iter_lig)
1149 with GText.No_such_mark _ -> true
1151 if new_similarsymbol then
1152 (if not(self#expand_virtual_if_any (source_buffer#get_iter_at_mark `INSERT) "")then
1154 let i = source_buffer#get_iter_at_mark `INSERT in
1155 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
1157 (match Virtuals.similar_symbols last_symbol with
1160 similarsymbols_orig <- eqclass;
1162 try Hashtbl.find similar_memory similarsymbols_orig
1164 let is_used = List.map (fun x -> x,false) eqclass in
1165 Hashtbl.add similar_memory eqclass is_used;
1170 List.partition (fun s -> List.assoc s is_used) eqclass
1172 match used @ unused with a::b::c -> a,b,c | _ -> assert false
1175 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
1177 old_used_memory <- List.assoc hd is_used;
1179 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
1181 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1182 write_similarsymbol hd;
1183 similarsymbols <- tl @ [ hd ]))
1185 match similarsymbols with
1188 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
1189 let last = HExtlib.list_last tl in
1190 let old_used_for_last = old_used_memory in
1191 old_used_memory <- List.assoc hd is_used;
1193 (hd, true) :: (last,old_used_for_last) ::
1194 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
1196 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1197 similarsymbols <- tl @ [ hd ];
1198 write_similarsymbol hd
1200 method private externalEditor () =
1201 let cmd = Helm_registry.get "matita.external_editor" in
1202 (* ZACK uncomment to enable interactive ask of external editor command *)
1205 "External editor command:
1206 %f will be substitute for the script name,
1207 %p for the cursor position in bytes,
1208 %l for the execution point in bytes."
1210 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1211 ~default:(Helm_registry.get "matita.external_editor") ()
1213 let script = MatitaScript.current () in
1214 let fname = script#filename in
1216 source_buffer#start_iter#get_slice
1217 ~stop:(source_buffer#get_iter_at_mark mark)
1219 let locked = `MARK script#locked_mark in
1220 let string_pos mark = string_of_int (String.length (slice mark)) in
1221 let cursor_pos = string_pos `INSERT in
1222 let locked_pos = string_pos locked in
1224 Pcre.replace ~pat:"%f" ~templ:fname
1225 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1226 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1229 let locked_before = slice locked in
1230 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1231 ignore (Unix.system cmd);
1232 source_buffer#set_text (HExtlib.input_file fname);
1233 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1234 source_buffer#move_mark locked locked_iter;
1235 source_buffer#apply_tag script#locked_tag
1236 ~start:source_buffer#start_iter ~stop:locked_iter;
1237 let locked_after = slice locked in
1241 for i = 0 to String.length locked_before - 1 do
1242 if locked_before.[i] <> locked_after.[i] then begin
1243 source_buffer#place_cursor
1244 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1245 script#goto `Cursor ();
1247 end else if locked_before.[i] = '\n' then begin
1254 | Invalid_argument _ -> script#goto `Bottom ()
1256 method loadScript file =
1257 let script = MatitaScript.current () in
1259 script#assignFileName (Some file);
1260 let file = script#filename in
1262 if Sys.file_exists file then file
1263 else BuildTimeConf.script_template
1265 source_view#source_buffer#begin_not_undoable_action ();
1266 script#loadFromFile content;
1267 source_view#source_buffer#end_not_undoable_action ();
1268 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1269 source_view#buffer#place_cursor source_view#buffer#start_iter;
1270 console#message ("'"^file^"' loaded.");
1271 self#_enableSaveTo file
1274 let s = MatitaScript.current () in
1275 let w = main#toplevel in
1276 let set x = w#set_title x in
1278 "Matita - " ^ Filename.basename s#filename ^
1279 (if b then "*" else "") ^
1280 " in " ^ s#buri_of_current_file
1284 method private _enableSaveTo file =
1285 self#main#saveMenuItem#misc#set_sensitive true
1287 method console = console
1288 method sourceView: GSourceView.source_view =
1289 (source_view: GSourceView.source_view)
1290 method fileSel = fileSel
1291 method findRepl = findRepl
1294 method newBrowserWin () =
1296 inherit browserWin ()
1297 val combo = GEdit.entry ()
1299 self#check_widgets ();
1300 let combo_widget = combo#coerce in
1301 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1302 combo#misc#grab_focus ()
1303 method browserUri = combo
1306 method newUriDialog () =
1307 let dialog = new uriChoiceDialog () in
1308 dialog#check_widgets ();
1311 method newConfirmationDialog () =
1312 let dialog = new confirmationDialog () in
1313 dialog#check_widgets ();
1316 method newEmptyDialog () =
1317 let dialog = new emptyDialog () in
1318 dialog#check_widgets ();
1321 method private addKeyBinding key callback =
1322 List.iter (fun evbox -> add_key_binding key callback evbox)
1325 method setQuitCallback callback =
1326 connect_menu_item main#quitMenuItem callback;
1327 ignore (main#toplevel#event#connect#delete
1328 (fun _ -> callback ();true));
1329 self#addKeyBinding GdkKeysyms._q callback
1331 method chooseFile ?(ok_not_exists = false) () =
1332 _ok_not_exists <- ok_not_exists;
1333 _only_directory <- false;
1334 fileSel#fileSelectionWin#show ();
1338 method private chooseDir ?(ok_not_exists = false) () =
1339 _ok_not_exists <- ok_not_exists;
1340 _only_directory <- true;
1341 fileSel#fileSelectionWin#show ();
1343 (* we should check that this is a directory *)
1346 method askText ?(title = "") ?(msg = "") () =
1347 let dialog = new textDialog () in
1348 dialog#textDialog#set_title title;
1349 dialog#textDialogLabel#set_label msg;
1350 let text = ref None in
1353 dialog#textDialog#destroy ();
1356 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1357 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1358 connect_button dialog#textDialogOkButton (fun _ ->
1359 let text = dialog#textDialogTextView#buffer#get_text () in
1360 return (Some text));
1361 dialog#textDialog#show ();
1365 method private updateFontSize () =
1366 self#sourceView#misc#modify_font_by_name
1367 (sprintf "%s %d" BuildTimeConf.script_font font_size);
1368 MatitaAutoGui.set_font_size font_size
1370 method increaseFontSize () =
1371 font_size <- font_size + 1;
1372 self#updateFontSize ()
1374 method decreaseFontSize () =
1375 font_size <- font_size - 1;
1376 self#updateFontSize ()
1378 method resetFontSize () =
1379 font_size <- default_font_size;
1380 self#updateFontSize ()
1385 let g = new gui () in
1386 gui_instance := Some g;
1387 MatitaMathView.set_gui g;
1390 let instance = singleton gui
1392 let non p x = not (p x)
1394 (* this is a shit and should be changed :-{ *)
1395 let interactive_uri_choice
1396 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1397 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1398 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1402 let gui = instance () in
1403 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1404 if (selection_mode <> `SINGLE) &&
1405 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1407 Lazy.force nonvars_uris
1409 let dialog = gui#newUriDialog () in
1410 if hide_uri_entry then
1411 dialog#uriEntryHBox#misc#hide ();
1414 dialog#uriChoiceSelectedButton#misc#hide ();
1415 dialog#uriChoiceConstantsButton#misc#hide ();
1417 dialog#okLabel#set_label ok_label;
1418 dialog#uriChoiceTreeView#selection#set_mode
1419 (selection_mode :> Gtk.Tags.selection_mode);
1420 let model = new stringListModel dialog#uriChoiceTreeView in
1421 let choices = ref None in
1425 dialog#copyButton#misc#show ();
1426 connect_button dialog#copyButton
1428 match model#easy_selection () with
1431 dialog#uriChoiceDialog#set_title title;
1432 dialog#uriChoiceLabel#set_text msg;
1433 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1434 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1437 dialog#uriChoiceDialog#destroy ();
1440 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1441 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1442 return (Some (Lazy.force nonvars_uris)));
1443 if ok_action = `AUTO then
1444 connect_button dialog#uriChoiceAutoButton (fun _ ->
1445 Helm_registry.set_bool "matita.auto_disambiguation" true;
1446 return (Some (Lazy.force nonvars_uris)))
1448 connect_button dialog#uriChoiceAutoButton (fun _ ->
1449 match model#easy_selection () with
1451 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1452 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1453 match model#easy_selection () with
1455 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1456 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1457 dialog#uriChoiceDialog#show ();
1459 (match !choices with
1460 | None -> raise MatitaTypes.Cancel
1461 | Some uris -> uris)
1465 let cols = new GTree.column_list in
1466 let id_col = cols#add Gobject.Data.string in
1467 let dsc_col = cols#add Gobject.Data.string in
1468 let interp_no_col = cols#add Gobject.Data.int in
1469 let tree_store = GTree.tree_store cols in
1470 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1471 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1472 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1473 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1474 fun tree_view choices ->
1477 tree_view#set_model (Some (tree_store :> GTree.model));
1478 ignore (tree_view#append_column id_view_col);
1479 ignore (tree_view#append_column dsc_view_col);
1480 let name_of_interp =
1481 (* try to find a reasonable name for an interpretation *)
1485 List.assoc "0" interp
1487 incr idx; string_of_int !idx
1489 tree_store#clear ();
1490 let idx = ref ~-1 in
1494 let interp_row = tree_store#append () in
1495 tree_store#set ~row:interp_row ~column:id_col
1496 (name_of_interp interp);
1497 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1500 let row = tree_store#append ~parent:interp_row () in
1501 tree_store#set ~row ~column:id_col id;
1502 tree_store#set ~row ~column:dsc_col dsc;
1503 tree_store#set ~row ~column:interp_no_col !idx)
1507 method get_interp_no tree_path =
1508 let iter = tree_store#get_iter tree_path in
1509 tree_store#get ~row:iter ~column:interp_no_col
1513 let interactive_string_choice
1514 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1516 let gui = instance () in
1517 let dialog = gui#newUriDialog () in
1518 dialog#uriEntryHBox#misc#hide ();
1519 dialog#uriChoiceSelectedButton#misc#hide ();
1520 dialog#uriChoiceAutoButton#misc#hide ();
1521 dialog#uriChoiceConstantsButton#misc#hide ();
1522 dialog#uriChoiceTreeView#selection#set_mode
1523 (`SINGLE :> Gtk.Tags.selection_mode);
1524 let model = new stringListModel dialog#uriChoiceTreeView in
1525 let choices = ref None in
1526 dialog#uriChoiceDialog#set_title title;
1527 let hack_len = MatitaGtkMisc.utf8_string_length text in
1528 let rec colorize acc_len = function
1530 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1531 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1533 let start, stop = HExtlib.loc_of_floc he in
1534 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1535 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1536 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1537 escape_pango_markup str1 ^ "<b>" ^
1538 escape_pango_markup str2 ^ "</b>" ^
1541 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1542 Printf.eprintf "(%d,%d)" start stop) locs; *)
1546 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1549 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1550 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1551 Printf.eprintf "(%d,%d)" start stop) locs;
1552 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1553 dialog#uriChoiceLabel#set_use_markup true;
1554 let txt = colorize 0 locs in
1555 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1556 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1558 dialog#uriChoiceLabel#set_label txt;
1559 List.iter model#easy_append uris;
1562 dialog#uriChoiceDialog#destroy ();
1565 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1566 connect_button dialog#uriChoiceForwardButton (fun _ ->
1567 match model#easy_selection () with
1569 | uris -> return (Some uris));
1570 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1571 dialog#uriChoiceDialog#show ();
1573 (match !choices with
1574 | None -> raise MatitaTypes.Cancel
1575 | Some uris -> uris)
1577 let interactive_interp_choice () text prefix_len choices =
1578 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1579 let filter_choices filter =
1580 let rec is_compatible filter =
1583 | ([],_,_)::tl -> is_compatible filter tl
1584 | (loc::tlloc,id,dsc)::tl ->
1586 if List.assoc (loc,id) filter = dsc then
1587 is_compatible filter ((tlloc,id,dsc)::tl)
1593 List.filter (fun (_,interp) -> is_compatible filter interp)
1595 let rec get_choices loc id =
1600 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1602 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1604 let example_interp =
1608 let ask_user id locs choices =
1609 interactive_string_choice
1611 ~title:"Ambiguous input"
1612 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1614 let rec classify ids filter partial_interpretations =
1616 [] -> List.map fst partial_interpretations
1617 | ([],_,_)::tl -> classify tl filter partial_interpretations
1618 | (loc::tlloc,id,dsc)::tl ->
1619 let choices = get_choices loc id partial_interpretations in
1622 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1625 match ask_user id [loc] choices with
1629 let filter = ((loc,id),chosen_dsc)::filter in
1630 let compatible_interps = filter_choices filter partial_interpretations in
1631 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1633 let enumerated_choices =
1634 let idx = ref ~-1 in
1635 List.map (fun interp -> incr idx; !idx,interp) choices
1637 classify example_interp [] enumerated_choices
1640 (* disambiguator callbacks *)
1641 Disambiguate.set_choose_uris_callback
1642 (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1643 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1644 Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1645 (* gtk initialization *)
1646 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1647 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1648 ignore (GMain.Main.init ())