#!/usr/bin/env ruby # -*- ruby -*- # $Id$ require 'mkmf' require 'ftools' $recursive = false $force = false $conly = true $inc_path = [] $infilename= nil $insert_require = true def valid_ruby_code?(code) begin eval("BEGIN {return true}; #{code}") rescue SyntaxError return false end return false end def print_usage print <] [-d] [] EOF end while( ARGV[0] ) case( ARGV[0] ) when "-r" ARGV.shift $recursive = true when "-R" ARGV.shift $recursive = false when "-l" ARGV.shift $insert_require = true when "-L" ARGV.shift $insert_require = false when "-c" ARGV.shift $conly = true when "-C" ARGV.shift $conly = false when "-f" ARGV.shift $force = true when "-F" ARGV.shift $force = false when "-I" ARGV.shift $inc_path << ARGV.shift when "-d" ARGV.shift $DEBUG = true when "-h","--help" print_usage() exit 0 when /-.*/ $stderr.print("unknown option '#{ARGV[0]}'.\n") print_usage() exit 0 else $infilename = ARGV.shift end end $inc_dir = File.join(CONFIG["prefix"], "lib", "ruby", CONFIG["MAJOR"] + "." + CONFIG["MINOR"], "dl") class H2RBError < StandardError; end class H2RB def initialize(inc_dir = nil, inc_path = nil, insert_require = nil) @inc_path = inc_path || [] @inc_dir = inc_dir || '.' @indent = 0 @parsed_files = [] @insert_require = insert_require || false end def find_path(file) if( ! file ) return nil end if( File.exist?(file) ) if( file[0] == ?/ ) return file else return file end end @inc_path.each{|path| full = File.join(path, file) if( File.exist?(full) ) return full end } return nil end def strip_comment(line) if( @commented ) if( e = line.index("*/") ) line[0..(e+1)] = "" @commented = false else line = "" end else if( s = line.index("/*") ) if( e = line.index("*/") ) line[s..(e+1)] = "" else line[s..-1] = "" @commented = true end elsif( s = line.index("//") ) line[s..(-1)] = "" end end line.gsub!(/\s+$/,"") return line end def up_indent @indent += 1 end def down_indent @indent -= 1 if( @indent < 0 ) raise end end def indent " " * @indent end def rescue_begin line = "#{indent}begin" up_indent return line end def rescue_nameerror down_indent line = [ "#{indent}rescue NameError => e", "#{indent} raise e if( $DEBUG )", "#{indent}end"].join($/) return line end def parse_enum(line) if( line =~ /enum\s+(\S+\s+)?\{(.+)\}/ ) enum_name = $1 enum_block = $2 if( enum_name ) line = "#{indent}# -- enum #{enum_name}\n" else line = "#{indent}# -- enum\n" end enums = enum_block.split(/,/).collect{|e| e.strip} i = 0 enums.each{|elem| var,val = elem.split(/=/).collect{|e| e.strip} if( val ) i = val.to_i end line += "#{indent}#{var} = #{i.to_s}\n" i += 1 } line += "#{indent}# -- end of enum" return line else return nil end end def parse_define(line) case line when /^#\s*define\s+(\S+)\(\)/ line = nil when /^#\s*define\s+(\S+)\((.+)\)\s+(.+)$/ if( @conly ) line = nil else defname = $1 defargs = $2 defval = $3 if( !valid_ruby_code?(defval) ) defval = "nil # #{defval}" end if( defname[0,1] =~ /^[A-Z]$/ ) line = "#{indent}#{defname} = proc{|#{defargs}| #{defval}}" else line = [ "#{indent}def #{defname}(#{defargs})", "#{indent} #{defval}", "#{indent}end" ].join("\n") end end when /^#\s*define\s+(\S+)\((.+)\)$/ if( @conly ) line = nil else defname = $1 defargs = $2 defval = nil if( !valid_ruby_code?(defval) ) defval = "nil # #{defval}" end if( defname[0,1] =~ /^[A-Z]$/ ) line = "#{indent}#{defname} = proc{|#{defargs}| #{defval}}" else line = [ "#{indent}def #{defname}(#{defargs})", "#{indent} #{defval}", "#{indent}end" ].join("\n") end end when /^#\s*define\s+(\S+)\s+(.+)$/ defname = $1 defval = $2 if( !valid_ruby_code?(defval) ) defval = "nil # #{defval}" end line = [rescue_begin, "#{indent}#{defname} = #{defval}", rescue_nameerror].join($/) when /^#\s*define\s+(\S+)$/ defname = $1 line = "#{indent}#{defname} = nil" else line = nil end return line end def parse_undef(line) case line when /^#\s*undef\s+([A-Z]\S+)$/ defname = $1 line = "#{indent}remove_const(:#{defname})" when /^#\s*undef\s+(\S+)$/ defname = $1 line = "#{indent}#{defname} = nil" else line = nil end return line end def parse_ifdef(line) case line when /^#\s*ifdef\s+(\S+)$/ defname = $1 line = [ rescue_begin, "#{indent}if( defined?(#{defname}) && ! #{defname}.nil? )"].join($/) else line = nil end return line end def parse_ifndef(line) case line when /^#\s*ifndef\s+(\S+)$/ defname = $1 line = [ rescue_begin, "#{indent}if( ! defined?(#{defname}) || #{defname}.nil? )"].join($/) else line = nil end return line end def parse_if(line) case line when /^#\s*if\s+(.+)$/ cond = $1 cond.gsub!(/defined(.+)/){ "defined?(#{$1}) && ! #{$1}.nil?" } if( valid_ruby_code?(cond) ) line = "#{indent}if( #{cond} )" else line = "#{indent}if( false ) # #{cond}" end line = [rescue_begin, line].join($/) else line = nil end return line end def parse_elif(line) case line when /^#\s*elif\s+(.+)$/ cond = $1 cond.gsub!("defined","defined?") line = "#{indent}elsif( #{cond} )" else line = nil end return line end def parse_else(line) case line when /^#\s*else\s*/ line = "#{indent}else" else line = nil end return line end def parse_endif(line) case line when /^#\s*endif\s*$/ line = ["#{indent}end", rescue_nameerror].join($/) else line = nil end return line end def parse_include(line) if( ! @insert_require ) return nil end file = nil case line when /^#\s*include "(.+)"$/ file = $1 line = "#{indent}require '#{file}'" when /^#\s*include \<(.+)\>$/ file = $1 line = "#{indent}require '#{file}'" else line = nil end if( @recursive && file && (!@parsed_files.include?(file)) ) parse(file, @recursive, @force, @conly) end return line end def open_files(infilename) if( ! infilename ) return [$stdin, $stdout] end old_infilename = infilename infilename = find_path(infilename) if( ! infilename ) $stderr.print("'#{old_infilename}' was not found.\n") return [nil,nil] end if( infilename ) if( infilename[0,1] == '/' ) outfilename = File.join(@inc_dir, infilename[1..-1] + ".rb") else outfilename = infilename + ".rb" end File.mkpath(File.dirname(outfilename)) else outfilename = nil end if( infilename ) fin = File.open(infilename,"r") else fin = $stdin end if( outfilename ) if( File.exist?(outfilename) && (!@force) ) $stderr.print("'#{outfilename}' have already existed.\n") return [fin, nil] end fout = File.open(outfilename,"w") else fout = $stdout end $stderr.print("#{infilename} -> #{outfilename}\n") if( fout ) dir = File.dirname(outfilename) if( dir[0,1] != "." && dir != "" ) fout.print("if( ! $LOAD_PATH.include?('#{dir}') )\n", " $LOAD_PATH.push('#{dir}')\n", "end\n") end end return [fin,fout] end def parse(infilename = nil, recursive = false, force = false, conly = false) @commented = false @recursive = recursive @force = force @conly = conly @parsed_files << infilename fin,fout = open_files(infilename) if( !fin ) return end begin line_number = 0 pre_line = nil fin.each_line{|line| line_number += 1 line.chop! if( $DEBUG ) $stderr.print("#{line_number}:(#{@indent}):", line, "\n") end if( pre_line ) line = pre_line + line pre_line = nil end if( line[-1,1] == "\\" ) pre_line = line[0..-2] next end if( eidx = line.index("enum ") ) pre_line = line[eidx .. -1] if( i = line.index("{") && j = line.index("}") ) line = line[0..j] pre_line = nil else next end end line = strip_comment(line) case line when /^enum\s/ line = parse_enum(line) when /^#\s*define\s/ line = parse_define(line) when /^#\s*undef\s/ line = parse_undef(line) when /^#\s*ifdef\s/ line = parse_ifdef(line) up_indent when /^#\s*ifndef\s/ line = parse_ifndef(line) up_indent when /^#\s*if\s/ line = parse_if(line) up_indent when /^#\s*elif\s/ down_indent line = parse_elif(line) up_indent when /^#\s*else/ down_indent line = parse_else(line) up_indent when /^#\s*endif/ down_indent line = parse_endif(line) when /^#\s*include\s/ line = parse_include(line) else line = nil end if( line && fout ) fout.print(line, " # #{line_number}",$/) end } ensure fin.close if fin fout.close if fout end end end h2rb = H2RB.new($inc_dir, $inc_path, $insert_require) h2rb.parse($infilename, $recursive, $force, $conly) ' href='#n188'>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
/*  Authors:
 *    Endi Sukma Dewata <edewata@redhat.com>
 *
 * Copyright (C) 2010 Red Hat
 * see file 'COPYING' for use and warranty information
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 only
 *
 * This program 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/* REQUIRES: ipa.js */

