why3ide.ml 78.4 KB
Newer Older
1 2 3
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
Guillaume Melquiond's avatar
Guillaume Melquiond committed
4
(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)
5 6 7 8 9 10 11
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

12
open Why3
13
open Format
14
open Gconfig
15
open Wstdlib
Sylvain Dailler's avatar
Sylvain Dailler committed
16 17
open Ide_utils
open History
18
open Itp_communication
19

20 21
external reset_gc : unit -> unit = "ml_reset_gc"

22
let debug = Debug.lookup_flag "ide_info"
23
let debug_stack_trace = Debug.lookup_flag "stack_trace"
24

25 26 27 28 29
(***************************)
(* Debugging Json protocol *)
(***************************)


30
(* TODO remove print_request_json and print_notification_json *)
31 32 33 34 35
exception Badparsing

let print_request_json fmt (r: ide_request) =
  (try (
    let s = Pp.string_of Json_util.print_request r in
36
    let x = Json_util.parse_request s in
37 38 39 40 41 42 43
    if r = x then () else raise Badparsing)
  with
    _ -> Format.eprintf "Bad parsing@.");
  Json_util.print_request fmt r

let print_notification_json fmt (n: notification) =
  (try (
44
    let x = Json_util.parse_notification (Pp.string_of Json_util.print_notification n) in
45 46 47 48 49 50 51 52
    if n = x then () else raise Badparsing)
  with
    _ -> Format.eprintf "Bad parsing@.");
  Json_util.print_notification fmt n

let debug_json = Debug.register_flag "json_proto"
    ~desc:"Print@ json@ requests@ and@ notifications@"

Clément Fumex's avatar
Clément Fumex committed
53 54 55
(*******************)
(* server protocol *)
(*******************)
56

MARCHE Claude's avatar
MARCHE Claude committed
57

58
module Protocol_why3ide = struct
Clément Fumex's avatar
Clément Fumex committed
59 60

  let debug_proto = Debug.register_flag "ide_proto"
61
      ~desc:"Print@ debugging@ messages@ about@ Why3Ide@ protocol@"
Clément Fumex's avatar
Clément Fumex committed
62 63

  let print_request_debug r =
64
    Debug.dprintf debug_proto "request %a@." print_request r;
65
    Debug.dprintf debug_json "%a@." print_request_json r
Clément Fumex's avatar
Clément Fumex committed
66

Sylvain Dailler's avatar
Sylvain Dailler committed
67
  let print_msg_debug m =
68
    Debug.dprintf debug_proto "message %a@." print_msg m
Clément Fumex's avatar
Clément Fumex committed
69 70

  let print_notify_debug n =
71
    Debug.dprintf debug_proto "handling notification %a@." print_notify n;
72
    Debug.dprintf debug_json "%a@." print_notification_json n
Clément Fumex's avatar
Clément Fumex committed
73 74 75 76

  let list_requests: ide_request list ref = ref []

  let get_requests () =
77 78
    let n = List.length !list_requests in
    if n > 0 then
79
      Debug.dprintf debug_proto "got %d new requests@." n;
Clément Fumex's avatar
Clément Fumex committed
80 81 82 83 84
    let l = List.rev !list_requests in
    list_requests := [];
    l

  let send_request r =
85
    print_request_debug r;
Clément Fumex's avatar
Clément Fumex committed
86 87 88 89 90
    list_requests := r :: !list_requests

  let notification_list: notification list ref = ref []

  let notify n =
91
(* too early, print when handling notifications
Clément Fumex's avatar
Clément Fumex committed
92
    print_notify_debug n;
93
 *)    notification_list := n :: !notification_list
Clément Fumex's avatar
Clément Fumex committed
94 95

  let get_notified () =
96 97
    let n = List.length !notification_list in
    if n > 0 then
98
      Debug.dprintf debug_proto "got %d new notifications@." n;
Clément Fumex's avatar
Clément Fumex committed
99 100 101
    let l = List.rev !notification_list in
    notification_list := [];
    l
Sylvain Dailler's avatar
Sylvain Dailler committed
102 103 104

end

105 106 107
(* True when session differs from the saved session *)
let session_needs_saving = ref false

Clément Fumex's avatar
Clément Fumex committed
108
let get_notified = Protocol_why3ide.get_notified
Sylvain Dailler's avatar
Sylvain Dailler committed
109

110 111 112 113 114
let send_request r =
  (* If request changes the session then session needs saving *)
  if modify_session r then
    session_needs_saving := true;
  Protocol_why3ide.send_request r
Sylvain Dailler's avatar
Sylvain Dailler committed
115

Clément Fumex's avatar
Clément Fumex committed
116 117 118
(****************************************)
(* server instance on the GTK scheduler *)
(****************************************)
119

120 121 122 123 124 125 126 127 128 129
(*
   The gtk scheduler is catching all exceptions avoiding the printing of the
   backtrace that is normally done by debug option stack_trace. To recover this
   behavior we catch exceptions ourselves. If "stack_trace" is on, we exit on
   first exception and print backtrace on standard output otherwise we raise
   the exception again (with information on error output).
*)
let backtrace_and_exit f () =
  try f () with
  | e ->
