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 [grafite_status#baseuri]
72 let save_moo grafite_status =
73 let script = MatitaScript.current () in
74 let baseuri = grafite_status#baseuri in
76 grafite_status#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 grafite_status#moo_content_rev;
89 LexiconMarshal.save_lexicon lexicon_fname
90 grafite_status#lstatus.LexiconEngine.lexicon_content_rev;
91 NCicLibrary.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
93 | _ -> clean_current_baseuri grafite_status
96 let ask_unsaved parent =
97 MatitaGtkMisc.ask_confirmation
98 ~parent ~title:"Unsaved work!"
99 ~message:("Your work is <b>unsaved</b>!\n\n"^
100 "<i>Do you want to save the script before continuing?</i>")
103 class interpErrorModel =
104 let cols = new GTree.column_list in
105 let id_col = cols#add Gobject.Data.string in
106 let dsc_col = cols#add Gobject.Data.string in
107 let interp_no_col = cols#add Gobject.Data.caml in
108 let tree_store = GTree.tree_store cols in
109 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
110 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
111 let id_view_col = GTree.view_column ~renderer:id_renderer () in
112 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
113 fun (tree_view: GTree.view) choices ->
116 tree_view#set_model (Some (tree_store :> GTree.model));
117 ignore (tree_view#append_column id_view_col);
118 ignore (tree_view#append_column dsc_view_col);
120 let idx1 = ref ~-1 in
125 if List.length choices = 1 then
128 (let loc_row = tree_store#append () in
131 [passes,envs_and_diffs,_,_] ->
132 tree_store#set ~row:loc_row ~column:id_col
133 ("Error location " ^ string_of_int (!idx1+1) ^
134 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
136 String.concat " " (List.map string_of_int passes) ^
138 tree_store#set ~row:loc_row ~column:interp_no_col
141 tree_store#set ~row:loc_row ~column:id_col
142 ("Error location " ^ string_of_int (!idx1+1));
143 tree_store#set ~row:loc_row ~column:interp_no_col
147 let idx2 = ref ~-1 in
149 (fun passes,envs_and_diffs,_,_ ->
152 if List.length lll = 1 then
155 let msg_row = tree_store#append ?parent:loc_row () in
156 (tree_store#set ~row:msg_row ~column:id_col
157 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
158 string_of_int (!idx2+1) ^
160 String.concat " " (List.map string_of_int passes) ^
162 tree_store#set ~row:msg_row ~column:interp_no_col
163 (!idx1,Some !idx2,None);
165 let idx3 = ref ~-1 in
167 (fun (passes,env,_) ->
170 match envs_and_diffs with
172 let interp_row = tree_store#append ?parent:msg_row () in
173 tree_store#set ~row:interp_row ~column:id_col
174 ("Interpretation " ^ string_of_int (!idx3+1) ^
176 String.concat " " (List.map string_of_int passes) ^
178 tree_store#set ~row:interp_row ~column:interp_no_col
179 (!idx1,Some !idx2,Some !idx3);
186 let row = tree_store#append ?parent:interp_row () in
187 tree_store#set ~row ~column:id_col id;
188 tree_store#set ~row ~column:dsc_col dsc;
189 tree_store#set ~row ~column:interp_no_col
190 (!idx1,Some !idx2,Some !idx3)
194 if List.length lll > 1 then
196 (fun p -> tree_view#expand_row (tree_store#get_path p))
200 method get_interp_no tree_path =
201 let iter = tree_store#get_iter tree_path in
202 tree_store#get ~row:iter ~column:interp_no_col
205 exception UseLibrary;;
207 let rec interactive_error_interp ~all_passes
208 (source_buffer:GSourceView2.source_buffer) notify_exn offset errorll filename
210 (* hook to save a script for each disambiguation error *)
213 source_buffer#get_text ~start:source_buffer#start_iter
214 ~stop:source_buffer#end_iter () in
215 let md5 = Digest.to_hex (Digest.string text) in
217 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
218 let ch = open_out filename in
219 output_string ch text;
222 assert (List.flatten errorll <> []);
224 let remove_non_significant =
225 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
226 let annotated_errorll () =
229 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
231 if all_passes then annotated_errorll () else
232 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
233 (* We remove passes 1,2 and 5,6 *)
236 ::(3,remove_non_significant (safe_list_nth errorll 2))
237 ::(4,remove_non_significant (safe_list_nth errorll 3))
240 if List.flatten (List.map snd res) <> [] then res
242 (* all errors (if any) are not significant: we keep them *)
245 ::(3,(safe_list_nth errorll 2))
246 ::(4,(safe_list_nth errorll 3))
249 if List.flatten (List.map snd res) <> [] then
252 "All disambiguation errors are not significant. Showing them anyway." ;
258 "No errors in phases 2 and 3. Showing all errors in all phases" ;
262 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
265 | [loffset,[_,envs_and_diffs,msg,significant]] ->
266 let _,env,diff = List.hd envs_and_diffs in
268 (MultiPassDisambiguator.DisambiguationError
269 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
271 let dialog = new disambiguationErrors () in
272 dialog#check_widgets ();
274 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
275 let model = new interpErrorModel dialog#treeview choices in
276 dialog#disambiguationErrors#set_title "Disambiguation error";
277 dialog#disambiguationErrorsLabel#set_label
278 "Click on an error to see the corresponding message:";
279 ignore (dialog#treeview#connect#cursor_changed
282 match fst (dialog#treeview#get_cursor ()) with
285 let idx1,idx2,idx3 = model#get_interp_no tree_path in
286 let loffset,lll = List.nth choices idx1 in
287 let _,envs_and_diffs,msg,significant =
289 Some idx2 -> List.nth lll idx2
291 [],[],lazy "Multiple error messages. Please select one.",true
295 Some idx3 -> List.nth envs_and_diffs idx3
296 | None -> [],[],[] (* dymmy value, used *) in
297 let script = MatitaScript.current () in
298 let error_tag = script#error_tag in
299 source_buffer#remove_tag error_tag
300 ~start:source_buffer#start_iter
301 ~stop:source_buffer#end_iter;
303 (MultiPassDisambiguator.DisambiguationError
304 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
307 dialog#disambiguationErrors#destroy ();
310 let fail _ = return () in
311 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
312 connect_button dialog#disambiguationErrorsOkButton
315 match fst (dialog#treeview#get_cursor ()) with
318 let idx1,idx2,idx3 = model#get_interp_no tree_path in
321 Some idx2, Some idx3 ->
322 let _,lll = List.nth choices idx1 in
323 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
324 let _,_,diff = List.nth envs_and_diffs idx3 in
326 | _,_ -> assert false
335 | DisambiguateTypes.Id id ->
336 LexiconAst.Ident_alias (id, desc)
337 | DisambiguateTypes.Symbol (symb, i)->
338 LexiconAst.Symbol_alias (symb, i, desc)
339 | DisambiguateTypes.Num i ->
340 LexiconAst.Number_alias (i, desc)
342 LexiconAstPp.pp_alias alias)
347 (source_buffer#get_iter_at_mark
348 (`NAME "beginning_of_statement")) newtxt ;
351 connect_button dialog#disambiguationErrorsMoreErrors
352 (fun _ -> return () ; raise UseLibrary);
353 connect_button dialog#disambiguationErrorsCancelButton fail;
354 dialog#disambiguationErrors#show ();
358 (** Selection handling
359 * Two clipboards are used: "clipboard" and "primary".
360 * "primary" is used by X, when you hit the middle button mouse is content is
361 * pasted between applications. In Matita this selection always contain the
362 * textual version of the selected term.
363 * "clipboard" is used inside Matita only and support ATM two different targets:
364 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
369 (* creation order _is_ relevant for windows placement *)
370 let main = new mainWin () in
371 let fileSel = new fileSelectionWin () in
372 let findRepl = new findReplWin () in
373 let keyBindingBoxes = (* event boxes which should receive global key events *)
374 [ main#mainWinEventBox ]
376 let console = new console ~buffer:main#logTextView#buffer () in
377 let (source_view: GSourceView2.source_view) =
378 GSourceView2.source_view
380 ~insert_spaces_instead_of_tabs:true ~tab_width:2
381 ~right_margin_position:80 ~show_right_margin:true
382 ~smart_home_end:`AFTER
383 ~packing:main#scriptScrolledWin#add
386 let default_font_size =
387 Helm_registry.get_opt_default Helm_registry.int
388 ~default:BuildTimeConf.default_font_size "matita.font_size"
390 let similarsymbols_tag_name = "similarsymbolos" in
391 let similarsymbols_tag = `NAME similarsymbols_tag_name in
392 let source_buffer = source_view#source_buffer in
394 val mutable chosen_file = None
395 val mutable _ok_not_exists = false
396 val mutable _only_directory = false
397 val mutable font_size = default_font_size
398 val mutable similarsymbols = []
399 val mutable similarsymbols_orig = []
400 val clipboard = GData.clipboard Gdk.Atom.clipboard
401 val primary = GData.clipboard Gdk.Atom.primary
403 method private reset_similarsymbols =
404 similarsymbols <- [];
405 similarsymbols_orig <- [];
406 try source_buffer#delete_mark similarsymbols_tag
407 with GText.No_such_mark _ -> ()
410 let s () = MatitaScript.current () in
411 (* glade's check widgets *)
412 List.iter (fun w -> w#check_widgets ())
413 (let c w = (w :> <check_widgets: unit -> unit>) in
414 [ c fileSel; c main; c findRepl]);
416 List.iter (* global key bindings *)
417 (fun (key, callback) -> self#addKeyBinding key callback)
420 toggle_win ~check:main#showProofMenuItem proof#proofWin;
422 toggle_win ~check:main#showCheckMenuItem check#checkWin;
426 let parse_txt_file file =
427 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
428 let l_rev = ref [] in
431 l_rev := input_line ch :: !l_rev;
440 ~authors:(parse_txt_file "AUTHORS")
441 (*~comments:"comments"*)
442 ~copyright:"Copyright (C) 2005, the HELM team"
443 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
444 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
446 ~version:BuildTimeConf.version
447 ~website:"http://matita.cs.unibo.it"
450 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
451 connect_menu_item main#contentsMenuItem (fun () ->
452 if 0 = Sys.command "which gnome-help" then
454 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
456 ignore (Sys.command cmd)
458 MatitaGtkMisc.report_error ~title:"help system error"
460 "The program gnome-help is not installed\n\n"^
461 "To browse the user manal it is necessary to install "^
462 "the gnome help syste (also known as yelp)")
463 ~parent:main#toplevel ());
464 connect_menu_item main#aboutMenuItem about_dialog#present;
466 let show_find_Repl () =
467 findRepl#toplevel#misc#show ();
468 findRepl#toplevel#misc#grab_focus ()
470 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
472 let highlight start end_ =
473 source_buffer#move_mark `INSERT ~where:start;
474 source_buffer#move_mark `SEL_BOUND ~where:end_;
475 source_view#scroll_mark_onscreen `INSERT
477 let text = findRepl#findEntry#text in
478 let iter = source_buffer#get_iter `SEL_BOUND in
479 match iter#forward_search text with
481 (match source_buffer#start_iter#forward_search text with
483 | Some (start,end_) -> highlight start end_)
484 | Some (start,end_) -> highlight start end_
487 let text = findRepl#replaceEntry#text in
488 let ins = source_buffer#get_iter `INSERT in
489 let sel = source_buffer#get_iter `SEL_BOUND in
490 if ins#compare sel < 0 then
492 ignore(source_buffer#delete_selection ());
493 source_buffer#insert text
496 connect_button findRepl#findButton find_forward;
497 connect_button findRepl#findReplButton replace;
498 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
499 ignore(findRepl#toplevel#event#connect#delete
500 ~callback:(fun _ -> hide_find_Repl ();true));
503 (* phase 1: we save the actual status of the marks and we undo *)
504 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
505 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
506 let locked_iter_offset = locked_iter#offset in
509 (source_view#buffer#create_mark ~name:"lock_point"
510 ~left_gravity:true locked_iter) in
511 source_view#source_buffer#undo ();
512 (* phase 2: we save the cursor position and we redo, restoring
513 the previous status of all the marks *)
514 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
517 (source_view#buffer#create_mark ~name:"undo_point"
518 ~left_gravity:true cursor_iter)
520 source_view#source_buffer#redo ();
521 let mark_iter = source_view#buffer#get_iter_at_mark mark in
522 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
523 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
524 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
525 source_view#buffer#delete_mark mark;
526 source_view#buffer#delete_mark mark2;
527 (* phase 3: if after the undo the cursor was in the locked area,
528 then we move it there again and we perform a goto *)
529 if mark_iter#offset < locked_iter_offset then
531 source_view#buffer#move_mark `INSERT ~where:mark_iter;
532 (MatitaScript.current ())#goto `Cursor ();
534 (* phase 4: we perform again the undo. This time we are sure that
535 the text to undo is not locked *)
536 source_view#source_buffer#undo ();
537 source_view#misc#grab_focus () in
540 (* phase 1: we save the actual status of the marks, we redo and
542 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
543 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
544 let locked_iter_offset = locked_iter#offset in
547 (source_view#buffer#create_mark ~name:"lock_point"
548 ~left_gravity:true locked_iter) in
549 source_view#source_buffer#redo ();
550 source_view#source_buffer#undo ();
551 (* phase 2: we save the cursor position and we restore
552 the previous status of all the marks *)
553 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
556 (source_view#buffer#create_mark ~name:"undo_point"
557 ~left_gravity:true cursor_iter)
559 let mark_iter = source_view#buffer#get_iter_at_mark mark in
560 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
561 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
562 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
563 source_view#buffer#delete_mark mark;
564 source_view#buffer#delete_mark mark2;
565 (* phase 3: if after the undo the cursor is in the locked area,
566 then we move it there again and we perform a goto *)
567 if mark_iter#offset < locked_iter_offset then
569 source_view#buffer#move_mark `INSERT ~where:mark_iter;
570 (MatitaScript.current ())#goto `Cursor ();
572 (* phase 4: we perform again the redo. This time we are sure that
573 the text to redo is not locked *)
574 source_view#source_buffer#redo ();
575 source_view#misc#grab_focus ()
577 connect_menu_item main#undoMenuItem safe_undo;
579 ignore(source_view#source_buffer#connect#can_undo
580 ~callback:main#undoMenuItem#misc#set_sensitive);
581 *) main#undoMenuItem#misc#set_sensitive true;
582 connect_menu_item main#redoMenuItem safe_redo;
584 ignore(source_view#source_buffer#connect#can_redo
585 ~callback:main#redoMenuItem#misc#set_sensitive);
586 *) main#redoMenuItem#misc#set_sensitive true;
587 ignore(source_view#connect#after#populate_popup
588 ~callback:(fun pre_menu ->
589 let menu = new GMenu.menu pre_menu in
590 let menuItems = menu#children in
591 let undoMenuItem, redoMenuItem =
593 [undo;redo;sep1;cut;copy;paste;delete;sep2;
594 selectall;sep3;inputmethod;insertunicodecharacter] ->
595 List.iter menu#remove [ copy; cut; delete; paste ];
597 | _ -> assert false in
599 let i = ref 2 in (* last occupied position *)
600 fun ?label ?stock () ->
602 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
605 let copy = add_menu_item ~stock:`COPY () in
606 let cut = add_menu_item ~stock:`CUT () in
607 let delete = add_menu_item ~stock:`DELETE () in
608 let paste = add_menu_item ~stock:`PASTE () in
609 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
610 copy#misc#set_sensitive self#canCopy;
611 cut#misc#set_sensitive self#canCut;
612 delete#misc#set_sensitive self#canDelete;
613 paste#misc#set_sensitive self#canPaste;
614 paste_pattern#misc#set_sensitive self#canPastePattern;
615 connect_menu_item copy self#copy;
616 connect_menu_item cut self#cut;
617 connect_menu_item delete self#delete;
618 connect_menu_item paste self#paste;
619 connect_menu_item paste_pattern self#pastePattern;
620 let new_undoMenuItem =
621 GMenu.image_menu_item
622 ~image:(GMisc.image ~stock:`UNDO ())
625 ~packing:(menu#insert ~pos:0) () in
626 new_undoMenuItem#misc#set_sensitive
627 (undoMenuItem#misc#get_flag `SENSITIVE);
628 menu#remove (undoMenuItem :> GMenu.menu_item);
629 connect_menu_item new_undoMenuItem safe_undo;
630 let new_redoMenuItem =
631 GMenu.image_menu_item
632 ~image:(GMisc.image ~stock:`REDO ())
635 ~packing:(menu#insert ~pos:1) () in
636 new_redoMenuItem#misc#set_sensitive
637 (redoMenuItem#misc#get_flag `SENSITIVE);
638 menu#remove (redoMenuItem :> GMenu.menu_item);
639 connect_menu_item new_redoMenuItem safe_redo));
641 connect_menu_item main#editMenu (fun () ->
642 main#copyMenuItem#misc#set_sensitive self#canCopy;
643 main#cutMenuItem#misc#set_sensitive self#canCut;
644 main#deleteMenuItem#misc#set_sensitive self#canDelete;
645 main#pasteMenuItem#misc#set_sensitive self#canPaste;
646 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
647 connect_menu_item main#copyMenuItem self#copy;
648 connect_menu_item main#cutMenuItem self#cut;
649 connect_menu_item main#deleteMenuItem self#delete;
650 connect_menu_item main#pasteMenuItem self#paste;
651 connect_menu_item main#pastePatternMenuItem self#pastePattern;
652 connect_menu_item main#selectAllMenuItem (fun () ->
653 source_buffer#move_mark `INSERT source_buffer#start_iter;
654 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
655 connect_menu_item main#findReplMenuItem show_find_Repl;
656 connect_menu_item main#externalEditorMenuItem self#externalEditor;
657 connect_menu_item main#ligatureButton self#nextSimilarSymbol;
658 ignore(source_buffer#connect#after#insert_text
659 ~callback:(fun iter str ->
660 if main#menuitemAutoAltL#active && (str = " " || str = "\n") then
661 ignore(self#expand_virtual_if_any iter str)));
662 ignore (findRepl#findEntry#connect#activate find_forward);
663 (* interface lockers *)
665 main#buttonsToolbar#misc#set_sensitive false;
666 main#scriptMenu#misc#set_sensitive false;
667 source_view#set_editable false
670 main#buttonsToolbar#misc#set_sensitive true;
671 main#scriptMenu#misc#set_sensitive true;
672 source_view#set_editable true;
673 (*The next line seems sufficient to avoid some unknown race condition *)
674 GtkThread.sync (fun () -> ()) ()
676 let worker_thread = ref None in
678 let floc, msg = MatitaExcPp.to_string exn in
683 let (x, y) = HExtlib.loc_of_floc floc in
684 let script = MatitaScript.current () in
685 let locked_mark = script#locked_mark in
686 let error_tag = script#error_tag in
688 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
689 let x' = baseoffset + x in
690 let y' = baseoffset + y in
691 let x_iter = source_buffer#get_iter (`OFFSET x') in
692 let y_iter = source_buffer#get_iter (`OFFSET y') in
693 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
695 id := Some (source_buffer#connect#changed ~callback:(fun () ->
696 source_buffer#remove_tag error_tag
697 ~start:source_buffer#start_iter
698 ~stop:source_buffer#end_iter;
700 | None -> assert false (* a race condition occurred *)
702 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
703 source_buffer#place_cursor
704 (source_buffer#get_iter (`OFFSET x'));
711 let saved_use_library= !MultiPassDisambiguator.use_library in
713 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
715 MultiPassDisambiguator.use_library := saved_use_library;
718 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
720 interactive_error_interp
721 ~all_passes:!all_disambiguation_passes source_buffer
722 notify_exn offset errorll (s())#filename
725 MultiPassDisambiguator.use_library := true;
728 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
729 interactive_error_interp ~all_passes:true source_buffer
730 notify_exn offset errorll (s())#filename
733 | exc -> notify_exn exc);
734 MultiPassDisambiguator.use_library := saved_use_library;
737 (try notify_exn exc with Sys.Break as e -> notify_exn e);
741 worker_thread := Some (Thread.create thread_main ())
744 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
745 let interrupt = ref None in
746 let old_callback = ref (function _ -> ()) in
747 let force_interrupt n =
748 (* This function is called just before the thread's timeslice ends *)
750 if Some(Thread.id(Thread.self())) = !interrupt then
751 (interrupt := None; raise Sys.Break) in
753 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
754 Sys.Signal_handle f -> old_callback := f
756 | Sys.Signal_default -> assert false
759 match !worker_thread with
761 | Some t -> interrupt := Some (Thread.id t) in
765 f (); source_view#misc#grab_focus ()
767 exc -> source_view#misc#grab_focus (); raise exc in
769 (* file selection win *)
770 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
771 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
774 fileSel#fileSelectionWin#misc#hide ();
779 let fname = fileSel#fileSelectionWin#filename in
780 if Sys.file_exists fname then
782 if HExtlib.is_regular fname && not (_only_directory) then
784 else if _only_directory && HExtlib.is_dir fname then
789 if _ok_not_exists then
792 | `CANCEL -> return None
794 | `DELETE_EVENT -> return None));
796 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
798 let adj = main#logScrolledWin#vadjustment in
799 ignore (adj#connect#changed
800 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
801 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
802 (* natural deduction palette *)
803 main#tacticsButtonsHandlebox#misc#hide ();
804 MatitaGtkMisc.toggle_callback
806 if b then main#tacticsButtonsHandlebox#misc#show ()
807 else main#tacticsButtonsHandlebox#misc#hide ())
808 ~check:main#menuitemPalette;
809 connect_button main#butImpl_intro
810 (fun () -> source_buffer#insert "apply rule (⇒#i […] (…));\n");
811 connect_button main#butAnd_intro
812 (fun () -> source_buffer#insert
813 "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
814 connect_button main#butOr_intro_left
815 (fun () -> source_buffer#insert "apply rule (∨#i_l (…));\n");
816 connect_button main#butOr_intro_right
817 (fun () -> source_buffer#insert "apply rule (∨#i_r (…));\n");
818 connect_button main#butNot_intro
819 (fun () -> source_buffer#insert "apply rule (¬#i […] (…));\n");
820 connect_button main#butTop_intro
821 (fun () -> source_buffer#insert "apply rule (⊤#i);\n");
822 connect_button main#butImpl_elim
823 (fun () -> source_buffer#insert
824 "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
825 connect_button main#butAnd_elim_left
826 (fun () -> source_buffer#insert "apply rule (∧#e_l (…));\n");
827 connect_button main#butAnd_elim_right
828 (fun () -> source_buffer#insert "apply rule (∧#e_r (…));\n");
829 connect_button main#butOr_elim
830 (fun () -> source_buffer#insert
831 "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
832 connect_button main#butNot_elim
833 (fun () -> source_buffer#insert
834 "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
835 connect_button main#butBot_elim
836 (fun () -> source_buffer#insert "apply rule (⊥#e (…));\n");
837 connect_button main#butRAA
838 (fun () -> source_buffer#insert "apply rule (RAA […] (…));\n");
839 connect_button main#butUseLemma
840 (fun () -> source_buffer#insert "apply rule (lem #premises name …);\n");
841 connect_button main#butDischarge
842 (fun () -> source_buffer#insert "apply rule (discharge […]);\n");
844 connect_button main#butForall_intro
845 (fun () -> source_buffer#insert "apply rule (∀#i {…} (…));\n");
846 connect_button main#butForall_elim
847 (fun () -> source_buffer#insert "apply rule (∀#e {…} (…));\n");
848 connect_button main#butExists_intro
849 (fun () -> source_buffer#insert "apply rule (∃#i {…} (…));\n");
850 connect_button main#butExists_elim
851 (fun () -> source_buffer#insert
852 "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
856 main#scriptNotebook#remove_page 1;
857 main#scriptNotebook#set_show_tabs false;
858 (* / TO BE REMOVED *)
859 let module Hr = Helm_registry in
860 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
862 | true -> main#toplevel#fullscreen ()
863 | false -> main#toplevel#unfullscreen ());
864 main#fullscreenMenuItem#set_active false;
865 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
868 CicNotation.set_active_notations
869 (List.map fst (CicNotation.get_all_notations ()))
871 CicNotation.set_active_notations []);
872 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
873 ~callback:(fun enabled -> Acic2content.hide_coercions := enabled);
874 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
875 ~callback:(fun enabled ->
876 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
877 main#unicodeAsTexMenuItem#set_active
878 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
880 HLog.set_log_callback self#console#log_callback;
881 GtkSignal.user_handler :=
883 | MatitaScript.ActionCancelled s -> HLog.error s
885 if not (Helm_registry.get_bool "matita.debug") then
890 let source_language_manager =
891 GSourceView2.source_language_manager ~default:true in
892 source_language_manager#set_search_path
893 (BuildTimeConf.runtime_base_dir ::
894 source_language_manager#search_path);
895 match source_language_manager#language "grafite" with
897 HLog.warn(sprintf "can't load a language file for \"grafite\" in %s"
898 BuildTimeConf.runtime_base_dir)
899 | Some x as matita_lang ->
900 source_buffer#set_language matita_lang;
901 source_buffer#set_highlight_syntax true
904 (s())#assignFileName None;
905 main#saveMenuItem#misc#set_sensitive false
907 let saveAsScript () =
909 match self#chooseFile ~ok_not_exists:true () with
912 script#assignFileName (Some f);
913 script#saveToFile ();
914 console#message ("'"^f^"' saved.\n");
920 if script#has_name then
921 (script#saveToFile ();
922 console#message ("'"^script#filename^"' saved.\n"))
925 let abandon_script () =
926 let grafite_status = (s ())#grafite_status in
927 if source_view#buffer#modified then
928 (match ask_unsaved main#toplevel with
929 | `YES -> saveScript ()
931 | `CANCEL -> raise MatitaTypes.Cancel);
932 save_moo grafite_status
937 match self#chooseFile () with
941 script#assignFileName (Some f);
942 source_view#source_buffer#begin_not_undoable_action ();
943 script#loadFromFile f;
944 source_view#source_buffer#end_not_undoable_action ();
945 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
946 source_view#buffer#place_cursor source_view#buffer#start_iter;
947 console#message ("'"^f^"' loaded.\n");
950 with MatitaTypes.Cancel -> ()
954 source_view#source_buffer#begin_not_undoable_action ();
957 source_view#source_buffer#end_not_undoable_action ();
959 (s ())#assignFileName None
962 source_buffer#place_cursor
963 (source_buffer#get_iter_at_mark (`NAME "locked")) in
964 let advance _ = (MatitaScript.current ())#advance (); cursor () in
965 let retract _ = (MatitaScript.current ())#retract (); cursor () in
966 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
967 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
968 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
969 let advance = locker (keep_focus advance) in
970 let retract = locker (keep_focus retract) in
971 let top = locker (keep_focus top) in
972 let bottom = locker (keep_focus bottom) in
973 let jump = locker (keep_focus jump) in
975 self#setQuitCallback (fun () ->
976 let script = MatitaScript.current () in
977 if source_view#buffer#modified then
978 match ask_unsaved main#toplevel with
981 save_moo script#grafite_status;
983 | `NO -> GMain.Main.quit ()
986 (save_moo script#grafite_status;
987 GMain.Main.quit ()));
988 connect_button main#scriptAdvanceButton advance;
989 connect_button main#scriptRetractButton retract;
990 connect_button main#scriptTopButton top;
991 connect_button main#scriptBottomButton bottom;
992 connect_button main#scriptJumpButton jump;
993 connect_button main#scriptAbortButton kill_worker;
994 connect_menu_item main#scriptAdvanceMenuItem advance;
995 connect_menu_item main#scriptRetractMenuItem retract;
996 connect_menu_item main#scriptTopMenuItem top;
997 connect_menu_item main#scriptBottomMenuItem bottom;
998 connect_menu_item main#scriptJumpMenuItem jump;
999 connect_menu_item main#openMenuItem loadScript;
1000 connect_menu_item main#saveMenuItem saveScript;
1001 connect_menu_item main#saveAsMenuItem saveAsScript;
1002 connect_menu_item main#newMenuItem newScript;
1003 connect_menu_item main#showCoercionsGraphMenuItem
1005 let c = MatitaMathView.cicBrowser () in
1006 c#load (`About `Coercions));
1007 connect_menu_item main#showHintsDbMenuItem
1009 let c = MatitaMathView.cicBrowser () in
1010 c#load (`About `Hints));
1011 connect_menu_item main#showAutoGuiMenuItem
1012 (fun _ -> MatitaAutoGui.auto_dialog Auto.get_auto_status);
1013 connect_menu_item main#showTermGrammarMenuItem
1015 let c = MatitaMathView.cicBrowser () in
1016 c#load (`About `Grammar));
1017 connect_menu_item main#showUnicodeTable
1019 let c = MatitaMathView.cicBrowser () in
1020 c#load (`About `TeX));
1021 (* script monospace font stuff *)
1022 self#updateFontSize ();
1024 main#debugMenu#misc#hide ();
1026 main#hintNotebook#misc#hide ();
1028 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1029 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1030 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1033 self#sourceView#misc#grab_focus ();
1034 (* main win dimension *)
1035 let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
1036 let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
1037 (* hack for xinerama, no proper support of monitors from lablgtk *)
1038 let width = if width > 1600 then width / 2 else width in
1039 let height = if height > 1200 then height / 2 else height in
1040 let main_w = width * 90 / 100 in
1041 let main_h = height * 80 / 100 in
1042 let script_w = main_w * 6 / 10 in
1043 main#toplevel#resize ~width:main_w ~height:main_h;
1044 main#hpaneScriptSequent#set_position script_w;
1046 ignore(source_view#connect#after#paste_clipboard
1047 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1048 (* clean_locked is set to true only "during" a PRIMARY paste
1049 operation (i.e. by clicking with the second mouse button) *)
1050 let clean_locked = ref false in
1051 ignore(source_view#event#connect#button_press
1054 if GdkEvent.Button.button button = 2 then
1055 clean_locked := true;
1058 ignore(source_view#event#connect#button_release
1059 ~callback:(fun button -> clean_locked := false; false));
1060 ignore(source_view#buffer#connect#after#apply_tag
1062 fun tag ~start:_ ~stop:_ ->
1064 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1067 clean_locked := false;
1068 (MatitaScript.current ())#clean_dirty_lock;
1069 clean_locked := true
1071 (* math view handling *)
1072 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1073 ignore(MatitaMathView.cicBrowser ()));
1074 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1075 self#increaseFontSize ();
1076 MatitaMathView.increase_font_size ();
1077 MatitaMathView.update_font_sizes ());
1078 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1079 self#decreaseFontSize ();
1080 MatitaMathView.decrease_font_size ();
1081 MatitaMathView.update_font_sizes ());
1082 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1083 self#resetFontSize ();
1084 MatitaMathView.reset_font_size ();
1085 MatitaMathView.update_font_sizes ());
1086 MatitaMathView.reset_font_size ();
1088 (** selections / clipboards handling *)
1090 method markupSelected = MatitaMathView.has_selection ()
1091 method private textSelected =
1092 (source_buffer#get_iter_at_mark `INSERT)#compare
1093 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1094 method private somethingSelected = self#markupSelected || self#textSelected
1095 method private markupStored = MatitaMathView.has_clipboard ()
1096 method private textStored = clipboard#text <> None
1097 method private somethingStored = self#markupStored || self#textStored
1099 method canCopy = self#somethingSelected
1100 method canCut = self#textSelected
1101 method canDelete = self#textSelected
1102 method canPaste = self#somethingStored
1103 method canPastePattern = self#markupStored
1106 if self#textSelected
1108 MatitaMathView.empty_clipboard ();
1109 source_view#buffer#copy_clipboard clipboard;
1111 MatitaMathView.copy_selection ()
1113 source_view#buffer#cut_clipboard clipboard;
1114 MatitaMathView.empty_clipboard ()
1115 method delete () = ignore (source_view#buffer#delete_selection ())
1117 if MatitaMathView.has_clipboard ()
1118 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1119 else source_view#buffer#paste_clipboard clipboard;
1120 (MatitaScript.current ())#clean_dirty_lock
1121 method pastePattern () =
1122 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1124 method private expand_virtual_if_any iter tok =
1126 let len = MatitaGtkMisc.utf8_string_length tok in
1128 let prev = iter#copy#backward_chars len in
1129 prev#get_slice ~stop:(prev#copy#backward_find_char
1130 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
1132 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
1133 self#reset_similarsymbols;
1134 let s = Glib.Utf8.from_unichar symb in
1135 assert(Glib.Utf8.validate s);
1136 source_buffer#delete ~start:iter
1137 ~stop:(iter#copy#backward_chars
1138 (MatitaGtkMisc.utf8_string_length inplaceof + len));
1139 source_buffer#insert ~iter
1140 (if inplaceof.[0] = '\\' then s else (s ^ tok));
1142 with Virtuals.Not_a_virtual -> false
1144 val similar_memory = Hashtbl.create 97
1145 val mutable old_used_memory = false
1147 method private nextSimilarSymbol () =
1148 let write_similarsymbol s =
1149 let s = Glib.Utf8.from_unichar s in
1150 let iter = source_buffer#get_iter_at_mark `INSERT in
1151 assert(Glib.Utf8.validate s);
1152 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
1153 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s;
1154 (try source_buffer#delete_mark similarsymbols_tag
1155 with GText.No_such_mark _ -> ());
1156 ignore(source_buffer#create_mark ~name:similarsymbols_tag_name
1157 (source_buffer#get_iter_at_mark `INSERT));
1159 let new_similarsymbol =
1161 let iter_ins = source_buffer#get_iter_at_mark `INSERT in
1162 let iter_lig = source_buffer#get_iter_at_mark similarsymbols_tag in
1163 not (iter_ins#equal iter_lig)
1164 with GText.No_such_mark _ -> true
1166 if new_similarsymbol then
1167 (if not(self#expand_virtual_if_any (source_buffer#get_iter_at_mark `INSERT) "")then
1169 let i = source_buffer#get_iter_at_mark `INSERT in
1170 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
1172 (match Virtuals.similar_symbols last_symbol with
1175 similarsymbols_orig <- eqclass;
1177 try Hashtbl.find similar_memory similarsymbols_orig
1179 let is_used = List.map (fun x -> x,false) eqclass in
1180 Hashtbl.add similar_memory eqclass is_used;
1185 List.partition (fun s -> List.assoc s is_used) eqclass
1187 match used @ unused with a::b::c -> a,b,c | _ -> assert false
1190 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
1192 old_used_memory <- List.assoc hd is_used;
1194 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
1196 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1197 write_similarsymbol hd;
1198 similarsymbols <- tl @ [ hd ]))
1200 match similarsymbols with
1203 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
1204 let last = HExtlib.list_last tl in
1205 let old_used_for_last = old_used_memory in
1206 old_used_memory <- List.assoc hd is_used;
1208 (hd, true) :: (last,old_used_for_last) ::
1209 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
1211 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1212 similarsymbols <- tl @ [ hd ];
1213 write_similarsymbol hd
1215 method private externalEditor () =
1216 let cmd = Helm_registry.get "matita.external_editor" in
1217 (* ZACK uncomment to enable interactive ask of external editor command *)
1220 "External editor command:
1221 %f will be substitute for the script name,
1222 %p for the cursor position in bytes,
1223 %l for the execution point in bytes."
1225 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1226 ~default:(Helm_registry.get "matita.external_editor") ()
1228 let script = MatitaScript.current () in
1229 let fname = script#filename in
1231 source_buffer#start_iter#get_slice
1232 ~stop:(source_buffer#get_iter_at_mark mark)
1234 let locked = `MARK script#locked_mark in
1235 let string_pos mark = string_of_int (String.length (slice mark)) in
1236 let cursor_pos = string_pos `INSERT in
1237 let locked_pos = string_pos locked in
1239 Pcre.replace ~pat:"%f" ~templ:fname
1240 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1241 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1244 let locked_before = slice locked in
1245 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1246 ignore (Unix.system cmd);
1247 source_buffer#set_text (HExtlib.input_file fname);
1248 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1249 source_buffer#move_mark locked locked_iter;
1250 source_buffer#apply_tag script#locked_tag
1251 ~start:source_buffer#start_iter ~stop:locked_iter;
1252 let locked_after = slice locked in
1256 for i = 0 to String.length locked_before - 1 do
1257 if locked_before.[i] <> locked_after.[i] then begin
1258 source_buffer#place_cursor
1259 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1260 script#goto `Cursor ();
1262 end else if locked_before.[i] = '\n' then begin
1269 | Invalid_argument _ -> script#goto `Bottom ()
1271 method loadScript file =
1272 let script = MatitaScript.current () in
1274 script#assignFileName (Some file);
1275 let file = script#filename in
1277 if Sys.file_exists file then file
1278 else BuildTimeConf.script_template
1280 source_view#source_buffer#begin_not_undoable_action ();
1281 script#loadFromFile content;
1282 source_view#source_buffer#end_not_undoable_action ();
1283 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1284 source_view#buffer#place_cursor source_view#buffer#start_iter;
1285 console#message ("'"^file^"' loaded.");
1286 self#_enableSaveTo file
1289 let s = MatitaScript.current () in
1290 let w = main#toplevel in
1291 let set x = w#set_title x in
1293 "Matita - " ^ Filename.basename s#filename ^
1294 (if b then "*" else "") ^
1295 " in " ^ s#buri_of_current_file
1299 method private _enableSaveTo file =
1300 self#main#saveMenuItem#misc#set_sensitive true
1302 method console = console
1303 method sourceView: GSourceView2.source_view =
1304 (source_view: GSourceView2.source_view)
1305 method fileSel = fileSel
1306 method findRepl = findRepl
1309 method newBrowserWin () =
1311 inherit browserWin ()
1312 val combo = GEdit.entry ()
1314 self#check_widgets ();
1315 let combo_widget = combo#coerce in
1316 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1317 combo#misc#grab_focus ()
1318 method browserUri = combo
1321 method newUriDialog () =
1322 let dialog = new uriChoiceDialog () in
1323 dialog#check_widgets ();
1326 method newConfirmationDialog () =
1327 let dialog = new confirmationDialog () in
1328 dialog#check_widgets ();
1331 method newEmptyDialog () =
1332 let dialog = new emptyDialog () in
1333 dialog#check_widgets ();
1336 method private addKeyBinding key callback =
1337 List.iter (fun evbox -> add_key_binding key callback evbox)
1340 method setQuitCallback callback =
1341 connect_menu_item main#quitMenuItem callback;
1342 ignore (main#toplevel#event#connect#delete
1343 (fun _ -> callback ();true));
1344 self#addKeyBinding GdkKeysyms._q callback
1346 method chooseFile ?(ok_not_exists = false) () =
1347 _ok_not_exists <- ok_not_exists;
1348 _only_directory <- false;
1349 fileSel#fileSelectionWin#show ();
1353 method private chooseDir ?(ok_not_exists = false) () =
1354 _ok_not_exists <- ok_not_exists;
1355 _only_directory <- true;
1356 fileSel#fileSelectionWin#show ();
1358 (* we should check that this is a directory *)
1361 method askText ?(title = "") ?(msg = "") () =
1362 let dialog = new textDialog () in
1363 dialog#textDialog#set_title title;
1364 dialog#textDialogLabel#set_label msg;
1365 let text = ref None in
1368 dialog#textDialog#destroy ();
1371 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1372 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1373 connect_button dialog#textDialogOkButton (fun _ ->
1374 let text = dialog#textDialogTextView#buffer#get_text () in
1375 return (Some text));
1376 dialog#textDialog#show ();
1380 method private updateFontSize () =
1381 self#sourceView#misc#modify_font_by_name
1382 (sprintf "%s %d" BuildTimeConf.script_font font_size);
1383 MatitaAutoGui.set_font_size font_size
1385 method increaseFontSize () =
1386 font_size <- font_size + 1;
1387 self#updateFontSize ()
1389 method decreaseFontSize () =
1390 font_size <- font_size - 1;
1391 self#updateFontSize ()
1393 method resetFontSize () =
1394 font_size <- default_font_size;
1395 self#updateFontSize ()
1400 let g = new gui () in
1401 gui_instance := Some g;
1402 MatitaMathView.set_gui g;
1405 let instance = singleton gui
1407 let non p x = not (p x)
1409 (* this is a shit and should be changed :-{ *)
1410 let interactive_uri_choice
1411 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1412 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1413 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1417 let gui = instance () in
1418 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1419 if (selection_mode <> `SINGLE) &&
1420 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1422 Lazy.force nonvars_uris
1424 let dialog = gui#newUriDialog () in
1425 if hide_uri_entry then
1426 dialog#uriEntryHBox#misc#hide ();
1429 dialog#uriChoiceSelectedButton#misc#hide ();
1430 dialog#uriChoiceConstantsButton#misc#hide ();
1432 dialog#okLabel#set_label ok_label;
1433 dialog#uriChoiceTreeView#selection#set_mode
1434 (selection_mode :> Gtk.Tags.selection_mode);
1435 let model = new stringListModel dialog#uriChoiceTreeView in
1436 let choices = ref None in
1440 dialog#copyButton#misc#show ();
1441 connect_button dialog#copyButton
1443 match model#easy_selection () with
1446 dialog#uriChoiceDialog#set_title title;
1447 dialog#uriChoiceLabel#set_text msg;
1448 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1449 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1452 dialog#uriChoiceDialog#destroy ();
1455 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1456 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1457 return (Some (Lazy.force nonvars_uris)));
1458 if ok_action = `AUTO then
1459 connect_button dialog#uriChoiceAutoButton (fun _ ->
1460 Helm_registry.set_bool "matita.auto_disambiguation" true;
1461 return (Some (Lazy.force nonvars_uris)))
1463 connect_button dialog#uriChoiceAutoButton (fun _ ->
1464 match model#easy_selection () with
1466 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1467 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1468 match model#easy_selection () with
1470 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1471 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1472 dialog#uriChoiceDialog#show ();
1474 (match !choices with
1475 | None -> raise MatitaTypes.Cancel
1476 | Some uris -> uris)
1480 let cols = new GTree.column_list in
1481 let id_col = cols#add Gobject.Data.string in
1482 let dsc_col = cols#add Gobject.Data.string in
1483 let interp_no_col = cols#add Gobject.Data.int in
1484 let tree_store = GTree.tree_store cols in
1485 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1486 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1487 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1488 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1489 fun tree_view choices ->
1492 tree_view#set_model (Some (tree_store :> GTree.model));
1493 ignore (tree_view#append_column id_view_col);
1494 ignore (tree_view#append_column dsc_view_col);
1495 let name_of_interp =
1496 (* try to find a reasonable name for an interpretation *)
1500 List.assoc "0" interp
1502 incr idx; string_of_int !idx
1504 tree_store#clear ();
1505 let idx = ref ~-1 in
1509 let interp_row = tree_store#append () in
1510 tree_store#set ~row:interp_row ~column:id_col
1511 (name_of_interp interp);
1512 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1515 let row = tree_store#append ~parent:interp_row () in
1516 tree_store#set ~row ~column:id_col id;
1517 tree_store#set ~row ~column:dsc_col dsc;
1518 tree_store#set ~row ~column:interp_no_col !idx)
1522 method get_interp_no tree_path =
1523 let iter = tree_store#get_iter tree_path in
1524 tree_store#get ~row:iter ~column:interp_no_col
1528 let interactive_string_choice
1529 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1531 let gui = instance () in
1532 let dialog = gui#newUriDialog () in
1533 dialog#uriEntryHBox#misc#hide ();
1534 dialog#uriChoiceSelectedButton#misc#hide ();
1535 dialog#uriChoiceAutoButton#misc#hide ();
1536 dialog#uriChoiceConstantsButton#misc#hide ();
1537 dialog#uriChoiceTreeView#selection#set_mode
1538 (`SINGLE :> Gtk.Tags.selection_mode);
1539 let model = new stringListModel dialog#uriChoiceTreeView in
1540 let choices = ref None in
1541 dialog#uriChoiceDialog#set_title title;
1542 let hack_len = MatitaGtkMisc.utf8_string_length text in
1543 let rec colorize acc_len = function
1545 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1546 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1548 let start, stop = HExtlib.loc_of_floc he in
1549 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1550 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1551 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1552 escape_pango_markup str1 ^ "<b>" ^
1553 escape_pango_markup str2 ^ "</b>" ^
1556 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1557 Printf.eprintf "(%d,%d)" start stop) locs; *)
1561 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1564 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1565 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1566 Printf.eprintf "(%d,%d)" start stop) locs;
1567 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1568 dialog#uriChoiceLabel#set_use_markup true;
1569 let txt = colorize 0 locs in
1570 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1571 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1573 dialog#uriChoiceLabel#set_label txt;
1574 List.iter model#easy_append uris;
1577 dialog#uriChoiceDialog#destroy ();
1580 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1581 connect_button dialog#uriChoiceForwardButton (fun _ ->
1582 match model#easy_selection () with
1584 | uris -> return (Some uris));
1585 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1586 dialog#uriChoiceDialog#show ();
1588 (match !choices with
1589 | None -> raise MatitaTypes.Cancel
1590 | Some uris -> uris)
1592 let interactive_interp_choice () text prefix_len choices =
1593 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1594 let filter_choices filter =
1595 let rec is_compatible filter =
1598 | ([],_,_)::tl -> is_compatible filter tl
1599 | (loc::tlloc,id,dsc)::tl ->
1601 if List.assoc (loc,id) filter = dsc then
1602 is_compatible filter ((tlloc,id,dsc)::tl)
1608 List.filter (fun (_,interp) -> is_compatible filter interp)
1610 let rec get_choices loc id =
1615 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1617 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1619 let example_interp =
1623 let ask_user id locs choices =
1624 interactive_string_choice
1626 ~title:"Ambiguous input"
1627 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1629 let rec classify ids filter partial_interpretations =
1631 [] -> List.map fst partial_interpretations
1632 | ([],_,_)::tl -> classify tl filter partial_interpretations
1633 | (loc::tlloc,id,dsc)::tl ->
1634 let choices = get_choices loc id partial_interpretations in
1637 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1640 match ask_user id [loc] choices with
1644 let filter = ((loc,id),chosen_dsc)::filter in
1645 let compatible_interps = filter_choices filter partial_interpretations in
1646 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1648 let enumerated_choices =
1649 let idx = ref ~-1 in
1650 List.map (fun interp -> incr idx; !idx,interp) choices
1652 classify example_interp [] enumerated_choices
1655 (* disambiguator callbacks *)
1656 Disambiguate.set_choose_uris_callback
1657 (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1658 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1659 Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1660 (* gtk initialization *)
1661 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1662 ignore (GMain.Main.init ())