function ipa_widget(spec) {

    spec = spec || {};

    var that = {};

    that.id = spec.id;
    that.name = spec.name;
    that.label = spec.label;
    that.read_only = spec.read_only;
    that._entity_name = spec.entity_name;

    that.width = spec.width;
    that.height = spec.height;

    that.undo = typeof spec.undo == 'undefined' ? true : spec.undo;

    that.init = spec.init || init;
    that.create = spec.create || create;
    that.setup = spec.setup || setup;
    that.load = spec.load || load;
    that.save = spec.save || save;
    that.update = spec.update || update;

    that.__defineGetter__("entity_name", function(){
        return that._entity_name;
    });

    that.__defineSetter__("entity_name", function(entity_name){
        that._entity_name = entity_name;
    });

    function init() {
        if (that.entity_name && !that.label){
            var param_info = ipa_get_param_info(that.entity_name, spec.name);
            if (param_info) that.label = param_info.label;
        }
    }

    function create(container) {
    }

    function setup(container) {
        that.container = container;
    }

    function load(record) {
        that.record = record;
        that.reset();
    }

    that.reset = function() {
        that.hide_undo();
        that.update();
    };

    function update() {
    }

    function save() {
        return [];
    }

    that.is_dirty = function() {

        var values = that.save();
        if (!values && !that.values) return false;
        if (!values || !that.values) return true;

        if (values.length != that.values.length) return true;
        for (var i=0; i<values.length; i++) {
            if (values[i] != that.values[i]) return true;
        }

        return false;
    };

    that.get_undo = function() {
        return $('span[name="undo"]', that.container);
    };

    that.show_undo = function() {
        var undo = that.get_undo();
        undo.css('display', 'inline');
    };

    that.hide_undo = function() {
        var undo = that.get_undo();
        undo.css('display', 'none');
    };

    that.refresh = function() {
    };

    // methods that should be invoked by subclasses
    that.widget_init = that.init;
    that.widget_create = that.create;
    that.widget_setup = that.setup;

    return that;
}