MARCHE Claude's avatar
MARCHE Claude committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143
     if Debug.test_flag debug_stack_trace then
       begin
         Printexc.print_backtrace stderr;
         Format.eprintf "exception '%a' was raised in a LablGtk callback.@."
                        Exn_printer.exn_printer e;
         exit 1
       end
     else
       begin
         Format.eprintf "exception '%a' was raised in a LablGtk callback.@."
                        Exn_printer.exn_printer e;
         Format.eprintf "This should not happen. Please report. @.";
         raise e
       end
144

145
module Scheduler = struct
146

147 148
    let blocking = false

149
    let multiplier = 3
150

Clément Fumex's avatar
Clément Fumex committed
151
    let idle ~prio f =
152
      let (_ : GMain.Idle.id) = GMain.Idle.add ~prio (backtrace_and_exit f) in ()
153

Clément Fumex's avatar
Clément Fumex committed
154
    let timeout ~ms f =
155 156
      let (_ : GMain.Timeout.id) =
        GMain.Timeout.add ~ms ~callback:(backtrace_and_exit f) in ()
Clément Fumex's avatar
Clément Fumex committed
157
end
158

159
module Server = Itp_server.Make (Scheduler) (Protocol_why3ide)
160

Clément Fumex's avatar
Clément Fumex committed
161 162 163
(************************)
(* parsing command line *)
(************************)
164

Clément Fumex's avatar
Clément Fumex committed
165 166
let files : string Queue.t = Queue.create ()
let opt_parser = ref None
167
let opt_batch = ref None
Clément Fumex's avatar
Clément Fumex committed
168

169
let spec = [
Clément Fumex's avatar
Clément Fumex committed
170 171 172 173
  "-F", Arg.String (fun s -> opt_parser := Some s),
      "<format> select input format (default: \"why\")";
  "--format", Arg.String (fun s -> opt_parser := Some s),
      " same as -F";
Sylvain Dailler's avatar
Sylvain Dailler committed
174
(*
Clément Fumex's avatar
Clément Fumex committed
175 176 177
  "-f",
   Arg.String (fun s -> input_files := s :: !input_files),
   "<file> add file to the project (ignored if it is already there)";
Sylvain Dailler's avatar
Sylvain Dailler committed
178
*)
179 180
  Termcode.arg_extra_expl_prefix;
  "--batch", Arg.String (fun s -> opt_batch := Some s), "";
Clément Fumex's avatar
Clément Fumex committed
181
]
182

Clément Fumex's avatar
Clément Fumex committed
183 184 185
let usage_str = sprintf
  "Usage: %s [options] [<file.why>|<project directory>]..."
  (Filename.basename Sys.argv.(0))
MARCHE Claude's avatar
MARCHE Claude committed
186

187 188 189
let env, gconfig = try
  let config, base_config, env =
    Whyconf.Args.initialize spec (fun f -> Queue.add f files) usage_str in
Clément Fumex's avatar
Clément Fumex committed
190 191 192
    if Queue.is_empty files then
      Whyconf.Args.exit_with_usage spec usage_str;
    Gconfig.load_config config base_config;
193
    env, Gconfig.config ()
Clément Fumex's avatar
Clément Fumex committed
194 195 196 197 198 199

  with e when not (Debug.test_flag Debug.stack_trace) ->
    eprintf "%a@." Exn_printer.exn_printer e;
    exit 1


MARCHE Claude's avatar
MARCHE Claude committed
200

MARCHE Claude's avatar
MARCHE Claude committed
201 202 203 204
(********************************)
(* Source language highlighting *)
(********************************)

MARCHE Claude's avatar
MARCHE Claude committed
205

MARCHE Claude's avatar
MARCHE Claude committed
206
let (why_lang, any_lang) =
Clément Fumex's avatar
Clément Fumex committed
207 208
  let main = Whyconf.get_main gconfig.config in
  let load_path = Filename.concat (Whyconf.datadir main) "lang" in
