gmain.save 59.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 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 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
(**************************************************************************)
(*                                                                        *)
(*  Copyright (C) 2010-                                                   *)
(*    François Bobot                                                     *)
(*    Jean-Christophe Filliâtre                                          *)
(*    Claude Marché                                                      *)
(*    Andrei Paskevich                                                    *)
(*                                                                        *)
(*  This software is free software; you can redistribute it and/or        *)
(*  modify it under the terms of the GNU Library General Public           *)
(*  License version 2.1, with the special exception on linking            *)
(*  described in file LICENSE.                                            *)
(*                                                                        *)
(*  This software is distributed in the hope that it will be useful,      *)
(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                  *)
(*                                                                        *)
(**************************************************************************)


(* TODO:

* when proof attempt is finished and is it the one currently selected,
the new output should be displayed on upper-right window

* when returning from edited proofs: should we run the prover again
   immediately ?

* bug trouve par Johannes:

Pour reproduire le bug :

1) Partir d'un répértoire sans fichier de projet
2) Lancer why3db, ajouter un fichier
3) Prouver quelques buts (pas tous)
4) Choisir "Hide Proved Goals"
5) Prouver le reste des buts, la fênetre devient vide
6) Décocher "Hide Proved Goals"

Maintenant, le fichier réapparait dans la liste, mais on ne peut pas le
déplier, donc accéder au sous-buts, stats des appels de prouvers etc ...

Ce n'est pas un bug très grave, parce qu'il suffit de quitter l'ide,
puis le relancer, et là on peut de nouveau déplier le fichier.

* Francois :

   - Les temps indiqués sont très bizarre, mais cela doit-être un bug
   plus profond, au niveau de l'appel des prouveurs (wall time au lieu
   de cpu time?)

   - Si on modifie le fichier à droite, les buts ne sont pas marqués
   obsolètes ou ajouté à gauche.

*)



open Format

let () =
  eprintf "Init the GTK interface...@?";
  ignore (GtkMain.Main.init ());
  eprintf " done.@."


open Why
open Whyconf
open Gconfig

(************************)
(* parsing command line *)
(************************)

let includes = ref []
let file = ref None
let opt_version = ref false

let spec = Arg.align [
  ("-I",
   Arg.String (fun s -> includes := s :: !includes),
   "<s> add s to loadpath") ;
(*
  ("-f",
   Arg.String (fun s -> input_files := s :: !input_files),
   "<f> add file f to the project (ignored if it is already there)") ;
*)
  ("-v",
   Arg.Set opt_version,
   " print version information") ;
]

let version_msg = sprintf "Why3 IDE, version %s (build date: %s)"
  Config.version Config.builddate

let usage_str = sprintf
  "Usage: %s [options] [<file.why>|<project directory>]"
  (Filename.basename Sys.argv.(0))

let set_file f = match !file with
  | Some _ ->
      raise (Arg.Bad "only one parameter")
  | None ->
      file := Some f

let () = Arg.parse spec set_file usage_str

let () =
  if !opt_version then begin
    printf "%s@." version_msg;
    exit 0
  end

let fname = match !file with
  | None ->
      Arg.usage spec usage_str;
      exit 1
  | Some f ->
      f

