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
75 match script#bos, script#eos with
78 GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
80 | _ -> clean_current_baseuri grafite_status
83 let ask_unsaved parent =
84 MatitaGtkMisc.ask_confirmation
85 ~parent ~title:"Unsaved work!"
86 ~message:("Your work is <b>unsaved</b>!\n\n"^
87 "<i>Do you want to save the script before continuing?</i>")
90 class interpErrorModel =
91 let cols = new GTree.column_list in
92 let id_col = cols#add Gobject.Data.string in
93 let dsc_col = cols#add Gobject.Data.string in
94 let interp_no_col = cols#add Gobject.Data.caml in
95 let tree_store = GTree.tree_store cols in
96 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
97 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
98 let id_view_col = GTree.view_column ~renderer:id_renderer () in
99 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
100 fun (tree_view: GTree.view) choices ->
103 tree_view#set_model (Some (tree_store :> GTree.model));
104 ignore (tree_view#append_column id_view_col);
105 ignore (tree_view#append_column dsc_view_col);
107 let idx1 = ref ~-1 in
112 if List.length choices = 1 then
115 (let loc_row = tree_store#append () in
118 [passes,envs_and_diffs,_,_] ->
119 tree_store#set ~row:loc_row ~column:id_col
120 ("Error location " ^ string_of_int (!idx1+1) ^
121 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
123 String.concat " " (List.map string_of_int passes) ^
125 tree_store#set ~row:loc_row ~column:interp_no_col
128 tree_store#set ~row:loc_row ~column:id_col
129 ("Error location " ^ string_of_int (!idx1+1));
130 tree_store#set ~row:loc_row ~column:interp_no_col
134 let idx2 = ref ~-1 in
136 (fun passes,envs_and_diffs,_,_ ->
139 if List.length lll = 1 then
142 let msg_row = tree_store#append ?parent:loc_row () in
143 (tree_store#set ~row:msg_row ~column:id_col
144 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
145 string_of_int (!idx2+1) ^
147 String.concat " " (List.map string_of_int passes) ^
149 tree_store#set ~row:msg_row ~column:interp_no_col
150 (!idx1,Some !idx2,None);
152 let idx3 = ref ~-1 in
154 (fun (passes,env,_) ->
157 match envs_and_diffs with
159 let interp_row = tree_store#append ?parent:msg_row () in
160 tree_store#set ~row:interp_row ~column:id_col
161 ("Interpretation " ^ string_of_int (!idx3+1) ^
163 String.concat " " (List.map string_of_int passes) ^
165 tree_store#set ~row:interp_row ~column:interp_no_col
166 (!idx1,Some !idx2,Some !idx3);
173 let row = tree_store#append ?parent:interp_row () in
174 tree_store#set ~row ~column:id_col id;
175 tree_store#set ~row ~column:dsc_col dsc;
176 tree_store#set ~row ~column:interp_no_col
177 (!idx1,Some !idx2,Some !idx3)
181 if List.length lll > 1 then
183 (fun p -> tree_view#expand_row (tree_store#get_path p))
187 method get_interp_no tree_path =
188 let iter = tree_store#get_iter tree_path in
189 tree_store#get ~row:iter ~column:interp_no_col
192 exception UseLibrary;;
194 let rec interactive_error_interp ~all_passes
195 (source_buffer:GSourceView2.source_buffer) notify_exn offset errorll filename
197 (* hook to save a script for each disambiguation error *)
200 source_buffer#get_text ~start:source_buffer#start_iter
201 ~stop:source_buffer#end_iter () in
202 let md5 = Digest.to_hex (Digest.string text) in
204 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
205 let ch = open_out filename in
206 output_string ch text;
209 assert (List.flatten errorll <> []);
211 let remove_non_significant =
212 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
213 let annotated_errorll () =
216 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
218 if all_passes then annotated_errorll () else
219 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
220 (* We remove passes 1,2 and 5,6 *)
223 ::(3,remove_non_significant (safe_list_nth errorll 2))
224 ::(4,remove_non_significant (safe_list_nth errorll 3))
227 if List.flatten (List.map snd res) <> [] then res
229 (* all errors (if any) are not significant: we keep them *)
232 ::(3,(safe_list_nth errorll 2))
233 ::(4,(safe_list_nth errorll 3))
236 if List.flatten (List.map snd res) <> [] then
239 "All disambiguation errors are not significant. Showing them anyway." ;
245 "No errors in phases 2 and 3. Showing all errors in all phases" ;
249 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
252 | [loffset,[_,envs_and_diffs,msg,significant]] ->
253 let _,env,diff = List.hd envs_and_diffs in
255 (MultiPassDisambiguator.DisambiguationError
256 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
258 let dialog = new disambiguationErrors () in
259 dialog#check_widgets ();
261 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
262 let model = new interpErrorModel dialog#treeview choices in
263 dialog#disambiguationErrors#set_title "Disambiguation error";
264 dialog#disambiguationErrorsLabel#set_label
265 "Click on an error to see the corresponding message:";
266 ignore (dialog#treeview#connect#cursor_changed
269 match fst (dialog#treeview#get_cursor ()) with
272 let idx1,idx2,idx3 = model#get_interp_no tree_path in
273 let loffset,lll = List.nth choices idx1 in
274 let _,envs_and_diffs,msg,significant =
276 Some idx2 -> List.nth lll idx2
278 [],[],lazy "Multiple error messages. Please select one.",true
282 Some idx3 -> List.nth envs_and_diffs idx3
283 | None -> [],[],[] (* dymmy value, used *) in
284 let script = MatitaScript.current () in
285 let error_tag = script#error_tag in
286 source_buffer#remove_tag error_tag
287 ~start:source_buffer#start_iter
288 ~stop:source_buffer#end_iter;
290 (MultiPassDisambiguator.DisambiguationError
291 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
294 dialog#disambiguationErrors#destroy ();
297 let fail _ = return () in
298 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
299 connect_button dialog#disambiguationErrorsOkButton
302 match fst (dialog#treeview#get_cursor ()) with
305 let idx1,idx2,idx3 = model#get_interp_no tree_path in
308 Some idx2, Some idx3 ->
309 let _,lll = List.nth choices idx1 in
310 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
311 let _,_,diff = List.nth envs_and_diffs idx3 in
313 | _,_ -> assert false
322 | DisambiguateTypes.Id id ->
323 GrafiteAst.Ident_alias (id, desc)
324 | DisambiguateTypes.Symbol (symb, i)->
325 GrafiteAst.Symbol_alias (symb, i, desc)
326 | DisambiguateTypes.Num i ->
327 GrafiteAst.Number_alias (i, desc)
329 GrafiteAstPp.pp_alias alias)
334 (source_buffer#get_iter_at_mark
335 (`NAME "beginning_of_statement")) newtxt ;
338 connect_button dialog#disambiguationErrorsMoreErrors
339 (fun _ -> return () ; raise UseLibrary);
340 connect_button dialog#disambiguationErrorsCancelButton fail;
341 dialog#disambiguationErrors#show ();
345 (** Selection handling
346 * Two clipboards are used: "clipboard" and "primary".
347 * "primary" is used by X, when you hit the middle button mouse is content is
348 * pasted between applications. In Matita this selection always contain the
349 * textual version of the selected term.
350 * "clipboard" is used inside Matita only and support ATM two different targets:
351 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
356 (* creation order _is_ relevant for windows placement *)
357 let main = new mainWin () in
358 let fileSel = new fileSelectionWin () in
359 let findRepl = new findReplWin () in
360 let keyBindingBoxes = (* event boxes which should receive global key events *)
361 [ main#mainWinEventBox ]
363 let console = new console ~buffer:main#logTextView#buffer () in
364 let (source_view: GSourceView2.source_view) =
365 GSourceView2.source_view
367 ~insert_spaces_instead_of_tabs:true ~tab_width:2
368 ~right_margin_position:80 ~show_right_margin:true
369 ~smart_home_end:`AFTER
370 ~packing:main#scriptScrolledWin#add
373 let default_font_size =
374 Helm_registry.get_opt_default Helm_registry.int
375 ~default:BuildTimeConf.default_font_size "matita.font_size"
377 let similarsymbols_tag_name = "similarsymbolos" in
378 let similarsymbols_tag = `NAME similarsymbols_tag_name in
379 let source_buffer = source_view#source_buffer in
381 val mutable chosen_file = None
382 val mutable _ok_not_exists = false
383 val mutable _only_directory = false
384 val mutable font_size = default_font_size
385 val mutable similarsymbols = []
386 val mutable similarsymbols_orig = []
387 val clipboard = GData.clipboard Gdk.Atom.clipboard
388 val primary = GData.clipboard Gdk.Atom.primary
390 method private reset_similarsymbols =
391 similarsymbols <- [];
392 similarsymbols_orig <- [];
393 try source_buffer#delete_mark similarsymbols_tag
394 with GText.No_such_mark _ -> ()
397 let s () = MatitaScript.current () in
398 (* glade's check widgets *)
399 List.iter (fun w -> w#check_widgets ())
400 (let c w = (w :> <check_widgets: unit -> unit>) in
401 [ c fileSel; c main; c findRepl]);
403 List.iter (* global key bindings *)
404 (fun (key, callback) -> self#addKeyBinding key callback)
407 toggle_win ~check:main#showProofMenuItem proof#proofWin;
409 toggle_win ~check:main#showCheckMenuItem check#checkWin;
413 let parse_txt_file file =
414 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
415 let l_rev = ref [] in
418 l_rev := input_line ch :: !l_rev;
427 ~authors:(parse_txt_file "AUTHORS")
428 (*~comments:"comments"*)
429 ~copyright:"Copyright (C) 2005, the HELM team"
430 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
431 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
433 ~version:BuildTimeConf.version
434 ~website:"http://matita.cs.unibo.it"
437 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
438 connect_menu_item main#contentsMenuItem (fun () ->
439 if 0 = Sys.command "which gnome-help" then
441 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
443 ignore (Sys.command cmd)
445 MatitaGtkMisc.report_error ~title:"help system error"
447 "The program gnome-help is not installed\n\n"^
448 "To browse the user manal it is necessary to install "^
449 "the gnome help syste (also known as yelp)")
450 ~parent:main#toplevel ());
451 connect_menu_item main#aboutMenuItem about_dialog#present;
453 let show_find_Repl () =
454 findRepl#toplevel#misc#show ();
455 findRepl#toplevel#misc#grab_focus ()
457 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
459 let highlight start end_ =
460 source_buffer#move_mark `INSERT ~where:start;
461 source_buffer#move_mark `SEL_BOUND ~where:end_;
462 source_view#scroll_mark_onscreen `INSERT
464 let text = findRepl#findEntry#text in
465 let iter = source_buffer#get_iter `SEL_BOUND in
466 match iter#forward_search text with
468 (match source_buffer#start_iter#forward_search text with
470 | Some (start,end_) -> highlight start end_)
471 | Some (start,end_) -> highlight start end_
474 let text = findRepl#replaceEntry#text in
475 let ins = source_buffer#get_iter `INSERT in
476 let sel = source_buffer#get_iter `SEL_BOUND in
477 if ins#compare sel < 0 then
479 ignore(source_buffer#delete_selection ());
480 source_buffer#insert text
483 connect_button findRepl#findButton find_forward;
484 connect_button findRepl#findReplButton replace;
485 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
486 ignore(findRepl#toplevel#event#connect#delete
487 ~callback:(fun _ -> hide_find_Repl ();true));
490 (* phase 1: we save the actual status of the marks and we undo *)
491 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
492 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
493 let locked_iter_offset = locked_iter#offset in
496 (source_view#buffer#create_mark ~name:"lock_point"
497 ~left_gravity:true locked_iter) in
498 source_view#source_buffer#undo ();
499 (* phase 2: we save the cursor position and we redo, restoring
500 the previous status of all the marks *)
501 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
504 (source_view#buffer#create_mark ~name:"undo_point"
505 ~left_gravity:true cursor_iter)
507 source_view#source_buffer#redo ();
508 let mark_iter = source_view#buffer#get_iter_at_mark mark in
509 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
510 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
511 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
512 source_view#buffer#delete_mark mark;
513 source_view#buffer#delete_mark mark2;
514 (* phase 3: if after the undo the cursor was in the locked area,
515 then we move it there again and we perform a goto *)
516 if mark_iter#offset < locked_iter_offset then
518 source_view#buffer#move_mark `INSERT ~where:mark_iter;
519 (MatitaScript.current ())#goto `Cursor ();
521 (* phase 4: we perform again the undo. This time we are sure that
522 the text to undo is not locked *)
523 source_view#source_buffer#undo ();
524 source_view#misc#grab_focus () in
527 (* phase 1: we save the actual status of the marks, we redo and
529 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
530 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
531 let locked_iter_offset = locked_iter#offset in
534 (source_view#buffer#create_mark ~name:"lock_point"
535 ~left_gravity:true locked_iter) in
536 source_view#source_buffer#redo ();
537 source_view#source_buffer#undo ();
538 (* phase 2: we save the cursor position and we restore
539 the previous status of all the marks *)
540 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
543 (source_view#buffer#create_mark ~name:"undo_point"
544 ~left_gravity:true cursor_iter)
546 let mark_iter = source_view#buffer#get_iter_at_mark mark in
547 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
548 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
549 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
550 source_view#buffer#delete_mark mark;
551 source_view#buffer#delete_mark mark2;
552 (* phase 3: if after the undo the cursor is in the locked area,
553 then we move it there again and we perform a goto *)
554 if mark_iter#offset < locked_iter_offset then
556 source_view#buffer#move_mark `INSERT ~where:mark_iter;
557 (MatitaScript.current ())#goto `Cursor ();
559 (* phase 4: we perform again the redo. This time we are sure that
560 the text to redo is not locked *)
561 source_view#source_buffer#redo ();
562 source_view#misc#grab_focus ()
564 connect_menu_item main#undoMenuItem safe_undo;
566 ignore(source_view#source_buffer#connect#can_undo
567 ~callback:main#undoMenuItem#misc#set_sensitive);
568 *) main#undoMenuItem#misc#set_sensitive true;
569 connect_menu_item main#redoMenuItem safe_redo;
571 ignore(source_view#source_buffer#connect#can_redo
572 ~callback:main#redoMenuItem#misc#set_sensitive);
573 *) main#redoMenuItem#misc#set_sensitive true;
574 ignore(source_view#connect#after#populate_popup
575 ~callback:(fun pre_menu ->
576 let menu = new GMenu.menu pre_menu in
577 let menuItems = menu#children in
578 let undoMenuItem, redoMenuItem =
580 [undo;redo;sep1;cut;copy;paste;delete;sep2;
581 selectall;sep3;inputmethod;insertunicodecharacter] ->
582 List.iter menu#remove [ copy; cut; delete; paste ];
584 | _ -> assert false in
586 let i = ref 2 in (* last occupied position *)
587 fun ?label ?stock () ->
589 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
592 let copy = add_menu_item ~stock:`COPY () in
593 let cut = add_menu_item ~stock:`CUT () in
594 let delete = add_menu_item ~stock:`DELETE () in
595 let paste = add_menu_item ~stock:`PASTE () in
596 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
597 copy#misc#set_sensitive self#canCopy;
598 cut#misc#set_sensitive self#canCut;
599 delete#misc#set_sensitive self#canDelete;
600 paste#misc#set_sensitive self#canPaste;
601 paste_pattern#misc#set_sensitive self#canPastePattern;
602 connect_menu_item copy self#copy;
603 connect_menu_item cut self#cut;
604 connect_menu_item delete self#delete;
605 connect_menu_item paste self#paste;
606 connect_menu_item paste_pattern self#pastePattern;
607 let new_undoMenuItem =
608 GMenu.image_menu_item
609 ~image:(GMisc.image ~stock:`UNDO ())
612 ~packing:(menu#insert ~pos:0) () in
613 new_undoMenuItem#misc#set_sensitive
614 (undoMenuItem#misc#get_flag `SENSITIVE);
615 menu#remove (undoMenuItem :> GMenu.menu_item);
616 connect_menu_item new_undoMenuItem safe_undo;
617 let new_redoMenuItem =
618 GMenu.image_menu_item
619 ~image:(GMisc.image ~stock:`REDO ())
622 ~packing:(menu#insert ~pos:1) () in
623 new_redoMenuItem#misc#set_sensitive
624 (redoMenuItem#misc#get_flag `SENSITIVE);
625 menu#remove (redoMenuItem :> GMenu.menu_item);
626 connect_menu_item new_redoMenuItem safe_redo));
628 connect_menu_item main#editMenu (fun () ->
629 main#copyMenuItem#misc#set_sensitive self#canCopy;
630 main#cutMenuItem#misc#set_sensitive self#canCut;
631 main#deleteMenuItem#misc#set_sensitive self#canDelete;
632 main#pasteMenuItem#misc#set_sensitive self#canPaste;
633 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
634 connect_menu_item main#copyMenuItem self#copy;
635 connect_menu_item main#cutMenuItem self#cut;
636 connect_menu_item main#deleteMenuItem self#delete;
637 connect_menu_item main#pasteMenuItem self#paste;
638 connect_menu_item main#pastePatternMenuItem self#pastePattern;
639 connect_menu_item main#selectAllMenuItem (fun () ->
640 source_buffer#move_mark `INSERT source_buffer#start_iter;
641 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
642 connect_menu_item main#findReplMenuItem show_find_Repl;
643 connect_menu_item main#externalEditorMenuItem self#externalEditor;
644 connect_menu_item main#ligatureButton self#nextSimilarSymbol;
645 ignore(source_buffer#connect#after#insert_text
646 ~callback:(fun iter str ->
647 if main#menuitemAutoAltL#active && (str = " " || str = "\n") then
648 ignore(self#expand_virtual_if_any iter str)));
649 ignore (findRepl#findEntry#connect#activate find_forward);
650 (* interface lockers *)
652 main#buttonsToolbar#misc#set_sensitive false;
653 main#scriptMenu#misc#set_sensitive false;
654 source_view#set_editable false
657 main#buttonsToolbar#misc#set_sensitive true;
658 main#scriptMenu#misc#set_sensitive true;
659 source_view#set_editable true;
660 (*The next line seems sufficient to avoid some unknown race condition *)
661 GtkThread.sync (fun () -> ()) ()
663 let worker_thread = ref None in
665 let floc, msg = MatitaExcPp.to_string exn in
670 let (x, y) = HExtlib.loc_of_floc floc in
671 let script = MatitaScript.current () in
672 let locked_mark = script#locked_mark in
673 let error_tag = script#error_tag in
675 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
676 let x' = baseoffset + x in
677 let y' = baseoffset + y in
678 let x_iter = source_buffer#get_iter (`OFFSET x') in
679 let y_iter = source_buffer#get_iter (`OFFSET y') in
680 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
682 id := Some (source_buffer#connect#changed ~callback:(fun () ->
683 source_buffer#remove_tag error_tag
684 ~start:source_buffer#start_iter
685 ~stop:source_buffer#end_iter;
687 | None -> assert false (* a race condition occurred *)
689 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
690 source_buffer#place_cursor
691 (source_buffer#get_iter (`OFFSET x'));
698 let saved_use_library= !MultiPassDisambiguator.use_library in
700 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
702 MultiPassDisambiguator.use_library := saved_use_library;
705 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
707 interactive_error_interp
708 ~all_passes:!all_disambiguation_passes source_buffer
709 notify_exn offset errorll (s())#filename
712 MultiPassDisambiguator.use_library := true;
715 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
716 interactive_error_interp ~all_passes:true source_buffer
717 notify_exn offset errorll (s())#filename
720 | exc -> notify_exn exc);
721 MultiPassDisambiguator.use_library := saved_use_library;
724 (try notify_exn exc with Sys.Break as e -> notify_exn e);
728 worker_thread := Some (Thread.create thread_main ())
731 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
732 let interrupt = ref None in
733 let old_callback = ref (function _ -> ()) in
734 let force_interrupt n =
735 (* This function is called just before the thread's timeslice ends *)
737 if Some(Thread.id(Thread.self())) = !interrupt then
738 (interrupt := None; raise Sys.Break) in
740 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
741 Sys.Signal_handle f -> old_callback := f
743 | Sys.Signal_default -> assert false
746 match !worker_thread with
748 | Some t -> interrupt := Some (Thread.id t) in
752 f (); source_view#misc#grab_focus ()
754 exc -> source_view#misc#grab_focus (); raise exc in
756 (* file selection win *)
757 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
758 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
761 fileSel#fileSelectionWin#misc#hide ();
766 let fname = fileSel#fileSelectionWin#filename in
767 if Sys.file_exists fname then
769 if HExtlib.is_regular fname && not (_only_directory) then
771 else if _only_directory && HExtlib.is_dir fname then
776 if _ok_not_exists then
779 | `CANCEL -> return None
781 | `DELETE_EVENT -> return None));
783 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
785 let adj = main#logScrolledWin#vadjustment in
786 ignore (adj#connect#changed
787 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
788 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
789 (* natural deduction palette *)
790 main#tacticsButtonsHandlebox#misc#hide ();
791 MatitaGtkMisc.toggle_callback
793 if b then main#tacticsButtonsHandlebox#misc#show ()
794 else main#tacticsButtonsHandlebox#misc#hide ())
795 ~check:main#menuitemPalette;
796 connect_button main#butImpl_intro
797 (fun () -> source_buffer#insert "apply rule (⇒#i […] (…));\n");
798 connect_button main#butAnd_intro
799 (fun () -> source_buffer#insert
800 "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
801 connect_button main#butOr_intro_left
802 (fun () -> source_buffer#insert "apply rule (∨#i_l (…));\n");
803 connect_button main#butOr_intro_right
804 (fun () -> source_buffer#insert "apply rule (∨#i_r (…));\n");
805 connect_button main#butNot_intro
806 (fun () -> source_buffer#insert "apply rule (¬#i […] (…));\n");
807 connect_button main#butTop_intro
808 (fun () -> source_buffer#insert "apply rule (⊤#i);\n");
809 connect_button main#butImpl_elim
810 (fun () -> source_buffer#insert
811 "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
812 connect_button main#butAnd_elim_left
813 (fun () -> source_buffer#insert "apply rule (∧#e_l (…));\n");
814 connect_button main#butAnd_elim_right
815 (fun () -> source_buffer#insert "apply rule (∧#e_r (…));\n");
816 connect_button main#butOr_elim
817 (fun () -> source_buffer#insert
818 "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
819 connect_button main#butNot_elim
820 (fun () -> source_buffer#insert
821 "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
822 connect_button main#butBot_elim
823 (fun () -> source_buffer#insert "apply rule (⊥#e (…));\n");
824 connect_button main#butRAA
825 (fun () -> source_buffer#insert "apply rule (RAA […] (…));\n");
826 connect_button main#butUseLemma
827 (fun () -> source_buffer#insert "apply rule (lem #premises name …);\n");
828 connect_button main#butDischarge
829 (fun () -> source_buffer#insert "apply rule (discharge […]);\n");
831 connect_button main#butForall_intro
832 (fun () -> source_buffer#insert "apply rule (∀#i {…} (…));\n");
833 connect_button main#butForall_elim
834 (fun () -> source_buffer#insert "apply rule (∀#e {…} (…));\n");
835 connect_button main#butExists_intro
836 (fun () -> source_buffer#insert "apply rule (∃#i {…} (…));\n");
837 connect_button main#butExists_elim
838 (fun () -> source_buffer#insert
839 "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
842 let module Hr = Helm_registry in
843 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
845 | true -> main#toplevel#fullscreen ()
846 | false -> main#toplevel#unfullscreen ());
847 main#fullscreenMenuItem#set_active false;
848 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
849 ~callback:(function b ->
852 Interpretations.toggle_active_interpretations s#grafite_status b
854 assert false (* MATITA1.0 ???
855 s#set_grafite_status status*)
857 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
858 ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
859 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
860 ~callback:(fun enabled ->
861 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
862 main#unicodeAsTexMenuItem#set_active
863 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
865 HLog.set_log_callback self#console#log_callback;
866 GtkSignal.user_handler :=
868 | MatitaScript.ActionCancelled s -> HLog.error s
870 if not (Helm_registry.get_bool "matita.debug") then
875 source_buffer#set_language (Some MatitaGtkMisc.matita_lang);
876 source_buffer#set_highlight_syntax true
879 (s())#assignFileName None;
880 main#saveMenuItem#misc#set_sensitive false
882 let saveAsScript () =
884 match self#chooseFile ~ok_not_exists:true () with
887 script#assignFileName (Some f);
888 script#saveToFile ();
889 console#message ("'"^f^"' saved.\n");
895 if script#has_name then
896 (script#saveToFile ();
897 console#message ("'"^script#filename^"' saved.\n"))
900 let abandon_script () =
901 let grafite_status = (s ())#grafite_status in
902 if source_view#buffer#modified then
903 (match ask_unsaved main#toplevel with
904 | `YES -> saveScript ()
906 | `CANCEL -> raise MatitaTypes.Cancel);
907 save_moo grafite_status
912 match self#chooseFile () with
916 script#assignFileName (Some f);
917 source_view#source_buffer#begin_not_undoable_action ();
918 script#loadFromFile f;
919 source_view#source_buffer#end_not_undoable_action ();
920 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
921 source_view#buffer#place_cursor source_view#buffer#start_iter;
922 console#message ("'"^f^"' loaded.\n");
925 with MatitaTypes.Cancel -> ()
929 source_view#source_buffer#begin_not_undoable_action ();
932 source_view#source_buffer#end_not_undoable_action ();
936 source_buffer#place_cursor
937 (source_buffer#get_iter_at_mark (`NAME "locked")) in
938 let advance _ = (MatitaScript.current ())#advance (); cursor () in
939 let retract _ = (MatitaScript.current ())#retract (); cursor () in
940 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
941 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
942 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
943 let advance = locker (keep_focus advance) in
944 let retract = locker (keep_focus retract) in
945 let top = locker (keep_focus top) in
946 let bottom = locker (keep_focus bottom) in
947 let jump = locker (keep_focus jump) in
949 self#setQuitCallback (fun () ->
950 let script = MatitaScript.current () in
951 if source_view#buffer#modified then
952 match ask_unsaved main#toplevel with
955 save_moo script#grafite_status;
957 | `NO -> GMain.Main.quit ()
960 (save_moo script#grafite_status;
961 GMain.Main.quit ()));
962 connect_button main#scriptAdvanceButton advance;
963 connect_button main#scriptRetractButton retract;
964 connect_button main#scriptTopButton top;
965 connect_button main#scriptBottomButton bottom;
966 connect_button main#scriptJumpButton jump;
967 connect_button main#scriptAbortButton kill_worker;
968 connect_menu_item main#scriptAdvanceMenuItem advance;
969 connect_menu_item main#scriptRetractMenuItem retract;
970 connect_menu_item main#scriptTopMenuItem top;
971 connect_menu_item main#scriptBottomMenuItem bottom;
972 connect_menu_item main#scriptJumpMenuItem jump;
973 connect_menu_item main#openMenuItem loadScript;
974 connect_menu_item main#saveMenuItem saveScript;
975 connect_menu_item main#saveAsMenuItem saveAsScript;
976 connect_menu_item main#newMenuItem newScript;
977 connect_menu_item main#showCoercionsGraphMenuItem
979 let c = MatitaMathView.cicBrowser () in
980 c#load (`About `Coercions));
981 connect_menu_item main#showHintsDbMenuItem
983 let c = MatitaMathView.cicBrowser () in
984 c#load (`About `Hints));
985 connect_menu_item main#showTermGrammarMenuItem
987 let c = MatitaMathView.cicBrowser () in
988 c#load (`About `Grammar));
989 connect_menu_item main#showUnicodeTable
991 let c = MatitaMathView.cicBrowser () in
992 c#load (`About `TeX));
993 (* script monospace font stuff *)
994 self#updateFontSize ();
996 main#debugMenu#misc#hide ();
998 main#hintNotebook#misc#hide ();
1000 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1001 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1002 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1005 self#sourceView#misc#grab_focus ();
1006 (* main win dimension *)
1007 let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
1008 let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
1009 (* hack for xinerama, no proper support of monitors from lablgtk *)
1010 let width = if width > 1600 then width / 2 else width in
1011 let height = if height > 1200 then height / 2 else height in
1012 let main_w = width * 90 / 100 in
1013 let main_h = height * 80 / 100 in
1014 let script_w = main_w * 6 / 10 in
1015 main#toplevel#resize ~width:main_w ~height:main_h;
1016 main#hpaneScriptSequent#set_position script_w;
1018 ignore(source_view#connect#after#paste_clipboard
1019 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1020 (* clean_locked is set to true only "during" a PRIMARY paste
1021 operation (i.e. by clicking with the second mouse button) *)
1022 let clean_locked = ref false in
1023 ignore(source_view#event#connect#button_press
1026 if GdkEvent.Button.button button = 2 then
1027 clean_locked := true;
1030 ignore(source_view#event#connect#button_release
1031 ~callback:(fun button -> clean_locked := false; false));
1032 ignore(source_view#buffer#connect#after#apply_tag
1034 fun tag ~start:_ ~stop:_ ->
1036 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1039 clean_locked := false;
1040 (MatitaScript.current ())#clean_dirty_lock;
1041 clean_locked := true
1043 (* math view handling *)
1044 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1045 ignore(MatitaMathView.cicBrowser ()));
1046 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1047 self#increaseFontSize ();
1048 MatitaMisc.increase_font_size ();
1049 MatitaMathView.update_font_sizes ());
1050 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1051 self#decreaseFontSize ();
1052 MatitaMisc.decrease_font_size ();
1053 MatitaMathView.update_font_sizes ());
1054 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1055 self#resetFontSize ();
1056 MatitaMisc.reset_font_size ();
1057 MatitaMathView.update_font_sizes ());
1058 MatitaMisc.reset_font_size ();
1060 (** selections / clipboards handling *)
1062 method markupSelected = MatitaMathView.has_selection ()
1063 method private textSelected =
1064 (source_buffer#get_iter_at_mark `INSERT)#compare
1065 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1066 method private somethingSelected = self#markupSelected || self#textSelected
1067 method private markupStored = MatitaMathView.has_clipboard ()
1068 method private textStored = clipboard#text <> None
1069 method private somethingStored = self#markupStored || self#textStored
1071 method canCopy = self#somethingSelected
1072 method canCut = self#textSelected
1073 method canDelete = self#textSelected
1074 method canPaste = self#somethingStored
1075 method canPastePattern = self#markupStored
1078 if self#textSelected
1080 MatitaMathView.empty_clipboard ();
1081 source_view#buffer#copy_clipboard clipboard;
1083 MatitaMathView.copy_selection ()
1085 source_view#buffer#cut_clipboard clipboard;
1086 MatitaMathView.empty_clipboard ()
1087 method delete () = ignore (source_view#buffer#delete_selection ())
1089 if MatitaMathView.has_clipboard ()
1090 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1091 else source_view#buffer#paste_clipboard clipboard;
1092 (MatitaScript.current ())#clean_dirty_lock
1093 method pastePattern () =
1094 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1096 method private expand_virtual_if_any iter tok =
1098 let len = MatitaGtkMisc.utf8_string_length tok in
1100 let prev = iter#copy#backward_chars len in
1101 prev#get_slice ~stop:(prev#copy#backward_find_char
1102 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
1104 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
1105 self#reset_similarsymbols;
1106 let s = Glib.Utf8.from_unichar symb in
1107 assert(Glib.Utf8.validate s);
1108 source_buffer#delete ~start:iter
1109 ~stop:(iter#copy#backward_chars
1110 (MatitaGtkMisc.utf8_string_length inplaceof + len));
1111 source_buffer#insert ~iter
1112 (if inplaceof.[0] = '\\' then s else (s ^ tok));
1114 with Virtuals.Not_a_virtual -> false
1116 val similar_memory = Hashtbl.create 97
1117 val mutable old_used_memory = false
1119 method private nextSimilarSymbol () =
1120 let write_similarsymbol s =
1121 let s = Glib.Utf8.from_unichar s in
1122 let iter = source_buffer#get_iter_at_mark `INSERT in
1123 assert(Glib.Utf8.validate s);
1124 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
1125 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s;
1126 (try source_buffer#delete_mark similarsymbols_tag
1127 with GText.No_such_mark _ -> ());
1128 ignore(source_buffer#create_mark ~name:similarsymbols_tag_name
1129 (source_buffer#get_iter_at_mark `INSERT));
1131 let new_similarsymbol =
1133 let iter_ins = source_buffer#get_iter_at_mark `INSERT in
1134 let iter_lig = source_buffer#get_iter_at_mark similarsymbols_tag in
1135 not (iter_ins#equal iter_lig)
1136 with GText.No_such_mark _ -> true
1138 if new_similarsymbol then
1139 (if not(self#expand_virtual_if_any (source_buffer#get_iter_at_mark `INSERT) "")then
1141 let i = source_buffer#get_iter_at_mark `INSERT in
1142 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
1144 (match Virtuals.similar_symbols last_symbol with
1147 similarsymbols_orig <- eqclass;
1149 try Hashtbl.find similar_memory similarsymbols_orig
1151 let is_used = List.map (fun x -> x,false) eqclass in
1152 Hashtbl.add similar_memory eqclass is_used;
1157 List.partition (fun s -> List.assoc s is_used) eqclass
1159 match used @ unused with a::b::c -> a,b,c | _ -> assert false
1162 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
1164 old_used_memory <- List.assoc hd is_used;
1166 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
1168 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1169 write_similarsymbol hd;
1170 similarsymbols <- tl @ [ hd ]))
1172 match similarsymbols with
1175 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
1176 let last = HExtlib.list_last tl in
1177 let old_used_for_last = old_used_memory in
1178 old_used_memory <- List.assoc hd is_used;
1180 (hd, true) :: (last,old_used_for_last) ::
1181 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
1183 Hashtbl.replace similar_memory similarsymbols_orig is_used;
1184 similarsymbols <- tl @ [ hd ];
1185 write_similarsymbol hd
1187 method private externalEditor () =
1188 let cmd = Helm_registry.get "matita.external_editor" in
1189 (* ZACK uncomment to enable interactive ask of external editor command *)
1192 "External editor command:
1193 %f will be substitute for the script name,
1194 %p for the cursor position in bytes,
1195 %l for the execution point in bytes."
1197 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1198 ~default:(Helm_registry.get "matita.external_editor") ()
1200 let script = MatitaScript.current () in
1201 let fname = script#filename in
1203 source_buffer#start_iter#get_slice
1204 ~stop:(source_buffer#get_iter_at_mark mark)
1206 let locked = `MARK script#locked_mark in
1207 let string_pos mark = string_of_int (String.length (slice mark)) in
1208 let cursor_pos = string_pos `INSERT in
1209 let locked_pos = string_pos locked in
1211 Pcre.replace ~pat:"%f" ~templ:fname
1212 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1213 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1216 let locked_before = slice locked in
1217 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1218 ignore (Unix.system cmd);
1219 source_buffer#set_text (HExtlib.input_file fname);
1220 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1221 source_buffer#move_mark locked locked_iter;
1222 source_buffer#apply_tag script#locked_tag
1223 ~start:source_buffer#start_iter ~stop:locked_iter;
1224 let locked_after = slice locked in
1228 for i = 0 to String.length locked_before - 1 do
1229 if locked_before.[i] <> locked_after.[i] then begin
1230 source_buffer#place_cursor
1231 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1232 script#goto `Cursor ();
1234 end else if locked_before.[i] = '\n' then begin
1241 | Invalid_argument _ -> script#goto `Bottom ()
1243 method loadScript file =
1244 let script = MatitaScript.current () in
1246 script#assignFileName (Some file);
1247 let file = script#filename in
1249 if Sys.file_exists file then file
1250 else BuildTimeConf.script_template
1252 source_view#source_buffer#begin_not_undoable_action ();
1253 script#loadFromFile content;
1254 source_view#source_buffer#end_not_undoable_action ();
1255 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1256 source_view#buffer#place_cursor source_view#buffer#start_iter;
1257 console#message ("'"^file^"' loaded.");
1258 self#_enableSaveTo file
1260 method private _enableSaveTo file =
1261 self#main#saveMenuItem#misc#set_sensitive true
1263 method console = console
1264 method sourceView: GSourceView2.source_view =
1265 (source_view: GSourceView2.source_view)
1266 method fileSel = fileSel
1267 method findRepl = findRepl
1270 method newBrowserWin () =
1272 inherit browserWin ()
1273 val combo = GEdit.entry ()
1275 self#check_widgets ();
1276 let combo_widget = combo#coerce in
1277 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1278 combo#misc#grab_focus ()
1279 method browserUri = combo
1282 method newUriDialog () =
1283 let dialog = new uriChoiceDialog () in
1284 dialog#check_widgets ();
1287 method newConfirmationDialog () =
1288 let dialog = new confirmationDialog () in
1289 dialog#check_widgets ();
1292 method newEmptyDialog () =
1293 let dialog = new emptyDialog () in
1294 dialog#check_widgets ();
1297 method private addKeyBinding key callback =
1298 List.iter (fun evbox -> add_key_binding key callback evbox)
1301 method setQuitCallback callback =
1302 connect_menu_item main#quitMenuItem callback;
1303 ignore (main#toplevel#event#connect#delete
1304 (fun _ -> callback ();true));
1305 self#addKeyBinding GdkKeysyms._q callback
1307 method chooseFile ?(ok_not_exists = false) () =
1308 _ok_not_exists <- ok_not_exists;
1309 _only_directory <- false;
1310 fileSel#fileSelectionWin#show ();
1314 method private chooseDir ?(ok_not_exists = false) () =
1315 _ok_not_exists <- ok_not_exists;
1316 _only_directory <- true;
1317 fileSel#fileSelectionWin#show ();
1319 (* we should check that this is a directory *)
1322 method askText ?(title = "") ?(msg = "") () =
1323 let dialog = new textDialog () in
1324 dialog#textDialog#set_title title;
1325 dialog#textDialogLabel#set_label msg;
1326 let text = ref None in
1329 dialog#textDialog#destroy ();
1332 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1333 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1334 connect_button dialog#textDialogOkButton (fun _ ->
1335 let text = dialog#textDialogTextView#buffer#get_text () in
1336 return (Some text));
1337 dialog#textDialog#show ();
1341 method private updateFontSize () =
1342 self#sourceView#misc#modify_font_by_name
1343 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1345 method increaseFontSize () =
1346 font_size <- font_size + 1;
1347 self#updateFontSize ()
1349 method decreaseFontSize () =
1350 font_size <- font_size - 1;
1351 self#updateFontSize ()
1353 method resetFontSize () =
1354 font_size <- default_font_size;
1355 self#updateFontSize ()
1360 let g = new gui () in
1361 gui_instance := Some g;
1362 MatitaMisc.set_gui g;
1365 let instance = singleton gui
1367 let non p x = not (p x)
1369 (* this is a shit and should be changed :-{ *)
1370 let interactive_uri_choice
1371 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1372 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1373 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1377 let gui = instance () in
1378 if (selection_mode <> `SINGLE) &&
1379 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1383 let dialog = gui#newUriDialog () in
1384 if hide_uri_entry then
1385 dialog#uriEntryHBox#misc#hide ();
1388 dialog#uriChoiceSelectedButton#misc#hide ();
1389 dialog#uriChoiceConstantsButton#misc#hide ();
1391 dialog#okLabel#set_label ok_label;
1392 dialog#uriChoiceTreeView#selection#set_mode
1393 (selection_mode :> Gtk.Tags.selection_mode);
1394 let model = new stringListModel dialog#uriChoiceTreeView in
1395 let choices = ref None in
1399 dialog#copyButton#misc#show ();
1400 connect_button dialog#copyButton
1402 match model#easy_selection () with
1405 dialog#uriChoiceDialog#set_title title;
1406 dialog#uriChoiceLabel#set_text msg;
1407 List.iter model#easy_append (List.map NReference.string_of_reference uris);
1408 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1411 dialog#uriChoiceDialog#destroy ();
1414 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1415 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1416 return (Some uris));
1417 if ok_action = `AUTO then
1418 connect_button dialog#uriChoiceAutoButton (fun _ ->
1419 Helm_registry.set_bool "matita.auto_disambiguation" true;
1422 connect_button dialog#uriChoiceAutoButton (fun _ ->
1423 match model#easy_selection () with
1425 | uris -> return (Some (List.map NReference.reference_of_string uris)));
1426 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1427 match model#easy_selection () with
1429 | uris -> return (Some (List.map NReference.reference_of_string uris)));
1430 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1431 dialog#uriChoiceDialog#show ();
1433 (match !choices with
1434 | None -> raise MatitaTypes.Cancel
1435 | Some uris -> uris)
1439 let cols = new GTree.column_list in
1440 let id_col = cols#add Gobject.Data.string in
1441 let dsc_col = cols#add Gobject.Data.string in
1442 let interp_no_col = cols#add Gobject.Data.int in
1443 let tree_store = GTree.tree_store cols in
1444 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1445 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1446 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1447 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1448 fun tree_view choices ->
1451 tree_view#set_model (Some (tree_store :> GTree.model));
1452 ignore (tree_view#append_column id_view_col);
1453 ignore (tree_view#append_column dsc_view_col);
1454 let name_of_interp =
1455 (* try to find a reasonable name for an interpretation *)
1459 List.assoc "0" interp
1461 incr idx; string_of_int !idx
1463 tree_store#clear ();
1464 let idx = ref ~-1 in
1468 let interp_row = tree_store#append () in
1469 tree_store#set ~row:interp_row ~column:id_col
1470 (name_of_interp interp);
1471 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1474 let row = tree_store#append ~parent:interp_row () in
1475 tree_store#set ~row ~column:id_col id;
1476 tree_store#set ~row ~column:dsc_col dsc;
1477 tree_store#set ~row ~column:interp_no_col !idx)
1481 method get_interp_no tree_path =
1482 let iter = tree_store#get_iter tree_path in
1483 tree_store#get ~row:iter ~column:interp_no_col
1487 let interactive_string_choice
1488 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1490 let gui = instance () in
1491 let dialog = gui#newUriDialog () in
1492 dialog#uriEntryHBox#misc#hide ();
1493 dialog#uriChoiceSelectedButton#misc#hide ();
1494 dialog#uriChoiceAutoButton#misc#hide ();
1495 dialog#uriChoiceConstantsButton#misc#hide ();
1496 dialog#uriChoiceTreeView#selection#set_mode
1497 (`SINGLE :> Gtk.Tags.selection_mode);
1498 let model = new stringListModel dialog#uriChoiceTreeView in
1499 let choices = ref None in
1500 dialog#uriChoiceDialog#set_title title;
1501 let hack_len = MatitaGtkMisc.utf8_string_length text in
1502 let rec colorize acc_len = function
1504 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1505 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1507 let start, stop = HExtlib.loc_of_floc he in
1508 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1509 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1510 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1511 escape_pango_markup str1 ^ "<b>" ^
1512 escape_pango_markup str2 ^ "</b>" ^
1515 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1516 Printf.eprintf "(%d,%d)" start stop) locs; *)
1520 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1523 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1524 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1525 Printf.eprintf "(%d,%d)" start stop) locs;
1526 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1527 dialog#uriChoiceLabel#set_use_markup true;
1528 let txt = colorize 0 locs in
1529 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1530 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1532 dialog#uriChoiceLabel#set_label txt;
1533 List.iter model#easy_append uris;
1536 dialog#uriChoiceDialog#destroy ();
1539 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1540 connect_button dialog#uriChoiceForwardButton (fun _ ->
1541 match model#easy_selection () with
1543 | uris -> return (Some uris));
1544 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1545 dialog#uriChoiceDialog#show ();
1547 (match !choices with
1548 | None -> raise MatitaTypes.Cancel
1549 | Some uris -> uris)
1551 let interactive_interp_choice () text prefix_len choices =
1552 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1553 let filter_choices filter =
1554 let rec is_compatible filter =
1557 | ([],_,_)::tl -> is_compatible filter tl
1558 | (loc::tlloc,id,dsc)::tl ->
1560 if List.assoc (loc,id) filter = dsc then
1561 is_compatible filter ((tlloc,id,dsc)::tl)
1567 List.filter (fun (_,interp) -> is_compatible filter interp)
1569 let rec get_choices loc id =
1574 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1576 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1578 let example_interp =
1582 let ask_user id locs choices =
1583 interactive_string_choice
1585 ~title:"Ambiguous input"
1586 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1588 let rec classify ids filter partial_interpretations =
1590 [] -> List.map fst partial_interpretations
1591 | ([],_,_)::tl -> classify tl filter partial_interpretations
1592 | (loc::tlloc,id,dsc)::tl ->
1593 let choices = get_choices loc id partial_interpretations in
1596 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1599 match ask_user id [loc] choices with
1603 let filter = ((loc,id),chosen_dsc)::filter in
1604 let compatible_interps = filter_choices filter partial_interpretations in
1605 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1607 let enumerated_choices =
1608 let idx = ref ~-1 in
1609 List.map (fun interp -> incr idx; !idx,interp) choices
1611 classify example_interp [] enumerated_choices
1614 (* disambiguator callbacks *)
1615 Disambiguate.set_choose_uris_callback
1616 (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1617 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1618 Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1619 (* gtk initialization *)
1620 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1621 ignore (GMain.Main.init ())