function ipa_text_widget(spec) {

    spec = spec || {};

    var that = ipa_widget(spec);

    that.size = spec.size || 30;

    that.create = function(container) {

        $('<input/>', {
            'type': 'text',
            'name': that.name,
            'size': that.size
        }).appendTo(container);

        if (that.undo) {
            $('<span/>', {
                'name': 'undo',
                'style': 'display: none;',
                'html': 'undo'
            }).appendTo(container);
        }
    };

    that.setup = function(container) {

        this.widget_setup(container);

        var input = $('input[name="'+that.name+'"]', that.container);
        input.keyup(function() {
            that.show_undo();
        });

        var undo = that.get_undo();
        undo.click(function() {
            that.reset();
        });
    };

    that.load = function(record) {

        that.values = record[that.name] || [''];

        if (that.read_only) {
            var input = $('input[name="'+that.name+'"]', that.container);
            var label = $('<label/>', {
                'name': that.name,
                'html': that.values[0]
            });
            input.replaceWith(label);

        } else {
            that.reset();
        }
    };

    that.save = function() {
        if (that.read_only) {
            return that.values;
        } else {
            var value = $('input[name="'+that.name+'"]', that.container).val();
            return [value];
        }
    };

    that.update = function() {
        var value = that.values && that.values.length ? that.values[0] : '';
        if (that.read_only) {
            $('label[name="'+that.name+'"]', that.container).val(value);
        } else {
            $('input[name="'+that.name+'"]', that.container).val(value);
        }
    };

    return that;
}