let lang =
  let main = get_main () in
  let load_path = Filename.concat (datadir main) "lang" in
  let languages_manager =
    GSourceView2.source_language_manager ~default:true
  in
  languages_manager#set_search_path
    (load_path :: languages_manager#search_path);
  match languages_manager#language "why" with
    | None ->
        Format.eprintf "language file for 'why' not found in directory %s@."
          load_path;
        exit 1
    | Some _ as l -> l

let source_text fname =
  let ic = open_in fname in
  let size = in_channel_length ic in
  let buf = String.create size in
  really_input ic buf 0 size;
  close_in ic;
  buf

(********************************)
(* loading WhyIDE configuration *)
(********************************)

let gconfig =
  let c = Gconfig.config in
  let loadpath = (Whyconf.loadpath (get_main ())) @ List.rev !includes in
  c.env <- Lexer.create_env loadpath;
  let provers = Whyconf.get_provers c.Gconfig.config in
  c.provers <-
    Util.Mstr.fold (Gconfig.get_prover_data c.env) provers Util.Mstr.empty;
  c

let () =
  Whyconf.load_plugins (get_main ())


(********************)
(* opening database *)
(********************)

let project_dir, file_to_read =
  if Sys.file_exists fname then
    begin
      if Sys.is_directory fname then
        begin
          eprintf "Info: found directory '%s' for the project@." fname;
          fname, None
        end
      else
        begin
          eprintf "Info: found regular file '%s'@." fname;
          let d =
            try Filename.chop_extension fname
            with Invalid_argument _ -> fname
          in
          eprintf "Info: using '%s' as directory for the project@." d;
          d, Some (Filename.concat Filename.parent_dir_name
		     (Filename.basename fname))
        end
    end
  else
    fname, None

let () =
  if not (Sys.file_exists project_dir) then
    begin
      eprintf "Info: '%s' does not exists. Creating directory of that name \
 for the project@." project_dir;
      Unix.mkdir project_dir 0o777
    end

let () =
  let dbfname = Filename.concat project_dir "project.db" in
  try
    Db.init_base dbfname
  with e ->
    eprintf "Error while opening database '%s'@." dbfname;
    eprintf "Aborting...@.";
    raise e


let read_file fn =
  let fn = Filename.concat project_dir fn in 
  let theories = Env.read_file gconfig.env fn in
  let theories =
    Theory.Mnm.fold
      (fun name th acc ->
         match th.Theory.th_name.Ident.id_origin with
           | Ident.User l -> (Loc.extract l,name,th)::acc
           | _ -> (Loc.dummy_floc,name,th)::acc)
      theories []
  in
  let theories = List.sort
    (fun (l1,_,_) (l2,_,_) -> Loc.compare l1 l2)
    theories
  in theories


(****************)
(* goals widget *)
(****************)


module Model = struct

(* TODO: remove, see below *)
(*
  type proof_attempt_status =
    | Scheduled (** external proof attempt is scheduled *)
    | Running (** external proof attempt is in progress *)
    | Success (** external proof attempt succeeded *)
    | Timeout (** external proof attempt was interrupted *)
    | Unknown (** external prover answered ``don't know'' or equivalent *)
    | HighFailure (** external prover call failed *)
*)

  type proof_attempt =
      { prover : prover_data;
        proof_goal : goal;
        proof_row : Gtk.tree_iter;
        proof_db : Db.proof_attempt;
(*
        mutable status : proof_attempt_status;
        mutable time : float;
        mutable output : string;
*)
(* TODO: replace the 3 fields above with *)
	mutable proof_state : Scheduler.proof_attempt_status;
(**)
        mutable proof_obsolete : bool;
        mutable edited_as : string;
      }

  and goal_parent =
    | Theory of theory
    | Transf of transf

  and goal =
      { goal_name : string;
	parent : goal_parent;
        task: Task.task;
        goal_row : Gtk.tree_iter;
        goal_db : Db.goal;
        mutable proved : bool;
        external_proofs: (string, proof_attempt) Hashtbl.t;
        transformations : (string, transf) Hashtbl.t;
      }

  and transf =
      { parent_goal : goal;
	mutable transf_proved : bool;
(*
        transf : Task.task Trans.trans;
*)
        transf_row : Gtk.tree_iter;
        transf_db : Db.transf;
        mutable subgoals : goal list;
      }

  and theory =
      { theory : Theory.theory;
        theory_row : Gtk.tree_iter;
        theory_db : Db.theory;
        theory_parent : file;
        mutable goals : goal list;
        mutable verified : bool;
      }

  and file =
      { file_name : string;
        file_row : Gtk.tree_iter;
        file_db : Db.file;
        mutable theories: theory list;
        mutable file_verified : bool;
      }


  type any_row =
    | Row_file of file
    | Row_theory of theory
    | Row_goal of goal
    | Row_proof_attempt of proof_attempt
    | Row_transformation of transf

  let all_files : file list ref = ref []

  let toggle_hide_proved_goals = ref false

  let cols = new GTree.column_list
  let name_column = cols#add Gobject.Data.string
  let icon_column = cols#add Gobject.Data.gobject
  let index_column : any_row GTree.column = cols#add Gobject.Data.caml
  let status_column = cols#add Gobject.Data.gobject
  let time_column = cols#add Gobject.Data.string
  let visible_column = cols#add Gobject.Data.boolean
(*
  let bg_column = cols#add (Gobject.Data.unsafe_boxed
  (Gobject.Type.from_name "GdkColor"))
*)

  let name_renderer = GTree.cell_renderer_text [`XALIGN 0.]
  let renderer = GTree.cell_renderer_text [`XALIGN 0.]
  let image_renderer = GTree.cell_renderer_pixbuf [ ]
  let icon_renderer = GTree.cell_renderer_pixbuf [ ]

  let view_name_column =
    GTree.view_column ~title:"Theories/Goals" ()

  let () =
    view_name_column#pack icon_renderer ;
    view_name_column#add_attribute icon_renderer "pixbuf" icon_column ;
    view_name_column#pack name_renderer;
    view_name_column#add_attribute name_renderer "text" name_column;
    view_name_column#set_resizable true;
    view_name_column#set_max_width 400;
(*
    view_name_column#add_attribute name_renderer "background-gdk" bg_column
*)
    ()

  let view_status_column =
    GTree.view_column ~title:"Status"
      ~renderer:(image_renderer, ["pixbuf", status_column])
      ()

  let view_time_column =
    GTree.view_column ~title:"Time"
      ~renderer:(renderer, ["text", time_column]) ()

  let () =
    view_status_column#set_resizable false;
    view_status_column#set_visible true;
    view_time_column#set_resizable false;
    view_time_column#set_visible true


  let create ~packing () =
    let model = GTree.tree_store cols in
    let model_filter = GTree.model_filter model in
    model_filter#set_visible_column visible_column;
    let view = GTree.view ~model:model_filter ~packing () in
(*
    let () = view#selection#set_mode `SINGLE in
*)
    let () = view#selection#set_mode `MULTIPLE in
    let () = view#set_rules_hint true in
    ignore (view#append_column view_name_column);
    ignore (view#append_column view_status_column);
    ignore (view#append_column view_time_column);
    model,model_filter,view

  let clear model = model#clear ()

end


(***************)
(* Main window *)
(***************)

let exit_function () =
  eprintf "saving IDE config file@.";
  save_config ();
  GMain.quit ()

let w = GWindow.window
  ~allow_grow:true ~allow_shrink:true
  ~width:gconfig.window_width
  ~height:gconfig.window_height
  ~title:"why GUI with database" ()

let (_ : GtkSignal.id) = w#connect#destroy ~callback:exit_function

let (_ : GtkSignal.id) =
  w#misc#connect#size_allocate
    ~callback:
    (fun {Gtk.width=w;Gtk.height=h} ->
       gconfig.window_height <- h;
       gconfig.window_width <- w)

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

(* Menu *)

let menubar = GMenu.menu_bar ~packing:vbox#pack ()

let factory = new GMenu.factory menubar

let accel_group = factory#accel_group

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

let tools_window_vbox =
  try
    GPack.vbox ~packing:(hb#pack ~expand:false) ~border_width:2 ()
  with Gtk.Error _ -> assert false

let context_frame =
  GBin.frame ~label:"Context"
    ~packing:(tools_window_vbox#pack ~expand:false) ()

let context_box =
  GPack.button_box `VERTICAL ~border_width:5 ~spacing:5
    ~packing:context_frame#add ()

let context_unproved_goals_only = ref true

let () =
  let b1 = GButton.radio_button
    ~packing:context_box#add ~label:"Unproved goals" ()
  in
  let (_ : GtkSignal.id) =
    b1#connect#clicked
      ~callback:(fun () -> context_unproved_goals_only := true)
  in
  let b2 = GButton.radio_button
    ~group:b1#group ~packing:context_box#add ~label:"All goals" ()
  in
  let (_ : GtkSignal.id) =
    b2#connect#clicked
      ~callback:(fun () -> context_unproved_goals_only := false)
  in ()


let provers_frame =
  GBin.frame ~label:"Provers"
    ~packing:(tools_window_vbox#pack ~expand:false) ()

let provers_box =
  GPack.button_box `VERTICAL ~border_width:5 ~spacing:5
  ~packing:provers_frame#add ()

let () = provers_frame#set_resize_mode `PARENT

let transf_frame =
  GBin.frame ~label:"Transformations"
    ~packing:(tools_window_vbox#pack ~expand:false) ()

let transf_box =
  GPack.button_box `VERTICAL ~border_width:5 ~spacing:5
  ~packing:transf_frame#add ()

let tools_frame =
  GBin.frame ~label:"Tools"
    ~packing:(tools_window_vbox#pack ~expand:false) ()

let tools_box =
  GPack.button_box `VERTICAL ~border_width:5 ~spacing:5
  ~packing:tools_frame#add ()

let cleaning_frame =
  GBin.frame ~label:"Cleaning"
    ~packing:(tools_window_vbox#pack ~expand:false) ()

let cleaning_box =
  GPack.button_box `VERTICAL ~border_width:5 ~spacing:5
  ~packing:cleaning_frame#add ()


(* horizontal paned *)

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


(* tree view *)
let scrollview =
  try
    GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~width:gconfig.tree_width
      ~packing:hp#add ()
  with Gtk.Error _ -> assert false

let () = scrollview#set_shadow_type `ETCHED_OUT
let (_ : GtkSignal.id) =
  scrollview#misc#connect#size_allocate
    ~callback:
    (fun {Gtk.width=w;Gtk.height=_h} ->
       gconfig.tree_width <- w)

let goals_model,filter_model,goals_view =
  Model.create ~packing:scrollview#add ()

let task_checksum t =
  fprintf str_formatter "%a@." Pretty.print_task t;
  let s = flush_str_formatter () in
(*
  eprintf "task = %s@." s;
*)
  Digest.to_hex (Digest.string s)


let info_window ?(callback=(fun () -> ())) mt s =
  let buttons = match mt with
    | `INFO -> GWindow.Buttons.close
    | `WARNING -> GWindow.Buttons.close
    | `QUESTION -> GWindow.Buttons.ok_cancel
    | `ERROR -> GWindow.Buttons.close
  in
  let d = GWindow.message_dialog
    ~message:s
    ~message_type:mt
    ~buttons
    ~title:"Why3 info or error"
    ~show:true ()
  in
  let (_ : GtkSignal.id) =
    d#connect#response
      ~callback:(function x -> d#destroy ();
		   if x = `OK then callback ())
  in ()

module Helpers = struct

  open Model
  open Scheduler

  let image_of_result ~obsolete result =
    match result with
    | Scheduled -> !image_scheduled
    | Running -> !image_running
    | InternalFailure _ -> !image_failure
    | Done r ->
	match obsolete,r.Call_provers.pr_answer with
	  | false, Call_provers.Valid -> !image_valid
	  | false, Call_provers.Invalid -> !image_invalid
	  | false, Call_provers.Timeout -> !image_timeout
	  | false, Call_provers.Unknown _ -> !image_unknown
	  | false, Call_provers.Failure _ -> !image_failure
	  | false, Call_provers.HighFailure -> !image_failure
	  | true, Call_provers.Valid -> !image_invalid_obs
	  | true, Call_provers.Invalid -> !image_invalid_obs
	  | true, Call_provers.Timeout -> !image_timeout_obs
	  | true, Call_provers.Unknown _ -> !image_unknown_obs
	  | true, Call_provers.Failure _ -> !image_failure_obs
	  | true, Call_provers.HighFailure -> !image_failure_obs

  let set_row_status b row =
    if b then 
      begin
	goals_view#collapse_row (goals_model#get_path row);
	goals_model#set ~row ~column:status_column !image_yes;
	if !toggle_hide_proved_goals then
	  goals_model#set ~row ~column:visible_column false
      end
    else
      begin
	goals_model#set ~row ~column:status_column !image_unknown;
	if !toggle_hide_proved_goals then
	  goals_model#set ~row ~column:visible_column true
      end

  let check_file_verified f =
    let b = List.for_all (fun t -> t.verified) f.theories in
    if f.file_verified <> b then
      begin
	f.file_verified <- b;
	set_row_status b f.file_row
      end

  let check_theory_proved t =
    let b = List.for_all (fun g -> g.proved) t.goals in
    if t.verified <> b then
      begin
	t.verified <- b;
	set_row_status b t.theory_row;
	check_file_verified t.theory_parent
      end

  let rec check_goal_proved g =
    let b1 = Hashtbl.fold 
      (fun _ a acc -> acc || 
	 match a.proof_state with
	   | Done { Call_provers.pr_answer = Call_provers.Valid} -> true
	   | _ -> false) g.external_proofs false
    in
    let b = Hashtbl.fold 
      (fun _ t acc -> acc || t.transf_proved) g.transformations b1
    in
    if g.proved <> b then
      begin
	g.proved <- b;
	set_row_status b g.goal_row;
	match g.parent with
          | Theory t -> check_theory_proved t
          | Transf t -> check_transf_proved t
      end

  and check_transf_proved t =
    let b = List.for_all (fun g -> g.proved) t.subgoals in
    if t.transf_proved <> b then
      begin
	t.transf_proved <- b;
	set_row_status b t.transf_row;
	check_goal_proved t.parent_goal
      end
    

  (* deprecated *)
  let set_file_verified f =
    f.file_verified <- true;
    let row = f.file_row in
    goals_view#collapse_row (goals_model#get_path row);
    goals_model#set ~row ~column:status_column !image_yes;
    if !toggle_hide_proved_goals then
      goals_model#set ~row ~column:visible_column false

  (* deprecated *)
  let set_theory_proved ~propagate  t =
    t.verified <- true;
    let row = t.theory_row in
    goals_view#collapse_row (goals_model#get_path row);
    goals_model#set ~row ~column:status_column !image_yes;
    if !toggle_hide_proved_goals then
      goals_model#set ~row ~column:visible_column false;
    let f = t.theory_parent in
    if propagate then
      if List.for_all (fun t ->
(*
                         let tname = t.theory.Theory.th_name.Ident.id_string in
                         eprintf "checking theory %s@." tname;
*)
                         t.verified) f.theories then
        set_file_verified f

  let rec set_proved ~propagate g =
    let row = g.goal_row in
    g.proved <- true;
    goals_view#collapse_row (goals_model#get_path row);
    goals_model#set ~row ~column:status_column !image_yes;
    if !toggle_hide_proved_goals then
      goals_model#set ~row ~column:visible_column false;
    if propagate then
      match g.parent with
        | Theory t ->
            if List.for_all (fun g -> g.proved) t.goals then
              set_theory_proved ~propagate t
        | Transf t ->
            if List.for_all (fun g -> g.proved) t.subgoals then
              begin
                set_proved ~propagate t.parent_goal;
              end

  let set_proof_state ~obsolete a res =
    a.proof_state <- res;
    let row = a.proof_row in
    goals_model#set ~row ~column:status_column
      (image_of_result ~obsolete res);
    
    let t = match res with
      | Done { Call_provers.pr_time = time } -> 
          Format.sprintf "%.2f" time
      | _ -> ""
    in
    let t = if obsolete then t ^ " (obsolete)" else t in
    goals_model#set ~row:a.Model.proof_row ~column:Model.time_column t


  let add_external_proof_row ~obsolete ~edit g p db_proof result (*_time*) =
    let parent = g.goal_row in
    let name = p.prover_name in
    let row = goals_model#prepend ~parent () in
    goals_model#set ~row ~column:icon_column !image_prover;
    goals_model#set ~row ~column:name_column
      (name ^ " " ^ p.prover_version);
    goals_model#set ~row ~column:visible_column true;
    goals_view#expand_row (goals_model#get_path parent);
    let a = { prover = p;
              proof_goal = g;
              proof_row = row;
              proof_db = db_proof;
(*
              status = status;
*)
              proof_obsolete = obsolete;
(*
              time = time;
              output = "";
*)
	      proof_state = result;
              edited_as = edit;
            }
    in
    goals_model#set ~row ~column:index_column (Row_proof_attempt a);
    Hashtbl.add g.external_proofs p.prover_id a;
    set_proof_state ~obsolete a result;
    a


  let add_goal_row parent name t db_goal =
    let parent_row = match parent with
      | Theory mth -> mth.theory_row
      | Transf mtr -> mtr.transf_row
    in
    let row = goals_model#append ~parent:parent_row () in
    let goal = { goal_name = name;
		 parent = parent;
                 task = t ;
                 goal_row = row;
                 goal_db = db_goal;
                 external_proofs = Hashtbl.create 7;
                 transformations = Hashtbl.create 3;
                 proved = false;
               }
    in
    goals_model#set ~row ~column:name_column name;
    goals_model#set ~row ~column:icon_column !image_file;
    goals_model#set ~row ~column:index_column (Row_goal goal);
    goals_model#set ~row ~column:visible_column true;
    goal


  let add_transformation_row g db_transf tr_name =
    let parent = g.Model.goal_row in
    let row = goals_model#append ~parent () in
    let tr = { Model.parent_goal = g;
               Model.transf_proved = false;
               Model.transf_row = row;
               Model.transf_db = db_transf;
               subgoals = [];
             }
    in
    goals_model#set ~row ~column:Model.name_column tr_name;
    goals_model#set ~row ~column:Model.icon_column !image_transf;
    goals_model#set ~row ~column:Model.index_column
      (Model.Row_transformation tr);
    goals_model#set ~row ~column:Model.visible_column true;
    goals_view#expand_row (goals_model#get_path parent);
    tr


  let add_theory_row mfile th db_theory =
    let tname = th.Theory.th_name.Ident.id_string in
    let parent = mfile.file_row in
    let row = goals_model#append ~parent () in
    let mth = { theory = th;
                theory_row = row;
                theory_db = db_theory;
                theory_parent = mfile;
                goals = [] ;
                verified = false }
    in
    goals_model#set ~row ~column:name_column tname;
    goals_model#set ~row ~column:icon_column !image_directory;
    goals_model#set ~row ~column:index_column (Row_theory mth);
    goals_model#set ~row ~column:visible_column true;
    mth


  let add_theory mfile th =
    let tasks = List.rev (Task.split_theory th None None) in
    let tname = th.Theory.th_name.Ident.id_string in
    let db_theory = Db.add_theory mfile.file_db tname in
    let mth = add_theory_row mfile th db_theory in
    let goals =
      List.fold_left
        (fun acc t ->
           let id = (Task.task_goal t).Decl.pr_name in
           let name = id.Ident.id_string in
           let sum = task_checksum t in
           let db_goal = Db.add_goal db_theory name sum in
           let goal = add_goal_row (Theory mth) name t db_goal in
           goal :: acc)
        []
        tasks
    in
    mth.goals <- List.rev goals;
    if goals = [] then set_theory_proved ~propagate:false mth;
    mth

  let add_file_row f dbfile =
      let parent = goals_model#append () in
      let mfile = { file_name = f;
                    file_row = parent;
                    file_db = dbfile;
                    theories = [] ;
                    file_verified = false }
      in
      all_files := !all_files @ [mfile];
      let name = Filename.basename f in
      goals_model#set ~row:parent ~column:name_column name;
      goals_model#set ~row:parent ~column:icon_column !image_directory;
      goals_model#set ~row:parent ~column:index_column (Row_file mfile);
      goals_model#set ~row:parent ~column:visible_column true;
      mfile

  let add_file f =
    let theories = read_file f in
    let dbfile = Db.add_file f in
    let mfile = add_file_row f dbfile in
    let mths =
      List.fold_left
        (fun acc (_,thname,t) ->
           eprintf "Adding theory '%s'@." thname;
           let mth = add_theory mfile t in
           mth :: acc
        )
        [] theories
    in
    mfile.theories <- List.rev mths;
    if theories = [] then set_file_verified mfile

end

(*********************************)
(*  read previous data from db   *)
(*********************************)

(*
type trans =
  | Trans_one of Task.task Trans.trans
  | Trans_list of Task.task Trans.tlist

let lookup_trans name =
  try
    let t = Trans.lookup_transform name gconfig.env in
    Trans_one t
  with Trans.UnknownTrans _ ->
    let t = Trans.lookup_transform_l name gconfig.env in
    Trans_list t

let split_transformation = lookup_trans "split_goal"
let unfold_transformation = lookup_trans "inline_goal"
let intro_transformation = lookup_trans "introduce_premises"

let apply_trans t task =
  match t with
    | Trans_one t -> [Trans.apply t task]
    | Trans_list t -> Trans.apply t task
*)

let split_transformation = Trans.lookup_transform_l "split_goal" gconfig.env
let inline_transformation = Trans.lookup_transform "inline_goal" gconfig.env
let intro_transformation = Trans.lookup_transform "introduce_premises" gconfig.env

let rec reimport_any_goal parent gname t db_goal goal_obsolete =
  let goal = Helpers.add_goal_row parent gname t db_goal in
  let proved = ref false in
  let external_proofs = Db.external_proofs db_goal in
  Db.Hprover.iter
    (fun pid a ->
       let pname = Db.prover_name pid in
       try
         let p = Util.Mstr.find pname gconfig.provers in
         let s,t,o,edit = Db.status_and_time a in
         if goal_obsolete && not o then Db.set_obsolete a;
         let obsolete = goal_obsolete or o in
         let s = match s with
           | Db.Undone -> Call_provers.HighFailure
           | Db.Success ->
               if not obsolete then proved := true;
               Call_provers.Valid
           | Db.Unknown -> Call_provers.Unknown ""
           | Db.Timeout -> Call_provers.Timeout
           | Db.Failure -> Call_provers.Failure ""
         in
	 let r = { Call_provers.pr_answer = s;
		   Call_provers.pr_output = "";
		   Call_provers.pr_time = t;
		 }
	 in
         let (_pa : Model.proof_attempt) =
           Helpers.add_external_proof_row ~obsolete ~edit goal p a 
	     (Scheduler.Done r) 
         in
         ((* something TODO ?*))
       with Not_found ->
         eprintf
           "Warning: prover %s appears in database but is not installed.@."
           pname
    )
    external_proofs;
  let transformations = Db.transformations db_goal in
  Db.Htransf.iter
    (fun tr_id tr ->
       let trname = Db.transf_name tr_id in
       eprintf "Reimporting transformation %s for goal %s @." trname gname;
       let subgoals = Trans.apply split_transformation t in
       let mtr = Helpers.add_transformation_row goal tr trname in
       let db_subgoals = Db.subgoals tr in
       let reimported_goals,db_subgoals,_ =
         List.fold_left
           (fun (acc,db_subgoals,count) subtask ->
              let _id = (Task.task_goal subtask).Decl.pr_name in
              let subgoal_name = gname ^ "." ^ (string_of_int count) in
              let sum = task_checksum subtask in
              let subtask_db,db_subgoals =
                try
		  let g = Util.Mstr.find sum db_subgoals in
		  (* a subgoal has the same check sum *)
		  (Some g, Util.Mstr.remove sum db_subgoals)
                with Not_found -> None,db_subgoals
              in
              ((count,subgoal_name,subtask,sum,subtask_db) :: acc,
	       db_subgoals,
	       count+1))
           ([],db_subgoals,1) subgoals
       in
       let other_goals =
	 Util.Mstr.fold
	   (fun _ g acc -> (Db.goal_name g,g)::acc)
	   db_subgoals
	   []
       in
       let other_goals =
	 List.sort (fun (s1,_) (s2,_) -> String.compare s1 s2) other_goals
       in
       let rec merge_goals new_goals old_goals proved acc =
	 match new_goals with
	   | [] -> acc, proved
	   | (_,subgoal_name,subtask,sum,g_opt)::rem ->
	       let db_g,subgoal_obsolete,old_goals =
		 match g_opt with
		   | Some g -> g,false,old_goals
		   | None ->
		       match old_goals with
			 | [] ->
			     (* create a new goal in db *)
			     Db.add_subgoal tr subgoal_name sum,
			     false, old_goals
			 | (_goal_name,g) :: r ->
			     g, true, r
	       in
               let subgoal,subgoal_proved =
                 reimport_any_goal
                   (Model.Transf mtr) subgoal_name subtask db_g
                   subgoal_obsolete
              in
              merge_goals rem old_goals (proved && subgoal_proved)
		(subgoal :: acc)
       in
       let goals, subgoals_proved =
	 merge_goals (List.rev reimported_goals) other_goals true []
       in
(*
       let goals,_,subgoals_proved =
         List.fold_left
           (fun (acc,count,proved) subtask ->
              let _id = (Task.task_goal subtask).Decl.pr_name in
              let subgoal_name = gname ^ "." ^ (string_of_int count) in
              let sum = task_checksum subtask in
              let subtask_db =
                try Util.Mstr.find sum db_subgoals
		  (* a subgoal has the same check sum *)
                with Not_found ->
		  (* otherwise, create a new one *)
                  Db.add_subgoal tr subgoal_name sum
              in
              let subgoal,subgoal_proved =
                reimport_any_goal
                  (Model.Transf mtr) subgoal_name subtask subtask_db
                  false (* subgoal_obsolete *)
              in
              (subgoal :: acc, count+1,proved && subgoal_proved))
           ([],1,true) subgoals
       in
*)
       mtr.Model.subgoals <- List.rev goals;
       if subgoals_proved (* TODO : && not obsolete *)
       then proved := true
    )
    transformations;
  if !proved then Helpers.set_proved ~propagate:false goal;
  goal,!proved


let reimport_root_goal mth tname goals t : Model.goal * bool =
  (* re-imports DB informations of a goal in theory mth (named tname)
     goals is a table, indexed by names of DB goals formerly known to be
     a in theory mth.  returns true whenever the task t is known to be
     proved *)
  let gname =
    (Task.task_goal t).Decl.pr_name.Ident.id_string
  in
  let sum = task_checksum t in
  let db_goal,goal_obsolete =
    try
      let dbg = Util.Mstr.find gname goals in
      let db_sum = Db.task_checksum dbg in
      let goal_obsolete = sum <> db_sum in
      if goal_obsolete then
        begin
          eprintf "Goal %s.%s has changed@." tname gname;
          Db.change_checksum dbg sum
        end;
      dbg,goal_obsolete
    with Not_found ->
      let dbg = Db.add_goal mth.Model.theory_db gname sum in
      dbg,false
  in
  reimport_any_goal (Model.Theory mth) gname t db_goal goal_obsolete

(* reimports all files *)
let files_in_db = Db.files ()

let () =
  List.iter
    (fun (f,fn) ->
       eprintf "Reimporting file '%s'@." fn;
       let mfile = Helpers.add_file_row fn f in
       try
	 let theories = read_file fn in
	 let ths = Db.theories f in
	 let (mths,file_proved) =
	   List.fold_left
             (fun (acc,file_proved) (_,tname,th) ->
		eprintf "Reimporting theory '%s'@."tname;
		let db_th =
		  try
                    Util.Mstr.find tname ths
		  with Not_found -> Db.add_theory f tname
		in
		let mth = Helpers.add_theory_row mfile th db_th in
		let goals = Db.goals db_th in
		let tasks = List.rev (Task.split_theory th None None) in
		let goals,proved = List.fold_left
		  (fun (acc,proved) t ->
                     let (g,p) = reimport_root_goal mth tname goals t in
                     (g::acc,proved && p))
		  ([],true) tasks
		in
		mth.Model.goals <- List.rev goals;
		(* TODO: what to do with remaining tasks in Db ???
		   for the moment they remain in the db, but they are not shown
		*)
		if proved then Helpers.set_theory_proved ~propagate:false mth;
		(mth::acc,file_proved && proved))
             ([],true) theories
	 in
	 (* TODO: detecter d'eventuelles vieilles theories, qui seraient donc
            dans [ths] mais pas dans [theories]
	 *)
	 mfile.Model.theories <- List.rev mths;
	 if file_proved then Helpers.set_file_verified mfile
      with e ->
	eprintf "@[Error while reading file@ '%s':@ %a@.@]" fn
          Exn_printer.exn_printer e;
	exit 1
    )
    files_in_db

(**********************************)
(* add new file from command line *)
(**********************************)

let () =
  match file_to_read with
    | None -> ()
    | Some fn ->
        if List.exists (fun (_,f) -> f = fn) files_in_db then
          eprintf "Info: file %s already in database@." fn
        else
          try
            Helpers.add_file fn
          with e ->
	    eprintf "@[Error while reading file@ '%s':@ %a@.@]" fn
              Exn_printer.exn_printer e;
	    exit 1


(**********************)
(* set up scheduler   *)
(**********************)

let () =
  begin
    Scheduler.async := GtkThread.async;
    Scheduler.maximum_running_proofs := gconfig.max_running_processes
  end

(*****************************************************)
(* method: run a given prover on each unproved goals *)
(*****************************************************)

(*
let callback_of_callback callback = function
  | Scheduler.Scheduled -> callback Model.Scheduled 0. ""
  | Scheduler.Running   -> callback Model.Running 0. ""
  | Scheduler.InternalFailure _ ->
    callback Model.HighFailure 0. "Prover call failed"
  | Scheduler.Done r ->
    let res = match r.Call_provers.pr_answer with
      | Call_provers.Valid -> Model.Success
      | Call_provers.Timeout -> Model.Timeout
      | Call_provers.Unknown _ | Call_provers.Invalid -> Model.Unknown
      | Call_provers.Failure _ | Call_provers.HighFailure ->
        Model.HighFailure in
    callback res r.Call_provers.pr_time r.Call_provers.pr_output
*)

(* q is a queue of proof attempt where to put the new one *)
let redo_external_proof q g a =
  let p = a.Model.prover in
  let callback result (* time output *) =
(* useless: done by set_proof_status
    a.Model.proof_state <- result;
*)
    Helpers.set_proof_state ~obsolete:false a result (*time*) ;
    let db_res, time = 
      match result with
	| Scheduler.Scheduled | Scheduler.Running -> Db.Undone, 0.0
	| Scheduler.InternalFailure _ -> Db.Failure, 0.0
	| Scheduler.Done r ->
	    let res = 
	      match r.Call_provers.pr_answer with
		| Call_provers.Valid -> 
		    Helpers.set_proved ~propagate:true a.Model.proof_goal;
		    Db.Success
		| Call_provers.Unknown _ -> Db.Unknown
		| Call_provers.Invalid -> Db.Invalid
		| Call_provers.Timeout -> Db.Timeout
		| Call_provers.Failure _ -> Db.Failure
		| Call_provers.HighFailure -> Db.Failure
	    in res, r.Call_provers.pr_time
    in
    Db.set_status a.Model.proof_db db_res time
  in
  let old = if a.Model.edited_as = "" then None else
    begin
      eprintf "Info: proving using edited file %s@." a.Model.edited_as;
      (Some (open_in a.Model.edited_as))
    end
  in
  Scheduler.schedule_some_proof_attempts
    ~debug:(gconfig.verbose > 0) ~timelimit:gconfig.time_limit ~memlimit:0
    ?old ~command:p.command ~driver:p.driver
    ~callback
    g.Model.task q

let rec prover_on_goal q p g =
  let id = p.prover_id in
  let a =
    try Hashtbl.find g.Model.external_proofs id
    with Not_found ->
      GtkThread.sync (fun () ->
      let db_prover = Db.prover_from_name id in
      let db_pa = Db.add_proof_attempt g.Model.goal_db db_prover in
      Helpers.add_external_proof_row ~obsolete:false ~edit:""
	g p db_pa Scheduler.Scheduled) ()
  in
  redo_external_proof q g a;
  Hashtbl.iter
    (fun _ t -> List.iter (prover_on_goal q p) t.Model.subgoals)
    g.Model.transformations

let rec prover_on_goal_or_children q p g =
  if not (g.Model.proved && !context_unproved_goals_only) then
    begin
      let r = ref true in
      Hashtbl.iter
	(fun _ t ->
	   r := false;
           List.iter (prover_on_goal_or_children q p)
             t.Model.subgoals) g.Model.transformations;
      if !r then prover_on_goal q p g
    end

let prover_on_selected_goal_or_children q pr row =
  let row = filter_model#get_iter row in
  match filter_model#get ~row ~column:Model.index_column with
    | Model.Row_goal g ->
        prover_on_goal_or_children q pr g
    | Model.Row_theory th ->
        List.iter (prover_on_goal_or_children q pr) th.Model.goals
    | Model.Row_file file ->
        List.iter
          (fun th ->
             List.iter (prover_on_goal_or_children q pr) th.Model.goals)
          file.Model.theories
    | Model.Row_proof_attempt a ->
        prover_on_goal_or_children q pr a.Model.proof_goal
    | Model.Row_transformation tr ->
        List.iter (prover_on_goal_or_children q pr) tr.Model.subgoals

let prover_on_selected_goals pr =
  ignore (Thread.create (fun pr ->
    let q = Queue.create () in
    List.iter
      (prover_on_selected_goal_or_children q pr)
      goals_view#selection#get_selected_rows;
    Scheduler.transfer_proof_attempts q ) pr)




(*****************************************************)
(* method: split selected goals *)
(*****************************************************)

let split_goal g =
  if not g.Model.proved then
    let callback subgoals =
      ignore (Thread.create (fun subgoals ->
      if List.length subgoals >= 2 then
        let transf_id_split =
          (GtkThread.sync Db.transf_from_name) "split_goal" in
        let db_transf =
          (GtkThread.sync Db.add_transformation)
            g.Model.goal_db transf_id_split
        in
        let tr = (GtkThread.sync Helpers.add_transformation_row) 
	  g db_transf "split_goal" 
	in
        let goal_name = g.Model.goal_name in
        let fold = (fun (acc,count) subtask ->
             let _id = (Task.task_goal subtask).Decl.pr_name in
             let subgoal_name =
               goal_name ^ "." ^ (string_of_int count)
             in
             let sum = task_checksum subtask in
             let subtask_db = Db.add_subgoal db_transf subgoal_name sum in
             let goal =
               Helpers.add_goal_row (Model.Transf tr) subgoal_name subtask
                 subtask_db
             in
             (goal :: acc, count+1)) in
        let goals,_ = List.fold_left (GtkThread.sync fold) ([],1) subgoals
        in
        tr.Model.subgoals <- List.rev goals;
        Hashtbl.add g.Model.transformations "split" tr) subgoals)
    in
    Scheduler.apply_transformation_l ~callback
      split_transformation g.Model.task

let inline_goal g =
  if not g.Model.proved then
    let callback subgoal =
      ignore (Thread.create (fun subgoal ->
	(* if List.length subgoals >= 2 then *)
        let transf_id_inline =
          (GtkThread.sync Db.transf_from_name) "inline_goal" in
        let db_transf =
          (GtkThread.sync Db.add_transformation)
            g.Model.goal_db transf_id_inline
        in
        let tr = (GtkThread.sync Helpers.add_transformation_row) 
	  g db_transf "inline_goal"
	in
        let goal_name = g.Model.goal_name in
        let fold = (fun (acc,count) subtask ->
             let _id = (Task.task_goal subtask).Decl.pr_name in
             let subgoal_name =
               goal_name ^ "." ^ (string_of_int count)
             in
             let sum = task_checksum subtask in
             let subtask_db = Db.add_subgoal db_transf subgoal_name sum in
             let goal =
               Helpers.add_goal_row (Model.Transf tr) subgoal_name subtask
                 subtask_db
             in
             (goal :: acc, count+1)) in
        let goals,_ = List.fold_left (GtkThread.sync fold) ([],1) [subgoal]
        in
        tr.Model.subgoals <- List.rev goals;
        Hashtbl.add g.Model.transformations "inline" tr) subgoal)
    in
    Scheduler.apply_transformation ~callback
      inline_transformation g.Model.task

let rec split_goal_or_children g =
  if not g.Model.proved then
    begin
      let r = ref true in
      Hashtbl.iter 
	(fun _ t ->
	   r := false;
           List.iter split_goal_or_children
             t.Model.subgoals) g.Model.transformations;
      if !r then split_goal g
    end

let rec inline_goal_or_children g =
  if not g.Model.proved then
    begin
      let r = ref true in
      Hashtbl.iter 
	(fun _ t ->
	   r := false;
           List.iter inline_goal_or_children
             t.Model.subgoals) g.Model.transformations;
      if !r then inline_goal g
    end

let split_selected_goal_or_children row =
  let row = filter_model#get_iter row in
  match filter_model#get ~row ~column:Model.index_column with
    | Model.Row_goal g ->
        split_goal_or_children g
    | Model.Row_theory th ->
        List.iter split_goal_or_children th.Model.goals
    | Model.Row_file file ->
        List.iter
          (fun th ->
             List.iter split_goal_or_children th.Model.goals)
          file.Model.theories
    | Model.Row_proof_attempt a ->
        split_goal_or_children a.Model.proof_goal
    | Model.Row_transformation tr ->
        List.iter split_goal_or_children tr.Model.subgoals


let inline_selected_goal_or_children row =
  let row = filter_model#get_iter row in
  match filter_model#get ~row ~column:Model.index_column with
    | Model.Row_goal g ->
        inline_goal_or_children g
    | Model.Row_theory th ->
        List.iter inline_goal_or_children th.Model.goals
    | Model.Row_file file ->
        List.iter
          (fun th ->
             List.iter inline_goal_or_children th.Model.goals)
          file.Model.theories
    | Model.Row_proof_attempt a ->
        inline_goal_or_children a.Model.proof_goal
    | Model.Row_transformation tr ->
        List.iter inline_goal_or_children tr.Model.subgoals

let split_selected_goals () =
  ignore (Thread.create (fun () ->
    List.iter
      split_selected_goal_or_children
      goals_view#selection#get_selected_rows) ())


let inline_selected_goals () =
  ignore (Thread.create (fun () ->
    List.iter
      inline_selected_goal_or_children
      goals_view#selection#get_selected_rows) ())


(*********************************)
(* add a new file in the project *)
(*********************************)

let filter_all_files () =
  let f = GFile.filter ~name:"All" () in
  f#add_pattern "*" ;
  f

let filter_why_files () =
  GFile.filter
    ~name:"Why3 source files"
    ~patterns:[ "*.why"; "*.mlw"] ()

let select_file () =
  let d = GWindow.file_chooser_dialog ~action:`OPEN
    ~title:"Why3: Add file in project"
    ()
  in
  d#add_button_stock `CANCEL `CANCEL ;
  d#add_select_button_stock `OPEN `OPEN ;
  d#add_filter (filter_why_files ()) ;
  d#add_filter (filter_all_files ()) ;
  begin match d#run () with
  | `OPEN ->
      begin
        match d#filename with
          | None -> ()
          | Some f ->
	      let f = Sysutil.relativize_filename project_dir f in
              eprintf "Adding file '%s'@." f;
              try
                Helpers.add_file f
              with e ->
	        fprintf str_formatter
                  "@[Error while reading file@ '%s':@ %a@]" f
                  Exn_printer.exn_printer e;
	        let msg = flush_str_formatter () in
	        info_window `ERROR msg
      end
  | `DELETE_EVENT | `CANCEL -> ()
  end ;
  d#destroy ()


let not_implemented () =
  info_window `INFO "This feature is not yet implemented, sorry."

(*************)
(* File menu *)
(*************)

let file_menu = factory#add_submenu "_File"
let file_factory = new GMenu.factory file_menu ~accel_group

let (_ : GMenu.image_menu_item) =
  file_factory#add_image_item ~key:GdkKeysyms._A
    ~label:"_Add file" ~callback:select_file
    ()

let (_ : GMenu.image_menu_item) =
  file_factory#add_image_item ~label:"_Preferences" ~callback:
    (fun () ->
       Gconfig.preferences gconfig;
       Scheduler.maximum_running_proofs := gconfig.max_running_processes)
    ()

let refresh_provers = ref (fun () -> ())

let add_refresh_provers f =
  let rp = !refresh_provers in
  refresh_provers := (fun () -> rp (); f ())

let (_ : GMenu.image_menu_item) =
  file_factory#add_image_item ~label:"_Detect provers" ~callback:
    (fun () -> Gconfig.run_auto_detection gconfig; !refresh_provers () )
    ()

let (_ : GMenu.image_menu_item) =
  file_factory#add_image_item ~key:GdkKeysyms._Q ~label:"_Quit"
    ~callback:exit_function ()

(*************)
(* View menu *)
(*************)

let view_menu = factory#add_submenu "_View"
let view_factory = new GMenu.factory view_menu ~accel_group
let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._E
    ~label:"Expand all" ~callback:(fun () -> goals_view#expand_all ()) ()



let rec collapse_proved_goal g =
  if g.Model.proved then
    begin
      let row = g.Model.goal_row in
      goals_view#collapse_row (goals_model#get_path row);
    end
  else
    Hashtbl.iter
      (fun _ t -> List.iter collapse_proved_goal t.Model.subgoals)
      g.Model.transformations

let collapse_verified_theory th =
  if th.Model.verified then
    begin
      let row = th.Model.theory_row in
      goals_view#collapse_row (goals_model#get_path row);
    end
  else
    List.iter collapse_proved_goal th.Model.goals

let collapse_verified_file f =
  if f.Model.file_verified then
    begin
      let row = f.Model.file_row in
      goals_view#collapse_row (goals_model#get_path row);
    end
  else
    List.iter collapse_verified_theory f.Model.theories

let collapse_all_verified_things () =
  List.iter collapse_verified_file !Model.all_files

let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._C
    ~label:"Collapse proved goals"
    ~callback:collapse_all_verified_things
    ()

let rec hide_proved_in_goal g =
  if g.Model.proved then
    begin
      let row = g.Model.goal_row in
      goals_view#collapse_row (goals_model#get_path row);
      goals_model#set ~row ~column:Model.visible_column false
    end
  else
    Hashtbl.iter
      (fun _ t -> List.iter hide_proved_in_goal t.Model.subgoals)
      g.Model.transformations

let hide_proved_in_theory th =
  if th.Model.verified then
    begin
      let row = th.Model.theory_row in
      goals_view#collapse_row (goals_model#get_path row);
      goals_model#set ~row ~column:Model.visible_column false
    end
  else
    List.iter hide_proved_in_goal th.Model.goals

let hide_proved_in_file f =
  if f.Model.file_verified then
    begin
      let row = f.Model.file_row in
      goals_view#collapse_row (goals_model#get_path row);
      goals_model#set ~row ~column:Model.visible_column false
    end
  else
    List.iter hide_proved_in_theory f.Model.theories

let hide_proved_in_files () =
  List.iter hide_proved_in_file !Model.all_files

let rec show_all_in_goal g =
  let row = g.Model.goal_row in
  goals_model#set ~row ~column:Model.visible_column true;
  if g.Model.proved then
    goals_view#collapse_row (goals_model#get_path row)
  else
    goals_view#expand_row (goals_model#get_path row);
  Hashtbl.iter
    (fun _ t -> List.iter show_all_in_goal t.Model.subgoals)
    g.Model.transformations

let show_all_in_theory th =
  let row = th.Model.theory_row in
  goals_model#set ~row ~column:Model.visible_column true;
  if th.Model.verified then
    goals_view#collapse_row (goals_model#get_path row)
  else
    begin
      goals_view#expand_row (goals_model#get_path row);
      List.iter show_all_in_goal th.Model.goals
    end

let show_all_in_file f =
  let row = f.Model.file_row in
  goals_model#set ~row ~column:Model.visible_column true;
  if f.Model.file_verified then
    goals_view#collapse_row (goals_model#get_path row)
  else
    begin
      goals_view#expand_row (goals_model#get_path row);
      List.iter show_all_in_theory f.Model.theories
    end

let show_all_in_files () =
  List.iter show_all_in_file !Model.all_files


let (_ : GMenu.check_menu_item) = view_factory#add_check_item
  ~callback:(fun b ->
               Model.toggle_hide_proved_goals := b;
               if b then hide_proved_in_files ()
               else show_all_in_files ())
  "Hide proved goals"


(**************)
(* Tools menu *)
(**************)


let () = add_refresh_provers (fun () ->
  List.iter (fun item -> item#destroy ()) provers_box#all_children)

let tools_menu = factory#add_submenu "_Tools"
let tools_factory = new GMenu.factory tools_menu ~accel_group

let () = add_refresh_provers (fun () ->
  List.iter (fun item -> item#destroy ()) tools_menu#all_children)

let () =
  let add_item_provers () =
    Util.Mstr.iter
      (fun _ p ->
         let n = p.prover_name ^ " " ^ p.prover_version in
         let (_ : GMenu.image_menu_item) =
           tools_factory#add_image_item ~label:n
             ~callback:(fun () -> prover_on_selected_goals p)
             ()
         in
         let b = GButton.button ~packing:provers_box#add ~label:n () in
(* prend de la place pour rien
         let i = GMisc.image ~pixbuf:(!image_prover) () in
         let () = b#set_image i#coerce in
*)
         let (_ : GtkSignal.id) =
           b#connect#pressed
             ~callback:(fun () -> prover_on_selected_goals p)
         in ())
      gconfig.provers
  in
  add_refresh_provers add_item_provers;
  add_item_provers ()

let () =
  let add_item_split () =
    ignore(tools_factory#add_image_item
             ~label:"Split selection"
             ~callback:split_selected_goals
             () : GMenu.image_menu_item) in
  add_refresh_provers add_item_split;
  add_item_split ()


let () =
  let b = GButton.button ~packing:transf_box#add ~label:"Split" () in
  let i = GMisc.image ~pixbuf:(!image_transf) () in
  let () = b#set_image i#coerce in
  let (_ : GtkSignal.id) =
    b#connect#pressed ~callback:split_selected_goals
  in ()

let () =
  let b = GButton.button ~packing:transf_box#add ~label:"Inline" () in
(**)
  let i = GMisc.image ~pixbuf:(!image_transf) () in
  let () = b#set_image i#coerce in
(**)
  let (_ : GtkSignal.id) =
    b#connect#pressed ~callback:inline_selected_goals
  in ()



(*************)
(* Help menu *)
(*************)


let help_menu = factory#add_submenu "_Help"
let help_factory = new GMenu.factory help_menu ~accel_group

let (_ : GMenu.image_menu_item) =
  help_factory#add_image_item
    ~label:"Legend"
    ~callback:show_legend_window
    ()

let (_ : GMenu.image_menu_item) =
  help_factory#add_image_item
    ~label:"About"
    ~callback:show_about_window
    ()


(******************************)
(* vertical paned on the right*)
(******************************)

let vp =
  try
    GPack.paned `VERTICAL ~packing:hp#add ()
  with Gtk.Error _ -> assert false

(******************)
(* goal text view *)
(******************)

let scrolled_task_view = GBin.scrolled_window
  ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
  ~packing:vp#add ()

let () = scrolled_task_view#set_shadow_type `ETCHED_OUT

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

let task_view =
  GSourceView2.source_view
    ~editable:false
    ~show_line_numbers:true
    ~packing:scrolled_task_view#add
    ~height:gconfig.task_height
    ()

let () = task_view#source_buffer#set_language lang
let () = task_view#set_highlight_current_line true

(***************)
(* source view *)
(***************)

let scrolled_source_view = GBin.scrolled_window
  ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
  ~packing:vp#add
  ()

let () = scrolled_source_view#set_shadow_type `ETCHED_OUT

let source_view =
  GSourceView2.source_view
    ~auto_indent:true
    ~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 *)
    ~packing:scrolled_source_view#add
    ()

let current_file = ref ""

(*
  source_view#misc#modify_font_by_name font_name;
*)
let () = source_view#source_buffer#set_language lang
let () = source_view#set_highlight_current_line true
(*
let () = source_view#source_buffer#set_text (source_text fname)
*)

let move_to_line (v : GSourceView2.source_view) line =
  if line <= v#buffer#line_count && line <> 0 then begin
    let it = v#buffer#get_iter (`LINE line) in
    let mark = `MARK (v#buffer#create_mark it) in
    v#scroll_to_mark ~use_align:true ~yalign:0.0 mark
  end

let orange_bg = source_view#buffer#create_tag
  ~name:"orange_bg" [`BACKGROUND "orange"]

let erase_color_loc (v:GSourceView2.source_view) =
  let buf = v#buffer in
  buf#remove_tag orange_bg ~start:buf#start_iter ~stop:buf#end_iter

let color_loc (v:GSourceView2.source_view) l b e =
  let buf = v#buffer in
  let top = buf#start_iter in
  let start = top#forward_lines (l-1) in
  let start = start#forward_chars b in
  let stop = start#forward_chars (e-b) in
  buf#apply_tag ~start ~stop orange_bg

let scroll_to_id id =
  match id.Ident.id_origin with
    | Ident.User loc ->
        let (f,l,b,e) = Loc.extract loc in
        if f <> !current_file then
          begin
            source_view#source_buffer#set_text (source_text f);
            current_file := f;
          end;
        move_to_line source_view (l-1);
        erase_color_loc source_view;
        color_loc source_view l b e
    | Ident.Fresh ->
        source_view#source_buffer#set_text
          "Fresh ident (no position available)\n";
        current_file := ""
    | Ident.Derived _ ->
        source_view#source_buffer#set_text
          "Derived ident (no position available)\n";
        current_file := ""

let color_label = function
  | _, Some loc when (fst loc).Lexing.pos_fname = !current_file ->
      let _, l, b, e = Loc.extract loc in
      color_loc source_view l b e
  | _ ->
      ()

let rec color_f_labels () f =
  List.iter color_label f.Term.f_label;
  Term.f_fold color_t_labels color_f_labels () f

and color_t_labels () t =
  List.iter color_label t.Term.t_label;
  Term.t_fold color_t_labels color_f_labels () t

let scroll_to_source_goal g =
  let t = g.Model.task in
  let id = (Task.task_goal t).Decl.pr_name in
  scroll_to_id id;
  match t with
    | Some
        { Task.task_decl =
            { Theory.td_node =
                Theory.Decl { Decl.d_node = Decl.Dprop (Decl.Pgoal, _, f)}}} ->
        color_f_labels () f
    | _ ->
        assert false

let scroll_to_theory th =
  let t = th.Model.theory in
  let id = t.Theory.th_name in
  scroll_to_id id

(* to be run when a row in the tree view is selected *)
let select_row p =
  let row = filter_model#get_iter p in
  match filter_model#get ~row ~column:Model.index_column with
    | Model.Row_goal g ->
        let t = g.Model.task in
        let t = Trans.apply intro_transformation t in
        let task_text = Pp.string_of Pretty.print_task t in
        task_view#source_buffer#set_text task_text;
        task_view#scroll_to_mark `INSERT;
        scroll_to_source_goal g
    | Model.Row_theory th ->
        task_view#source_buffer#set_text "";
        scroll_to_theory th
    | Model.Row_file _file ->
        task_view#source_buffer#set_text "";
        (* scroll_to_file file *)
    | Model.Row_proof_attempt a ->
	let o =
          match a.Model.proof_state with
	    | Scheduler.Done r -> r.Call_provers.pr_output;
	    | _ -> "No information available"
	in
	task_view#source_buffer#set_text o;
        scroll_to_source_goal a.Model.proof_goal
    | Model.Row_transformation tr ->
        task_view#source_buffer#set_text "";
        scroll_to_source_goal tr.Model.parent_goal




(*****************************)
(* method: edit current goal *)
(*****************************)


let ft_of_th th =
  (Filename.basename th.Model.theory_parent.Model.file_name,
   th.Model.theory.Theory.th_name.Ident.id_string)

let rec ft_of_goal g =
  match g.Model.parent with
    | Model.Transf tr -> ft_of_goal tr.Model.parent_goal
    | Model.Theory th -> ft_of_th th

let ft_of_pa a =
  ft_of_goal a.Model.proof_goal

let edit_selected_row p =
  let row = filter_model#get_iter p in
  match filter_model#get ~row ~column:Model.index_column with
    | Model.Row_goal _g ->
        ()
    | Model.Row_theory _th ->
        ()
    | Model.Row_file _file ->
        ()
    | Model.Row_proof_attempt a ->
        let g = a.Model.proof_goal in
	let t = g.Model.task in
	let driver = a.Model.prover.driver in
	let file =
          match a.Model.edited_as with
            | "" ->
		let (fn,tn) = ft_of_pa a in
		let file = Driver.file_of_task driver
                  (Filename.concat project_dir fn) tn t
		in
		(* Uniquify the filename if it exists on disk *)
		let i =
                  try String.rindex file '.'
                  with _ -> String.length file
		in
		let name = String.sub file 0 i in
		let ext = String.sub file i (String.length file - i) in
		let i = ref 1 in
		while Sys.file_exists
		  (name ^ "_" ^ (string_of_int !i) ^ ext) do
		    incr i
		done;
		let file = name ^ "_" ^ (string_of_int !i) ^ ext in
		a.Model.edited_as <- file;
		Db.set_edited_as a.Model.proof_db file;
		file
	    | f -> f
	in
        let old_status = a.Model.proof_state in
        Helpers.set_proof_state ~obsolete:false a Scheduler.Running;
        let callback () =
          Helpers.set_proof_state ~obsolete:false a old_status;
        in
        let editor =
          match a.Model.prover.editor with
            | "" -> gconfig.default_editor
            | _ -> a.Model.prover.editor
        in
        Scheduler.edit_proof ~debug:false ~editor
          ~file
          ~driver
          ~callback
          t
    | Model.Row_transformation _tr ->
        ()

let edit_current_proof () =
  match goals_view#selection#get_selected_rows with
    | [] -> ()
    | [r] -> edit_selected_row r
    | _ ->
	info_window `INFO "Please select exactly one proof to edit"


let add_item_edit () =
  ignore (tools_factory#add_image_item
            ~label:"Edit current proof"
            ~callback:edit_current_proof
            () : GMenu.image_menu_item)

let () =
  add_refresh_provers add_item_edit;
  add_item_edit ()


let () =
  let b = GButton.button ~packing:tools_box#add ~label:"Edit" () in
  let i = GMisc.image ~pixbuf:(!image_editor) () in
  let () = b#set_image i#coerce in
  let (_ : GtkSignal.id) =
    b#connect#pressed ~callback:edit_current_proof
  in ()

let () =
  let b = GButton.button ~packing:tools_box#add ~label:"(Replay)" () in
(*
  let i = GMisc.image ~pixbuf:(!image_replay) () in
  let () = b#set_image i#coerce in
*)
  let (_ : GtkSignal.id) =
    b#connect#pressed ~callback:not_implemented
  in ()

(*************)
(* removing  *)
(*************)

let remove_proof_attempt a =
  Db.remove_proof_attempt a.Model.proof_db;
  let (_:bool) = goals_model#remove a.Model.proof_row in
  let g = a.Model.proof_goal in
  Hashtbl.remove g.Model.external_proofs a.Model.prover.prover_id;
  Helpers.check_goal_proved g

let remove_transf t =
  (* TODO: remove subgoals first !!! *)
  Db.remove_transformation t.Model.transf_db;
  let (_:bool) = goals_model#remove t.Model.transf_row in
  let g = t.Model.parent_goal in
  Hashtbl.remove g.Model.transformations "split" (* hack !! *);
  Helpers.check_goal_proved g
  

let confirm_remove_row r =
  let row = filter_model#get_iter r in
  match filter_model#get ~row ~column:Model.index_column with
    | Model.Row_goal _g ->
	info_window `ERROR "Cannot remove a goal"
    | Model.Row_theory _th ->
	info_window `ERROR "Cannot remove a theory"
    | Model.Row_file _file ->
	info_window `ERROR "Cannot remove a file"
    | Model.Row_proof_attempt a ->
	info_window
	  ~callback:(fun () -> remove_proof_attempt a)
	  `QUESTION
	  "Do you really want to remove the selected proof attempt?"
    | Model.Row_transformation tr ->
	info_window
	  ~callback:(fun () -> remove_transf tr)
	  `QUESTION
	  "Do you really want to remove the selected transformation and all its subgoals?"

let confirm_remove_selection () =
  match goals_view#selection#get_selected_rows with
    | [] -> ()
    | [r] -> confirm_remove_row r
    | _ ->
        info_window `INFO "Please select exactly one item to remove"

let () =
  let b = GButton.button ~packing:cleaning_box#add ~label:"Remove" () in
  let i = GMisc.image ~pixbuf:(!image_remove) () in
  let () = b#set_image i#coerce in
  let (_ : GtkSignal.id) =
    b#connect#pressed ~callback:confirm_remove_selection
  in ()


(***************)
(* Bind events *)
(***************)

(* row selection on tree view on the left *)
let (_ : GtkSignal.id) =
  goals_view#selection#connect#after#changed ~callback:
    begin fun () ->
      match goals_view#selection#get_selected_rows with
        | [p] -> select_row p
        | [] -> ()
        | _ -> ()
    end

let () = w#add_accel_group accel_group
let () = w#show ()
(*
let () = tools_window#show ()
*)
let () = GtkThread.main ()

(*
Local Variables:
compile-command: "unset LANG; make -C ../.. bin/why3ide.byte"
End:
*)