MARCHE Claude's avatar
MARCHE Claude committed
209 210 211 212 213 214 215 216
  let languages_manager =
    GSourceView2.source_language_manager ~default:true
  in
  languages_manager#set_search_path
    (load_path :: languages_manager#search_path);
  let why_lang =
    match languages_manager#language "why3" with
    | None ->
Clément Fumex's avatar
Clément Fumex committed
217
        eprintf "language file for 'why3' not found in directory %s@."
MARCHE Claude's avatar
MARCHE Claude committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
          load_path;
        exit 1
    | Some _ as l -> l in
  let any_lang filename =
    match languages_manager#guess_language ~filename () with
    | None -> why_lang
    | Some _ as l -> l in
  (why_lang, any_lang)

(* Borrowed from Frama-C src/gui/source_manager.ml:
Try to convert a source file either as UTF-8 or as locale. *)
let try_convert s =
  try
    if Glib.Utf8.validate s then s else Glib.Convert.locale_to_utf8 s
  with Glib.Convert.Error _ ->
    try
      Glib.Convert.convert_with_fallback
        ~fallback:"#neither UTF-8 nor locale nor ISO-8859-15#"
        ~to_codeset:"UTF-8"
        ~from_codeset:"ISO_8859-15"
        s
    with Glib.Convert.Error _ as e -> Printexc.to_string e

MARCHE Claude's avatar
MARCHE Claude committed
241

242 243 244 245 246 247 248 249 250 251 252 253
(****************************)
(* Color handling in source *)
(****************************)

(* For each view, we have to recreate the tags *)
let create_colors v =
  let premise_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"premise_tag" [`BACKGROUND gconfig.premise_color] in
  let neg_premise_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"neg_premise_tag" [`BACKGROUND gconfig.neg_premise_color] in
  let goal_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"goal_tag" [`BACKGROUND gconfig.goal_color] in
254 255
  let error_line_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"error_line_tag" [`BACKGROUND gconfig.error_line_color] in
256 257 258 259 260
  let error_tag (v: GSourceView2.source_view) = v#buffer#create_tag
      ~name:"error_tag" [`BACKGROUND gconfig.error_color] in
  let _ : GText.tag = premise_tag v in
  let _ : GText.tag = neg_premise_tag v in
  let _ : GText.tag = goal_tag v in
261
  let _ : GText.tag = error_line_tag v in
262 263 264 265 266 267 268 269 270
  let _ : GText.tag = error_tag v in
  ()

(* Erase all the source location tags in a source file *)
let erase_color_loc (v:GSourceView2.source_view) =
  let buf = v#buffer in
  buf#remove_tag_by_name "premise_tag" ~start:buf#start_iter ~stop:buf#end_iter;
  buf#remove_tag_by_name "neg_premise_tag" ~start:buf#start_iter ~stop:buf#end_iter;
  buf#remove_tag_by_name "goal_tag" ~start:buf#start_iter ~stop:buf#end_iter;
271 272
  buf#remove_tag_by_name "error_tag" ~start:buf#start_iter ~stop:buf#end_iter;
  buf#remove_tag_by_name "error_line_tag" ~start:buf#start_iter ~stop:buf#end_iter
273 274


MARCHE Claude's avatar
MARCHE Claude committed
275

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
(*******************)
(* Graphical tools *)
(*******************)

(* Elements needed for usage of graphical elements *)

(* [quit_on_saved] set to true by exit function to delay quiting after Saved
   notification is received *)
let quit_on_saved = ref false

(* Exit brutally without asking anything *)
let exit_function_unsafe () =
  send_request Exit_req;
  GMain.quit ()

291
(* Contains quadruples (tab page, source_view, file_has_been_modified, label_of_tab):
292 293 294 295 296 297 298 299 300
   - tab_page is a unique number for each pages of the notebook
   - source_view is the graphical element inside a tab
   - has_been_modified is a reference to a boolean stating if the current tab
     source has been modified
   - label_of_tab is the mutable title of the tab
*)
let source_view_table : (int * GSourceView2.source_view * bool ref * GMisc.label) Hstr.t =
  Hstr.create 14

301 302 303
(* The corresponding file does not have a source view *)
exception Nosourceview of string

304 305 306 307 308
let get_source_view_table (file:string) =
  match Hstr.find source_view_table file with
  | v -> v
  | exception Not_found -> raise (Nosourceview file)

309 310 311 312 313 314
(* This returns the source_view of a file *)
let get_source_view (file: string) : GSourceView2.source_view =
  match Hstr.find source_view_table file with
  | (_, v, _, _) -> v
  | exception Not_found -> raise (Nosourceview file)

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
(* Saving function for sources *)
let save_sources () =
  Hstr.iter
    (fun k (_n, (s: GSourceView2.source_view), b, _l) ->
      if !b then
        let text_to_save = s#source_buffer#get_text () in
        send_request (Save_file_req (k, text_to_save))
    )
    source_view_table

(* True if there exist a file which needs saving *)
let files_need_saving () =
  Hstr.fold (fun _k (_, _, b, _) acc -> !b || acc) source_view_table false

(* Ask if the user wants to save session before exit. Exit is then delayed until
   the [Saved] notification is received *)
let exit_function_safe () =
  if not !session_needs_saving && not (files_need_saving ()) then
    exit_function_unsafe ()
  else
    let answer =
      GToolbox.question_box
        ~title:"Why3 saving session and files"
        ~buttons:["Yes"; "No"; "Cancel"]
        "Do you want to save the session and unsaved files?"
    in
    begin
      match answer with
      | 1 -> save_sources(); send_request Save_req; quit_on_saved := true
      | 2 -> exit_function_unsafe ()
      | _ -> ()
    end

(* Update name of the tab when the label changes so that it has a * as prefix *)
let update_label_change (label: GMisc.label) =
  let s = label#text in
  if not (Strings.has_prefix "*" s) then
    label#set_text ("*" ^ s)

(* Update name of the tab when the label is saved. Removes * prefix *)
let update_label_saved (label: GMisc.label) =
  let s = label#text in
  if (Strings.has_prefix "*" s) then
    label#set_text (String.sub s 1 (String.length s - 1))

MARCHE Claude's avatar
MARCHE Claude committed
360

361 362 363
(**********************)
(* Graphical elements *)
(**********************)
364

365
let initialization_complete = ref false
366 367 368 369 370 371
let warnings = Queue.create ()

let record_warning ?loc msg =
  Format.eprintf "%awarning: %s@."
    (Pp.print_option Loc.report_position) loc msg;
  Queue.push (loc,msg) warnings
372 373

let () =
374
  Warning.set_hook record_warning;
375 376 377 378 379 380 381 382 383 384 385 386 387 388
  let dir =
    try
      Server_utils.get_session_dir ~allow_mkdir:true files
    with Invalid_argument s ->
      Format.eprintf "Error: %s@." s;
      Whyconf.Args.exit_with_usage spec usage_str
  in
  Server.init_server gconfig.config env dir;
  Queue.iter (fun f -> send_request (Add_file_req f)) files;
  send_request Get_global_infos;
  Debug.dprintf debug "Init the GTK interface...@?";
  ignore (GtkMain.Main.init ());
  Debug.dprintf debug " done.@.";
  Gconfig.init ()
MARCHE Claude's avatar
MARCHE Claude committed
389

390
let window_title =
391
  match !opt_batch with
392 393
  | Some _ -> "Why3 Batch Mode"
  | None -> "Why3 Interactive Proof Session"
394

395
let main_window : GWindow.window =
396 397
  let w = GWindow.window
            ~allow_grow:true ~allow_shrink:true
398 399
            ~width:gconfig.window_width
            ~height:gconfig.window_height
400
            ~title:window_title ()
401 402 403 404 405 406 407 408 409
  in
  (* callback to record the new size of the main window when changed, so
   that on restart the window size is the same as the last session *)
  let (_ : GtkSignal.id) =
    w#misc#connect#size_allocate
      ~callback:
      (fun {Gtk.width=w;Gtk.height=h} ->
       gconfig.window_height <- h;
       gconfig.window_width <- w)
410 411
  in
  w
412 413

(* the main window contains a vertical box, containing:
414 415
   1. the menu [menubar]
   2. an horizontal box [hb]
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
 *)

let vbox = GPack.vbox ~packing:main_window#add ()

let menubar = GMenu.menu_bar
  ~packing:(vbox#pack ?from:None ?expand:None ?fill:None ?padding:None)
  ()

let hb = GPack.hbox ~packing:vbox#add ()

(* 1. Menu *)

let factory = new GMenu.factory menubar

let accel_group = factory#accel_group

MARCHE Claude's avatar
MARCHE Claude committed
432 433 434 435 436 437 438 439 440 441
let create_menu_item (factory:GMenu.menu GMenu.factory)
                     ?key label tooltip =
  let i = factory#add_item ?key label in
  i#misc#set_tooltip_markup tooltip;
  i

let connect_menu_item i ~callback =
  let (_ : GtkSignal.id) = i#connect#activate ~callback in ()

(* 1.1 "File" menu items *)
MARCHE Claude's avatar
MARCHE Claude committed
442

443 444
let file_menu = factory#add_submenu "_File"
let file_factory = new GMenu.factory file_menu ~accel_group
MARCHE Claude's avatar
MARCHE Claude committed
445
let menu_add_file =
446
  create_menu_item file_factory "Add file to session"
MARCHE Claude's avatar
MARCHE Claude committed
447 448
                   "Insert another file in the current session"
let menu_preferences =
449
  create_menu_item file_factory "Preferences"
MARCHE Claude's avatar
MARCHE Claude committed
450 451
                   "Open Preferences Window"
let menu_save_session =
452
  create_menu_item file_factory "Save session"
MARCHE Claude's avatar
MARCHE Claude committed
453
                   "Save the current proof session on disk"
454
let menu_save_files =
455
  create_menu_item file_factory "Save files"
456 457 458
                   "Save the edited source files on disk"
let menu_save_session_and_files =
  create_menu_item file_factory ~key:GdkKeysyms._S "_Save session and files"
459 460 461 462
                   "Save the current proof session and the source files"
let menu_refresh =
  create_menu_item file_factory ~key:GdkKeysyms._R "Save all and _Refresh session"
                   "Save the current proof session and the source files, then refresh the proof session with updated source files."
463

MARCHE Claude's avatar
MARCHE Claude committed
464 465 466 467 468 469 470 471
let menu_quit =
  create_menu_item file_factory ~key:GdkKeysyms._Q "_Quit"
                   "Quit the interface. See the Preferences for setting the policy on automatic file saving at exit."

(* 1.2 "Tools" menu items *)

let tools_menu = factory#add_submenu "_Tools"
let tools_factory = new GMenu.factory tools_menu ~accel_group
472
let tools_accel_group = GtkData.AccelGroup.create ()
MARCHE Claude's avatar
MARCHE Claude committed
473

474 475 476 477 478
let strategies_factory =
  let tools_submenu_strategies = tools_factory#add_submenu "Strategies" in
  let ( _ : GMenu.menu_item) = tools_factory#add_separator () in
  new GMenu.factory tools_submenu_strategies

479 480 481 482
let provers_factory =
  let tools_submenu_provers = tools_factory#add_submenu "Provers" in
  let ( _ : GMenu.menu_item) = tools_factory#add_separator () in
  new GMenu.factory tools_submenu_provers
MARCHE Claude's avatar
MARCHE Claude committed
483

484 485


MARCHE Claude's avatar
MARCHE Claude committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
(* 1.3 "View" menu items *)



(****************************)
(* actions of the interface *)
(****************************)


(***********************************)
(* connection of actions to signals *)
(***********************************)

(* File menu signals *)

501 502 503 504 505 506 507 508
let send_session_config_to_server () =
  let nb = gconfig.session_nb_processes in
  send_request (Set_config_param("max_tasks",nb));
  let nb = gconfig.session_time_limit in
  send_request (Set_config_param("timelimit",nb));
  let nb = gconfig.session_mem_limit in
  send_request (Set_config_param("memlimit",nb))

MARCHE Claude's avatar
MARCHE Claude committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
let () =
  let callback () =
    Gconfig.preferences gconfig;
    (* TODO:
      begin
        match !current_env_session with
          | None -> ()
          | Some e ->
              Session.update_env_session_config e gconfig.config;
              Session.unload_provers e
      end;
      recreate_gui ();
(*
      Mprover.iter
        (fun p pi ->
          Debug.dprintf debug "editor for %a : %s@." Whyconf.print_prover p
            pi.editor)
        (Whyconf.get_provers gconfig.config);
     *)
     *)
529 530
    Hstr.iter
      (fun _ (_,source_view,_,_) ->
531 532
       source_view#set_editable gconfig.allow_source_editing;
       source_view#set_auto_indent gconfig.allow_source_editing)
533
      source_view_table;
534
    send_session_config_to_server ()
MARCHE Claude's avatar
MARCHE Claude committed
535 536 537 538 539 540 541
  in
  connect_menu_item menu_preferences ~callback

let () =
  connect_menu_item
    menu_save_session
    ~callback:(fun () -> send_request Save_req)
542

543 544 545 546 547 548 549 550 551 552 553
let () =
  connect_menu_item
    menu_save_session_and_files
    ~callback:(fun () -> save_sources(); send_request Save_req)

let () =
  connect_menu_item
    menu_save_files
    ~callback:(fun () -> save_sources())


MARCHE Claude's avatar
MARCHE Claude committed
554 555 556 557
let () =
  connect_menu_item
    menu_quit
    ~callback:exit_function_safe
558

MARCHE Claude's avatar
MARCHE Claude committed
559 560 561 562 563 564 565
let (_ : GtkSignal.id) =
  main_window#connect#destroy
    ~callback:exit_function_safe

let (_ : GtkSignal.id) =
  main_window#event#connect#delete
    ~callback:(fun _ -> exit_function_safe (); true)
566

567 568
(* 2. horizontal box contains:
   2.1 TODO: a tool box ?
569 570 571
   2.2 a horizontal paned [hp] containing:
     2.2.1 a scrolled window to hold the tree view of the session [scrolledview]
     2.2.2 a vertical paned containing [vpan222]
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
*)

let hp = GPack.paned `HORIZONTAL ~packing:hb#add ()

let scrollview =
  let sv =
    GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~width:gconfig.tree_width ~shadow_type:`ETCHED_OUT
      ~packing:hp#add ()
  in
  let (_ : GtkSignal.id) =
    sv#misc#connect#size_allocate
      ~callback:
      (fun {Gtk.width=w;Gtk.height=_h} ->
       gconfig.tree_width <- w)
  in sv

590
(** {2 view for the session tree} *)
MARCHE Claude's avatar
MARCHE Claude committed
591 592 593 594
let scrolled_session_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
MARCHE Claude's avatar
MARCHE Claude committed
595
    ~packing:scrollview#add_with_viewport
MARCHE Claude's avatar
MARCHE Claude committed
596 597
    ()

598 599 600 601 602 603 604
(* Vertical pan *)
let vpan222 = GPack.paned `VERTICAL ~packing:hp#add ()

(*  the scrolled window 2.2.1 [scrolled_session_view] contains a GTK tree

*)

605 606
(** {3 the model for tree view} *)

607
let cols = new GTree.column_list
608
(* first column: unique id of the object *)
Clément Fumex's avatar
Clément Fumex committed
609
let node_id_column = cols#add Gobject.Data.int
610 611 612 613 614
(* second column: an icon identifying the object: file,theory, goal, transformation *)
let icon_column = cols#add Gobject.Data.gobject
(* third column: name of the object *)
let name_column = cols#add Gobject.Data.string
(* fourth column: icon status for the object: proved/unproved, unknown, timeout, etc. *)
615
let status_column = cols#add Gobject.Data.gobject
616
(* fifth column: extra status info: time, obsolete status, limits *)
617
let time_column = cols#add Gobject.Data.string
MARCHE Claude's avatar
MARCHE Claude committed
618

619 620 621 622 623
(* first view column: icon and name *)
let view_name_column =
  let v = GTree.view_column ~title:"Theories/Goals" () in
  (* icon attribute *)
  let icon_renderer = GTree.cell_renderer_pixbuf [ ] in
624
  v#pack icon_renderer ~expand:false;
625 626 627 628
  v#add_attribute icon_renderer "pixbuf" icon_column;
  let name_renderer = GTree.cell_renderer_text [`XALIGN 0.] in
  v#pack name_renderer;
  v#add_attribute name_renderer "text" name_column;
629
  (* v#set_sizing `AUTOSIZE; *)
630
  v#set_resizable true;
631
  (*  v#set_max_width 1000;*)
632 633 634 635 636 637 638 639 640 641 642 643
  v

(* second view column: status *)
let view_status_column =
  let status_renderer = GTree.cell_renderer_pixbuf [ ] in
  let v = GTree.view_column ~title:"Status"
                            ~renderer:(status_renderer, ["pixbuf", status_column])
                            ()
  in
  v#set_resizable false;
  v#set_visible true;
  v
644 645 646

let view_time_column =
  let renderer = GTree.cell_renderer_text [`XALIGN 0.] in
647 648 649 650 651 652
  let v = GTree.view_column ~title:"Time"
                            ~renderer:(renderer, ["text", time_column]) ()
  in
  v#set_resizable false;
  v#set_visible true;
  v
653

654
let goals_model,goals_view =
655
  Debug.dprintf debug "Creating tree model...@?";
656 657 658
  let model = GTree.tree_store cols in
  let view = GTree.view ~model ~packing:scrolled_session_view#add () in
  let () = view#selection#set_mode (* `SINGLE *) `MULTIPLE in
659
(*
660
  let () = view#set_rules_hint true in
661 662
*)
  let () = view#set_enable_search false in
663
  let _: int = view#append_column view_status_column in
664
  let _: int = view#append_column view_name_column in
665
  let _: int = view#append_column view_time_column in
666
  view#set_expander_column (Some view_name_column);
667
  Debug.dprintf debug "done@.";
668
  model,view
669

670 671 672 673 674 675 676 677 678 679 680 681

(***********************************)
(* Mapping session to the GTK tree *)
(***********************************)

type pa_status = Controller_itp.proof_attempt_status
      * bool   (* obsolete or not *) (* TODO *)
      * Call_provers.resource_limit

let node_id_type : node_type Hint.t = Hint.create 17
let node_id_proved : bool Hint.t = Hint.create 17
let node_id_pa : pa_status Hint.t = Hint.create 17
682
let node_id_detached : bool Hint.t = Hint.create 17
683 684

let get_node_type id = Hint.find node_id_type id
685 686 687 688 689

let get_node_proved id =
  try Hint.find node_id_proved id
  with Not_found -> false

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
let get_node_id_pa id = Hint.find node_id_pa id

let get_obs (pa_st: pa_status) = match pa_st with
| _, b, _ -> b

let get_proof_attempt (pa_st: pa_status) = match pa_st with
| pa, _, _ -> pa

let get_limit (pa_st: pa_status) = match pa_st with
| _, _, l -> l

let get_node_obs id = get_obs (get_node_id_pa id)
let get_node_proof_attempt id = get_proof_attempt (get_node_id_pa id)
let get_node_limit id = get_limit (get_node_id_pa id)

let get_node_id iter = goals_model#get ~row:iter ~column:node_id_column

(* To each node we have the corresponding row_reference *)
let node_id_to_gtree : GTree.row_reference Hint.t = Hint.create 42
(* TODO exception for those: *)
let get_node_row id = Hint.find node_id_to_gtree id

712 713 714
let get_node_detached id =
  Hint.find node_id_detached id

715 716 717 718 719 720 721 722 723 724 725 726 727 728
(******************************)
(* Initialization of the tree *)
(******************************)

let remove_tree goals_model =
  Hint.iter (fun _x i ->
    try ignore(goals_model#remove (i#iter)) with _ -> ())
    node_id_to_gtree

let clear_tree_and_table goals_model =
  remove_tree goals_model;
  Hint.clear node_id_to_gtree;
  Hint.clear node_id_type;
  Hint.clear node_id_proved;
729 730
  Hint.clear node_id_pa;
  Hint.clear node_id_detached
731 732 733 734 735


(**************)
(* Menu items *)
(**************)
736

Clément Fumex's avatar
Clément Fumex committed
737
(* vpan222 contains:
738
   2.2.2.1 a notebook containing view of the current task, source code etc
739
   2.2.2.2 a vertical pan which contains [vbox2222]
Clément Fumex's avatar
Clément Fumex committed
740
     2.2.2.2.1 the input field to type commands
741
     2.2.2.2.2 a scrolled window to hold the output of the commands
742 743
 *)

744 745 746
(***********************************)
(*    notebook on the top 2.2.2.1  *)
(***********************************)
747

748
(* notebook is composed of a Task page and several source files pages *)
749 750
let notebook = GPack.notebook ~packing:vpan222#add ()

751 752 753
(********************************)
(* Task view (part of notebook) *)
(********************************)
754 755 756 757 758
let task_page,scrolled_task_view =
  let label = GMisc.label ~text:"Task" () in
  0, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(notebook#append_page ~tab_label:label#coerce w)) ()

759 760
let scrolled_task_view =
  GBin.scrolled_window
761
    ~height:gconfig.task_height
762 763
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
764
    ~packing:scrolled_task_view#add ()
765

766 767 768 769 770 771 772
let (_ : GtkSignal.id) =
  scrolled_task_view#misc#connect#size_allocate
    ~callback:
    (fun {Gtk.width=_w;Gtk.height=h} ->
       gconfig.task_height <- h)


773 774 775
let task_view =
  GSourceView2.source_view
    ~editable:false
Clément Fumex's avatar
Clément Fumex committed
776
    ~cursor_visible:false
777 778 779 780
    ~show_line_numbers:true
    ~packing:scrolled_task_view#add
    ()

781

782
(* Creating a page for source code view *)
783
let create_source_view =
784
  (* Counter for pages *)
785
  let n = ref 1 in
786 787
  (* Create a page with tabname [f] and buffer equal to [content] in the
     notebook. Also add a corresponding page in source_view_table. *)
788 789 790
  let create_source_view f content =
    if not (Hstr.mem source_view_table f) then
      begin
791
        let label = GMisc.label ~text:f () in
792 793
        let source_page, scrolled_source_view =
          !n, GPack.vbox ~homogeneous:false ~packing:
794 795
            (fun w -> ignore(notebook#append_page ~tab_label:label#coerce w)) ()
        in
796 797 798 799 800 801 802
        let scrolled_source_view =
          GBin.scrolled_window
            ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
            ~shadow_type:`ETCHED_OUT
            ~packing:scrolled_source_view#add () in
        let source_view =
          GSourceView2.source_view
803
            ~auto_indent:gconfig.allow_source_editing
804 805 806 807
            ~insert_spaces_instead_of_tabs:true ~tab_width:2
            ~show_line_numbers:true
            ~right_margin_position:80 ~show_right_margin:true
            (* ~smart_home_end:true *)
808
            ~editable:gconfig.allow_source_editing
809 810
            ~packing:scrolled_source_view#add
            () in
811 812
        let has_changed = ref false in
        Hstr.add source_view_table f (source_page, source_view, has_changed, label);
813
        n := !n + 1;
814
        source_view#source_buffer#begin_not_undoable_action ();
815
        source_view#source_buffer#set_text content;
816
        source_view#source_buffer#end_not_undoable_action ();
817 818 819 820 821 822 823 824 825 826 827
        (* At initialization, file has not changed. When it changes, changes the
           name of the tab and update has_changed boolean. *)
        let (_: GtkSignal.id) = source_view#source_buffer#connect#changed
          ~callback:(fun () ->
            try
              let _source_page, _source_view, has_changed, label =
                Hstr.find source_view_table f in
              update_label_change label;
              has_changed := true;
              ()
            with Not_found -> () ) in
828 829
        Gconfig.add_modifiable_mono_font_view source_view#misc;
        source_view#source_buffer#set_language why_lang;
830 831 832
        (* We have to create the tags for background colors for each view.
           They are not reusable from the other views.  *)
        create_colors source_view;
833 834 835
        Gconfig.set_fonts ()
      end in
  create_source_view
836 837 838



839 840
(* End of notebook *)

841 842 843 844 845
(*
  2.2.2.2 a vertical pan which contains [vbox2222]
    2.2.2.2.1 the input field to type commands [hbox22221]
    2.2.2.2.2 a scrolled window to hold the output of the commands [message_zone]
*)
Clément Fumex's avatar
Clément Fumex committed
846
let vbox2222 = GPack.vbox ~packing:vpan222#add  ()
847

848 849 850 851
(* 2.2.2.2.1 Horizontal box [hbox22221]
     [monitor] number of scheduled/running provers
     [command_entry] Commands to run on the session
*)
852 853 854 855 856 857
let hbox22221 =
  GPack.hbox
    ~packing:(vbox2222#pack ?from:None ?expand:None ?fill:None ?padding:None) ()

let monitor =
  GMisc.label
MARCHE Claude's avatar
MARCHE Claude committed
858
    ~text:"  0/0/0"
859
    ~width:100
MARCHE Claude's avatar
MARCHE Claude committed
860
    ~xalign:0.0
861
    ~packing:(hbox22221#pack ?from:None ?expand:None ?fill:None ?padding:None) ()
862

863 864 865 866
let command_entry =
  GEdit.entry
    ~text:"type commands here"
    ~packing:hbox22221#add ()
MARCHE Claude's avatar
MARCHE Claude committed
867

868 869 870 871 872 873 874 875 876 877
(* Part 2.2.2.2.2 contains messages returned by the IDE/server *)
let messages_notebook = GPack.notebook ~packing:vbox2222#add ()

let error_page,error_view =
  let label = GMisc.label ~text:"Messages" () in
  0, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(messages_notebook#append_page ~tab_label:label#coerce w)) ()

let log_page,log_view =
  let label = GMisc.label ~text:"Log" () in
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
  1, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(messages_notebook#append_page ~tab_label:label#coerce w)) ()

(* tab 3: edited proof *)
let edited_page,edited_tab =
  let label = GMisc.label ~text:"Edited proof" () in
  2, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(messages_notebook#append_page ~tab_label:label#coerce w)) ()

let scrolled_edited_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT ~packing:edited_tab#add ()

let edited_view =
  GSourceView2.source_view
    ~editable:false
    ~show_line_numbers:true
    ~packing:scrolled_edited_view#add
    ()

(* tab 4: prover output *)
let output_page,output_tab =
  let label = GMisc.label ~text:"Prover output" () in
  3, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(messages_notebook#append_page ~tab_label:label#coerce w)) ()

let scrolled_output_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT ~packing:output_tab#add ()

let output_view =
  GSourceView2.source_view
    ~editable:false
    ~show_line_numbers:true
    ~packing:scrolled_output_view#add
    ()


(* tab 5: counterexample *)
let counterexample_page,counterexample_tab =
  let label = GMisc.label ~text:"Counterexample" () in
  4, GPack.vbox ~homogeneous:false ~packing:
922 923
    (fun w -> ignore(messages_notebook#append_page ~tab_label:label#coerce w)) ()

924 925 926 927 928 929 930 931 932 933 934 935
let scrolled_counterexample_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT ~packing:counterexample_tab#add ()

let counterexample_view =
  GSourceView2.source_view
    ~editable:false
    ~show_line_numbers:true
    ~packing:scrolled_counterexample_view#add
    ()

936 937
(* Allow colors locations on counterexample view *)
let () = create_colors counterexample_view
938

MARCHE Claude's avatar
MARCHE Claude committed
939
let message_zone =
940 941
  let sv = GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
942 943 944 945 946 947 948 949 950
      ~shadow_type:`ETCHED_OUT ~packing:error_view#add ()
  in
  GText.view ~editable:false ~cursor_visible:false
    ~packing:sv#add ()

let log_zone =
  let sv = GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~shadow_type:`ETCHED_OUT ~packing:log_view#add ()
951
  in
MARCHE Claude's avatar
MARCHE Claude committed
952
  GText.view ~editable:false ~cursor_visible:false
953 954
    ~packing:sv#add ()

955 956
(* Create a tag for errors in the message zone. *)
let message_zone_error_tag = message_zone#buffer#create_tag
957
  ~name:"error_tag" [`BACKGROUND gconfig.error_color]
958

959 960
(**** Message-zone printing functions *****)

MARCHE Claude's avatar
MARCHE Claude committed
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
let add_to_log =
  let old = ref None in
  fun notif_kind s ->
  let (_,_,_,n) as x =
    match !old with
    | Some(line,oldnotif_kind,olds,oldn)
         when notif_kind = oldnotif_kind && s = olds ->
       let start = log_zone#buffer#get_iter (`LINE line) in
       let stop = log_zone#buffer#end_iter in
       log_zone#buffer#delete ~start ~stop;
       (line,oldnotif_kind,olds,oldn+1)
    | _ ->
       let line = log_zone#buffer#line_count in
       (line,notif_kind,s,1)
  in
  old := Some x;
  log_zone#buffer#insert ("["^ notif_kind);
  if n>1 then
    log_zone#buffer#insert (" (repeated " ^ (string_of_int n) ^ " times)");
  log_zone#buffer#insert ("] " ^ s ^ "\n");
981 982
  log_zone#scroll_to_mark `INSERT

983 984
let clear_message_zone () =
  let buf = message_zone#buffer in
985
  buf#remove_tag_by_name "error_tag" ~start:buf#start_iter ~stop:buf#end_iter;
986 987
  buf#delete ~start:buf#start_iter ~stop:buf#end_iter

988
(* Function used to print stuff on the message_zone *)
MARCHE Claude's avatar
MARCHE Claude committed
989
let print_message ~kind ~notif_kind fmt =
990
  (* TODO: use kasprintf once OCaml 4.03 is used *)
991 992
  Format.kfprintf
    (fun _ -> let s = flush_str_formatter () in
MARCHE Claude's avatar
MARCHE Claude committed
993
              let s = try_convert s in
MARCHE Claude's avatar
MARCHE Claude committed
994
              add_to_log notif_kind s;
995
              let buf = message_zone#buffer in
MARCHE Claude's avatar
MARCHE Claude committed
996 997
              if kind>0 then
                begin
998 999 1000
                  if Strings.ends_with notif_kind "error" ||
                     Strings.ends_with notif_kind "Error"
                  then
1001
                    buf#insert ~tags:[message_zone_error_tag] (s ^ "\n")
1002
                  else
1003
                    buf#insert (s ^ "\n");
1004
                  messages_notebook#goto_page error_page;
MARCHE Claude's avatar
MARCHE Claude committed
1005
                end)
1006 1007 1008
    str_formatter
    fmt

1009 1010 1011 1012 1013 1014 1015
let display_warnings fmt warnings =
  let nwarn = ref 0 in
  try
    Queue.iter (fun (loc,msg) ->
      if !nwarn = 4 then begin
        Format.fprintf fmt "[%d more warnings. See stderr for details]@\n" (Queue.length warnings - !nwarn);
        raise Exit
1016
      end;
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
      incr nwarn;
      match loc with
      | None ->
        Format.fprintf fmt "%s@\n@\n" msg
      | Some l ->
        (* scroll_to_loc ~color:error_tag ~yalign:0.5 loc; *)
        Format.fprintf fmt "%a: %s@\n@\n" Loc.gen_report_position l msg
    ) warnings;
  with Exit -> ()

let display_warnings () =
  if Queue.is_empty warnings then ()
  else begin
    print_message ~kind:1 ~notif_kind:"warning" "%a" display_warnings warnings;
    Queue.clear warnings;
  end
1033

1034 1035 1036 1037
let print_message ~kind ~notif_kind fmt =
  display_warnings (); print_message ~kind ~notif_kind fmt


1038

1039

1040
(**** Monitor *****)
Clément Fumex's avatar
Clément Fumex committed
1041

1042
let fan =
1043
  let s = Bytes.of_string "\226\150\129" in
1044
  let c = Char.code (Bytes.get s 2) in
1045
  let a = Array.init 8 (fun i ->
1046 1047