function ipa_checkbox_widget(spec) {

    spec = spec || {};

    var that = ipa_widget(spec);

    that.create = function(container) {

        $('<input/>', {
            'type': 'checkbox',
            'name': that.name
        }).appendTo(container);

        if (that.undo) {
            $('<span/>', {
                'name': 'undo',
                'style': 'display: none;',
                'html': 'undo'
            }).appendTo(container);
        }
    };

    that.setup = function(container) {

        that.widget_setup(container);

        var input = $('input[name="'+that.name+'"]', that.container);
        input.change(function() {
            that.show_undo();
        });

        var undo = that.get_undo();
        undo.click(function() {
            that.reset();
        });
    };

    that.load = function(record) {
        that.values = record[that.name] || [false];
        that.reset();
    };

    that.save = function() {
        var value = $('input[name="'+that.name+'"]', that.container).is(':checked');
        return [value];
    };

    that.update = function() {
        var value = that.values && that.values.length ? that.values[0] : false;
        $('input[name="'+that.name+'"]', that.container).get(0).checked = value;
    };

    return that;
}

function ipa_radio_widget(spec) {

    spec = spec || {};

    var that = ipa_widget(spec);

    that.options = spec.options;

    that.create = function(container) {

        for (var i=0; i<that.options.length; i++) {
            var option = that.options[i];

            $('<input/>', {
                'type': 'radio',
                'name': that.name,
                'value': option.value
            }).appendTo(container);

            container.append(option.label);
        }

        if (that.undo) {
            $('<span/>', {
                'name': 'undo',
                'style': 'display: none;',
                'html': 'undo'
            }).appendTo(container);
        }
    };

    that.setup = function(container) {

        that.widget_setup(container);

        var input = $('input[name="'+that.name+'"]', that.container);
        input.change(function() {
            that.show_undo();
        });

        var undo = that.get_undo();
        undo.click(function() {
            that.reset();
        });
    };

    that.load = function(record) {
        that.values = record[that.name] || [''];
        that.reset();
    };

    that.save = function() {
        var input = $('input[name="'+that.name+'"]:checked', that.container);
        if (!input.length) return [];
        return [input.val()];
    };

    that.update = function() {
        if (that.values && that.values.length) {
            var input = $('input[name="'+that.name+'"][value="'+that.values[0]+'"]', that.container);
            if (input.length) {
                input.get(0).checked = true;
                return;
            }
        }

        $('input[name="'+that.name+'"]', that.container).each(function() {
            var input = this;
            input.checked = false;
        });
    };

    // methods that should be invoked by subclasses
    that.radio_save = that.save;

    return that;
}

function ipa_textarea_widget(spec) {

    spec = spec || {};

    var that = ipa_widget(spec);

    that.rows = spec.rows || 5;
    that.cols = spec.cols || 40;

    that.create = function(container) {

        $('<textarea/>', {
            'rows': that.rows,
            'cols': that.cols,
            'name': that.name
        }).appendTo(container);

        if (that.undo) {
            $('<span/>', {
                'name': 'undo',
                'style': 'display: none;',
                'html': 'undo'
            }).appendTo(container);
        }
    };

    that.setup = function(container) {

        that.widget_setup(container);

        var input = $('textarea[name="'+that.name+'"]', that.container);
        input.keyup(function() {
            undo.css('display', 'inline');
        });

        var undo = that.get_undo();
        undo.click(function() {
            that.reset();
        });
    };

    that.load = function(record) {
        that.values = record[that.name] || [''];
        that.reset();
    };

    that.save = function() {
        var value = $('textarea[name="'+that.name+'"]', that.container).val();
        return [value];
    };

    that.update = function() {
        var value = that.values && that.values.length ? that.values[0] : '';
        $('textarea[name="'+that.name+'"]', that.container).val(value);
    };

    return that;
}

function ipa_button_widget(spec) {

    spec = spec || {};

    spec.setup = spec.setup || setup;
    spec.load = spec.load || load;
    spec.save = spec.save || save;

    var that = ipa_widget(spec);

    that.click = spec.click;

    function setup(container) {

        that.widget_setup(container);

        var input = $('[name="'+that.name+'"]', that.container);
        input.replaceWith(ipa_button({ 'label': that.label, 'click': that.click }));
    }

    function load(record) {
    }

    function save() {
        return [];
    }

    return that;
}


function ipa_column(spec) {

    spec = spec || {};

    var that = {};

    that.name = spec.name;
    that.label = spec.label;
    that.primary_key = spec.primary_key;
    that.width = spec.width;
    that.entity_name = spec.entity_name;

    that.setup = spec.setup || setup;

    that.init = function() {
        if (that.entity_name && !that.label) {
            var param_info = ipa_get_param_info(that.entity_name, that.name);
            if (param_info) that.label = param_info.label;
        }
    };

    function setup(container, record) {

        container.empty();

        var value = record[that.name];
        value = value ? value.toString() : '';

        container.append(value);
    }

    return that;
}

function ipa_table_widget(spec) {

    spec = spec || {};

    var that = ipa_widget(spec);

    that.scrollable = spec.scrollable;
    that.save_values = typeof spec.save_values == 'undefined' ? true : spec.save_values;

    that.columns = [];
    that.columns_by_name = {};

    that.get_columns = function() {
        return that.columns;
    };

    that.get_column = function(name) {
        return that.columns_by_name[name];
    };

    that.add_column = function(column) {
        that.columns.push(column);
        that.columns_by_name[column.name] = column;
    };

    that.set_columns = function(columns) {
        that.clear_columns();
        for (var i=0; i<columns.length; i++) {
            that.add_column(columns[i]);
        }
    };

    that.clear_columns = function() {
        that.columns = [];
        that.columns_by_name = {};
    };

    that.create_column = function(spec) {
        var column = ipa_column(spec);
        that.add_column(column);
        return column;
    };

    that.init = function() {
        that.widget_init();

        for (var i=0; i<that.columns.length; i++) {
            var column = that.columns[i];
            column.init();
        }
    };

    that.create = function(container) {

        var table = $('<table/>', {
            'class': 'search-table'
        }).appendTo(container);

        if (that.scrollable) {
            table.addClass('scrollable');
        }

        var thead = $('<thead/>').appendTo(table);

        var tr = $('<tr/>').appendTo(thead);

        var th = $('<th/>', {
            'style': 'width: 22px;'
        }).appendTo(tr);

        $('<input/>', {
            'type': 'checkbox',
            'name': 'select'
        }).appendTo(th);

        for (var i=0; i<that.columns.length; i++) {
            var column = that.columns[i];

            th = $('<th/>').appendTo(tr);

            if (that.scrollable && (i == that.columns.length-1)) {
                if (column.width) {
                    var width = parseInt(column.width.substring(0, column.width.length-2));
                    width += 16;
                    th.css('width', width+'px');
                }
            } else {
                if (column.width) {
                    th.css('width', column.width);
                }
            }

            var label = column.label;

            $('<span/>', {
                'style': 'float: left;',
                'html': label
            }).appendTo(th);

            if (i == that.columns.length-1) {
                $('<span/>', {
                    'name': 'buttons',
                    'style': 'float: right;'
                }).appendTo(th);
            }
        }

        var tbody = $('<tbody/>').appendTo(table);

        if (that.height) {
            tbody.css('height', that.height);
        }

        tr = $('<tr/>').appendTo(tbody);

        var td = $('<td/>', {
            'style': 'width: 22px;'
        }).appendTo(tr);

        $('<input/>', {
            'type': 'checkbox',
            'name': 'select',
            'value': 'user'
        }).appendTo(td);

        for (var i=0; i<that.columns.length; i++) {
            var column = that.columns[i];

            td = $('<td/>').appendTo(tr);
            if (column.width) {
                td.css('width', column.width);
            }

            $('<span/>', {
                'name': column.name
            }).appendTo(td);
        }

        var tfoot = $('<tfoot/>').appendTo(table);

        tr = $('<tr/>').appendTo(tfoot);

        td = $('<td/>', { colspan: that.columns.length+1 }).appendTo(tr);

        $('<span/>', {
            'name': 'summary'
        }).appendTo(td);
    };


    that.select_changed = function(){
    };


    that.setup = function(container) {

        that.widget_setup(container);

        that.table = $('table', that.container);
        that.thead = $('thead', that.table);
        that.tbody = $('tbody', that.table);
        that.tfoot = $('tfoot', that.table);

        var select_all_checkbox = $('input[name=select]', that.thead);
        select_all_checkbox.attr('title', 'Select All');

        select_all_checkbox.change(function() {
            var checked = select_all_checkbox.is(':checked');
            select_all_checkbox.attr('title', checked ? 'Unselect All' : 'Select All');
            var checkboxes = $('input[name=select]', that.tbody).get();
            for (var i=0; i<checkboxes.length; i++) {
                checkboxes[i].checked = checked;
            }
            that.select_changed();
            return false;
        });

        that.row = that.tbody.children().first();
        that.row.detach();
    };

    that.empty = function() {
        that.tbody.empty();
    };

    that.load = function(result) {

        that.empty();

        that.values = result[that.name];
        if (!that.values) return;

        for (var i=0; i<that.values.length; i++) {
            var record = that.get_record(result, i);
            that.add_record(record);
        }
    };

    that.save = function() {
        if (that.save_values) {
            var values = [];

            $('input[name="select"]', that.tbody).each(function() {
                values.push($(this).val());
            });

            return values;

        } else {
            return null;
        }
    };

    that.get_selected_values = function() {
        var values = [];

        $('input[name="select"]:checked', that.tbody).each(function() {
            values.push($(this).val());
        });

        return values;
    };

    that.get_record = function(result, index) {
        var record = {};
        for (var i=0; i<that.columns.length; i++){
            var name = that.columns[i].name;
            var values = result[name];
            if (!values) continue;
            record[name] = values[index];
        }
        return record;
    };

    that.add_record = function(record) {

        var tr = that.row.clone();
        tr.appendTo(that.tbody);

        for (var i=0; i<that.columns.length; i++){
            var column = that.columns[i];

            var value = record[column.name];
            value = value ? value.toString() : '';

            if (column.primary_key) {
                // set checkbox value
                $('input[name="select"]', tr).val(value);

                $('input[name="select"]', tr).click(function(){
                    that.select_changed();
                });

            }

            var span = $('span[name="'+column.name+'"]', tr);

            column.setup(span, record);
        }
    };

    that.add_rows = function(rows) {
        for (var i=0; i<rows.length; i++) {
            that.tbody.append(rows[i]);
        }
    };

    that.remove_selected_rows = function() {
        var rows = [];
        that.tbody.children().each(function() {
            var tr = $(this);
            if (!$('input[name="select"]', tr).get(0).checked) return;
            tr.detach();
            rows.push(tr);
        });
        return rows;
    };

    that.refresh = function() {

        function on_success(data, text_status, xhr) {
            that.load(data.result.result);
        }

        function on_error(xhr, text_status, error_thrown) {
            var summary = $('span[name=summary]', that.tfoot).empty();
            summary.append('<p>Error: '+error_thrown.name+'</p>');
            summary.append('<p>'+error_thrown.title+'</p>');
            summary.append('<p>'+error_thrown.message+'</p>');
        }

        var pkey = $.bbq.getState(that.entity_name + '-pkey', true) || '';
        ipa_cmd('show', [pkey], {'all': true, 'rights': true}, on_success, on_error, that.entity_name);
    };

    if (spec.columns) {
        for (var i=0; i<spec.columns; i++) {
            that.create_column(spec.columns[i]);
        }
    }

    // methods that should be invoked by subclasses
    that.table_init = that.init;
    that.table_create = that.create;
    that.table_setup = that.setup;

    return that;
}

/**
 * This is a base class for dialog boxes.
 */
function ipa_dialog(spec) {

    spec = spec || {};

    var that = {};

    that.name = spec.name;
    that.title = spec.title;
    that.template = spec.template;
    that._entity_name = spec.entity_name;

    that.width = spec.width || 400;

    that.buttons = {};

    that.fields = [];
    that.fields_by_name = {};

    that.__defineGetter__("entity_name", function(){
        return that._entity_name;
    });

    that.__defineSetter__("entity_name", function(entity_name){
        that._entity_name = entity_name;

        for (var i=0; i<that.fields.length; i++) {
            that.fields[i].entity_name = entity_name;
        }
    });

    that.add_button = function(name, handler) {
        that.buttons[name] = handler;
    };

    that.get_field = function(name) {
        return that.fields_by_name[name];
    };

    that.add_field = function(field) {
        that.fields.push(field);
        that.fields_by_name[field.name] = field;
    };

    that.init = function() {
        for (var i=0; i<that.fields.length; i++) {
            var field = that.fields[i];
            field.entity_name = that.entity_name;
            field.init();
        }
    };

    /**
     * Create content layout
     */
    that.create = function() {

        var table = $('<table/>').appendTo(that.container);

        for (var i=0; i<that.fields.length; i++) {
            var field = that.fields[i];

            var tr = $('<tr/>').appendTo(table);

            var td = $('<td/>', {
                'style': 'vertical-align: top;'
            }).appendTo(tr);
            td.append(field.label+': ');

            td = $('<td/>', {
                'style': 'vertical-align: top;'
            }).appendTo(tr);

            var span = $('<span/>', { 'name': field.name }).appendTo(td);
            field.create(span);
        }
    };

    /**
     * Setup behavior
     */
    that.setup = function() {
        for (var i=0; i<that.fields.length; i++) {
            var field = that.fields[i];

            var span = $('span[name="'+field.name+'"]', that.container);
            field.setup(span);
        }
    };

    /**
     * Open dialog
     */
    that.open = function(container) {

        that.container = $('<div/>').appendTo(container);

        if (that.template) {
            var template = IPA.get_template(that.template);
            that.container.load(
                template,
                function(data, text_status, xhr) {
                    that.setup();
                    that.container.dialog({
                        'title': that.title,
                        'modal': true,
                        'width': that.width,
                        'height': that.height,
                        'buttons': that.buttons
                    });
                }
            );

        } else {
            that.create();
            that.setup();

            that.container.dialog({
                'title': that.title,
                'modal': true,
                'width': that.width,
                'height': that.height,
                'buttons': that.buttons
            });
        }
    };

    that.option = function(name, value) {
        that.container.dialog('option', name, value);
    };

    that.get_record = function() {
        var record = {};
        for (var i=0; i<that.fields.length; i++) {
            var field = that.fields[i];
            var values = field.save();
            record[field.name] = values[0];
        }
        return record;
    };

    that.close = function() {
        that.container.dialog('destroy');
        that.container.remove();
    };

    that.reset = function() {
        for (var i=0; i<that.fields.length; i++) {
            var field = that.fields[i];
            field.reset();
        }
    };

    that.dialog_init = that.init;
    that.dialog_create = that.create;
    that.dialog_setup = that.setup;
    that.dialog_open = that.open;

    return that;
}

/**
 * This dialog provides an interface for searching and selecting
 * values from the available results.
 */
function ipa_adder_dialog(spec) {

    spec = spec || {};

    var that = ipa_dialog(spec);

    that.width = spec.width || '600px';

    that.columns = [];
    that.columns_by_name = {};

    that.get_column = function(name) {
        return that.columns_by_name[name];
    };

    that.add_column = function(column) {
        that.columns.push(column);
        that.columns_by_name[column.name] = column;
    };

    that.set_columns = function(columns) {
        that.clear_columns();
        for (var i=0; i<columns.length; i++) {
            that.add_column(columns[i]);
        }
    };

    that.clear_columns = function() {
        that.columns = [];
        that.columns_by_name = {};
    };

    that.create_column = function(spec) {
        var column = ipa_column(spec);
        that.add_column(column);
        return column;
    };

    that.init = function() {
        that.available_table = ipa_table_widget({
            name: 'available',
            scrollable: true,
            height: '151px'
        });

        that.available_table.set_columns(that.columns);

        that.available_table.init();

        that.selected_table = ipa_table_widget({
            name: 'selected',
            scrollable: true,
            height: '151px'
        });

        that.selected_table.set_columns(that.columns);

        that.selected_table.init();

        that.dialog_init();
    };

    that.create = function() {

        // do not call that.dialog_create();

        var search_panel = $('<div/>', {
            'class': 'adder-dialog-filter'
        }).appendTo(that.container);

        $('<input/>', {
            type: 'text',
            name: 'filter',
            style: 'width: 244px'
        }).appendTo(search_panel);

        search_panel.append(' ');

        $('<input/>', {
            type: 'button',
            name: 'find',
            value: 'Find'
        }).appendTo(search_panel);

        var results_panel = $('<div/>', {
            'class': 'adder-dialog-results'
        }).appendTo(that.container);

        var available_panel = $('<div/>', {
            name: 'available',
            'class': 'adder-dialog-available'
        }).appendTo(results_panel);

        $('<div/>', {
            html: 'Available',
            'class': 'ui-widget-header'
        }).appendTo(available_panel);

        that.available_table.create(available_panel);

        var buttons_panel = $('<div/>', {
            name: 'buttons',
            'class': 'adder-dialog-buttons'
        }).appendTo(results_panel);

        var p = $('<p/>').appendTo(buttons_panel);
        $('<input />', {
            type: 'button',
            name: 'remove',
            value: '<<'
        }).appendTo(p);

        p = $('<p/>').appendTo(buttons_panel);
        $('<input />', {
            type: 'button',
            name: 'add',
            value: '>>'
        }).appendTo(p);

        var selected_panel = $('<div/>', {
            name: 'selected',
            'class': 'adder-dialog-selected'
        }).appendTo(results_panel);

        $('<div/>', {
            html: 'Prospective',
            'class': 'ui-widget-header'
        }).appendTo(selected_panel);

        that.selected_table.create(selected_panel);
    };

    that.setup = function() {

        // do not call that.dialog_setup();

        var available_panel = $('div[name=available]', that.container);
        that.available_table.setup(available_panel);

        var selected_panel = $('div[name=selected]', that.container);
        that.selected_table.setup(selected_panel);

        that.filter_field = $('input[name=filter]', that.container);

        var button = $('input[name=find]', that.container);
        that.find_button = ipa_button({
            'label': button.val(),
            'icon': 'ui-icon-search',
            'click': function() { that.search(); }
        });
        button.replaceWith(that.find_button);

        button = $('input[name=remove]', that.container);
        that.remove_button = ipa_button({
            'label': button.val(),
            'icon': 'ui-icon-trash',
            'click': function() {
                that.remove();
            }
        });
        button.replaceWith(that.remove_button);

        button = $('input[name=add]', that.container);
        that.add_button = ipa_button({
            'label': button.val(),
            'icon': 'ui-icon-plus',
            'click': function() {
                that.add();
            }
        });
        button.replaceWith(that.add_button);

        that.search();
    };

    that.open = function(container) {
        that.buttons = {
            'Enroll': function() {
                that.execute();
            },
            'Cancel': function() {
                that.close();
            }
        };

        that.dialog_open(container);
    };

    that.add = function() {
        var rows = that.available_table.remove_selected_rows();
        that.selected_table.add_rows(rows);
    };

    that.remove = function() {
        var rows = that.selected_table.remove_selected_rows();
        that.available_table.add_rows(rows);
    };

    that.get_filter = function() {
        return that.filter_field.val();
    };

    that.clear_available_values = function() {
        that.available_table.empty();
    };

    that.clear_selected_values = function() {
        that.selected_table.empty();
    };

    that.add_available_value = function(record) {
        that.available_table.add_record(record);
    };

    that.get_selected_values = function() {
        return that.selected_table.save();
    };

    that.close = function() {
        that.container.dialog('close');
    };

    that.adder_dialog_init = that.init;
    that.adder_dialog_create = that.create;
    that.adder_dialog_setup = that.setup;

    return that;
}

/**
 * This dialog displays the values to be deleted.
 */
function ipa_deleter_dialog(spec) {

    spec = spec || {};

    var that = ipa_dialog(spec);

    that.title = spec.title || IPA.messages.button.remove;
    that.remove = spec.remove;

    that.values = spec.values || [];

    that.add_value = function(value) {
        that.values.push(value);
    };

    that.set_values = function(values) {
        that.values = that.values.concat(values);
    };

    that.create = function() {
        var ul = $('<ul/>');
        ul.appendTo(that.container);

        for (var i=0; i<that.values.length; i++) {
            $('<li/>',{
                'text': that.values[i]
            }).appendTo(ul);
        }

        $('<p/>', {
            'text': IPA.messages.search.delete_confirm
        }).appendTo(that.container);
    };

    that.open = function(container) {
        that.buttons = {
            'Delete': that.remove,
            'Cancel': that.close
        };

        that.dialog_open(container);
    };

    return that;
}