file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Main.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/Main.java
package java_cup; import java.util.Enumeration; import java.io.*; /** This class serves as the main driver for the JavaCup system. * It accepts user options and coordinates overall control flow. * The main flow of control includes the following activities: * <ul> * <li> Parse user supplied arguments and options. * <li> Open output files. * <li> Parse the specification from standard input. * <li> Check for unused terminals, non-terminals, and productions. * <li> Build the state machine, tables, etc. * <li> Output the generated code. * <li> Close output files. * <li> Print a summary if requested. * </ul> * * Options to the main program include: <dl> * <dt> -package name * <dd> specify package generated classes go in [default none] * <dt> -parser name * <dd> specify parser class name [default "parser"] * <dt> -symbols name * <dd> specify name for symbol constant class [default "sym"] * <dt> -interface * <dd> emit symbol constant <i>interface</i>, rather than class * <dt> -nonterms * <dd> put non terminals in symbol constant class * <dt> -expect # * <dd> number of conflicts expected/allowed [default 0] * <dt> -compact_red * <dd> compact tables by defaulting to most frequent reduce * <dt> -nowarn * <dd> don't warn about useless productions, etc. * <dt> -nosummary * <dd> don't print the usual summary of parse states, etc. * <dt> -progress * <dd> print messages to indicate progress of the system * <dt> -time * <dd> print time usage summary * <dt> -dump_grammar * <dd> produce a dump of the symbols and grammar * <dt> -dump_states * <dd> produce a dump of parse state machine * <dt> -dump_tables * <dd> produce a dump of the parse tables * <dt> -dump * <dd> produce a dump of all of the above * <dt> -debug * <dd> turn on debugging messages within JavaCup * <dt> -nopositions * <dd> don't generate the positions code * <dt> -noscanner * <dd> don't refer to java_cup.runtime.Scanner in the parser * (for compatibility with old runtimes) * <dt> -version * <dd> print version information for JavaCUP and halt. * </dl> * * @version last updated: 7/3/96 * @author Frank Flannery */ public class Main { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Only constructor is private, so we do not allocate any instances of this class. */ private Main() { } /*-------------------------*/ /* Options set by the user */ /*-------------------------*/ /** User option -- do we print progress messages. */ protected static boolean print_progress = true; /** User option -- do we produce a dump of the state machine */ protected static boolean opt_dump_states = false; /** User option -- do we produce a dump of the parse tables */ protected static boolean opt_dump_tables = false; /** User option -- do we produce a dump of the grammar */ protected static boolean opt_dump_grammar = false; /** User option -- do we show timing information as a part of the summary */ protected static boolean opt_show_timing = false; /** User option -- do we run produce extra debugging messages */ protected static boolean opt_do_debug = false; /** User option -- do we compact tables by making most common reduce the default action */ protected static boolean opt_compact_red = false; /** User option -- should we include non terminal symbol numbers in the symbol constant class. */ protected static boolean include_non_terms = false; /** User option -- do not print a summary. */ protected static boolean no_summary = false; /** User option -- number of conflicts to expect */ protected static int expect_conflicts = 0; /* frankf added this 6/18/96 */ /** User option -- should generator generate code for left/right values? */ protected static boolean lr_values = true; /** User option -- should symbols be put in a class or an interface? [CSA]*/ protected static boolean sym_interface = false; /** User option -- should generator suppress references to * java_cup.runtime.Scanner for compatibility with old runtimes? */ protected static boolean suppress_scanner = false; /*----------------------------------------------------------------------*/ /* Timing data (not all of these time intervals are mutually exclusive) */ /*----------------------------------------------------------------------*/ /** Timing data -- when did we start */ protected static long start_time = 0; /** Timing data -- when did we end preliminaries */ protected static long prelim_end = 0; /** Timing data -- when did we end parsing */ protected static long parse_end = 0; /** Timing data -- when did we end checking */ protected static long check_end = 0; /** Timing data -- when did we end dumping */ protected static long dump_end = 0; /** Timing data -- when did we end state and table building */ protected static long build_end = 0; /** Timing data -- when did we end nullability calculation */ protected static long nullability_end = 0; /** Timing data -- when did we end first set calculation */ protected static long first_end = 0; /** Timing data -- when did we end state machine construction */ protected static long machine_end = 0; /** Timing data -- when did we end table construction */ protected static long table_end = 0; /** Timing data -- when did we end checking for non-reduced productions */ protected static long reduce_check_end = 0; /** Timing data -- when did we finish emitting code */ protected static long emit_end = 0; /** Timing data -- when were we completely done */ protected static long final_time = 0; /* Additional timing information is also collected in emit */ /*-----------------------------------------------------------*/ /*--- Main Program ------------------------------------------*/ /*-----------------------------------------------------------*/ /** The main driver for the system. * @param argv an array of strings containing command line arguments. */ public static void main(String argv[]) throws internal_error, java.io.IOException, java.lang.Exception { boolean did_output = false; start_time = System.currentTimeMillis(); /* process user options and arguments */ parse_args(argv); /* frankf 6/18/96 hackish, yes, but works */ emit.set_lr_values(lr_values); /* open output files */ if (print_progress) System.err.println("Opening files..."); /* use a buffered version of standard input */ input_file = new BufferedInputStream(System.in); prelim_end = System.currentTimeMillis(); /* parse spec into internal data structures */ if (print_progress) System.err.println("Parsing specification from standard input..."); parse_grammar_spec(); parse_end = System.currentTimeMillis(); /* don't proceed unless we are error free */ if (lexer.error_count == 0) { /* check for unused bits */ if (print_progress) System.err.println("Checking specification..."); check_unused(); check_end = System.currentTimeMillis(); /* build the state machine and parse tables */ if (print_progress) System.err.println("Building parse tables..."); build_parser(); build_end = System.currentTimeMillis(); /* output the generated code, if # of conflicts permits */ if (lexer.error_count != 0) { // conflicts! don't emit code, don't dump tables. opt_dump_tables = false; } else { // everything's okay, emit parser. if (print_progress) System.err.println("Writing parser..."); open_files(); emit_parser(); did_output = true; } } /* fix up the times to make the summary easier */ emit_end = System.currentTimeMillis(); /* do requested dumps */ if (opt_dump_grammar) dump_grammar(); if (opt_dump_states) dump_machine(); if (opt_dump_tables) dump_tables(); dump_end = System.currentTimeMillis(); /* close input/output files */ if (print_progress) System.err.println("Closing files..."); close_files(); /* produce a summary if desired */ if (!no_summary) emit_summary(did_output); /* If there were errors during the run, * exit with non-zero status (makefile-friendliness). --CSA */ if (lexer.error_count != 0) System.exit(100); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Print a "usage message" that described possible command line options, * then exit. * @param message a specific error message to preface the usage message by. */ protected static void usage(String message) { System.err.println(); System.err.println(message); System.err.println(); System.err.println( "Usage: " + version.program_name + " [options] [filename]\n" + " and expects a specification file on standard input if no filename is given.\n" + " Legal options include:\n" + " -package name specify package generated classes go in [default none]\n" + " -parser name specify parser class name [default \"parser\"]\n" + " -symbols name specify name for symbol constant class [default \"sym\"]\n"+ " -interface put symbols in an interface, rather than a class\n" + " -nonterms put non terminals in symbol constant class\n" + " -expect # number of conflicts expected/allowed [default 0]\n" + " -compact_red compact tables by defaulting to most frequent reduce\n" + " -nowarn don't warn about useless productions, etc.\n" + " -nosummary don't print the usual summary of parse states, etc.\n" + " -nopositions don't propagate the left and right token position values\n" + " -noscanner don't refer to java_cup.runtime.Scanner\n" + " -progress print messages to indicate progress of the system\n" + " -time print time usage summary\n" + " -dump_grammar produce a human readable dump of the symbols and grammar\n"+ " -dump_states produce a dump of parse state machine\n"+ " -dump_tables produce a dump of the parse tables\n"+ " -dump produce a dump of all of the above\n"+ " -version print the version information for CUP and exit\n" ); System.exit(1); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Parse command line options and arguments to set various user-option * flags and variables. * @param argv the command line arguments to be parsed. */ protected static void parse_args(String argv[]) { int len = argv.length; int i; /* parse the options */ for (i=0; i<len; i++) { /* try to get the various options */ if (argv[i].equals("-package")) { /* must have an arg */ if (++i >= len || argv[i].startsWith("-") || argv[i].endsWith(".cup")) usage("-package must have a name argument"); /* record the name */ emit.package_name = argv[i]; } else if (argv[i].equals("-parser")) { /* must have an arg */ if (++i >= len || argv[i].startsWith("-") || argv[i].endsWith(".cup")) usage("-parser must have a name argument"); /* record the name */ emit.parser_class_name = argv[i]; } else if (argv[i].equals("-symbols")) { /* must have an arg */ if (++i >= len || argv[i].startsWith("-") || argv[i].endsWith(".cup")) usage("-symbols must have a name argument"); /* record the name */ emit.symbol_const_class_name = argv[i]; } else if (argv[i].equals("-nonterms")) { include_non_terms = true; } else if (argv[i].equals("-expect")) { /* must have an arg */ if (++i >= len || argv[i].startsWith("-") || argv[i].endsWith(".cup")) usage("-expect must have a name argument"); /* record the number */ try { expect_conflicts = Integer.parseInt(argv[i]); } catch (NumberFormatException e) { usage("-expect must be followed by a decimal integer"); } } else if (argv[i].equals("-compact_red")) opt_compact_red = true; else if (argv[i].equals("-nosummary")) no_summary = true; else if (argv[i].equals("-nowarn")) emit.nowarn = true; else if (argv[i].equals("-dump_states")) opt_dump_states = true; else if (argv[i].equals("-dump_tables")) opt_dump_tables = true; else if (argv[i].equals("-progress")) print_progress = true; else if (argv[i].equals("-dump_grammar")) opt_dump_grammar = true; else if (argv[i].equals("-dump")) opt_dump_states = opt_dump_tables = opt_dump_grammar = true; else if (argv[i].equals("-time")) opt_show_timing = true; else if (argv[i].equals("-debug")) opt_do_debug = true; /* frankf 6/18/96 */ else if (argv[i].equals("-nopositions")) lr_values = false; /* CSA 12/21/97 */ else if (argv[i].equals("-interface")) sym_interface = true; /* CSA 23-Jul-1999 */ else if (argv[i].equals("-noscanner")) suppress_scanner = true; /* CSA 23-Jul-1999 */ else if (argv[i].equals("-version")) { System.out.println(version.title_str); System.exit(1); } /* CSA 24-Jul-1999; suggestion by Jean Vaucher */ else if (!argv[i].startsWith("-") && i==len-1) { /* use input from file. */ try { System.setIn(new FileInputStream(argv[i])); } catch (java.io.FileNotFoundException e) { usage("Unable to open \"" + argv[i] +"\" for input"); } } else { usage("Unrecognized option \"" + argv[i] + "\""); } } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /*-------*/ /* Files */ /*-------*/ /** Input file. This is a buffered version of System.in. */ protected static BufferedInputStream input_file; /** Output file for the parser class. */ protected static PrintWriter parser_class_file; /** Output file for the symbol constant class. */ protected static PrintWriter symbol_class_file; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Open various files used by the system. */ protected static void open_files() { File fil; String out_name; /* open each of the output files */ /* parser class */ out_name = emit.parser_class_name + ".java"; fil = new File(out_name); try { parser_class_file = new PrintWriter( new BufferedOutputStream(new FileOutputStream(fil), 4096)); } catch(Exception e) { System.err.println("Can't open \"" + out_name + "\" for output"); System.exit(3); } /* symbol constants class */ out_name = emit.symbol_const_class_name + ".java"; fil = new File(out_name); try { symbol_class_file = new PrintWriter( new BufferedOutputStream(new FileOutputStream(fil), 4096)); } catch(Exception e) { System.err.println("Can't open \"" + out_name + "\" for output"); System.exit(4); } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Close various files used by the system. */ protected static void close_files() throws java.io.IOException { if (input_file != null) input_file.close(); if (parser_class_file != null) parser_class_file.close(); if (symbol_class_file != null) symbol_class_file.close(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Parse the grammar specification from standard input. This produces * sets of terminal, non-terminals, and productions which can be accessed * via static variables of the respective classes, as well as the setting * of various variables (mostly in the emit class) for small user supplied * items such as the code to scan with. */ protected static void parse_grammar_spec() throws java.lang.Exception { parser parser_obj; /* create a parser and parse with it */ parser_obj = new parser(); try { if (opt_do_debug) parser_obj.debug_parse(); else parser_obj.parse(); } catch (Exception e) { /* something threw an exception. catch it and emit a message so we have a line number to work with, then re-throw it */ lexer.emit_error("Internal error: Unexpected exception"); throw e; } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Check for unused symbols. Unreduced productions get checked when * tables are created. */ protected static void check_unused() { terminal term; non_terminal nt; /* check for unused terminals */ for (Enumeration t = terminal.all(); t.hasMoreElements(); ) { term = (terminal)t.nextElement(); /* don't issue a message for EOF */ if (term == terminal.EOF) continue; /* or error */ if (term == terminal.error) continue; /* is this one unused */ if (term.use_count() == 0) { /* count it and warn if we are doing warnings */ emit.unused_term++; if (!emit.nowarn) { System.err.println("Warning: Terminal \"" + term.name() + "\" was declared but never used"); lexer.warning_count++; } } } /* check for unused non terminals */ for (Enumeration n = non_terminal.all(); n.hasMoreElements(); ) { nt = (non_terminal)n.nextElement(); /* is this one unused */ if (nt.use_count() == 0) { /* count and warn if we are doing warnings */ emit.unused_term++; if (!emit.nowarn) { System.err.println("Warning: Non terminal \"" + nt.name() + "\" was declared but never used"); lexer.warning_count++; } } } } /* . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* . . Internal Results of Generating the Parser . .*/ /* . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Start state in the overall state machine. */ protected static lalr_state start_state; /** Resulting parse action table. */ protected static parse_action_table action_table; /** Resulting reduce-goto table. */ protected static parse_reduce_table reduce_table; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Build the (internal) parser from the previously parsed specification. * This includes:<ul> * <li> Computing nullability of non-terminals. * <li> Computing first sets of non-terminals and productions. * <li> Building the viable prefix recognizer machine. * <li> Filling in the (internal) parse tables. * <li> Checking for unreduced productions. * </ul> */ protected static void build_parser() throws internal_error { /* compute nullability of all non terminals */ if (opt_do_debug || print_progress) System.err.println(" Computing non-terminal nullability..."); non_terminal.compute_nullability(); nullability_end = System.currentTimeMillis(); /* compute first sets of all non terminals */ if (opt_do_debug || print_progress) System.err.println(" Computing first sets..."); non_terminal.compute_first_sets(); first_end = System.currentTimeMillis(); /* build the LR viable prefix recognition machine */ if (opt_do_debug || print_progress) System.err.println(" Building state machine..."); start_state = lalr_state.build_machine(emit.start_production); machine_end = System.currentTimeMillis(); /* build the LR parser action and reduce-goto tables */ if (opt_do_debug || print_progress) System.err.println(" Filling in tables..."); action_table = new parse_action_table(); reduce_table = new parse_reduce_table(); for (Enumeration st = lalr_state.all(); st.hasMoreElements(); ) { lalr_state lst = (lalr_state)st.nextElement(); lst.build_table_entries( action_table, reduce_table); } table_end = System.currentTimeMillis(); /* check and warn for non-reduced productions */ if (opt_do_debug || print_progress) System.err.println(" Checking for non-reduced productions..."); action_table.check_reductions(); reduce_check_end = System.currentTimeMillis(); /* if we have more conflicts than we expected issue a message and die */ if (emit.num_conflicts > expect_conflicts) { System.err.println("*** More conflicts encountered than expected " + "-- parser generation aborted"); lexer.error_count++; // indicate the problem. // we'll die on return, after clean up. } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Call the emit routines necessary to write out the generated parser. */ protected static void emit_parser() throws internal_error { emit.symbols(symbol_class_file, include_non_terms, sym_interface); emit.parser(parser_class_file, action_table, reduce_table, start_state.index(), emit.start_production, opt_compact_red, suppress_scanner); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Helper routine to optionally return a plural or non-plural ending. * @param val the numerical value determining plurality. */ protected static String plural(int val) { if (val == 1) return ""; else return "s"; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Emit a long summary message to standard error (System.err) which * summarizes what was found in the specification, how many states were * produced, how many conflicts were found, etc. A detailed timing * summary is also produced if it was requested by the user. * @param output_produced did the system get far enough to generate code. */ protected static void emit_summary(boolean output_produced) { final_time = System.currentTimeMillis(); if (no_summary) return; System.err.println("------- " + version.title_str + " Parser Generation Summary -------"); /* error and warning count */ System.err.println(" " + lexer.error_count + " error" + plural(lexer.error_count) + " and " + lexer.warning_count + " warning" + plural(lexer.warning_count)); /* basic stats */ System.err.print(" " + terminal.number() + " terminal" + plural(terminal.number()) + ", "); System.err.print(non_terminal.number() + " non-terminal" + plural(non_terminal.number()) + ", and "); System.err.println(production.number() + " production" + plural(production.number()) + " declared, "); System.err.println(" producing " + lalr_state.number() + " unique parse states."); /* unused symbols */ System.err.println(" " + emit.unused_term + " terminal" + plural(emit.unused_term) + " declared but not used."); System.err.println(" " + emit.unused_non_term + " non-terminal" + plural(emit.unused_term) + " declared but not used."); /* productions that didn't reduce */ System.err.println(" " + emit.not_reduced + " production" + plural(emit.not_reduced) + " never reduced."); /* conflicts */ System.err.println(" " + emit.num_conflicts + " conflict" + plural(emit.num_conflicts) + " detected" + " (" + expect_conflicts + " expected)."); /* code location */ if (output_produced) System.err.println(" Code written to \"" + emit.parser_class_name + ".java\", and \"" + emit.symbol_const_class_name + ".java\"."); else System.err.println(" No code produced."); if (opt_show_timing) show_times(); System.err.println( "---------------------------------------------------- (" + version.version_str + ")"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce the optional timing summary as part of an overall summary. */ protected static void show_times() { long total_time = final_time - start_time; System.err.println(". . . . . . . . . . . . . . . . . . . . . . . . . "); System.err.println(" Timing Summary"); System.err.println(" Total time " + timestr(final_time-start_time, total_time)); System.err.println(" Startup " + timestr(prelim_end-start_time, total_time)); System.err.println(" Parse " + timestr(parse_end-prelim_end, total_time) ); if (check_end != 0) System.err.println(" Checking " + timestr(check_end-parse_end, total_time)); if (check_end != 0 && build_end != 0) System.err.println(" Parser Build " + timestr(build_end-check_end, total_time)); if (nullability_end != 0 && check_end != 0) System.err.println(" Nullability " + timestr(nullability_end-check_end, total_time)); if (first_end != 0 && nullability_end != 0) System.err.println(" First sets " + timestr(first_end-nullability_end, total_time)); if (machine_end != 0 && first_end != 0) System.err.println(" State build " + timestr(machine_end-first_end, total_time)); if (table_end != 0 && machine_end != 0) System.err.println(" Table build " + timestr(table_end-machine_end, total_time)); if (reduce_check_end != 0 && table_end != 0) System.err.println(" Checking " + timestr(reduce_check_end-table_end, total_time)); if (emit_end != 0 && build_end != 0) System.err.println(" Code Output " + timestr(emit_end-build_end, total_time)); if (emit.symbols_time != 0) System.err.println(" Symbols " + timestr(emit.symbols_time, total_time)); if (emit.parser_time != 0) System.err.println(" Parser class " + timestr(emit.parser_time, total_time)); if (emit.action_code_time != 0) System.err.println(" Actions " + timestr(emit.action_code_time, total_time)); if (emit.production_table_time != 0) System.err.println(" Prod table " + timestr(emit.production_table_time, total_time)); if (emit.action_table_time != 0) System.err.println(" Action tab " + timestr(emit.action_table_time, total_time)); if (emit.goto_table_time != 0) System.err.println(" Reduce tab " + timestr(emit.goto_table_time, total_time)); System.err.println(" Dump Output " + timestr(dump_end-emit_end, total_time)); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Helper routine to format a decimal based display of seconds and * percentage of total time given counts of milliseconds. Note: this * is broken for use with some instances of negative time (since we don't * use any negative time here, we let if be for now). * @param time_val the value being formatted (in ms). * @param total_time total time percentages are calculated against (in ms). */ protected static String timestr(long time_val, long total_time) { boolean neg; long ms = 0; long sec = 0; long percent10; String pad; /* work with positives only */ neg = time_val < 0; if (neg) time_val = -time_val; /* pull out seconds and ms */ ms = time_val % 1000; sec = time_val / 1000; /* construct a pad to blank fill seconds out to 4 places */ if (sec < 10) pad = " "; else if (sec < 100) pad = " "; else if (sec < 1000) pad = " "; else pad = ""; /* calculate 10 times the percentage of total */ percent10 = (time_val*1000)/total_time; /* build and return the output string */ return (neg ? "-" : "") + pad + sec + "." + ((ms%1000)/100) + ((ms%100)/10) + (ms%10) + "sec" + " (" + percent10/10 + "." + percent10%10 + "%)"; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a human readable dump of the grammar. */ public static void dump_grammar() throws internal_error { System.err.println("===== Terminals ====="); for (int tidx=0, cnt=0; tidx < terminal.number(); tidx++, cnt++) { System.err.print("["+tidx+"]"+terminal.find(tidx).name()+" "); if ((cnt+1) % 5 == 0) System.err.println(); } System.err.println(); System.err.println(); System.err.println("===== Non terminals ====="); for (int nidx=0, cnt=0; nidx < non_terminal.number(); nidx++, cnt++) { System.err.print("["+nidx+"]"+non_terminal.find(nidx).name()+" "); if ((cnt+1) % 5 == 0) System.err.println(); } System.err.println(); System.err.println(); System.err.println("===== Productions ====="); for (int pidx=0; pidx < production.number(); pidx++) { production prod = production.find(pidx); System.err.print("["+pidx+"] "+prod.lhs().the_symbol().name() + " ::= "); for (int i=0; i<prod.rhs_length(); i++) if (prod.rhs(i).is_action()) System.err.print("{action} "); else System.err.print( ((symbol_part)prod.rhs(i)).the_symbol().name() + " "); System.err.println(); } System.err.println(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a (semi-) human readable dump of the complete viable prefix * recognition state machine. */ public static void dump_machine() { lalr_state ordered[] = new lalr_state[lalr_state.number()]; /* put the states in sorted order for a nicer display */ for (Enumeration s = lalr_state.all(); s.hasMoreElements(); ) { lalr_state st = (lalr_state)s.nextElement(); ordered[st.index()] = st; } System.err.println("===== Viable Prefix Recognizer ====="); for (int i = 0; i<lalr_state.number(); i++) { if (ordered[i] == start_state) System.err.print("START "); System.err.println(ordered[i]); System.err.println("-------------------"); } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a (semi-) human readable dumps of the parse tables */ public static void dump_tables() { System.err.println(action_table); System.err.println(reduce_table); } /*-----------------------------------------------------------*/ }
31,598
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
symbol_set.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/symbol_set.java
package java_cup; import java.util.Hashtable; import java.util.Enumeration; /** This class represents a set of symbols and provides a series of * set operations to manipulate them. * * @see java_cup.symbol * @version last updated: 11/25/95 * @author Scott Hudson */ public class symbol_set { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Constructor for an empty set. */ public symbol_set() { } /** Constructor for cloning from another set. * @param other the set we are cloning from. */ public symbol_set(symbol_set other) throws internal_error { not_null(other); _all = (Hashtable)other._all.clone(); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** A hash table to hold the set. Symbols are keyed using their name string. */ protected Hashtable _all = new Hashtable(11); /** Access to all elements of the set. */ public Enumeration all() {return _all.elements();} /** size of the set */ public int size() {return _all.size();} /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** Helper function to test for a null object and throw an exception * if one is found. * @param obj the object we are testing. */ protected void not_null(Object obj) throws internal_error { if (obj == null) throw new internal_error("Null object used in set operation"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if the set contains a particular symbol. * @param sym the symbol we are looking for. */ public boolean contains(symbol sym) {return _all.containsKey(sym.name());} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if this set is an (improper) subset of another. * @param other the set we are testing against. */ public boolean is_subset_of(symbol_set other) throws internal_error { not_null(other); /* walk down our set and make sure every element is in the other */ for (Enumeration e = all(); e.hasMoreElements(); ) if (!other.contains((symbol)e.nextElement())) return false; /* they were all there */ return true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if this set is an (improper) superset of another. * @param other the set we are are testing against. */ public boolean is_superset_of(symbol_set other) throws internal_error { not_null(other); return other.is_subset_of(this); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Add a single symbol to the set. * @param sym the symbol we are adding. * @return true if this changes the set. */ public boolean add(symbol sym) throws internal_error { Object previous; not_null(sym); /* put the object in */ previous = _all.put(sym.name(),sym); /* if we had a previous, this is no change */ return previous == null; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Remove a single symbol if it is in the set. * @param sym the symbol we are removing. */ public void remove(symbol sym) throws internal_error { not_null(sym); _all.remove(sym.name()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Add (union) in a complete set. * @param other the set we are adding in. * @return true if this changes the set. */ public boolean add(symbol_set other) throws internal_error { boolean result = false; not_null(other); /* walk down the other set and do the adds individually */ for (Enumeration e = other.all(); e.hasMoreElements(); ) result = add((symbol)e.nextElement()) || result; return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Remove (set subtract) a complete set. * @param other the set we are removing. */ public void remove(symbol_set other) throws internal_error { not_null(other); /* walk down the other set and do the removes individually */ for (Enumeration e = other.all(); e.hasMoreElements(); ) remove((symbol)e.nextElement()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(symbol_set other) { if (other == null || other.size() != size()) return false; /* once we know they are the same size, then improper subset does test */ try { return is_subset_of(other); } catch (internal_error e) { /* can't throw the error (because super class doesn't), so we crash */ e.crash(); return false; } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof symbol_set)) return false; else return equals((symbol_set)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Compute a hash code. */ public int hashCode() { int result = 0; int cnt; Enumeration e; /* hash together codes from at most first 5 elements */ for (e = all(), cnt=0 ; e.hasMoreElements() && cnt<5; cnt++) result ^= ((symbol)e.nextElement()).hashCode(); return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { String result; boolean comma_flag; result = "{"; comma_flag = false; for (Enumeration e = all(); e.hasMoreElements(); ) { if (comma_flag) result += ", "; else comma_flag = true; result += ((symbol)e.nextElement()).name(); } result += "}"; return result; } /*-----------------------------------------------------------*/ }
6,570
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
version.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/version.java
package java_cup; /** This class contains version and authorship information. * It contains only static data elements and basically just a central * place to put this kind of information so it can be updated easily * for each release. * * Version numbers used here are broken into 3 parts: major, minor, and * update, and are written as v<major>.<minor>.<update> (e.g. v0.10a). * Major numbers will change at the time of major reworking of some * part of the system. Minor numbers for each public release or * change big enough to cause incompatibilities. Finally update * letter will be incremented for small bug fixes and changes that * probably wouldn't be noticed by a user. * * @version last updated: 12/22/97 [CSA] * @author Frank Flannery */ public class version { /** The major version number. */ public static final int major = 0; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The minor version number. */ public static final int minor = 10; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The update letter. */ public static final char update = 'k'; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** String for the current version. */ public static final String version_str = "v" + major + "." + minor + update; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Full title of the system */ public static final String title_str = "CUP " + version_str; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Name of the author */ public static final String author_str = "Scott E. Hudson, Frank Flannery, and C. Scott Ananian"; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The command name normally used to invoke this program */ public static final String program_name = "java_cup"; }
1,963
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
production.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/production.java
package java_cup; import java.util.Hashtable; import java.util.Enumeration; /** This class represents a production in the grammar. It contains * a LHS non terminal, and an array of RHS symbols. As various * transformations are done on the RHS of the production, it may shrink. * As a result a separate length is always maintained to indicate how much * of the RHS array is still valid.<p> * * I addition to construction and manipulation operations, productions provide * methods for factoring out actions (see remove_embedded_actions()), for * computing the nullability of the production (i.e., can it derive the empty * string, see check_nullable()), and operations for computing its first * set (i.e., the set of terminals that could appear at the beginning of some * string derived from the production, see check_first_set()). * * @see java_cup.production_part * @see java_cup.symbol_part * @see java_cup.action_part * @version last updated: 7/3/96 * @author Frank Flannery */ public class production { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Full constructor. This constructor accepts a LHS non terminal, * an array of RHS parts (including terminals, non terminals, and * actions), and a string for a final reduce action. It does several * manipulations in the process of creating a production object. * After some validity checking it translates labels that appear in * actions into code for accessing objects on the runtime parse stack. * It them merges adjacent actions if they appear and moves any trailing * action into the final reduce actions string. Next it removes any * embedded actions by factoring them out with new action productions. * Finally it assigns a unique index to the production.<p> * * Factoring out of actions is accomplished by creating new "hidden" * non terminals. For example if the production was originally: <pre> * A ::= B {action} C D * </pre> * then it is factored into two productions:<pre> * A ::= B X C D * X ::= {action} * </pre> * (where X is a unique new non terminal). This has the effect of placing * all actions at the end where they can be handled as part of a reduce by * the parser. */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l, String action_str) throws internal_error { int i; action_part tail_action; String declare_str; int rightlen = rhs_l; /* remember the length */ if (rhs_l >= 0) _rhs_length = rhs_l; else if (rhs_parts != null) _rhs_length = rhs_parts.length; else _rhs_length = 0; /* make sure we have a valid left-hand-side */ if (lhs_sym == null) throw new internal_error( "Attempt to construct a production with a null LHS"); /* I'm not translating labels anymore, I'm adding code to declare labels as valid variables. This way, the users code string is untouched 6/96 frankf */ /* check if the last part of the right hand side is an action. If it is, it won't be on the stack, so we don't want to count it in the rightlen. Then when we search down the stack for a Symbol, we don't try to search past action */ if (rhs_l > 0) { if (rhs_parts[rhs_l - 1].is_action()) { rightlen = rhs_l - 1; } else { rightlen = rhs_l; } } /* get the generated declaration code for the necessary labels. */ declare_str = declare_labels( rhs_parts, rightlen, action_str); if (action_str == null) action_str = declare_str; else action_str = declare_str + action_str; /* count use of lhs */ lhs_sym.note_use(); /* create the part for left-hand-side */ _lhs = new symbol_part(lhs_sym); /* merge adjacent actions (if any) */ _rhs_length = merge_adjacent_actions(rhs_parts, _rhs_length); /* strip off any trailing action */ tail_action = strip_trailing_action(rhs_parts, _rhs_length); if (tail_action != null) _rhs_length--; /* Why does this run through the right hand side happen over and over? here a quick combination of two prior runs plus one I wanted of my own frankf 6/25/96 */ /* allocate and copy over the right-hand-side */ /* count use of each rhs symbol */ _rhs = new production_part[_rhs_length]; for (i=0; i<_rhs_length; i++) { _rhs[i] = rhs_parts[i]; if (!_rhs[i].is_action()) { ((symbol_part)_rhs[i]).the_symbol().note_use(); if (((symbol_part)_rhs[i]).the_symbol() instanceof terminal) { _rhs_prec = ((terminal)((symbol_part)_rhs[i]).the_symbol()).precedence_num(); _rhs_assoc = ((terminal)((symbol_part)_rhs[i]).the_symbol()).precedence_side(); } } } /*now action string is really declaration string, so put it in front! 6/14/96 frankf */ if (action_str == null) action_str = ""; if (tail_action != null && tail_action.code_string() != null) action_str = action_str + "\t\t" + tail_action.code_string(); /* stash the action */ _action = new action_part(action_str); /* rewrite production to remove any embedded actions */ remove_embedded_actions(); /* assign an index */ _index = next_index++; /* put us in the global collection of productions */ _all.put(new Integer(_index),this); /* put us in the production list of the lhs non terminal */ lhs_sym.add_production(this); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor with no action string. */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l) throws internal_error { this(lhs_sym,rhs_parts,rhs_l,null); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Constructor with precedence and associativity of production contextually define */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l, String action_str, int prec_num, int prec_side) throws internal_error { this(lhs_sym,rhs_parts,rhs_l,action_str); /* set the precedence */ set_precedence_num(prec_num); set_precedence_side(prec_side); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Constructor w/ no action string and contextual precedence defined */ public production( non_terminal lhs_sym, production_part rhs_parts[], int rhs_l, int prec_num, int prec_side) throws internal_error { this(lhs_sym,rhs_parts,rhs_l,null); /* set the precedence */ set_precedence_num(prec_num); set_precedence_side(prec_side); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /*-----------------------------------------------------------*/ /*--- (Access to) Static (Class) Variables ------------------*/ /*-----------------------------------------------------------*/ /** Table of all productions. Elements are stored using their index as * the key. */ protected static Hashtable _all = new Hashtable(); /** Access to all productions. */ public static Enumeration all() {return _all.elements();} /** Lookup a production by index. */ public static production find(int indx) { return (production) _all.get(new Integer(indx)); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Total number of productions. */ public static int number() {return _all.size();} /** Static counter for assigning unique index numbers. */ protected static int next_index; /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The left hand side non-terminal. */ protected symbol_part _lhs; /** The left hand side non-terminal. */ public symbol_part lhs() {return _lhs;} /** The precedence of the rule */ protected int _rhs_prec = -1; protected int _rhs_assoc = -1; /** Access to the precedence of the rule */ public int precedence_num() { return _rhs_prec; } public int precedence_side() { return _rhs_assoc; } /** Setting the precedence of a rule */ public void set_precedence_num(int prec_num) { _rhs_prec = prec_num; } public void set_precedence_side(int prec_side) { _rhs_assoc = prec_side; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** A collection of parts for the right hand side. */ protected production_part _rhs[]; /** Access to the collection of parts for the right hand side. */ public production_part rhs(int indx) throws internal_error { if (indx >= 0 && indx < _rhs_length) return _rhs[indx]; else throw new internal_error( "Index out of range for right hand side of production"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** How much of the right hand side array we are presently using. */ protected int _rhs_length; /** How much of the right hand side array we are presently using. */ public int rhs_length() {return _rhs_length;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** An action_part containing code for the action to be performed when we * reduce with this production. */ protected action_part _action; /** An action_part containing code for the action to be performed when we * reduce with this production. */ public action_part action() {return _action;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Index number of the production. */ protected int _index; /** Index number of the production. */ public int index() {return _index;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Count of number of reductions using this production. */ protected int _num_reductions = 0; /** Count of number of reductions using this production. */ public int num_reductions() {return _num_reductions;} /** Increment the count of reductions with this non-terminal */ public void note_reduction_use() {_num_reductions++;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Is the nullability of the production known or unknown? */ protected boolean _nullable_known = false; /** Is the nullability of the production known or unknown? */ public boolean nullable_known() {return _nullable_known;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Nullability of the production (can it derive the empty string). */ protected boolean _nullable = false; /** Nullability of the production (can it derive the empty string). */ public boolean nullable() {return _nullable;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** First set of the production. This is the set of terminals that * could appear at the front of some string derived from this production. */ protected terminal_set _first_set = new terminal_set(); /** First set of the production. This is the set of terminals that * could appear at the front of some string derived from this production. */ public terminal_set first_set() {return _first_set;} /*-----------------------------------------------------------*/ /*--- Static Methods ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Determine if a given character can be a label id starter. * @param c the character in question. */ protected static boolean is_id_start(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_'); //later need to handle non-8-bit chars here } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if a character can be in a label id. * @param c the character in question. */ protected static boolean is_id_char(char c) { return is_id_start(c) || (c >= '0' && c <= '9'); } /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Return label declaration code * @param labelname the label name * @param stack_type the stack type of label? * @author frankf */ protected String make_declaration( String labelname, String stack_type, int offset) { String ret; /* Put in the left/right value labels */ if (emit.lr_values()) ret = "\t\tint " + labelname + "left = ((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + offset + ")).left;\n" + "\t\tint " + labelname + "right = ((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + offset + ")).right;\n"; else ret = ""; /* otherwise, just declare label. */ return ret + "\t\t" + stack_type + " " + labelname + " = (" + stack_type + ")((" + "java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + offset + ")).value;\n"; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Declare label names as valid variables within the action string * @param rhs array of RHS parts. * @param rhs_len how much of rhs to consider valid. * @param final_action the final action string of the production. * @param lhs_type the object type associated with the LHS symbol. */ protected String declare_labels( production_part rhs[], int rhs_len, String final_action) { String declaration = ""; symbol_part part; action_part act_part; int pos; /* walk down the parts and extract the labels */ for (pos = 0; pos < rhs_len; pos++) { if (!rhs[pos].is_action()) { part = (symbol_part)rhs[pos]; /* if it has a label, make declaration! */ if (part.label() != null) { declaration = declaration + make_declaration(part.label(), part.the_symbol().stack_type(), rhs_len-pos-1); } } } return declaration; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Helper routine to merge adjacent actions in a set of RHS parts * @param rhs_parts array of RHS parts. * @param len amount of that array that is valid. * @return remaining valid length. */ protected int merge_adjacent_actions(production_part rhs_parts[], int len) { int from_loc, to_loc, merge_cnt; /* bail out early if we have no work to do */ if (rhs_parts == null || len == 0) return 0; merge_cnt = 0; to_loc = -1; for (from_loc=0; from_loc<len; from_loc++) { /* do we go in the current position or one further */ if (to_loc < 0 || !rhs_parts[to_loc].is_action() || !rhs_parts[from_loc].is_action()) { /* next one */ to_loc++; /* clear the way for it */ if (to_loc != from_loc) rhs_parts[to_loc] = null; } /* if this is not trivial? */ if (to_loc != from_loc) { /* do we merge or copy? */ if (rhs_parts[to_loc] != null && rhs_parts[to_loc].is_action() && rhs_parts[from_loc].is_action()) { /* merge */ rhs_parts[to_loc] = new action_part( ((action_part)rhs_parts[to_loc]).code_string() + ((action_part)rhs_parts[from_loc]).code_string()); merge_cnt++; } else { /* copy */ rhs_parts[to_loc] = rhs_parts[from_loc]; } } } /* return the used length */ return len - merge_cnt; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Helper routine to strip a trailing action off rhs and return it * @param rhs_parts array of RHS parts. * @param len how many of those are valid. * @return the removed action part. */ protected action_part strip_trailing_action( production_part rhs_parts[], int len) { action_part result; /* bail out early if we have nothing to do */ if (rhs_parts == null || len == 0) return null; /* see if we have a trailing action */ if (rhs_parts[len-1].is_action()) { /* snip it out and return it */ result = (action_part)rhs_parts[len-1]; rhs_parts[len-1] = null; return result; } else return null; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Remove all embedded actions from a production by factoring them * out into individual action production using new non terminals. * if the original production was: <pre> * A ::= B {action1} C {action2} D * </pre> * then it will be factored into: <pre> * A ::= B NT$1 C NT$2 D * NT$1 ::= {action1} * NT$2 ::= {action2} * </pre> * where NT$1 and NT$2 are new system created non terminals. */ /* the declarations added to the parent production are also passed along, as they should be perfectly valid in this code string, since it was originally a code string in the parent, not on its own. frank 6/20/96 */ protected void remove_embedded_actions( ) throws internal_error { non_terminal new_nt; production new_prod; String declare_str; /* walk over the production and process each action */ for (int act_loc = 0; act_loc < rhs_length(); act_loc++) if (rhs(act_loc).is_action()) { declare_str = declare_labels( _rhs, act_loc, ""); /* create a new non terminal for the action production */ new_nt = non_terminal.create_new(); new_nt.is_embedded_action = true; /* 24-Mar-1998, CSA */ /* create a new production with just the action */ new_prod = new action_production(this, new_nt, null, 0, declare_str + ((action_part)rhs(act_loc)).code_string()); /* replace the action with the generated non terminal */ _rhs[act_loc] = new symbol_part(new_nt); } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Check to see if the production (now) appears to be nullable. * A production is nullable if its RHS could derive the empty string. * This results when the RHS is empty or contains only non terminals * which themselves are nullable. */ public boolean check_nullable() throws internal_error { production_part part; symbol sym; int pos; /* if we already know bail out early */ if (nullable_known()) return nullable(); /* if we have a zero size RHS we are directly nullable */ if (rhs_length() == 0) { /* stash and return the result */ return set_nullable(true); } /* otherwise we need to test all of our parts */ for (pos=0; pos<rhs_length(); pos++) { part = rhs(pos); /* only look at non-actions */ if (!part.is_action()) { sym = ((symbol_part)part).the_symbol(); /* if its a terminal we are definitely not nullable */ if (!sym.is_non_term()) return set_nullable(false); /* its a non-term, is it marked nullable */ else if (!((non_terminal)sym).nullable()) /* this one not (yet) nullable, so we aren't */ return false; } } /* if we make it here all parts are nullable */ return set_nullable(true); } /** set (and return) nullability */ boolean set_nullable(boolean v) { _nullable_known = true; _nullable = v; return v; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Update (and return) the first set based on current NT firsts. * This assumes that nullability has already been computed for all non * terminals and productions. */ public terminal_set check_first_set() throws internal_error { int part; symbol sym; /* walk down the right hand side till we get past all nullables */ for (part=0; part<rhs_length(); part++) { /* only look at non-actions */ if (!rhs(part).is_action()) { sym = ((symbol_part)rhs(part)).the_symbol(); /* is it a non-terminal?*/ if (sym.is_non_term()) { /* add in current firsts from that NT */ _first_set.add(((non_terminal)sym).first_set()); /* if its not nullable, we are done */ if (!((non_terminal)sym).nullable()) break; } else { /* its a terminal -- add that to the set */ _first_set.add((terminal)sym); /* we are done */ break; } } } /* return our updated first set */ return first_set(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(production other) { if (other == null) return false; return other._index == _index; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof production)) return false; else return equals((production)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a hash code. */ public int hashCode() { /* just use a simple function of the index */ return _index*13; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { String result; /* catch any internal errors */ try { result = "production [" + index() + "]: "; result += ((lhs() != null) ? lhs().toString() : "$$NULL-LHS$$"); result += " :: = "; for (int i = 0; i<rhs_length(); i++) result += rhs(i) + " "; result += ";"; if (action() != null && action().code_string() != null) result += " {" + action().code_string() + "}"; if (nullable_known()) if (nullable()) result += "[NULLABLE]"; else result += "[NOT NULLABLE]"; } catch (internal_error e) { /* crash on internal error since we can't throw it from here (because superclass does not throw anything. */ e.crash(); result = null; } return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a simpler string. */ public String to_simple_string() throws internal_error { String result; result = ((lhs() != null) ? lhs().the_symbol().name() : "NULL_LHS"); result += " ::= "; for (int i = 0; i < rhs_length(); i++) if (!rhs(i).is_action()) result += ((symbol_part)rhs(i)).the_symbol().name() + " "; return result; } /*-----------------------------------------------------------*/ }
24,176
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
production_part.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/production_part.java
package java_cup; /** This class represents one part (either a symbol or an action) of a * production. In this base class it contains only an optional label * string that the user can use to refer to the part within actions.<p> * * This is an abstract class. * * @see java_cup.production * @version last updated: 11/25/95 * @author Scott Hudson */ public abstract class production_part { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Simple constructor. */ public production_part(String lab) { _label = lab; } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** Optional label for referring to the part within an action (null for * no label). */ protected String _label; /** Optional label for referring to the part within an action (null for * no label). */ public String label() {return _label;} /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Indicate if this is an action (rather than a symbol). Here in the * base class, we don't this know yet, so its an abstract method. */ public abstract boolean is_action(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(production_part other) { if (other == null) return false; /* compare the labels */ if (label() != null) return label().equals(other.label()); else return other.label() == null; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof production_part)) return false; else return equals((production_part)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a hash code. */ public int hashCode() { return label()==null ? 0 : label().hashCode(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { if (label() != null) return label() + ":"; else return " "; } /*-----------------------------------------------------------*/ }
2,756
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
parser.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/parser.java
//---------------------------------------------------- // The following code was generated by CUP v0.10k // Sun Jul 25 13:35:26 EDT 1999 //---------------------------------------------------- package java_cup; import java_cup.runtime.*; import java.util.Hashtable; /** CUP v0.10k generated parser. * @version Sun Jul 25 13:35:26 EDT 1999 */ public class parser extends java_cup.runtime.lr_parser { /** Default constructor. */ public parser() {super();} /** Constructor which sets the default scanner. */ public parser(java_cup.runtime.Scanner s) {super(s);} /** Production table. */ protected static final short _production_table[][] = unpackFromStrings(new String[] { "\000\153\000\002\002\004\000\002\055\002\000\002\003" + "\012\000\002\003\007\000\002\056\002\000\002\004\006" + "\000\002\004\003\000\002\005\004\000\002\005\003\000" + "\002\057\002\000\002\020\006\000\002\010\003\000\002" + "\010\003\000\002\010\003\000\002\010\003\000\002\007" + "\002\000\002\007\004\000\002\006\006\000\002\013\006" + "\000\002\022\006\000\002\023\006\000\002\014\004\000" + "\002\014\003\000\002\024\005\000\002\024\004\000\002" + "\024\005\000\002\024\004\000\002\060\002\000\002\024" + "\006\000\002\061\002\000\002\024\006\000\002\062\002" + "\000\002\044\005\000\002\063\002\000\002\045\005\000" + "\002\026\005\000\002\026\003\000\002\027\005\000\002" + "\027\003\000\002\040\003\000\002\040\003\000\002\043" + "\004\000\002\043\003\000\002\064\002\000\002\041\007" + "\000\002\065\002\000\002\041\007\000\002\066\002\000" + "\002\041\007\000\002\042\005\000\002\042\003\000\002" + "\052\003\000\002\053\003\000\002\067\002\000\002\015" + "\007\000\002\015\003\000\002\016\004\000\002\016\003" + "\000\002\070\002\000\002\071\002\000\002\030\010\000" + "\002\072\002\000\002\030\005\000\002\035\005\000\002" + "\035\003\000\002\036\005\000\002\036\003\000\002\031" + "\004\000\002\031\003\000\002\032\004\000\002\032\003" + "\000\002\051\004\000\002\051\003\000\002\017\005\000" + "\002\017\003\000\002\021\005\000\002\021\003\000\002" + "\025\003\000\002\025\005\000\002\033\003\000\002\034" + "\003\000\002\046\003\000\002\046\003\000\002\047\003" + "\000\002\047\003\000\002\050\003\000\002\054\003\000" + "\002\054\003\000\002\054\003\000\002\054\003\000\002" + "\054\003\000\002\054\003\000\002\054\003\000\002\054" + "\003\000\002\054\003\000\002\054\003\000\002\054\003" + "\000\002\054\003\000\002\054\003\000\002\054\003\000" + "\002\054\003\000\002\054\003\000\002\012\004\000\002" + "\012\003\000\002\011\002\000\002\011\003\000\002\037" + "\002" }); /** Access to production table. */ public short[][] production_table() {return _production_table;} /** Parse-action table. */ protected static final short[][] _action_table = unpackFromStrings(new String[] { "\000\247\000\026\003\006\004\000\005\000\007\000\010" + "\000\011\000\012\000\013\000\014\000\035\000\001\002" + "\000\004\002\251\001\002\000\024\004\200\005\uff97\007" + "\uff97\010\uff97\011\uff97\012\uff97\013\uff97\014\uff97\035\uff97" + "\001\002\000\010\011\007\012\012\035\014\001\002\000" + "\042\003\163\006\026\007\027\010\040\011\036\012\022" + "\013\042\014\030\015\017\016\015\026\033\027\023\030" + "\035\031\041\035\025\036\160\001\002\000\020\003\uffeb" + "\011\uffeb\012\uffeb\016\uffeb\026\uffeb\035\uffeb\036\uffeb\001" + "\002\000\020\003\uff97\011\007\012\012\016\uff97\026\065" + "\035\014\036\uff97\001\002\000\004\011\061\001\002\000" + "\042\003\034\006\026\007\027\010\040\011\036\012\022" + "\013\042\014\030\015\017\016\015\026\033\027\023\030" + "\035\031\041\035\025\036\016\001\002\000\042\003\uff9a" + "\006\uff9a\007\uff9a\010\uff9a\011\uff9a\012\uff9a\013\uff9a\014" + "\uff9a\015\uff9a\016\uff9a\026\uff9a\027\uff9a\030\uff9a\031\uff9a" + "\035\uff9a\036\uff9a\001\002\000\022\003\uffa1\017\uffa1\022" + "\uffa1\025\uffa1\032\uffa1\033\uffa1\036\uffa1\037\uffa1\001\002" + "\000\014\017\uffb1\020\uffb1\022\uffab\033\uffab\036\uffab\001" + "\002\000\022\003\uffa2\017\uffa2\022\uffa2\025\uffa2\032\uffa2" + "\033\uffa2\036\uffa2\037\uffa2\001\002\000\006\017\uffe0\020" + "\055\001\002\000\010\022\051\033\uffb4\036\uffb4\001\002" + "\000\022\003\uffa6\017\uffa6\022\uffa6\025\uffa6\032\uffa6\033" + "\uffa6\036\uffa6\037\uffa6\001\002\000\022\003\uff9f\017\uff9f" + "\022\uff9f\025\uff9f\032\uff9f\033\uff9f\036\uff9f\037\uff9f\001" + "\002\000\006\033\047\036\045\001\002\000\022\003\uffa5" + "\017\uffa5\022\uffa5\025\uffa5\032\uffa5\033\uffa5\036\uffa5\037" + "\uffa5\001\002\000\022\003\uffaa\017\uffaa\022\uffaa\025\uffaa" + "\032\uffaa\033\uffaa\036\uffaa\037\uffaa\001\002\000\022\003" + "\uffa9\017\uffa9\022\uffa9\025\uffa9\032\uffa9\033\uffa9\036\uffa9" + "\037\uffa9\001\002\000\022\003\uffa3\017\uffa3\022\uffa3\025" + "\uffa3\032\uffa3\033\uffa3\036\uffa3\037\uffa3\001\002\000\012" + "\017\uffb7\022\uffb7\033\uffb7\036\uffb7\001\002\000\020\003" + "\uffe7\011\uffe7\012\uffe7\016\uffe7\026\uffe7\035\uffe7\036\uffe7" + "\001\002\000\022\003\uffa0\017\uffa0\022\uffa0\025\uffa0\032" + "\uffa0\033\uffa0\036\uffa0\037\uffa0\001\002\000\012\017\uffe4" + "\022\uff9c\033\uff9c\036\uff9c\001\002\000\022\003\uff9e\017" + "\uff9e\022\uff9e\025\uff9e\032\uff9e\033\uff9e\036\uff9e\037\uff9e" + "\001\002\000\022\003\uffa7\017\uffa7\022\uffa7\025\uffa7\032" + "\uffa7\033\uffa7\036\uffa7\037\uffa7\001\002\000\006\017\uffdb" + "\020\uffdb\001\002\000\022\003\uffa8\017\uffa8\022\uffa8\025" + "\uffa8\032\uffa8\033\uffa8\036\uffa8\037\uffa8\001\002\000\022" + "\003\uff9d\017\uff9d\022\uff9d\025\uff9d\032\uff9d\033\uff9d\036" + "\uff9d\037\uff9d\001\002\000\022\003\uffa4\017\uffa4\022\uffa4" + "\025\uffa4\032\uffa4\033\uffa4\036\uffa4\037\uffa4\001\002\000" + "\004\017\044\001\002\000\020\003\uffe3\011\uffe3\012\uffe3" + "\016\uffe3\026\uffe3\035\uffe3\036\uffe3\001\002\000\006\017" + "\uffb1\020\uffb1\001\002\000\020\003\uffe8\011\uffe8\012\uffe8" + "\016\uffe8\026\uffe8\035\uffe8\036\uffe8\001\002\000\004\034" + "\050\001\002\000\006\033\uffb3\036\uffb3\001\002\000\042" + "\003\054\006\026\007\027\010\040\011\036\012\022\013" + "\042\014\030\015\017\016\015\026\033\027\023\030\035" + "\031\041\035\025\036\053\001\002\000\012\017\uffb8\022" + "\uffb8\033\uffb8\036\uffb8\001\002\000\022\003\uffab\017\uffab" + "\022\uffab\025\uffab\032\uffab\033\uffab\036\uffab\037\uffab\001" + "\002\000\022\003\uff9c\017\uff9c\022\uff9c\025\uff9c\032\uff9c" + "\033\uff9c\036\uff9c\037\uff9c\001\002\000\004\036\045\001" + "\002\000\004\017\057\001\002\000\020\003\uffdf\011\uffdf" + "\012\uffdf\016\uffdf\026\uffdf\035\uffdf\036\uffdf\001\002\000" + "\006\017\uffdc\020\uffdc\001\002\000\042\003\uff9b\006\uff9b" + "\007\uff9b\010\uff9b\011\uff9b\012\uff9b\013\uff9b\014\uff9b\015" + "\uff9b\016\uff9b\026\uff9b\027\uff9b\030\uff9b\031\uff9b\035\uff9b" + "\036\uff9b\001\002\000\010\003\uff97\016\116\036\uff97\001" + "\002\000\012\003\uffda\016\uffda\026\065\036\uffda\001\002" + "\000\010\003\uffd9\016\uffd9\036\uffd9\001\002\000\010\027" + "\071\030\072\031\070\001\002\000\020\003\uffec\011\uffec" + "\012\uffec\016\uffec\026\uffec\035\uffec\036\uffec\001\002\000" + "\012\003\uffd7\016\uffd7\026\uffd7\036\uffd7\001\002\000\006" + "\003\uffd2\036\uffd2\001\002\000\006\003\uffd6\036\uffd6\001" + "\002\000\006\003\uffd4\036\uffd4\001\002\000\006\003\077" + "\036\074\001\002\000\022\003\uffae\017\uffae\020\uffae\023" + "\uffae\025\uffae\032\uffae\036\uffae\037\uffae\001\002\000\010" + "\017\uffcd\020\uffcd\025\uffcd\001\002\000\006\017\uffce\020" + "\uffce\001\002\000\022\003\uffad\017\uffad\020\uffad\023\uffad" + "\025\uffad\032\uffad\036\uffad\037\uffad\001\002\000\006\017" + "\102\020\103\001\002\000\006\017\uffcf\020\uffcf\001\002" + "\000\012\003\uffd3\016\uffd3\026\uffd3\036\uffd3\001\002\000" + "\006\003\077\036\074\001\002\000\006\017\uffd0\020\uffd0" + "\001\002\000\006\003\077\036\074\001\002\000\006\017" + "\107\020\103\001\002\000\012\003\uffd5\016\uffd5\026\uffd5" + "\036\uffd5\001\002\000\006\003\077\036\074\001\002\000" + "\006\017\112\020\103\001\002\000\012\003\uffd1\016\uffd1" + "\026\uffd1\036\uffd1\001\002\000\012\003\uffd8\016\uffd8\026" + "\uffd8\036\uffd8\001\002\000\006\003\uffca\036\uffca\001\002" + "\000\006\003\126\036\120\001\002\000\004\015\117\001" + "\002\000\006\003\122\036\120\001\002\000\006\017\uffb0" + "\024\uffb0\001\002\000\004\017\uffcc\001\002\000\004\017" + "\uffaf\001\002\000\004\017\124\001\002\000\006\003\uffcb" + "\036\uffcb\001\002\000\004\024\uffc7\001\002\000\006\017" + "\uffc4\024\uffaf\001\002\000\010\002\ufffe\003\126\036\120" + "\001\002\000\010\002\uffc8\003\uffc8\036\uffc8\001\002\000" + "\010\002\uffc9\003\uffc9\036\uffc9\001\002\000\004\017\133" + "\001\002\000\010\002\uffc3\003\uffc3\036\uffc3\001\002\000" + "\004\024\135\001\002\000\016\003\uffc6\017\uffc6\025\uffc6" + "\032\uffc6\036\uffc6\037\uffc6\001\002\000\016\003\uff97\017" + "\uff97\025\uff97\032\uff97\036\uff97\037\uff97\001\002\000\016" + "\003\uffbd\017\uffbd\025\uffbd\032\uffbd\036\uffbd\037\uffbd\001" + "\002\000\016\003\077\017\uffbf\025\uffbf\032\147\036\074" + "\037\146\001\002\000\006\017\uffc1\025\uffc1\001\002\000" + "\006\017\143\025\144\001\002\000\010\002\uffc5\003\uffc5" + "\036\uffc5\001\002\000\016\003\uff97\017\uff97\025\uff97\032" + "\uff97\036\uff97\037\uff97\001\002\000\006\017\uffc2\025\uffc2" + "\001\002\000\016\003\uffbb\017\uffbb\025\uffbb\032\uffbb\036" + "\uffbb\037\uffbb\001\002\000\006\003\077\036\074\001\002" + "\000\020\003\uff97\017\uff97\023\154\025\uff97\032\uff97\036" + "\uff97\037\uff97\001\002\000\016\003\uffbe\017\uffbe\025\uffbe" + "\032\uffbe\036\uffbe\037\uffbe\001\002\000\016\003\uffb9\017" + "\uffb9\025\uffb9\032\uffb9\036\uffb9\037\uffb9\001\002\000\016" + "\003\uffbc\017\uffbc\025\uffbc\032\uffbc\036\uffbc\037\uffbc\001" + "\002\000\042\003\054\006\026\007\027\010\040\011\036" + "\012\022\013\042\014\030\015\017\016\015\026\033\027" + "\023\030\035\031\041\035\025\036\053\001\002\000\016" + "\003\uffba\017\uffba\025\uffba\032\uffba\036\uffba\037\uffba\001" + "\002\000\016\003\uffac\017\uffac\025\uffac\032\uffac\036\uffac" + "\037\uffac\001\002\000\006\017\uffc0\025\uffc0\001\002\000" + "\014\017\uffb2\020\uffb2\022\uffab\033\uffab\036\uffab\001\002" + "\000\006\033\047\036\170\001\002\000\006\017\uffdd\020" + "\uffdd\001\002\000\012\017\uffe6\022\uff9c\033\uff9c\036\uff9c" + "\001\002\000\020\003\uffe9\011\uffe9\012\uffe9\016\uffe9\026" + "\uffe9\035\uffe9\036\uffe9\001\002\000\006\017\uffe2\020\167" + "\001\002\000\004\017\172\001\002\000\004\036\170\001" + "\002\000\006\017\uffb2\020\uffb2\001\002\000\006\017\uffde" + "\020\uffde\001\002\000\020\003\uffe1\011\uffe1\012\uffe1\016" + "\uffe1\026\uffe1\035\uffe1\036\uffe1\001\002\000\004\017\174" + "\001\002\000\020\003\uffe5\011\uffe5\012\uffe5\016\uffe5\026" + "\uffe5\035\uffe5\036\uffe5\001\002\000\020\003\uffea\011\uffea" + "\012\uffea\016\uffea\026\uffea\035\uffea\036\uffea\001\002\000" + "\022\005\ufffb\007\ufffb\010\ufffb\011\ufffb\012\ufffb\013\ufffb" + "\014\ufffb\035\ufffb\001\002\000\022\005\uff97\007\uff97\010" + "\uff97\011\uff97\012\uff97\013\uff97\014\uff97\035\uff97\001\002" + "\000\042\003\054\006\026\007\027\010\040\011\036\012" + "\022\013\042\014\030\015\017\016\015\026\033\027\023" + "\030\035\031\041\035\025\036\053\001\002\000\006\017" + "\ufffd\022\051\001\002\000\004\017\203\001\002\000\022" + "\005\ufffc\007\ufffc\010\ufffc\011\ufffc\012\ufffc\013\ufffc\014" + "\ufffc\035\ufffc\001\002\000\022\005\210\007\ufff2\010\ufff2" + "\011\ufff2\012\ufff2\013\ufff2\014\ufff2\035\ufff2\001\002\000" + "\022\005\ufff9\007\ufff9\010\ufff9\011\ufff9\012\ufff9\013\ufff9" + "\014\ufff9\035\ufff9\001\002\000\020\007\223\010\224\011" + "\007\012\012\013\227\014\225\035\014\001\002\000\022" + "\005\ufffa\007\ufffa\010\ufffa\011\ufffa\012\ufffa\013\ufffa\014" + "\ufffa\035\ufffa\001\002\000\042\003\054\006\026\007\027" + "\010\040\011\036\012\022\013\042\014\030\015\017\016" + "\015\026\033\027\023\030\035\031\041\035\025\036\053" + "\001\002\000\006\017\uffb5\022\215\001\002\000\004\017" + "\ufff8\001\002\000\004\017\214\001\002\000\022\005\ufff7" + "\007\ufff7\010\ufff7\011\ufff7\012\ufff7\013\ufff7\014\ufff7\035" + "\ufff7\001\002\000\044\003\054\006\026\007\027\010\040" + "\011\036\012\022\013\042\014\030\015\017\016\015\021" + "\216\026\033\027\023\030\035\031\041\035\025\036\053" + "\001\002\000\004\017\uffb6\001\002\000\020\007\ufff3\010" + "\ufff3\011\ufff3\012\ufff3\013\ufff3\014\ufff3\035\ufff3\001\002" + "\000\020\007\ufff5\010\ufff5\011\ufff5\012\ufff5\013\ufff5\014" + "\ufff5\035\ufff5\001\002\000\020\007\ufff1\010\ufff1\011\ufff1" + "\012\ufff1\013\ufff1\014\ufff1\035\ufff1\001\002\000\020\007" + "\ufff4\010\ufff4\011\ufff4\012\ufff4\013\ufff4\014\ufff4\035\ufff4" + "\001\002\000\004\006\246\001\002\000\004\006\243\001" + "\002\000\004\015\240\001\002\000\020\007\ufff6\010\ufff6" + "\011\ufff6\012\ufff6\013\ufff6\014\ufff6\035\ufff6\001\002\000" + "\004\015\234\001\002\000\020\003\uff97\011\007\012\012" + "\016\uff97\026\065\035\014\036\uff97\001\002\000\010\003" + "\uff97\016\116\036\uff97\001\002\000\006\003\126\036\120" + "\001\002\000\010\002\uffff\003\126\036\120\001\002\000" + "\004\037\235\001\002\000\022\007\uff99\010\uff99\011\uff99" + "\012\uff99\013\uff99\014\uff99\017\236\035\uff99\001\002\000" + "\020\007\uff98\010\uff98\011\uff98\012\uff98\013\uff98\014\uff98" + "\035\uff98\001\002\000\020\007\uffee\010\uffee\011\uffee\012" + "\uffee\013\uffee\014\uffee\035\uffee\001\002\000\004\037\241" + "\001\002\000\022\007\uff99\010\uff99\011\uff99\012\uff99\013" + "\uff99\014\uff99\017\236\035\uff99\001\002\000\020\007\uffed" + "\010\uffed\011\uffed\012\uffed\013\uffed\014\uffed\035\uffed\001" + "\002\000\004\037\244\001\002\000\022\007\uff99\010\uff99" + "\011\uff99\012\uff99\013\uff99\014\uff99\017\236\035\uff99\001" + "\002\000\020\007\uffef\010\uffef\011\uffef\012\uffef\013\uffef" + "\014\uffef\035\uffef\001\002\000\004\037\247\001\002\000" + "\022\007\uff99\010\uff99\011\uff99\012\uff99\013\uff99\014\uff99" + "\017\236\035\uff99\001\002\000\020\007\ufff0\010\ufff0\011" + "\ufff0\012\ufff0\013\ufff0\014\ufff0\035\ufff0\001\002\000\004" + "\002\001\001\002" }); /** Access to parse-action table. */ public short[][] action_table() {return _action_table;} /** <code>reduce_goto</code> table. */ protected static final short[][] _reduce_table = unpackFromStrings(new String[] { "\000\247\000\006\003\003\055\004\001\001\000\002\001" + "\001\000\006\004\176\037\175\001\001\000\010\012\012" + "\014\010\024\007\001\001\000\016\017\020\025\160\026" + "\164\033\161\044\163\054\030\001\001\000\002\001\001" + "\000\016\012\012\024\065\037\063\040\061\041\066\043" + "\062\001\001\000\002\001\001\000\016\017\020\025\023" + "\027\017\034\036\045\031\054\030\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\004\063\055\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\010\027\017\034\036\045\045" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\002\001\001\000\004\061\042\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\002\001\001\000\002\001\001\000\002\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\002" + "\001\001\000\002\001\001\000\004\054\051\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\004" + "\034\057\001\001\000\002\001\001\000\002\001\001\000" + "\002\001\001\000\002\001\001\000\006\015\114\037\113" + "\001\001\000\004\041\112\001\001\000\002\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\004" + "\066\107\001\001\000\004\064\104\001\001\000\004\065" + "\072\001\001\000\012\042\077\047\074\052\100\053\075" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\002\001\001\000\010\047\074\052\103\053\075\001" + "\001\000\002\001\001\000\012\042\105\047\074\052\100" + "\053\075\001\001\000\002\001\001\000\002\001\001\000" + "\012\042\110\047\074\052\100\053\075\001\001\000\002" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\010\016\126\030\127\046\124\001\001\000\002" + "\001\001\000\004\046\120\001\001\000\002\001\001\000" + "\004\067\122\001\001\000\002\001\001\000\002\001\001" + "\000\002\001\001\000\004\070\133\001\001\000\004\072" + "\131\001\001\000\006\030\130\046\124\001\001\000\002" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\004\071\135\001\001\000\012" + "\031\137\035\141\036\140\037\136\001\001\000\002\001" + "\001\000\006\032\150\047\147\001\001\000\002\001\001" + "\000\002\001\001\000\002\001\001\000\010\031\137\036" + "\144\037\136\001\001\000\002\001\001\000\002\001\001" + "\000\006\047\074\053\156\001\001\000\006\037\151\051" + "\152\001\001\000\002\001\001\000\002\001\001\000\002" + "\001\001\000\006\050\154\054\155\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\010\026\164\033\161\044\174\001\001\000\002\001" + "\001\000\004\060\172\001\001\000\002\001\001\000\004" + "\062\165\001\001\000\002\001\001\000\004\033\170\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\002\001\001\000\002\001\001\000\002\001\001\000" + "\002\001\001\000\006\005\203\037\204\001\001\000\006" + "\017\200\054\030\001\001\000\004\056\201\001\001\000" + "\002\001\001\000\002\001\001\000\006\007\205\020\206" + "\001\001\000\002\001\001\000\022\006\225\010\220\012" + "\012\013\217\014\227\022\221\023\216\024\007\001\001" + "\000\002\001\001\000\010\017\210\021\211\054\030\001" + "\001\000\002\001\001\000\004\057\212\001\001\000\002" + "\001\001\000\002\001\001\000\004\054\051\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\002" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\016\012\012\024\065\037\063\040\230\041\066\043" + "\062\001\001\000\006\015\231\037\113\001\001\000\010" + "\016\232\030\127\046\124\001\001\000\006\030\130\046" + "\124\001\001\000\002\001\001\000\004\011\236\001\001" + "\000\002\001\001\000\002\001\001\000\002\001\001\000" + "\004\011\241\001\001\000\002\001\001\000\002\001\001" + "\000\004\011\244\001\001\000\002\001\001\000\002\001" + "\001\000\004\011\247\001\001\000\002\001\001\000\002" + "\001\001" }); /** Access to <code>reduce_goto</code> table. */ public short[][] reduce_table() {return _reduce_table;} /** Instance of action encapsulation class. */ protected CUP$parser$actions action_obj; /** Action encapsulation object initializer. */ protected void init_actions() { action_obj = new CUP$parser$actions(this); } /** Invoke a user supplied parse action. */ public java_cup.runtime.Symbol do_action( int act_num, java_cup.runtime.lr_parser parser, java.util.Stack stack, int top) throws java.lang.Exception { /* call code in generated class */ return action_obj.CUP$parser$do_action(act_num, parser, stack, top); } /** Indicates start state. */ public int start_state() {return 0;} /** Indicates start production. */ public int start_production() {return 0;} /** <code>EOF</code> Symbol index. */ public int EOF_sym() {return 0;} /** <code>error</code> Symbol index. */ public int error_sym() {return 1;} /** User initialization code. */ public void user_init() throws java.lang.Exception { lexer.init(); } /** Scan to get the next Symbol. */ public java_cup.runtime.Symbol scan() throws java.lang.Exception { return lexer.next_token(); } /* override error routines */ public void report_fatal_error( String message, Object info) { done_parsing(); lexer.emit_error(message); System.err.println("Can't recover from previous error(s), giving up."); System.exit(1); } public void report_error(String message, Object info) { lexer.emit_error(message); } } /** Cup generated class to encapsulate user supplied action code.*/ class CUP$parser$actions { /** helper routine to clone a new production part adding a given label */ protected production_part add_lab(production_part part, String lab) throws internal_error { /* if there is no label, or this is an action, just return the original */ if (lab == null || part.is_action()) return part; /* otherwise build a new one with the given label attached */ return new symbol_part(((symbol_part)part).the_symbol(),lab); } /** max size of right hand side we will support */ protected final int MAX_RHS = 200; /** array for accumulating right hand side parts */ protected production_part[] rhs_parts = new production_part[MAX_RHS]; /** where we are currently in building a right hand side */ protected int rhs_pos = 0; /** start a new right hand side */ protected void new_rhs() {rhs_pos = 0; } /** add a new right hand side part */ protected void add_rhs_part(production_part part) throws java.lang.Exception { if (rhs_pos >= MAX_RHS) throw new Exception("Internal Error: Productions limited to " + MAX_RHS + " symbols and actions"); rhs_parts[rhs_pos] = part; rhs_pos++; } /** string to build up multiple part names */ protected String multipart_name = new String(); /** append a new name segment to the accumulated multipart name */ protected void append_multipart(String name) { String dot = ""; /* if we aren't just starting out, put on a dot */ if (multipart_name.length() != 0) dot = "."; multipart_name = multipart_name.concat(dot + name); } /** table of declared symbols -- contains production parts indexed by name */ protected Hashtable symbols = new Hashtable(); /** table of just non terminals -- contains non_terminals indexed by name */ protected Hashtable non_terms = new Hashtable(); /** declared start non_terminal */ protected non_terminal start_nt = null; /** left hand side non terminal of the current production */ protected non_terminal lhs_nt; /** Current precedence number */ int _cur_prec = 0; /** Current precedence side */ int _cur_side = assoc.no_prec; /** update the precedences we are declaring */ protected void update_precedence(int p) { _cur_side = p; _cur_prec++; } /** add relevant data to terminals */ protected void add_precedence(String term) { if (term == null) { System.err.println("Unable to add precedence to nonexistent terminal"); } else { symbol_part sp = (symbol_part)symbols.get(term); if (sp == null) { System.err.println("Could find terminal " + term + " while declaring precedence"); } else { java_cup.symbol sym = sp.the_symbol(); if (sym instanceof terminal) ((terminal)sym).set_precedence(_cur_side, _cur_prec); else System.err.println("Precedence declaration: Can't find terminal " + term); } } } private final parser parser; /** Constructor */ CUP$parser$actions(parser parser) { this.parser = parser; } /** Method with the actual generated action code. */ public final java_cup.runtime.Symbol CUP$parser$do_action( int CUP$parser$act_num, java_cup.runtime.lr_parser CUP$parser$parser, java.util.Stack CUP$parser$stack, int CUP$parser$top) throws java.lang.Exception { /* Symbol object for return from actions */ java_cup.runtime.Symbol CUP$parser$result; /* select the action based on the action number */ switch (CUP$parser$act_num) { /*. . . . . . . . . . . . . . . . . . . .*/ case 106: // empty ::= { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(29/*empty*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 105: // opt_semi ::= SEMI { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(7/*opt_semi*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 104: // opt_semi ::= { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(7/*opt_semi*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 103: // non_terminal ::= NONTERMINAL { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(8/*non_terminal*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 102: // non_terminal ::= NON TERMINAL { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(8/*non_terminal*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 101: // robust_id ::= error { String RESULT = null; lexer.emit_error("Illegal use of reserved word"); RESULT="ILLEGAL"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 100: // robust_id ::= NONASSOC { String RESULT = null; RESULT = "nonassoc"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 99: // robust_id ::= RIGHT { String RESULT = null; RESULT = "right"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 98: // robust_id ::= LEFT { String RESULT = null; RESULT = "left"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 97: // robust_id ::= PRECEDENCE { String RESULT = null; RESULT = "precedence"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 96: // robust_id ::= START { String RESULT = null; RESULT = "start"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 95: // robust_id ::= WITH { String RESULT = null; RESULT = "with"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 94: // robust_id ::= SCAN { String RESULT = null; RESULT = "scan"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 93: // robust_id ::= INIT { String RESULT = null; RESULT = "init"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 92: // robust_id ::= NONTERMINAL { String RESULT = null; RESULT = "nonterminal"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 91: // robust_id ::= NON { String RESULT = null; RESULT = "non"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 90: // robust_id ::= TERMINAL { String RESULT = null; RESULT = "terminal"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 89: // robust_id ::= PARSER { String RESULT = null; RESULT = "parser"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 88: // robust_id ::= ACTION { String RESULT = null; RESULT = "action"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 87: // robust_id ::= CODE { String RESULT = null; RESULT = "code"; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 86: // robust_id ::= ID { String RESULT = null; int the_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int the_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String the_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; RESULT = the_id; CUP$parser$result = new java_cup.runtime.Symbol(42/*robust_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 85: // label_id ::= robust_id { String RESULT = null; int the_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int the_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String the_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; RESULT = the_id; CUP$parser$result = new java_cup.runtime.Symbol(38/*label_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 84: // symbol_id ::= error { String RESULT = null; lexer.emit_error("Illegal use of reserved word"); RESULT="ILLEGAL"; CUP$parser$result = new java_cup.runtime.Symbol(37/*symbol_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 83: // symbol_id ::= ID { String RESULT = null; int the_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int the_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String the_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; RESULT = the_id; CUP$parser$result = new java_cup.runtime.Symbol(37/*symbol_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 82: // nt_id ::= error { String RESULT = null; lexer.emit_error("Illegal use of reserved word"); RESULT="ILLEGAL"; CUP$parser$result = new java_cup.runtime.Symbol(36/*nt_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 81: // nt_id ::= ID { String RESULT = null; int the_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int the_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String the_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; RESULT = the_id; CUP$parser$result = new java_cup.runtime.Symbol(36/*nt_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 80: // new_non_term_id ::= ID { Object RESULT = null; int non_term_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int non_term_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String non_term_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* see if this non terminal has been declared before */ if (symbols.get(non_term_id) != null) { /* issue a message */ lexer.emit_error( "java_cup.runtime.Symbol \"" + non_term_id + "\" has already been declared"); } else { if (multipart_name.equals("")) { append_multipart("Object"); } /* build the non terminal object */ non_terminal this_nt = new non_terminal(non_term_id, multipart_name); /* put it in the non_terms table */ non_terms.put(non_term_id, this_nt); /* build a production_part and put it in the symbols table */ symbols.put(non_term_id, new symbol_part(this_nt)); } CUP$parser$result = new java_cup.runtime.Symbol(26/*new_non_term_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 79: // new_term_id ::= ID { Object RESULT = null; int term_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int term_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String term_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* see if this terminal has been declared before */ if (symbols.get(term_id) != null) { /* issue a message */ lexer.emit_error("java_cup.runtime.Symbol \"" + term_id + "\" has already been declared"); } else { /* if no type declared, declare one */ if (multipart_name.equals("")) { append_multipart("Object"); } /* build a production_part and put it in the table */ symbols.put(term_id, new symbol_part(new terminal(term_id, multipart_name))); } CUP$parser$result = new java_cup.runtime.Symbol(25/*new_term_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 78: // type_id ::= type_id LBRACK RBRACK { Object RESULT = null; multipart_name = multipart_name.concat("[]"); CUP$parser$result = new java_cup.runtime.Symbol(19/*type_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 77: // type_id ::= multipart_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(19/*type_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 76: // import_id ::= multipart_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(15/*import_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 75: // import_id ::= multipart_id DOT STAR { Object RESULT = null; append_multipart("*"); CUP$parser$result = new java_cup.runtime.Symbol(15/*import_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 74: // multipart_id ::= robust_id { Object RESULT = null; int an_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int an_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String an_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; append_multipart(an_id); CUP$parser$result = new java_cup.runtime.Symbol(13/*multipart_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 73: // multipart_id ::= multipart_id DOT robust_id { Object RESULT = null; int another_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int another_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String another_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; append_multipart(another_id); CUP$parser$result = new java_cup.runtime.Symbol(13/*multipart_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 72: // opt_label ::= empty { String RESULT = null; RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(39/*opt_label*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 71: // opt_label ::= COLON label_id { String RESULT = null; int labidleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int labidright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String labid = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; RESULT = labid; CUP$parser$result = new java_cup.runtime.Symbol(39/*opt_label*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 70: // prod_part ::= CODE_STRING { Object RESULT = null; int code_strleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int code_strright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String code_str = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* add a new production part */ add_rhs_part(new action_part(code_str)); CUP$parser$result = new java_cup.runtime.Symbol(24/*prod_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 69: // prod_part ::= symbol_id opt_label { Object RESULT = null; int symidleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; int symidright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; String symid = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; int labidleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int labidright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String labid = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* try to look up the id */ production_part symb = (production_part)symbols.get(symid); /* if that fails, symbol is undeclared */ if (symb == null) { if (lexer.error_count == 0) lexer.emit_error("java_cup.runtime.Symbol \"" + symid + "\" has not been declared"); } else { /* add a labeled production part */ add_rhs_part(add_lab(symb, labid)); } CUP$parser$result = new java_cup.runtime.Symbol(24/*prod_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 68: // prod_part_list ::= empty { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(23/*prod_part_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 67: // prod_part_list ::= prod_part_list prod_part { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(23/*prod_part_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 66: // rhs ::= prod_part_list { Object RESULT = null; if (lhs_nt != null) { /* build the production */ production p = new production(lhs_nt, rhs_parts, rhs_pos); /* if we have no start non-terminal declared and this is the first production, make its lhs nt the start_nt and build a special start production for it. */ if (start_nt == null) { start_nt = lhs_nt; /* build a special start production */ new_rhs(); add_rhs_part(add_lab(new symbol_part(start_nt),"start_val")); add_rhs_part(new symbol_part(terminal.EOF)); add_rhs_part(new action_part("RESULT = start_val;")); emit.start_production = new production(non_terminal.START_nt, rhs_parts, rhs_pos); new_rhs(); } } /* reset the rhs accumulation in any case */ new_rhs(); CUP$parser$result = new java_cup.runtime.Symbol(28/*rhs*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 65: // rhs ::= prod_part_list PERCENT_PREC term_id { Object RESULT = null; int term_nameleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int term_nameright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String term_name = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; java_cup.symbol sym = null; if (lhs_nt != null) { /* Find the precedence symbol */ if (term_name == null) { System.err.println("No terminal for contextual precedence"); sym = null; } else { sym = ((symbol_part)symbols.get(term_name)).the_symbol(); } /* build the production */ production p; if ((sym!=null) && (sym instanceof terminal)) { p = new production(lhs_nt, rhs_parts, rhs_pos, ((terminal)sym).precedence_num(), ((terminal)sym).precedence_side()); ((symbol_part)symbols.get(term_name)).the_symbol().note_use(); } else { System.err.println("Invalid terminal " + term_name + " for contextual precedence assignment"); p = new production(lhs_nt, rhs_parts, rhs_pos); } /* if we have no start non-terminal declared and this is the first production, make its lhs nt the start_nt and build a special start production for it. */ if (start_nt == null) { start_nt = lhs_nt; /* build a special start production */ new_rhs(); add_rhs_part(add_lab(new symbol_part(start_nt),"start_val")); add_rhs_part(new symbol_part(terminal.EOF)); add_rhs_part(new action_part("RESULT = start_val;")); if ((sym!=null) && (sym instanceof terminal)) { emit.start_production = new production(non_terminal.START_nt, rhs_parts, rhs_pos, ((terminal)sym).precedence_num(), ((terminal)sym).precedence_side()); } else { emit.start_production = new production(non_terminal.START_nt, rhs_parts, rhs_pos); } new_rhs(); } } /* reset the rhs accumulation in any case */ new_rhs(); CUP$parser$result = new java_cup.runtime.Symbol(28/*rhs*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 64: // rhs_list ::= rhs { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(27/*rhs_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 63: // rhs_list ::= rhs_list BAR rhs { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(27/*rhs_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 62: // production ::= error NT$13 SEMI { Object RESULT = null; // propagate RESULT from NT$13 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(22/*production*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 61: // NT$13 ::= { Object RESULT = null; lexer.emit_error("Syntax Error"); CUP$parser$result = new java_cup.runtime.Symbol(56/*NT$13*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 60: // production ::= nt_id NT$11 COLON_COLON_EQUALS NT$12 rhs_list SEMI { Object RESULT = null; // propagate RESULT from NT$11 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-4)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-4)).value; // propagate RESULT from NT$12 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; int lhs_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).left; int lhs_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).right; String lhs_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-5)).value; CUP$parser$result = new java_cup.runtime.Symbol(22/*production*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 59: // NT$12 ::= { Object RESULT = null; int lhs_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; int lhs_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; String lhs_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; CUP$parser$result = new java_cup.runtime.Symbol(55/*NT$12*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 58: // NT$11 ::= { Object RESULT = null; int lhs_idleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int lhs_idright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String lhs_id = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* lookup the lhs nt */ lhs_nt = (non_terminal)non_terms.get(lhs_id); /* if it wasn't declared, emit a message */ if (lhs_nt == null) { if (lexer.error_count == 0) lexer.emit_error("LHS non terminal \"" + lhs_id + "\" has not been declared"); } /* reset the rhs accumulation */ new_rhs(); CUP$parser$result = new java_cup.runtime.Symbol(54/*NT$11*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 57: // production_list ::= production { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(12/*production_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 56: // production_list ::= production_list production { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(12/*production_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 55: // start_spec ::= empty { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(11/*start_spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 54: // start_spec ::= START WITH nt_id NT$10 SEMI { Object RESULT = null; // propagate RESULT from NT$10 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; int start_nameleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; int start_nameright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; String start_name = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; CUP$parser$result = new java_cup.runtime.Symbol(11/*start_spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 53: // NT$10 ::= { Object RESULT = null; int start_nameleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int start_nameright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String start_name = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* verify that the name has been declared as a non terminal */ non_terminal nt = (non_terminal)non_terms.get(start_name); if (nt == null) { lexer.emit_error( "Start non terminal \"" + start_name + "\" has not been declared"); } else { /* remember the non-terminal for later */ start_nt = nt; /* build a special start production */ new_rhs(); add_rhs_part(add_lab(new symbol_part(start_nt), "start_val")); add_rhs_part(new symbol_part(terminal.EOF)); add_rhs_part(new action_part("RESULT = start_val;")); emit.start_production = new production(non_terminal.START_nt, rhs_parts, rhs_pos); new_rhs(); } CUP$parser$result = new java_cup.runtime.Symbol(53/*NT$10*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 52: // term_id ::= symbol_id { String RESULT = null; int symleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int symright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String sym = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; /* check that the symbol_id is a terminal */ if (symbols.get(sym) == null) { /* issue a message */ lexer.emit_error("Terminal \"" + sym + "\" has not been declared"); } RESULT = sym; CUP$parser$result = new java_cup.runtime.Symbol(41/*term_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 51: // terminal_id ::= term_id { String RESULT = null; int symleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left; int symright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right; String sym = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-0)).value; add_precedence(sym); RESULT = sym; CUP$parser$result = new java_cup.runtime.Symbol(40/*terminal_id*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 50: // terminal_list ::= terminal_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(32/*terminal_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 49: // terminal_list ::= terminal_list COMMA terminal_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(32/*terminal_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 48: // preced ::= PRECEDENCE NONASSOC NT$9 terminal_list SEMI { Object RESULT = null; // propagate RESULT from NT$9 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; CUP$parser$result = new java_cup.runtime.Symbol(31/*preced*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 47: // NT$9 ::= { Object RESULT = null; update_precedence(assoc.nonassoc); CUP$parser$result = new java_cup.runtime.Symbol(52/*NT$9*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 46: // preced ::= PRECEDENCE RIGHT NT$8 terminal_list SEMI { Object RESULT = null; // propagate RESULT from NT$8 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; CUP$parser$result = new java_cup.runtime.Symbol(31/*preced*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 45: // NT$8 ::= { Object RESULT = null; update_precedence(assoc.right); CUP$parser$result = new java_cup.runtime.Symbol(51/*NT$8*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 44: // preced ::= PRECEDENCE LEFT NT$7 terminal_list SEMI { Object RESULT = null; // propagate RESULT from NT$7 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; CUP$parser$result = new java_cup.runtime.Symbol(31/*preced*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 43: // NT$7 ::= { Object RESULT = null; update_precedence(assoc.left); CUP$parser$result = new java_cup.runtime.Symbol(50/*NT$7*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 42: // precedence_l ::= preced { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(33/*precedence_l*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 41: // precedence_l ::= precedence_l preced { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(33/*precedence_l*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 40: // precedence_list ::= empty { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(30/*precedence_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 39: // precedence_list ::= precedence_l { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(30/*precedence_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 38: // non_term_name_list ::= new_non_term_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(21/*non_term_name_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 37: // non_term_name_list ::= non_term_name_list COMMA new_non_term_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(21/*non_term_name_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 36: // term_name_list ::= new_term_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(20/*term_name_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 35: // term_name_list ::= term_name_list COMMA new_term_id { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(20/*term_name_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 34: // declares_non_term ::= non_term_name_list NT$6 SEMI { Object RESULT = null; // propagate RESULT from NT$6 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(35/*declares_non_term*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 33: // NT$6 ::= { Object RESULT = null; /* reset the accumulated multipart name */ multipart_name = new String(); CUP$parser$result = new java_cup.runtime.Symbol(49/*NT$6*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 32: // declares_term ::= term_name_list NT$5 SEMI { Object RESULT = null; // propagate RESULT from NT$5 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(34/*declares_term*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 31: // NT$5 ::= { Object RESULT = null; /* reset the accumulated multipart name */ multipart_name = new String(); CUP$parser$result = new java_cup.runtime.Symbol(48/*NT$5*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 30: // symbol ::= non_terminal error NT$4 SEMI { Object RESULT = null; // propagate RESULT from NT$4 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(18/*symbol*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 29: // NT$4 ::= { Object RESULT = null; /* reset the accumulated multipart name */ multipart_name = new String(); CUP$parser$result = new java_cup.runtime.Symbol(47/*NT$4*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 28: // symbol ::= TERMINAL error NT$3 SEMI { Object RESULT = null; // propagate RESULT from NT$3 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(18/*symbol*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 27: // NT$3 ::= { Object RESULT = null; /* reset the accumulated multipart name */ multipart_name = new String(); CUP$parser$result = new java_cup.runtime.Symbol(46/*NT$3*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 26: // symbol ::= non_terminal declares_non_term { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(18/*symbol*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 25: // symbol ::= non_terminal type_id declares_non_term { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(18/*symbol*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 24: // symbol ::= TERMINAL declares_term { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(18/*symbol*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 23: // symbol ::= TERMINAL type_id declares_term { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(18/*symbol*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 22: // symbol_list ::= symbol { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(10/*symbol_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 21: // symbol_list ::= symbol_list symbol { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(10/*symbol_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 20: // scan_code ::= SCAN WITH CODE_STRING opt_semi { Object RESULT = null; int user_codeleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; int user_coderight = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; String user_code = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; if (emit.scan_code!=null) lexer.emit_error("Redundant scan code (skipping)"); else /* save the user code */ emit.scan_code = user_code; CUP$parser$result = new java_cup.runtime.Symbol(17/*scan_code*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 19: // init_code ::= INIT WITH CODE_STRING opt_semi { Object RESULT = null; int user_codeleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; int user_coderight = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; String user_code = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; if (emit.init_code!=null) lexer.emit_error("Redundant init code (skipping)"); else /* save the user code */ emit.init_code = user_code; CUP$parser$result = new java_cup.runtime.Symbol(16/*init_code*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 18: // parser_code_part ::= PARSER CODE CODE_STRING opt_semi { Object RESULT = null; int user_codeleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; int user_coderight = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; String user_code = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; if (emit.parser_code!=null) lexer.emit_error("Redundant parser code (skipping)"); else /* save the user included code string */ emit.parser_code = user_code; CUP$parser$result = new java_cup.runtime.Symbol(9/*parser_code_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 17: // action_code_part ::= ACTION CODE CODE_STRING opt_semi { Object RESULT = null; int user_codeleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; int user_coderight = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; String user_code = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; if (emit.action_code!=null) lexer.emit_error("Redundant action code (skipping)"); else /* save the user included code string */ emit.action_code = user_code; CUP$parser$result = new java_cup.runtime.Symbol(4/*action_code_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 16: // code_parts ::= code_parts code_part { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(5/*code_parts*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 15: // code_parts ::= { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(5/*code_parts*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 14: // code_part ::= scan_code { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(6/*code_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 13: // code_part ::= init_code { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(6/*code_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 12: // code_part ::= parser_code_part { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(6/*code_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 11: // code_part ::= action_code_part { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(6/*code_part*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 10: // import_spec ::= IMPORT import_id NT$2 SEMI { Object RESULT = null; // propagate RESULT from NT$2 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(14/*import_spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 9: // NT$2 ::= { Object RESULT = null; /* save this import on the imports list */ emit.import_list.push(multipart_name); /* reset the accumulated multipart name */ multipart_name = new String(); CUP$parser$result = new java_cup.runtime.Symbol(45/*NT$2*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 8: // import_list ::= empty { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(3/*import_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 7: // import_list ::= import_list import_spec { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(3/*import_list*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 6: // package_spec ::= empty { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(2/*package_spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 5: // package_spec ::= PACKAGE multipart_id NT$1 SEMI { Object RESULT = null; // propagate RESULT from NT$1 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; CUP$parser$result = new java_cup.runtime.Symbol(2/*package_spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 4: // NT$1 ::= { Object RESULT = null; /* save the package name */ emit.package_name = multipart_name; /* reset the accumulated multipart name */ multipart_name = new String(); CUP$parser$result = new java_cup.runtime.Symbol(44/*NT$1*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 3: // spec ::= error symbol_list precedence_list start_spec production_list { Object RESULT = null; CUP$parser$result = new java_cup.runtime.Symbol(1/*spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 2: // spec ::= NT$0 package_spec import_list code_parts symbol_list precedence_list start_spec production_list { Object RESULT = null; // propagate RESULT from NT$0 if ( ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-7)).value != null ) RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-7)).value; CUP$parser$result = new java_cup.runtime.Symbol(1/*spec*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-7)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 1: // NT$0 ::= { Object RESULT = null; /* declare "error" as a terminal */ symbols.put("error", new symbol_part(terminal.error)); /* declare start non terminal */ non_terms.put("$START", non_terminal.START_nt); CUP$parser$result = new java_cup.runtime.Symbol(43/*NT$0*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } return CUP$parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 0: // $START ::= spec EOF { Object RESULT = null; int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; RESULT = start_val; CUP$parser$result = new java_cup.runtime.Symbol(0/*$START*/, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-0)).right, RESULT); } /* ACCEPT */ CUP$parser$parser.done_parsing(); return CUP$parser$result; /* . . . . . .*/ default: throw new Exception( "Invalid action number found in internal parse table"); } } }
95,111
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
lalr_transition.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/lalr_transition.java
package java_cup; /** This class represents a transition in an LALR viable prefix recognition * machine. Transitions can be under terminals for non-terminals. They are * internally linked together into singly linked lists containing all the * transitions out of a single state via the _next field. * * @see java_cup.lalr_state * @version last updated: 11/25/95 * @author Scott Hudson * */ public class lalr_transition { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Full constructor. * @param on_sym symbol we are transitioning on. * @param to_st state we transition to. * @param nxt next transition in linked list. */ public lalr_transition(symbol on_sym, lalr_state to_st, lalr_transition nxt) throws internal_error { /* sanity checks */ if (on_sym == null) throw new internal_error("Attempt to create transition on null symbol"); if (to_st == null) throw new internal_error("Attempt to create transition to null state"); /* initialize */ _on_symbol = on_sym; _to_state = to_st; _next = nxt; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor with null next. * @param on_sym symbol we are transitioning on. * @param to_st state we transition to. */ public lalr_transition(symbol on_sym, lalr_state to_st) throws internal_error { this(on_sym, to_st, null); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The symbol we make the transition on. */ protected symbol _on_symbol; /** The symbol we make the transition on. */ public symbol on_symbol() {return _on_symbol;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The state we transition to. */ protected lalr_state _to_state; /** The state we transition to. */ public lalr_state to_state() {return _to_state;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Next transition in linked list of transitions out of a state */ protected lalr_transition _next; /** Next transition in linked list of transitions out of a state */ public lalr_transition next() {return _next;} /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Convert to a string. */ public String toString() { String result; result = "transition on " + on_symbol().name() + " to state ["; result += _to_state.index(); result += "]"; return result; } /*-----------------------------------------------------------*/ }
3,088
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
lr_item_core.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/lr_item_core.java
package java_cup; /** The "core" of an LR item. This includes a production and the position * of a marker (the "dot") within the production. Typically item cores * are written using a production with an embedded "dot" to indicate their * position. For example: <pre> * A ::= B * C d E * </pre> * This represents a point in a parse where the parser is trying to match * the given production, and has succeeded in matching everything before the * "dot" (and hence is expecting to see the symbols after the dot next). See * lalr_item, lalr_item_set, and lalr_start for full details on the meaning * and use of items. * * @see java_cup.lalr_item * @see java_cup.lalr_item_set * @see java_cup.lalr_state * @version last updated: 11/25/95 * @author Scott Hudson */ public class lr_item_core { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Full constructor. * @param prod production this item uses. * @param pos position of the "dot" within the item. */ public lr_item_core(production prod, int pos) throws internal_error { symbol after_dot = null; production_part part; if (prod == null) throw new internal_error( "Attempt to create an lr_item_core with a null production"); _the_production = prod; if (pos < 0 || pos > _the_production.rhs_length()) throw new internal_error( "Attempt to create an lr_item_core with a bad dot position"); _dot_pos = pos; /* compute and cache hash code now */ _core_hash_cache = 13*_the_production.hashCode() + pos; /* cache the symbol after the dot */ if (_dot_pos < _the_production.rhs_length()) { part = _the_production.rhs(_dot_pos); if (!part.is_action()) _symbol_after_dot = ((symbol_part)part).the_symbol(); } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor for dot at start of right hand side. * @param prod production this item uses. */ public lr_item_core(production prod) throws internal_error { this(prod,0); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The production for the item. */ protected production _the_production; /** The production for the item. */ public production the_production() {return _the_production;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The position of the "dot" -- this indicates the part of the production * that the marker is before, so 0 indicates a dot at the beginning of * the RHS. */ protected int _dot_pos; /** The position of the "dot" -- this indicates the part of the production * that the marker is before, so 0 indicates a dot at the beginning of * the RHS. */ public int dot_pos() {return _dot_pos;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Cache of the hash code. */ protected int _core_hash_cache; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Cache of symbol after the dot. */ protected symbol _symbol_after_dot = null; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Is the dot at the end of the production? */ public boolean dot_at_end() { return _dot_pos >= _the_production.rhs_length(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Return the symbol after the dot. If there is no symbol after the dot * we return null. */ public symbol symbol_after_dot() { /* use the cached symbol */ return _symbol_after_dot; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if we have a dot before a non terminal, and if so which one * (return null or the non terminal). */ public non_terminal dot_before_nt() { symbol sym; /* get the symbol after the dot */ sym = symbol_after_dot(); /* if it exists and is a non terminal, return it */ if (sym != null && sym.is_non_term()) return (non_terminal)sym; else return null; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a new lr_item_core that results from shifting the dot one * position to the right. */ public lr_item_core shift_core() throws internal_error { if (dot_at_end()) throw new internal_error( "Attempt to shift past end of an lr_item_core"); return new lr_item_core(_the_production, _dot_pos+1); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison for the core only. This is separate out because we * need separate access in a super class. */ public boolean core_equals(lr_item_core other) { return other != null && _the_production.equals(other._the_production) && _dot_pos == other._dot_pos; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(lr_item_core other) {return core_equals(other);} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof lr_item_core)) return false; else return equals((lr_item_core)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Hash code for the core (separated so we keep non overridden version). */ public int core_hashCode() { return _core_hash_cache; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Hash code for the item. */ public int hashCode() { return _core_hash_cache; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Return the hash code that object would have provided for us so we have * a (nearly) unique id for debugging. */ protected int obj_hash() { return super.hashCode(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string (separated out from toString() so we can call it * from subclass that overrides toString()). */ public String to_simple_string() throws internal_error { String result; production_part part; if (_the_production.lhs() != null && _the_production.lhs().the_symbol() != null && _the_production.lhs().the_symbol().name() != null) result = _the_production.lhs().the_symbol().name(); else result = "$$NULL$$"; result += " ::= "; for (int i = 0; i<_the_production.rhs_length(); i++) { /* do we need the dot before this one? */ if (i == _dot_pos) result += "(*) "; /* print the name of the part */ if (_the_production.rhs(i) == null) { result += "$$NULL$$ "; } else { part = _the_production.rhs(i); if (part == null) result += "$$NULL$$ "; else if (part.is_action()) result += "{ACTION} "; else if (((symbol_part)part).the_symbol() != null && ((symbol_part)part).the_symbol().name() != null) result += ((symbol_part)part).the_symbol().name() + " "; else result += "$$NULL$$ "; } } /* put the dot after if needed */ if (_dot_pos == _the_production.rhs_length()) result += "(*) "; return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string */ public String toString() { /* can't throw here since super class doesn't, so we crash instead */ try { return to_simple_string(); } catch(internal_error e) { e.crash(); return null; } } /*-----------------------------------------------------------*/ }
8,333
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
internal_error.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/internal_error.java
package java_cup; /** Exception subclass for reporting internal errors in JavaCup. */ public class internal_error extends Exception { /** Constructor with a message */ public internal_error(String msg) { super(msg); } /** Method called to do a forced error exit on an internal error for cases when we can't actually throw the exception. */ public void crash() { System.err.println("JavaCUP Fatal Internal Error Detected"); System.err.println(getMessage()); printStackTrace(); System.exit(-1); } }
573
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
terminal_set.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/terminal_set.java
package java_cup; import java.util.BitSet; /** A set of terminals implemented as a bitset. * @version last updated: 11/25/95 * @author Scott Hudson */ public class terminal_set { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Constructor for an empty set. */ public terminal_set() { /* allocate the bitset at what is probably the right size */ _elements = new BitSet(terminal.number()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor for cloning from another set. * @param other the set we are cloning from. */ public terminal_set(terminal_set other) throws internal_error { not_null(other); _elements = (BitSet)other._elements.clone(); } /*-----------------------------------------------------------*/ /*--- (Access to) Static (Class) Variables ------------------*/ /*-----------------------------------------------------------*/ /** Constant for the empty set. */ public static final terminal_set EMPTY = new terminal_set(); /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** Bitset to implement the actual set. */ protected BitSet _elements; /*-----------------------------------------------------------*/ /*--- General Methods ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Helper function to test for a null object and throw an exception if * one is found. * @param obj the object we are testing. */ protected void not_null(Object obj) throws internal_error { if (obj == null) throw new internal_error("Null object used in set operation"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if the set is empty. */ public boolean empty() { return equals(EMPTY); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if the set contains a particular terminal. * @param sym the terminal symbol we are looking for. */ public boolean contains(terminal sym) throws internal_error { not_null(sym); return _elements.get(sym.index()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Given its index determine if the set contains a particular terminal. * @param indx the index of the terminal in question. */ public boolean contains(int indx) { return _elements.get(indx); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if this set is an (improper) subset of another. * @param other the set we are testing against. */ public boolean is_subset_of(terminal_set other) throws internal_error { not_null(other); /* make a copy of the other set */ BitSet copy_other = (BitSet)other._elements.clone(); /* and or in */ copy_other.or(_elements); /* if it hasn't changed, we were a subset */ return copy_other.equals(other._elements); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if this set is an (improper) superset of another. * @param other the set we are testing against. */ public boolean is_superset_of(terminal_set other) throws internal_error { not_null(other); return other.is_subset_of(this); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Add a single terminal to the set. * @param sym the terminal being added. * @return true if this changes the set. */ public boolean add(terminal sym) throws internal_error { boolean result; not_null(sym); /* see if we already have this */ result = _elements.get(sym.index()); /* if not we add it */ if (!result) _elements.set(sym.index()); return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Remove a terminal if it is in the set. * @param sym the terminal being removed. */ public void remove(terminal sym) throws internal_error { not_null(sym); _elements.clear(sym.index()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Add (union) in a complete set. * @param other the set being added. * @return true if this changes the set. */ public boolean add(terminal_set other) throws internal_error { not_null(other); /* make a copy */ BitSet copy = (BitSet)_elements.clone(); /* or in the other set */ _elements.or(other._elements); /* changed if we are not the same as the copy */ return !_elements.equals(copy); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if this set intersects another. * @param other the other set in question. */ public boolean intersects(terminal_set other) throws internal_error { not_null(other); /* make a copy of the other set */ BitSet copy = (BitSet)other._elements.clone(); /* xor out our values */ copy.xor(this._elements); /* see if its different */ return !copy.equals(other._elements); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(terminal_set other) { if (other == null) return false; else return _elements.equals(other._elements); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof terminal_set)) return false; else return equals((terminal_set)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to string. */ public String toString() { String result; boolean comma_flag; result = "{"; comma_flag = false; for (int t = 0; t < terminal.number(); t++) { if (_elements.get(t)) { if (comma_flag) result += ", "; else comma_flag = true; result += terminal.find(t).name(); } } result += "}"; return result; } /*-----------------------------------------------------------*/ }
6,874
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
parse_action.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/parse_action.java
package java_cup; /** This class serves as the base class for entries in a parse action table. * Full entries will either be SHIFT(state_num), REDUCE(production), NONASSOC, * or ERROR. Objects of this base class will default to ERROR, while * the other three types will be represented by subclasses. * * @see java_cup.reduce_action * @see java_cup.shift_action * @version last updated: 7/2/96 * @author Frank Flannery */ public class parse_action { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Simple constructor. */ public parse_action() { /* nothing to do in the base class */ } /*-----------------------------------------------------------*/ /*--- (Access to) Static (Class) Variables ------------------*/ /*-----------------------------------------------------------*/ /** Constant for action type -- error action. */ public static final int ERROR = 0; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constant for action type -- shift action. */ public static final int SHIFT = 1; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constants for action type -- reduce action. */ public static final int REDUCE = 2; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constants for action type -- reduce action. */ public static final int NONASSOC = 3; /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Quick access to the type -- base class defaults to error. */ public int kind() {return ERROR;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality test. */ public boolean equals(parse_action other) { /* we match all error actions */ return other != null && other.kind() == ERROR; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality test. */ public boolean equals(Object other) { if (other instanceof parse_action) return equals((parse_action)other); else return false; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Compute a hash code. */ public int hashCode() { /* all objects of this class hash together */ return 0xCafe123; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to string. */ public String toString() {return "ERROR";} /*-----------------------------------------------------------*/ }
2,867
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
lalr_state.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/lalr_state.java
package java_cup; import java.util.Hashtable; import java.util.Enumeration; import java.util.Stack; /** This class represents a state in the LALR viable prefix recognition machine. * A state consists of an LALR item set and a set of transitions to other * states under terminal and non-terminal symbols. Each state represents * a potential configuration of the parser. If the item set of a state * includes an item such as: <pre> * [A ::= B * C d E , {a,b,c}] * </pre> * this indicates that when the parser is in this state it is currently * looking for an A of the given form, has already seen the B, and would * expect to see an a, b, or c after this sequence is complete. Note that * the parser is normally looking for several things at once (represented * by several items). In our example above, the state would also include * items such as: <pre> * [C ::= * X e Z, {d}] * [X ::= * f, {e}] * </pre> * to indicate that it was currently looking for a C followed by a d (which * would be reduced into a C, matching the first symbol in our production * above), and the terminal f followed by e.<p> * * At runtime, the parser uses a viable prefix recognition machine made up * of these states to parse. The parser has two operations, shift and reduce. * In a shift, it consumes one Symbol and makes a transition to a new state. * This corresponds to "moving the dot past" a terminal in one or more items * in the state (these new shifted items will then be found in the state at * the end of the transition). For a reduce operation, the parser is * signifying that it is recognizing the RHS of some production. To do this * it first "backs up" by popping a stack of previously saved states. It * pops off the same number of states as are found in the RHS of the * production. This leaves the machine in the same state is was in when the * parser first attempted to find the RHS. From this state it makes a * transition based on the non-terminal on the LHS of the production. This * corresponds to placing the parse in a configuration equivalent to having * replaced all the symbols from the the input corresponding to the RHS with * the symbol on the LHS. * * @see java_cup.lalr_item * @see java_cup.lalr_item_set * @see java_cup.lalr_transition * @version last updated: 7/3/96 * @author Frank Flannery * */ public class lalr_state { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Constructor for building a state from a set of items. * @param itms the set of items that makes up this state. */ public lalr_state(lalr_item_set itms) throws internal_error { /* don't allow null or duplicate item sets */ if (itms == null) throw new internal_error( "Attempt to construct an LALR state from a null item set"); if (find_state(itms) != null) throw new internal_error( "Attempt to construct a duplicate LALR state"); /* assign a unique index */ _index = next_index++; /* store the items */ _items = itms; /* add to the global collection, keyed with its item set */ _all.put(_items,this); } /*-----------------------------------------------------------*/ /*--- (Access to) Static (Class) Variables ------------------*/ /*-----------------------------------------------------------*/ /** Collection of all states. */ protected static Hashtable _all = new Hashtable(); /** Collection of all states. */ public static Enumeration all() {return _all.elements();} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Indicate total number of states there are. */ public static int number() {return _all.size();} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Hash table to find states by their kernels (i.e, the original, * unclosed, set of items -- which uniquely define the state). This table * stores state objects using (a copy of) their kernel item sets as keys. */ protected static Hashtable _all_kernels = new Hashtable(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Find and return state with a given a kernel item set (or null if not * found). The kernel item set is the subset of items that were used to * originally create the state. These items are formed by "shifting the * dot" within items of other states that have a transition to this one. * The remaining elements of this state's item set are added during closure. * @param itms the kernel set of the state we are looking for. */ public static lalr_state find_state(lalr_item_set itms) { if (itms == null) return null; else return (lalr_state)_all.get(itms); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Static counter for assigning unique state indexes. */ protected static int next_index = 0; /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The item set for this state. */ protected lalr_item_set _items; /** The item set for this state. */ public lalr_item_set items() {return _items;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** List of transitions out of this state. */ protected lalr_transition _transitions = null; /** List of transitions out of this state. */ public lalr_transition transitions() {return _transitions;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Index of this state in the parse tables */ protected int _index; /** Index of this state in the parse tables */ public int index() {return _index;} /*-----------------------------------------------------------*/ /*--- Static Methods ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Helper routine for debugging -- produces a dump of the given state * onto System.out. */ protected static void dump_state(lalr_state st) throws internal_error { lalr_item_set itms; lalr_item itm; production_part part; if (st == null) { System.out.println("NULL lalr_state"); return; } System.out.println("lalr_state [" + st.index() + "] {"); itms = st.items(); for (Enumeration e = itms.all(); e.hasMoreElements(); ) { itm = (lalr_item)e.nextElement(); System.out.print(" ["); System.out.print(itm.the_production().lhs().the_symbol().name()); System.out.print(" ::= "); for (int i = 0; i<itm.the_production().rhs_length(); i++) { if (i == itm.dot_pos()) System.out.print("(*) "); part = itm.the_production().rhs(i); if (part.is_action()) System.out.print("{action} "); else System.out.print(((symbol_part)part).the_symbol().name() + " "); } if (itm.dot_at_end()) System.out.print("(*) "); System.out.println("]"); } System.out.println("}"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Propagate lookahead sets through the constructed viable prefix * recognizer. When the machine is constructed, each item that results in the creation of another such that its lookahead is included in the other's will have a propagate link set up for it. This allows additions to the lookahead of one item to be included in other items that it was used to directly or indirectly create. */ protected static void propagate_all_lookaheads() throws internal_error { /* iterate across all states */ for (Enumeration st = all(); st.hasMoreElements(); ) { /* propagate lookaheads out of that state */ ((lalr_state)st.nextElement()).propagate_lookaheads(); } } /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Add a transition out of this state to another. * @param on_sym the symbol the transition is under. * @param to_st the state the transition goes to. */ public void add_transition(symbol on_sym, lalr_state to_st) throws internal_error { lalr_transition trans; /* create a new transition object and put it in our list */ trans = new lalr_transition(on_sym, to_st, _transitions); _transitions = trans; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Build an LALR viable prefix recognition machine given a start * production. This method operates by first building a start state * from the start production (based on a single item with the dot at * the beginning and EOF as expected lookahead). Then for each state * it attempts to extend the machine by creating transitions out of * the state to new or existing states. When considering extension * from a state we make a transition on each symbol that appears before * the dot in some item. For example, if we have the items: <pre> * [A ::= a b * X c, {d,e}] * [B ::= a b * X d, {a,b}] * </pre> * in some state, then we would be making a transition under X to a new * state. This new state would be formed by a "kernel" of items * corresponding to moving the dot past the X. In this case: <pre> * [A ::= a b X * c, {d,e}] * [B ::= a b X * Y, {a,b}] * </pre> * The full state would then be formed by "closing" this kernel set of * items so that it included items that represented productions of things * the parser was now looking for. In this case we would items * corresponding to productions of Y, since various forms of Y are expected * next when in this state (see lalr_item_set.compute_closure() for details * on closure). <p> * * The process of building the viable prefix recognizer terminates when no * new states can be added. However, in order to build a smaller number of * states (i.e., corresponding to LALR rather than canonical LR) the state * building process does not maintain full loookaheads in all items. * Consequently, after the machine is built, we go back and propagate * lookaheads through the constructed machine using a call to * propagate_all_lookaheads(). This makes use of propagation links * constructed during the closure and transition process. * * @param start_prod the start production of the grammar * @see java_cup.lalr_item_set#compute_closure * @see java_cup.lalr_state#propagate_all_lookaheads */ public static lalr_state build_machine(production start_prod) throws internal_error { lalr_state start_state; lalr_item_set start_items; lalr_item_set new_items; lalr_item_set linked_items; lalr_item_set kernel; Stack work_stack = new Stack(); lalr_state st, new_st; symbol_set outgoing; lalr_item itm, new_itm, existing, fix_itm; symbol sym, sym2; Enumeration i, s, fix; /* sanity check */ if (start_prod == null) throw new internal_error( "Attempt to build viable prefix recognizer using a null production"); /* build item with dot at front of start production and EOF lookahead */ start_items = new lalr_item_set(); itm = new lalr_item(start_prod); itm.lookahead().add(terminal.EOF); start_items.add(itm); /* create copy the item set to form the kernel */ kernel = new lalr_item_set(start_items); /* create the closure from that item set */ start_items.compute_closure(); /* build a state out of that item set and put it in our work set */ start_state = new lalr_state(start_items); work_stack.push(start_state); /* enter the state using the kernel as the key */ _all_kernels.put(kernel, start_state); /* continue looking at new states until we have no more work to do */ while (!work_stack.empty()) { /* remove a state from the work set */ st = (lalr_state)work_stack.pop(); /* gather up all the symbols that appear before dots */ outgoing = new symbol_set(); for (i = st.items().all(); i.hasMoreElements(); ) { itm = (lalr_item)i.nextElement(); /* add the symbol before the dot (if any) to our collection */ sym = itm.symbol_after_dot(); if (sym != null) outgoing.add(sym); } /* now create a transition out for each individual symbol */ for (s = outgoing.all(); s.hasMoreElements(); ) { sym = (symbol)s.nextElement(); /* will be keeping the set of items with propagate links */ linked_items = new lalr_item_set(); /* gather up shifted versions of all the items that have this symbol before the dot */ new_items = new lalr_item_set(); for (i = st.items().all(); i.hasMoreElements();) { itm = (lalr_item)i.nextElement(); /* if this is the symbol we are working on now, add to set */ sym2 = itm.symbol_after_dot(); if (sym.equals(sym2)) { /* add to the kernel of the new state */ new_items.add(itm.shift()); /* remember that itm has propagate link to it */ linked_items.add(itm); } } /* use new items as state kernel */ kernel = new lalr_item_set(new_items); /* have we seen this one already? */ new_st = (lalr_state)_all_kernels.get(kernel); /* if we haven't, build a new state out of the item set */ if (new_st == null) { /* compute closure of the kernel for the full item set */ new_items.compute_closure(); /* build the new state */ new_st = new lalr_state(new_items); /* add the new state to our work set */ work_stack.push(new_st); /* put it in our kernel table */ _all_kernels.put(kernel, new_st); } /* otherwise relink propagation to items in existing state */ else { /* walk through the items that have links to the new state */ for (fix = linked_items.all(); fix.hasMoreElements(); ) { fix_itm = (lalr_item)fix.nextElement(); /* look at each propagate link out of that item */ for (int l =0; l < fix_itm.propagate_items().size(); l++) { /* pull out item linked to in the new state */ new_itm = (lalr_item)fix_itm.propagate_items().elementAt(l); /* find corresponding item in the existing state */ existing = new_st.items().find(new_itm); /* fix up the item so it points to the existing set */ if (existing != null) fix_itm.propagate_items().setElementAt(existing ,l); } } } /* add a transition from current state to that state */ st.add_transition(sym, new_st); } } /* all done building states */ /* propagate complete lookahead sets throughout the states */ propagate_all_lookaheads(); return start_state; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Propagate lookahead sets out of this state. This recursively * propagates to all items that have propagation links from some item * in this state. */ protected void propagate_lookaheads() throws internal_error { /* recursively propagate out from each item in the state */ for (Enumeration itm = items().all(); itm.hasMoreElements(); ) ((lalr_item)itm.nextElement()).propagate_lookaheads(null); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Fill in the parse table entries for this state. There are two * parse tables that encode the viable prefix recognition machine, an * action table and a reduce-goto table. The rows in each table * correspond to states of the machine. The columns of the action table * are indexed by terminal symbols and correspond to either transitions * out of the state (shift entries) or reductions from the state to some * previous state saved on the stack (reduce entries). All entries in the * action table that are not shifts or reduces, represent errors. The * reduce-goto table is indexed by non terminals and represents transitions * out of a state on that non-terminal.<p> * Conflicts occur if more than one action needs to go in one entry of the * action table (this cannot happen with the reduce-goto table). Conflicts * are resolved by always shifting for shift/reduce conflicts and choosing * the lowest numbered production (hence the one that appeared first in * the specification) in reduce/reduce conflicts. All conflicts are * reported and if more conflicts are detected than were declared by the * user, code generation is aborted. * * @param act_table the action table to put entries in. * @param reduce_table the reduce-goto table to put entries in. */ public void build_table_entries( parse_action_table act_table, parse_reduce_table reduce_table) throws internal_error { parse_action_row our_act_row; parse_reduce_row our_red_row; lalr_item itm; parse_action act, other_act; symbol sym; terminal_set conflict_set = new terminal_set(); /* pull out our rows from the tables */ our_act_row = act_table.under_state[index()]; our_red_row = reduce_table.under_state[index()]; /* consider each item in our state */ for (Enumeration i = items().all(); i.hasMoreElements(); ) { itm = (lalr_item)i.nextElement(); /* if its completed (dot at end) then reduce under the lookahead */ if (itm.dot_at_end()) { act = new reduce_action(itm.the_production()); /* consider each lookahead symbol */ for (int t = 0; t < terminal.number(); t++) { /* skip over the ones not in the lookahead */ if (!itm.lookahead().contains(t)) continue; /* if we don't already have an action put this one in */ if (our_act_row.under_term[t].kind() == parse_action.ERROR) { our_act_row.under_term[t] = act; } else { /* we now have at least one conflict */ terminal term = terminal.find(t); other_act = our_act_row.under_term[t]; /* if the other act was not a shift */ if ((other_act.kind() != parse_action.SHIFT) && (other_act.kind() != parse_action.NONASSOC)) { /* if we have lower index hence priority, replace it*/ if (itm.the_production().index() < ((reduce_action)other_act).reduce_with().index()) { /* replace the action */ our_act_row.under_term[t] = act; } } else { /* Check precedences,see if problem is correctable */ if(fix_with_precedence(itm.the_production(), t, our_act_row, act)) { term = null; } } if(term!=null) { conflict_set.add(term); } } } } } /* consider each outgoing transition */ for (lalr_transition trans=transitions(); trans!=null; trans=trans.next()) { /* if its on an terminal add a shift entry */ sym = trans.on_symbol(); if (!sym.is_non_term()) { act = new shift_action(trans.to_state()); /* if we don't already have an action put this one in */ if ( our_act_row.under_term[sym.index()].kind() == parse_action.ERROR) { our_act_row.under_term[sym.index()] = act; } else { /* we now have at least one conflict */ production p = ((reduce_action)our_act_row.under_term[sym.index()]).reduce_with(); /* shift always wins */ if (!fix_with_precedence(p, sym.index(), our_act_row, act)) { our_act_row.under_term[sym.index()] = act; conflict_set.add(terminal.find(sym.index())); } } } else { /* for non terminals add an entry to the reduce-goto table */ our_red_row.under_non_term[sym.index()] = trans.to_state(); } } /* if we end up with conflict(s), report them */ if (!conflict_set.empty()) report_conflicts(conflict_set); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Procedure that attempts to fix a shift/reduce error by using * precedences. --frankf 6/26/96 * * if a production (also called rule) or the lookahead terminal * has a precedence, then the table can be fixed. if the rule * has greater precedence than the terminal, a reduce by that rule * in inserted in the table. If the terminal has a higher precedence, * it is shifted. if they have equal precedence, then the associativity * of the precedence is used to determine what to put in the table: * if the precedence is left associative, the action is to reduce. * if the precedence is right associative, the action is to shift. * if the precedence is non associative, then it is a syntax error. * * @param p the production * @param term_index the index of the lokahead terminal * @param parse_action_row a row of the action table * @param act the rule in conflict with the table entry */ protected boolean fix_with_precedence( production p, int term_index, parse_action_row table_row, parse_action act) throws internal_error { terminal term = terminal.find(term_index); /* if the production has a precedence number, it can be fixed */ if (p.precedence_num() > assoc.no_prec) { /* if production precedes terminal, put reduce in table */ if (p.precedence_num() > term.precedence_num()) { table_row.under_term[term_index] = insert_reduce(table_row.under_term[term_index],act); return true; } /* if terminal precedes rule, put shift in table */ else if (p.precedence_num() < term.precedence_num()) { table_row.under_term[term_index] = insert_shift(table_row.under_term[term_index],act); return true; } else { /* they are == precedence */ /* equal precedences have equal sides, so only need to look at one: if it is right, put shift in table */ if (term.precedence_side() == assoc.right) { table_row.under_term[term_index] = insert_shift(table_row.under_term[term_index],act); return true; } /* if it is left, put reduce in table */ else if (term.precedence_side() == assoc.left) { table_row.under_term[term_index] = insert_reduce(table_row.under_term[term_index],act); return true; } /* if it is nonassoc, we're not allowed to have two nonassocs of equal precedence in a row, so put in NONASSOC */ else if (term.precedence_side() == assoc.nonassoc) { table_row.under_term[term_index] = new nonassoc_action(); return true; } else { /* something really went wrong */ throw new internal_error("Unable to resolve conflict correctly"); } } } /* check if terminal has precedence, if so, shift, since rule does not have precedence */ else if (term.precedence_num() > assoc.no_prec) { table_row.under_term[term_index] = insert_shift(table_row.under_term[term_index],act); return true; } /* otherwise, neither the rule nor the terminal has a precedence, so it can't be fixed. */ return false; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* given two actions, and an action type, return the action of that action type. give an error if they are of the same action, because that should never have tried to be fixed */ protected parse_action insert_action( parse_action a1, parse_action a2, int act_type) throws internal_error { if ((a1.kind() == act_type) && (a2.kind() == act_type)) { throw new internal_error("Conflict resolution of bogus actions"); } else if (a1.kind() == act_type) { return a1; } else if (a2.kind() == act_type) { return a2; } else { throw new internal_error("Conflict resolution of bogus actions"); } } /* find the shift in the two actions */ protected parse_action insert_shift( parse_action a1, parse_action a2) throws internal_error { return insert_action(a1, a2, parse_action.SHIFT); } /* find the reduce in the two actions */ protected parse_action insert_reduce( parse_action a1, parse_action a2) throws internal_error { return insert_action(a1, a2, parse_action.REDUCE); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce warning messages for all conflicts found in this state. */ protected void report_conflicts(terminal_set conflict_set) throws internal_error { lalr_item itm, compare; symbol shift_sym; boolean after_itm; /* consider each element */ for (Enumeration itms = items().all(); itms.hasMoreElements(); ) { itm = (lalr_item)itms.nextElement(); /* clear the S/R conflict set for this item */ /* if it results in a reduce, it could be a conflict */ if (itm.dot_at_end()) { /* not yet after itm */ after_itm = false; /* compare this item against all others looking for conflicts */ for (Enumeration comps = items().all(); comps.hasMoreElements(); ) { compare = (lalr_item)comps.nextElement(); /* if this is the item, next one is after it */ if (itm == compare) after_itm = true; /* only look at it if its not the same item */ if (itm != compare) { /* is it a reduce */ if (compare.dot_at_end()) { /* only look at reduces after itm */ if (after_itm) /* does the comparison item conflict? */ if (compare.lookahead().intersects(itm.lookahead())) /* report a reduce/reduce conflict */ report_reduce_reduce(itm, compare); } } } /* report S/R conflicts under all the symbols we conflict under */ for (int t = 0; t < terminal.number(); t++) if (conflict_set.contains(t)) report_shift_reduce(itm,t); } } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a warning message for one reduce/reduce conflict. * * @param itm1 first item in conflict. * @param itm2 second item in conflict. */ protected void report_reduce_reduce(lalr_item itm1, lalr_item itm2) throws internal_error { boolean comma_flag = false; System.err.println("*** Reduce/Reduce conflict found in state #"+index()); System.err.print (" between "); System.err.println(itm1.to_simple_string()); System.err.print (" and "); System.err.println(itm2.to_simple_string()); System.err.print(" under symbols: {" ); for (int t = 0; t < terminal.number(); t++) { if (itm1.lookahead().contains(t) && itm2.lookahead().contains(t)) { if (comma_flag) System.err.print(", "); else comma_flag = true; System.err.print(terminal.find(t).name()); } } System.err.println("}"); System.err.print(" Resolved in favor of "); if (itm1.the_production().index() < itm2.the_production().index()) System.err.println("the first production.\n"); else System.err.println("the second production.\n"); /* count the conflict */ emit.num_conflicts++; lexer.warning_count++; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a warning message for one shift/reduce conflict. * * @param red_itm the item with the reduce. * @param conflict_sym the index of the symbol conflict occurs under. */ protected void report_shift_reduce( lalr_item red_itm, int conflict_sym) throws internal_error { lalr_item itm; symbol shift_sym; /* emit top part of message including the reduce item */ System.err.println("*** Shift/Reduce conflict found in state #"+index()); System.err.print (" between "); System.err.println(red_itm.to_simple_string()); /* find and report on all items that shift under our conflict symbol */ for (Enumeration itms = items().all(); itms.hasMoreElements(); ) { itm = (lalr_item)itms.nextElement(); /* only look if its not the same item and not a reduce */ if (itm != red_itm && !itm.dot_at_end()) { /* is it a shift on our conflicting terminal */ shift_sym = itm.symbol_after_dot(); if (!shift_sym.is_non_term() && shift_sym.index() == conflict_sym) { /* yes, report on it */ System.err.println(" and " + itm.to_simple_string()); } } } System.err.println(" under symbol "+ terminal.find(conflict_sym).name()); System.err.println(" Resolved in favor of shifting.\n"); /* count the conflict */ emit.num_conflicts++; lexer.warning_count++; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison. */ public boolean equals(lalr_state other) { /* we are equal if our item sets are equal */ return other != null && items().equals(other.items()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof lalr_state)) return false; else return equals((lalr_state)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a hash code. */ public int hashCode() { /* just use the item set hash code */ return items().hashCode(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { String result; lalr_transition tr; /* dump the item set */ result = "lalr_state [" + index() + "]: " + _items + "\n"; /* do the transitions */ for (tr = transitions(); tr != null; tr = tr.next()) { result += tr; result += "\n"; } return result; } /*-----------------------------------------------------------*/ }
31,583
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
lexer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/lexer.java
package java_cup; import java_cup.runtime.Symbol; import java.util.Hashtable; /** This class implements a small scanner (aka lexical analyzer or lexer) for * the JavaCup specification. This scanner reads characters from standard * input (System.in) and returns integers corresponding to the terminal * number of the next Symbol. Once end of input is reached the EOF Symbol is * returned on every subsequent call.<p> * Symbols currently returned include: <pre> * Symbol Constant Returned Symbol Constant Returned * ------ ----------------- ------ ----------------- * "package" PACKAGE "import" IMPORT * "code" CODE "action" ACTION * "parser" PARSER "terminal" TERMINAL * "non" NON "init" INIT * "scan" SCAN "with" WITH * "start" START "precedence" PRECEDENCE * "left" LEFT "right" RIGHT * "nonassoc" NONASSOC "%prec PRECENT_PREC * [ LBRACK ] RBRACK * ; SEMI * , COMMA * STAR * . DOT : COLON * ::= COLON_COLON_EQUALS | BAR * identifier ID {:...:} CODE_STRING * "nonterminal" NONTERMINAL * </pre> * All symbol constants are defined in sym.java which is generated by * JavaCup from parser.cup.<p> * * In addition to the scanner proper (called first via init() then with * next_token() to get each Symbol) this class provides simple error and * warning routines and keeps a count of errors and warnings that is * publicly accessible.<p> * * This class is "static" (i.e., it has only static members and methods). * * @version last updated: 7/3/96 * @author Frank Flannery */ public class lexer { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** The only constructor is private, so no instances can be created. */ private lexer() { } /*-----------------------------------------------------------*/ /*--- Static (Class) Variables ------------------------------*/ /*-----------------------------------------------------------*/ /** First character of lookahead. */ protected static int next_char; /** Second character of lookahead. */ protected static int next_char2; /** Second character of lookahead. */ protected static int next_char3; /** Second character of lookahead. */ protected static int next_char4; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** EOF constant. */ protected static final int EOF_CHAR = -1; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Table of keywords. Keywords are initially treated as identifiers. * Just before they are returned we look them up in this table to see if * they match one of the keywords. The string of the name is the key here, * which indexes Integer objects holding the symbol number. */ protected static Hashtable keywords = new Hashtable(23); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Table of single character symbols. For ease of implementation, we * store all unambiguous single character Symbols in this table of Integer * objects keyed by Integer objects with the numerical value of the * appropriate char (currently Character objects have a bug which precludes * their use in tables). */ protected static Hashtable char_symbols = new Hashtable(11); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Current line number for use in error messages. */ protected static int current_line = 1; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Character position in current line. */ protected static int current_position = 1; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Character position in current line. */ protected static int absolute_position = 1; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Count of total errors detected so far. */ public static int error_count = 0; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Count of warnings issued so far */ public static int warning_count = 0; /*-----------------------------------------------------------*/ /*--- Static Methods ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Initialize the scanner. This sets up the keywords and char_symbols * tables and reads the first two characters of lookahead. */ public static void init() throws java.io.IOException { /* set up the keyword table */ keywords.put("package", new Integer(sym.PACKAGE)); keywords.put("import", new Integer(sym.IMPORT)); keywords.put("code", new Integer(sym.CODE)); keywords.put("action", new Integer(sym.ACTION)); keywords.put("parser", new Integer(sym.PARSER)); keywords.put("terminal", new Integer(sym.TERMINAL)); keywords.put("non", new Integer(sym.NON)); keywords.put("nonterminal",new Integer(sym.NONTERMINAL));// [CSA] keywords.put("init", new Integer(sym.INIT)); keywords.put("scan", new Integer(sym.SCAN)); keywords.put("with", new Integer(sym.WITH)); keywords.put("start", new Integer(sym.START)); keywords.put("precedence", new Integer(sym.PRECEDENCE)); keywords.put("left", new Integer(sym.LEFT)); keywords.put("right", new Integer(sym.RIGHT)); keywords.put("nonassoc", new Integer(sym.NONASSOC)); /* set up the table of single character symbols */ char_symbols.put(new Integer(';'), new Integer(sym.SEMI)); char_symbols.put(new Integer(','), new Integer(sym.COMMA)); char_symbols.put(new Integer('*'), new Integer(sym.STAR)); char_symbols.put(new Integer('.'), new Integer(sym.DOT)); char_symbols.put(new Integer('|'), new Integer(sym.BAR)); char_symbols.put(new Integer('['), new Integer(sym.LBRACK)); char_symbols.put(new Integer(']'), new Integer(sym.RBRACK)); /* read two characters of lookahead */ next_char = System.in.read(); if (next_char == EOF_CHAR) { next_char2 = EOF_CHAR; next_char3 = EOF_CHAR; next_char4 = EOF_CHAR; } else { next_char2 = System.in.read(); if (next_char2 == EOF_CHAR) { next_char3 = EOF_CHAR; next_char4 = EOF_CHAR; } else { next_char3 = System.in.read(); if (next_char3 == EOF_CHAR) { next_char4 = EOF_CHAR; } else { next_char4 = System.in.read(); } } } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Advance the scanner one character in the input stream. This moves * next_char2 to next_char and then reads a new next_char2. */ protected static void advance() throws java.io.IOException { int old_char; old_char = next_char; next_char = next_char2; if (next_char == EOF_CHAR) { next_char2 = EOF_CHAR; next_char3 = EOF_CHAR; next_char4 = EOF_CHAR; } else { next_char2 = next_char3; if (next_char2 == EOF_CHAR) { next_char3 = EOF_CHAR; next_char4 = EOF_CHAR; } else { next_char3 = next_char4; if (next_char3 == EOF_CHAR) { next_char4 = EOF_CHAR; } else { next_char4 = System.in.read(); } } } /* count this */ absolute_position++; current_position++; if (old_char == '\n' || (old_char == '\r' && next_char!='\n')) { current_line++; current_position = 1; } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Emit an error message. The message will be marked with both the * current line number and the position in the line. Error messages * are printed on standard error (System.err). * @param message the message to print. */ public static void emit_error(String message) { System.err.println("Error at " + current_line + "(" + current_position + "): " + message); error_count++; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Emit a warning message. The message will be marked with both the * current line number and the position in the line. Messages are * printed on standard error (System.err). * @param message the message to print. */ public static void emit_warn(String message) { System.err.println("Warning at " + current_line + "(" + current_position + "): " + message); warning_count++; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if a character is ok to start an id. * @param ch the character in question. */ protected static boolean id_start_char(int ch) { /* allow for % in identifiers. a hack to allow my %prec in. Should eventually make lex spec for this frankf */ return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '_'); // later need to deal with non-8-bit chars here } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if a character is ok for the middle of an id. * @param ch the character in question. */ protected static boolean id_char(int ch) { return id_start_char(ch) || (ch >= '0' && ch <= '9'); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Try to look up a single character symbol, returns -1 for not found. * @param ch the character in question. */ protected static int find_single_char(int ch) { Integer result; result = (Integer)char_symbols.get(new Integer((char)ch)); if (result == null) return -1; else return result.intValue(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Handle swallowing up a comment. Both old style C and new style C++ * comments are handled. */ protected static void swallow_comment() throws java.io.IOException { /* next_char == '/' at this point */ /* is it a traditional comment */ if (next_char2 == '*') { /* swallow the opener */ advance(); advance(); /* swallow the comment until end of comment or EOF */ for (;;) { /* if its EOF we have an error */ if (next_char == EOF_CHAR) { emit_error("Specification file ends inside a comment"); return; } /* if we can see the closer we are done */ if (next_char == '*' && next_char2 == '/') { advance(); advance(); return; } /* otherwise swallow char and move on */ advance(); } } /* is its a new style comment */ if (next_char2 == '/') { /* swallow the opener */ advance(); advance(); /* swallow to '\n', '\r', '\f', or EOF */ while (next_char != '\n' && next_char != '\r' && next_char != '\f' && next_char!=EOF_CHAR) advance(); return; } /* shouldn't get here, but... if we get here we have an error */ emit_error("Malformed comment in specification -- ignored"); advance(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Swallow up a code string. Code strings begin with "{:" and include all characters up to the first occurrence of ":}" (there is no way to include ":}" inside a code string). The routine returns a String object suitable for return by the scanner. */ protected static Symbol do_code_string() throws java.io.IOException { StringBuffer result = new StringBuffer(); /* at this point we have lookahead of "{:" -- swallow that */ advance(); advance(); /* save chars until we see ":}" */ while (!(next_char == ':' && next_char2 == '}')) { /* if we have run off the end issue a message and break out of loop */ if (next_char == EOF_CHAR) { emit_error("Specification file ends inside a code string"); break; } /* otherwise record the char and move on */ result.append(new Character((char)next_char)); advance(); } /* advance past the closer and build a return Symbol */ advance(); advance(); return new Symbol(sym.CODE_STRING, result.toString()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Process an identifier. Identifiers begin with a letter, underscore, * or dollar sign, which is followed by zero or more letters, numbers, * underscores or dollar signs. This routine returns a String suitable * for return by the scanner. */ protected static Symbol do_id() throws java.io.IOException { StringBuffer result = new StringBuffer(); String result_str; Integer keyword_num; char buffer[] = new char[1]; /* next_char holds first character of id */ buffer[0] = (char)next_char; result.append(buffer,0,1); advance(); /* collect up characters while they fit in id */ while(id_char(next_char)) { buffer[0] = (char)next_char; result.append(buffer,0,1); advance(); } /* extract a string and try to look it up as a keyword */ result_str = result.toString(); keyword_num = (Integer)keywords.get(result_str); /* if we found something, return that keyword */ if (keyword_num != null) return new Symbol(keyword_num.intValue()); /* otherwise build and return an id Symbol with an attached string */ return new Symbol(sym.ID, result_str); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Return one Symbol. This is the main external interface to the scanner. * It consumes sufficient characters to determine the next input Symbol * and returns it. To help with debugging, this routine actually calls * real_next_token() which does the work. If you need to debug the * parser, this can be changed to call debug_next_token() which prints * a debugging message before returning the Symbol. */ public static Symbol next_token() throws java.io.IOException { return real_next_token(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Debugging version of next_token(). This routine calls the real scanning * routine, prints a message on System.out indicating what the Symbol is, * then returns it. */ public static Symbol debug_next_token() throws java.io.IOException { Symbol result = real_next_token(); System.out.println("# next_Symbol() => " + result.sym); return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The actual routine to return one Symbol. This is normally called from * next_token(), but for debugging purposes can be called indirectly from * debug_next_token(). */ protected static Symbol real_next_token() throws java.io.IOException { int sym_num; for (;;) { /* look for white space */ if (next_char == ' ' || next_char == '\t' || next_char == '\n' || next_char == '\f' || next_char == '\r') { /* advance past it and try the next character */ advance(); continue; } /* look for a single character symbol */ sym_num = find_single_char(next_char); if (sym_num != -1) { /* found one -- advance past it and return a Symbol for it */ advance(); return new Symbol(sym_num); } /* look for : or ::= */ if (next_char == ':') { /* if we don't have a second ':' return COLON */ if (next_char2 != ':') { advance(); return new Symbol(sym.COLON); } /* move forward and look for the '=' */ advance(); if (next_char2 == '=') { advance(); advance(); return new Symbol(sym.COLON_COLON_EQUALS); } else { /* return just the colon (already consumed) */ return new Symbol(sym.COLON); } } /* find a "%prec" string and return it. otherwise, a '%' was found, which has no right being in the specification otherwise */ if (next_char == '%') { advance(); if ((next_char == 'p') && (next_char2 == 'r') && (next_char3 == 'e') && (next_char4 == 'c')) { advance(); advance(); advance(); advance(); return new Symbol(sym.PERCENT_PREC); } else { emit_error("Found extraneous percent sign"); } } /* look for a comment */ if (next_char == '/' && (next_char2 == '*' || next_char2 == '/')) { /* swallow then continue the scan */ swallow_comment(); continue; } /* look for start of code string */ if (next_char == '{' && next_char2 == ':') return do_code_string(); /* look for an id or keyword */ if (id_start_char(next_char)) return do_id(); /* look for EOF */ if (next_char == EOF_CHAR) return new Symbol(sym.EOF); /* if we get here, we have an unrecognized character */ emit_warn("Unrecognized character '" + new Character((char)next_char) + "'(" + next_char + ") -- ignored"); /* advance past it */ advance(); } } /*-----------------------------------------------------------*/ }
18,202
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
lalr_item.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/lalr_item.java
package java_cup; import java.util.Stack; import java.util.Enumeration; /** This class represents an LALR item. Each LALR item consists of * a production, a "dot" at a position within that production, and * a set of lookahead symbols (terminal). (The first two of these parts * are provide by the super class). An item is designed to represent a * configuration that the parser may be in. For example, an item of the * form: <pre> * [A ::= B * C d E , {a,b,c}] * </pre> * indicates that the parser is in the middle of parsing the production <pre> * A ::= B C d E * </pre> * that B has already been parsed, and that we will expect to see a lookahead * of either a, b, or c once the complete RHS of this production has been * found.<p> * * Items may initially be missing some items from their lookahead sets. * Links are maintained from each item to the set of items that would need * to be updated if symbols are added to its lookahead set. During * "lookahead propagation", we add symbols to various lookahead sets and * propagate these changes across these dependency links as needed. * * @see java_cup.lalr_item_set * @see java_cup.lalr_state * @version last updated: 11/25/95 * @author Scott Hudson */ public class lalr_item extends lr_item_core { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Full constructor. * @param prod the production for the item. * @param pos the position of the "dot" within the production. * @param look the set of lookahead symbols. */ public lalr_item(production prod, int pos, terminal_set look) throws internal_error { super(prod, pos); _lookahead = look; _propagate_items = new Stack(); needs_propagation = true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor with default position (dot at start). * @param prod the production for the item. * @param look the set of lookahead symbols. */ public lalr_item(production prod, terminal_set look) throws internal_error { this(prod,0,look); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor with default position and empty lookahead set. * @param prod the production for the item. */ public lalr_item(production prod) throws internal_error { this(prod,0,new terminal_set()); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The lookahead symbols of the item. */ protected terminal_set _lookahead; /** The lookahead symbols of the item. */ public terminal_set lookahead() {return _lookahead;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Links to items that the lookahead needs to be propagated to. */ protected Stack _propagate_items; /** Links to items that the lookahead needs to be propagated to */ public Stack propagate_items() {return _propagate_items;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Flag to indicate that this item needs to propagate its lookahead * (whether it has changed or not). */ protected boolean needs_propagation; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Add a new item to the set of items we propagate to. */ public void add_propagate(lalr_item prop_to) { _propagate_items.push(prop_to); needs_propagation = true; } /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Propagate incoming lookaheads through this item to others need to * be changed. * @params incoming symbols to potentially be added to lookahead of this item. */ public void propagate_lookaheads(terminal_set incoming) throws internal_error { boolean change = false; /* if we don't need to propagate, then bail out now */ if (!needs_propagation && (incoming == null || incoming.empty())) return; /* if we have null incoming, treat as an empty set */ if (incoming != null) { /* add the incoming to the lookahead of this item */ change = lookahead().add(incoming); } /* if we changed or need it anyway, propagate across our links */ if (change || needs_propagation) { /* don't need to propagate again */ needs_propagation = false; /* propagate our lookahead into each item we are linked to */ for (int i = 0; i < propagate_items().size(); i++) ((lalr_item)propagate_items().elementAt(i)) .propagate_lookaheads(lookahead()); } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce the new lalr_item that results from shifting the dot one position * to the right. */ public lalr_item shift() throws internal_error { lalr_item result; /* can't shift if we have dot already at the end */ if (dot_at_end()) throw new internal_error("Attempt to shift past end of an lalr_item"); /* create the new item w/ the dot shifted by one */ result = new lalr_item(the_production(), dot_pos()+1, new terminal_set(lookahead())); /* change in our lookahead needs to be propagated to this item */ add_propagate(result); return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Calculate lookahead representing symbols that could appear after the * symbol that the dot is currently in front of. Note: this routine must * not be invoked before first sets and nullability has been calculated * for all non terminals. */ public terminal_set calc_lookahead(terminal_set lookahead_after) throws internal_error { terminal_set result; int pos; production_part part; symbol sym; /* sanity check */ if (dot_at_end()) throw new internal_error( "Attempt to calculate a lookahead set with a completed item"); /* start with an empty result */ result = new terminal_set(); /* consider all nullable symbols after the one to the right of the dot */ for (pos = dot_pos()+1; pos < the_production().rhs_length(); pos++) { part = the_production().rhs(pos); /* consider what kind of production part it is -- skip actions */ if (!part.is_action()) { sym = ((symbol_part)part).the_symbol(); /* if its a terminal add it in and we are done */ if (!sym.is_non_term()) { result.add((terminal)sym); return result; } else { /* otherwise add in first set of the non terminal */ result.add(((non_terminal)sym).first_set()); /* if its nullable we continue adding, if not, we are done */ if (!((non_terminal)sym).nullable()) return result; } } } /* if we get here everything past the dot was nullable we add in the lookahead for after the production and we are done */ result.add(lookahead_after); return result; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if everything from the symbol one beyond the dot all the * way to the end of the right hand side is nullable. This would indicate * that the lookahead of this item must be included in the lookaheads of * all items produced as a closure of this item. Note: this routine should * not be invoked until after first sets and nullability have been * calculated for all non terminals. */ public boolean lookahead_visible() throws internal_error { production_part part; symbol sym; /* if the dot is at the end, we have a problem, but the cleanest thing to do is just return true. */ if (dot_at_end()) return true; /* walk down the rhs and bail if we get a non-nullable symbol */ for (int pos = dot_pos() + 1; pos < the_production().rhs_length(); pos++) { part = the_production().rhs(pos); /* skip actions */ if (!part.is_action()) { sym = ((symbol_part)part).the_symbol(); /* if its a terminal we fail */ if (!sym.is_non_term()) return false; /* if its not nullable we fail */ if (!((non_terminal)sym).nullable()) return false; } } /* if we get here its all nullable */ return true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison -- here we only require the cores to be equal since * we need to do sets of items based only on core equality (ignoring * lookahead sets). */ public boolean equals(lalr_item other) { if (other == null) return false; return super.equals(other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof lalr_item)) return false; else return equals((lalr_item)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Return a hash code -- here we only hash the core since we only test core * matching in LALR items. */ public int hashCode() { return super.hashCode(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to string. */ public String toString() { String result = ""; // additional output for debugging: // result += "(" + obj_hash() + ")"; result += "["; result += super.toString(); result += ", "; if (lookahead() != null) { result += "{"; for (int t = 0; t < terminal.number(); t++) if (lookahead().contains(t)) result += terminal.find(t).name() + " "; result += "}"; } else result += "NULL LOOKAHEAD!!"; result += "]"; // additional output for debugging: // result += " -> "; // for (int i = 0; i<propagate_items().size(); i++) // result+=((lalr_item)(propagate_items().elementAt(i))).obj_hash()+" "; // // if (needs_propagation) result += " NP"; return result; } /*-----------------------------------------------------------*/ }
10,920
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
action_part.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/action_part.java
package java_cup; /** * This class represents a part of a production which contains an * action. These are eventually eliminated from productions and converted * to trailing actions by factoring out with a production that derives the * empty string (and ends with this action). * * @see java_cup.production * @version last update: 11/25/95 * @author Scott Hudson */ public class action_part extends production_part { /*-----------------------------------------------------------*/ /*--- Constructors ------------------------------------------*/ /*-----------------------------------------------------------*/ /** Simple constructor. * @param code_str string containing the actual user code. */ public action_part(String code_str) { super(/* never have a label on code */null); _code_string = code_str; } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** String containing code for the action in question. */ protected String _code_string; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** String containing code for the action in question. */ public String code_string() {return _code_string;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Set the code string. */ public void set_code_string(String new_str) {_code_string = new_str;} /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Override to report this object as an action. */ public boolean is_action() { return true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality comparison for properly typed object. */ public boolean equals(action_part other) { /* compare the strings */ return other != null && super.equals(other) && other.code_string().equals(code_string()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality comparison. */ public boolean equals(Object other) { if (!(other instanceof action_part)) return false; else return equals((action_part)other); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Produce a hash code. */ public int hashCode() { return super.hashCode() ^ (code_string()==null ? 0 : code_string().hashCode()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { return super.toString() + "{" + code_string() + "}"; } /*-----------------------------------------------------------*/ }
2,963
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
sym.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/sym.java
//---------------------------------------------------- // The following code was generated by CUP v0.10k // Sun Jul 25 13:35:26 EDT 1999 //---------------------------------------------------- package java_cup; /** CUP generated class containing symbol constants. */ public class sym { /* terminals */ public static final int NON = 8; public static final int NONTERMINAL = 27; public static final int STAR = 15; public static final int SEMI = 13; public static final int CODE = 4; public static final int EOF = 0; public static final int NONASSOC = 23; public static final int LEFT = 21; public static final int PACKAGE = 2; public static final int COLON = 17; public static final int WITH = 11; public static final int IMPORT = 3; public static final int error = 1; public static final int COLON_COLON_EQUALS = 18; public static final int COMMA = 14; public static final int DOT = 16; public static final int SCAN = 10; public static final int ID = 28; public static final int INIT = 9; public static final int PARSER = 6; public static final int TERMINAL = 7; public static final int PRECEDENCE = 20; public static final int LBRACK = 25; public static final int RBRACK = 26; public static final int PERCENT_PREC = 24; public static final int START = 12; public static final int RIGHT = 22; public static final int BAR = 19; public static final int ACTION = 5; public static final int CODE_STRING = 29; }
1,514
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
parse_reduce_table.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/parse_reduce_table.java
package java_cup; import java.util.Enumeration; /** This class represents the complete "reduce-goto" table of the parser. * It has one row for each state in the parse machines, and a column for * each terminal symbol. Each entry contains a state number to shift to * as the last step of a reduce. * * @see java_cup.parse_reduce_row * @version last updated: 11/25/95 * @author Scott Hudson */ public class parse_reduce_table { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Simple constructor. Note: all terminals, non-terminals, and productions * must already have been entered, and the viable prefix recognizer should * have been constructed before this is called. */ public parse_reduce_table() { /* determine how many states we are working with */ _num_states = lalr_state.number(); /* allocate the array and fill it in with empty rows */ under_state = new parse_reduce_row[_num_states]; for (int i=0; i<_num_states; i++) under_state[i] = new parse_reduce_row(); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** How many rows/states in the machine/table. */ protected int _num_states; /** How many rows/states in the machine/table. */ public int num_states() {return _num_states;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Actual array of rows, one per state */ public parse_reduce_row[] under_state; /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Convert to a string. */ public String toString() { String result; lalr_state goto_st; int cnt; result = "-------- REDUCE_TABLE --------\n"; for (int row = 0; row < num_states(); row++) { result += "From state #" + row + "\n"; cnt = 0; for (int col = 0; col < under_state[row].size(); col++) { /* pull out the table entry */ goto_st = under_state[row].under_non_term[col]; /* if it has action in it, print it */ if (goto_st != null) { result += " [non term " + col + "->"; result += "state " + goto_st.index() + "]"; /* end the line after the 3rd one */ cnt++; if (cnt == 3) { result += "\n"; cnt = 0; } } } /* finish the line if we haven't just done that */ if (cnt != 0) result += "\n"; } result += "-----------------------------"; return result; } /*-----------------------------------------------------------*/ }
3,043
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
symbol.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/symbol.java
package java_cup; /** This abstract class serves as the base class for grammar symbols (i.e., * both terminals and non-terminals). Each symbol has a name string, and * a string giving the type of object that the symbol will be represented by * on the runtime parse stack. In addition, each symbol maintains a use count * in order to detect symbols that are declared but never used, and an index * number that indicates where it appears in parse tables (index numbers are * unique within terminals or non terminals, but not across both). * * @see java_cup.terminal * @see java_cup.non_terminal * @version last updated: 7/3/96 * @author Frank Flannery */ public abstract class symbol { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Full constructor. * @param nm the name of the symbol. * @param tp a string with the type name. */ public symbol(String nm, String tp) { /* sanity check */ if (nm == null) nm = ""; /* apply default if no type given */ if (tp == null) tp = "Object"; _name = nm; _stack_type = tp; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Constructor with default type. * @param nm the name of the symbol. */ public symbol(String nm) { this(nm, null); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** String for the human readable name of the symbol. */ protected String _name; /** String for the human readable name of the symbol. */ public String name() {return _name;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** String for the type of object used for the symbol on the parse stack. */ protected String _stack_type; /** String for the type of object used for the symbol on the parse stack. */ public String stack_type() {return _stack_type;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Count of how many times the symbol appears in productions. */ protected int _use_count = 0; /** Count of how many times the symbol appears in productions. */ public int use_count() {return _use_count;} /** Increment the use count. */ public void note_use() {_use_count++;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Index of this symbol (terminal or non terminal) in the parse tables. * Note: indexes are unique among terminals and unique among non terminals, * however, a terminal may have the same index as a non-terminal, etc. */ protected int _index; /** Index of this symbol (terminal or non terminal) in the parse tables. * Note: indexes are unique among terminals and unique among non terminals, * however, a terminal may have the same index as a non-terminal, etc. */ public int index() {return _index;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Indicate if this is a non-terminal. Here in the base class we * don't know, so this is abstract. */ public abstract boolean is_non_term(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Convert to a string. */ public String toString() { return name(); } /*-----------------------------------------------------------*/ }
3,724
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
reduce_action.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/reduce_action.java
package java_cup; /** This class represents a reduce action within the parse table. * The action simply stores the production that it reduces with and * responds to queries about its type. * * @version last updated: 11/25/95 * @author Scott Hudson */ public class reduce_action extends parse_action { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Simple constructor. * @param prod the production this action reduces with. */ public reduce_action(production prod ) throws internal_error { /* sanity check */ if (prod == null) throw new internal_error( "Attempt to create a reduce_action with a null production"); _reduce_with = prod; } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The production we reduce with. */ protected production _reduce_with; /** The production we reduce with. */ public production reduce_with() {return _reduce_with;} /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Quick access to type of action. */ public int kind() {return REDUCE;} /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Equality test. */ public boolean equals(reduce_action other) { return other != null && other.reduce_with() == reduce_with(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Generic equality test. */ public boolean equals(Object other) { if (other instanceof reduce_action) return equals((reduce_action)other); else return false; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Compute a hash code. */ public int hashCode() { /* use the hash code of the production we are reducing with */ return reduce_with().hashCode(); } /** Convert to string. */ public String toString() { return "REDUCE(with prod " + reduce_with().index() + ")"; } /*-----------------------------------------------------------*/ }
2,513
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
lr_parser.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/runtime/lr_parser.java
package java_cup.runtime; import java.util.Stack; /** This class implements a skeleton table driven LR parser. In general, * LR parsers are a form of bottom up shift-reduce parsers. Shift-reduce * parsers act by shifting input onto a parse stack until the Symbols * matching the right hand side of a production appear on the top of the * stack. Once this occurs, a reduce is performed. This involves removing * the Symbols corresponding to the right hand side of the production * (the so called "handle") and replacing them with the non-terminal from * the left hand side of the production. <p> * * To control the decision of whether to shift or reduce at any given point, * the parser uses a state machine (the "viable prefix recognition machine" * built by the parser generator). The current state of the machine is placed * on top of the parse stack (stored as part of a Symbol object representing * a terminal or non terminal). The parse action table is consulted * (using the current state and the current lookahead Symbol as indexes) to * determine whether to shift or to reduce. When the parser shifts, it * changes to a new state by pushing a new Symbol (containing a new state) * onto the stack. When the parser reduces, it pops the handle (right hand * side of a production) off the stack. This leaves the parser in the state * it was in before any of those Symbols were matched. Next the reduce-goto * table is consulted (using the new state and current lookahead Symbol as * indexes) to determine a new state to go to. The parser then shifts to * this goto state by pushing the left hand side Symbol of the production * (also containing the new state) onto the stack.<p> * * This class actually provides four LR parsers. The methods parse() and * debug_parse() provide two versions of the main parser (the only difference * being that debug_parse() emits debugging trace messages as it parses). * In addition to these main parsers, the error recovery mechanism uses two * more. One of these is used to simulate "parsing ahead" in the input * without carrying out actions (to verify that a potential error recovery * has worked), and the other is used to parse through buffered "parse ahead" * input in order to execute all actions and re-synchronize the actual parser * configuration.<p> * * This is an abstract class which is normally filled out by a subclass * generated by the JavaCup parser generator. In addition to supplying * the actual parse tables, generated code also supplies methods which * invoke various pieces of user supplied code, provide access to certain * special Symbols (e.g., EOF and error), etc. Specifically, the following * abstract methods are normally supplied by generated code: * <dl compact> * <dt> short[][] production_table() * <dd> Provides a reference to the production table (indicating the index of * the left hand side non terminal and the length of the right hand side * for each production in the grammar). * <dt> short[][] action_table() * <dd> Provides a reference to the parse action table. * <dt> short[][] reduce_table() * <dd> Provides a reference to the reduce-goto table. * <dt> int start_state() * <dd> Indicates the index of the start state. * <dt> int start_production() * <dd> Indicates the index of the starting production. * <dt> int EOF_sym() * <dd> Indicates the index of the EOF Symbol. * <dt> int error_sym() * <dd> Indicates the index of the error Symbol. * <dt> Symbol do_action() * <dd> Executes a piece of user supplied action code. This always comes at * the point of a reduce in the parse, so this code also allocates and * fills in the left hand side non terminal Symbol object that is to be * pushed onto the stack for the reduce. * <dt> void init_actions() * <dd> Code to initialize a special object that encapsulates user supplied * actions (this object is used by do_action() to actually carry out the * actions). * </dl> * * In addition to these routines that <i>must</i> be supplied by the * generated subclass there are also a series of routines that <i>may</i> * be supplied. These include: * <dl> * <dt> Symbol scan() * <dd> Used to get the next input Symbol from the scanner. * <dt> Scanner getScanner() * <dd> Used to provide a scanner for the default implementation of * scan(). * <dt> int error_sync_size() * <dd> This determines how many Symbols past the point of an error * must be parsed without error in order to consider a recovery to * be valid. This defaults to 3. Values less than 2 are not * recommended. * <dt> void report_error(String message, Object info) * <dd> This method is called to report an error. The default implementation * simply prints a message to System.err and where the error occurred. * This method is often replaced in order to provide a more sophisticated * error reporting mechanism. * <dt> void report_fatal_error(String message, Object info) * <dd> This method is called when a fatal error that cannot be recovered from * is encountered. In the default implementation, it calls * report_error() to emit a message, then throws an exception. * <dt> void syntax_error(Symbol cur_token) * <dd> This method is called as soon as syntax error is detected (but * before recovery is attempted). In the default implementation it * invokes: report_error("Syntax error", null); * <dt> void unrecovered_syntax_error(Symbol cur_token) * <dd> This method is called if syntax error recovery fails. In the default * implementation it invokes:<br> * report_fatal_error("Couldn't repair and continue parse", null); * </dl> * * @see java_cup.runtime.Symbol * @see java_cup.runtime.Symbol * @see java_cup.runtime.virtual_parse_stack * @version last updated: 7/3/96 * @author Frank Flannery */ public abstract class lr_parser { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Simple constructor. */ public lr_parser() { /* nothing to do here */ } /** Constructor that sets the default scanner. [CSA/davidm] */ public lr_parser(Scanner s) { this(); /* in case default constructor someday does something */ setScanner(s); } /*-----------------------------------------------------------*/ /*--- (Access to) Static (Class) Variables ------------------*/ /*-----------------------------------------------------------*/ /** The default number of Symbols after an error we much match to consider * it recovered from. */ protected final static int _error_sync_size = 3; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The number of Symbols after an error we much match to consider it * recovered from. */ protected int error_sync_size() {return _error_sync_size; } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** Table of production information (supplied by generated subclass). * This table contains one entry per production and is indexed by * the negative-encoded values (reduce actions) in the action_table. * Each entry has two parts, the index of the non-terminal on the * left hand side of the production, and the number of Symbols * on the right hand side. */ public abstract short[][] production_table(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The action table (supplied by generated subclass). This table is * indexed by state and terminal number indicating what action is to * be taken when the parser is in the given state (i.e., the given state * is on top of the stack) and the given terminal is next on the input. * States are indexed using the first dimension, however, the entries for * a given state are compacted and stored in adjacent index, value pairs * which are searched for rather than accessed directly (see get_action()). * The actions stored in the table will be either shifts, reduces, or * errors. Shifts are encoded as positive values (one greater than the * state shifted to). Reduces are encoded as negative values (one less * than the production reduced by). Error entries are denoted by zero. * * @see java_cup.runtime.lr_parser#get_action */ public abstract short[][] action_table(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The reduce-goto table (supplied by generated subclass). This * table is indexed by state and non-terminal number and contains * state numbers. States are indexed using the first dimension, however, * the entries for a given state are compacted and stored in adjacent * index, value pairs which are searched for rather than accessed * directly (see get_reduce()). When a reduce occurs, the handle * (corresponding to the RHS of the matched production) is popped off * the stack. The new top of stack indicates a state. This table is * then indexed by that state and the LHS of the reducing production to * indicate where to "shift" to. * * @see java_cup.runtime.lr_parser#get_reduce */ public abstract short[][] reduce_table(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The index of the start state (supplied by generated subclass). */ public abstract int start_state(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The index of the start production (supplied by generated subclass). */ public abstract int start_production(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The index of the end of file terminal Symbol (supplied by generated * subclass). */ public abstract int EOF_sym(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The index of the special error Symbol (supplied by generated subclass). */ public abstract int error_sym(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Internal flag to indicate when parser should quit. */ protected boolean _done_parsing = false; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** This method is called to indicate that the parser should quit. This is * normally called by an accept action, but can be used to cancel parsing * early in other circumstances if desired. */ public void done_parsing() { _done_parsing = true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Global parse state shared by parse(), error recovery, and * debugging routines */ /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Indication of the index for top of stack (for use by actions). */ protected int tos; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The current lookahead Symbol. */ protected Symbol cur_token, prev_token; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The parse stack itself. */ protected Stack stack = new Stack(); /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Direct reference to the production table. */ protected short[][] production_tab; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Direct reference to the action table. */ protected short[][] action_tab; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Direct reference to the reduce-goto table. */ protected short[][] reduce_tab; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** This is the scanner object used by the default implementation * of scan() to get Symbols. To avoid name conflicts with existing * code, this field is private. [CSA/davidm] */ private Scanner _scanner; /** * Simple accessor method to set the default scanner. */ public void setScanner(Scanner s) { _scanner = s; } /** * Simple accessor method to get the default scanner. */ public Scanner getScanner() { return _scanner; } /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Perform a bit of user supplied action code (supplied by generated * subclass). Actions are indexed by an internal action number assigned * at parser generation time. * * @param act_num the internal index of the action to be performed. * @param parser the parser object we are acting for. * @param stack the parse stack of that object. * @param top the index of the top element of the parse stack. */ public abstract Symbol do_action( int act_num, lr_parser parser, Stack stack, int top) throws java.lang.Exception; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** User code for initialization inside the parser. Typically this * initializes the scanner. This is called before the parser requests * the first Symbol. Here this is just a placeholder for subclasses that * might need this and we perform no action. This method is normally * overridden by the generated code using this contents of the "init with" * clause as its body. */ public void user_init() throws java.lang.Exception { } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Initialize the action object. This is called before the parser does * any parse actions. This is filled in by generated code to create * an object that encapsulates all action code. */ protected abstract void init_actions() throws java.lang.Exception; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Get the next Symbol from the input (supplied by generated subclass). * Once end of file has been reached, all subsequent calls to scan * should return an EOF Symbol (which is Symbol number 0). By default * this method returns getScanner().next_token(); this implementation * can be overriden by the generated parser using the code declared in * the "scan with" clause. Do not recycle objects; every call to * scan() should return a fresh object. */ public Symbol scan() throws java.lang.Exception { Symbol sym = getScanner().next_token(); return (sym!=null) ? sym : new Symbol(EOF_sym()); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Report a fatal error. This method takes a message string and an * additional object (to be used by specializations implemented in * subclasses). Here in the base class a very simple implementation * is provided which reports the error then throws an exception. * * @param message an error message. * @param info an extra object reserved for use by specialized subclasses. */ public void report_fatal_error( String message, Object info) throws java.lang.Exception { /* stop parsing (not really necessary since we throw an exception, but) */ done_parsing(); /* use the normal error message reporting to put out the message */ report_error(message, info); /* throw an exception */ throw new Exception("Can't recover from previous error(s)"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Report a non fatal error (or warning). This method takes a message * string and an additional object (to be used by specializations * implemented in subclasses). Here in the base class a very simple * implementation is provided which simply prints the message to * System.err. * * @param message an error message. * @param info an extra object reserved for use by specialized subclasses. */ public void report_error(String message, Object info) { System.err.print(message); if (info instanceof Symbol) if (((Symbol)info).left != -1) System.err.println(" at character " + ((Symbol)info).left + " of input"); else System.err.println(""); else System.err.println(""); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** This method is called when a syntax error has been detected and recovery * is about to be invoked. Here in the base class we just emit a * "Syntax error" error message. * * @param cur_token the current lookahead Symbol. */ public void syntax_error(Symbol cur_token) { report_error("Syntax error", cur_token); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** This method is called if it is determined that syntax error recovery * has been unsuccessful. Here in the base class we report a fatal error. * * @param cur_token the current lookahead Symbol. */ public void unrecovered_syntax_error(Symbol cur_token) throws java.lang.Exception { report_fatal_error("Couldn't repair and continue parse", cur_token); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Fetch an action from the action table. The table is broken up into * rows, one per state (rows are indexed directly by state number). * Within each row, a list of index, value pairs are given (as sequential * entries in the table), and the list is terminated by a default entry * (denoted with a Symbol index of -1). To find the proper entry in a row * we do a linear or binary search (depending on the size of the row). * * @param state the state index of the action being accessed. * @param sym the Symbol index of the action being accessed. */ protected final short get_action(int state, int sym) { short tag; int first, last, probe; short[] row = action_tab[state]; /* linear search if we are < 10 entries */ if (row.length < 20) for (probe = 0; probe < row.length; probe++) { /* is this entry labeled with our Symbol or the default? */ tag = row[probe++]; if (tag == sym || tag == -1) { /* return the next entry */ return row[probe]; } } /* otherwise binary search */ else { first = 0; last = (row.length-1)/2 - 1; /* leave out trailing default entry */ while (first <= last) { probe = (first+last)/2; if (sym == row[probe*2]) return row[probe*2+1]; else if (sym > row[probe*2]) first = probe+1; else last = probe-1; } /* not found, use the default at the end */ return row[row.length-1]; } /* shouldn't happened, but if we run off the end we return the default (error == 0) */ return 0; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Fetch a state from the reduce-goto table. The table is broken up into * rows, one per state (rows are indexed directly by state number). * Within each row, a list of index, value pairs are given (as sequential * entries in the table), and the list is terminated by a default entry * (denoted with a Symbol index of -1). To find the proper entry in a row * we do a linear search. * * @param state the state index of the entry being accessed. * @param sym the Symbol index of the entry being accessed. */ protected final short get_reduce(int state, int sym) { short tag; short[] row = reduce_tab[state]; /* if we have a null row we go with the default */ if (row == null) return -1; for (int probe = 0; probe < row.length; probe++) { /* is this entry labeled with our Symbol or the default? */ tag = row[probe++]; if (tag == sym || tag == -1) { /* return the next entry */ return row[probe]; } } /* if we run off the end we return the default (error == -1) */ return -1; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** This method provides the main parsing routine. It returns only when * done_parsing() has been called (typically because the parser has * accepted, or a fatal error has been reported). See the header * documentation for the class regarding how shift/reduce parsers operate * and how the various tables are used. */ public Symbol parse() throws java.lang.Exception { /* the current action code */ int act; /* the Symbol/stack element returned by a reduce */ Symbol lhs_sym = null; /* information about production being reduced with */ short handle_size, lhs_sym_num; /* set up direct reference to tables to drive the parser */ production_tab = production_table(); action_tab = action_table(); reduce_tab = reduce_table(); /* initialize the action encapsulation object */ init_actions(); /* do user initialization */ user_init(); /* get the first token */ cur_token = scan(); /* push dummy Symbol with start state to get us underway */ stack.removeAllElements(); stack.push(new Symbol(0, start_state())); tos = 0; /* continue until we are told to stop */ for (_done_parsing = false; !_done_parsing; ) { /* Check current token for freshness. */ if (cur_token.used_by_parser) throw new Error("Symbol recycling detected (fix your scanner)."); /* current state is always on the top of the stack */ /* look up action out of the current state with the current input */ act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym); /* decode the action -- > 0 encodes shift */ if (act > 0) { /* shift to the encoded state by pushing it on the stack */ cur_token.parse_state = act-1; cur_token.used_by_parser = true; stack.push(cur_token); tos++; /* advance to the next Symbol */ prev_token = cur_token; cur_token = scan(); } /* if its less than zero, then it encodes a reduce action */ else if (act < 0) { /* perform the action for the reduce */ lhs_sym = do_action((-act)-1, this, stack, tos); /* look up information about the production */ lhs_sym_num = production_tab[(-act)-1][0]; handle_size = production_tab[(-act)-1][1]; /* pop the handle off the stack */ for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; } /* look up the state to go to from the one popped back to */ act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num); /* shift to that state */ lhs_sym.parse_state = act; lhs_sym.used_by_parser = true; stack.push(lhs_sym); tos++; } /* finally if the entry is zero, we have an error */ else if (act == 0) { /* call user syntax error reporting routine */ syntax_error(cur_token); /* try to error recover */ if (!error_recovery(false)) { /* if that fails give up with a fatal syntax error */ unrecovered_syntax_error(cur_token); /* just in case that wasn't fatal enough, end parse */ done_parsing(); } else { lhs_sym = (Symbol)stack.peek(); } } } return lhs_sym; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Write a debugging message to System.err for the debugging version * of the parser. * * @param mess the text of the debugging message. */ public void debug_message(String mess) { System.err.println(mess); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Dump the parse stack for debugging purposes. */ public void dump_stack() { if (stack == null) { debug_message("# Stack dump requested, but stack is null"); return; } debug_message("============ Parse Stack Dump ============"); /* dump the stack */ for (int i=0; i<stack.size(); i++) { debug_message("Symbol: " + ((Symbol)stack.elementAt(i)).sym + " State: " + ((Symbol)stack.elementAt(i)).parse_state); } debug_message("=========================================="); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Do debug output for a reduce. * * @param prod_num the production we are reducing with. * @param nt_num the index of the LHS non terminal. * @param rhs_size the size of the RHS. */ public void debug_reduce(int prod_num, int nt_num, int rhs_size) { debug_message("# Reduce with prod #" + prod_num + " [NT=" + nt_num + ", " + "SZ=" + rhs_size + "]"); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Do debug output for shift. * * @param shift_tkn the Symbol being shifted onto the stack. */ public void debug_shift(Symbol shift_tkn) { debug_message("# Shift under term #" + shift_tkn.sym + " to state #" + shift_tkn.parse_state); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Do debug output for stack state. [CSA] */ public void debug_stack() { StringBuffer sb=new StringBuffer("## STACK:"); for (int i=0; i<stack.size(); i++) { Symbol s = (Symbol) stack.elementAt(i); sb.append(" <state "+s.parse_state+", sym "+s.sym+">"); if ((i%3)==2 || (i==(stack.size()-1))) { debug_message(sb.toString()); sb = new StringBuffer(" "); } } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Perform a parse with debugging output. This does exactly the * same things as parse(), except that it calls debug_shift() and * debug_reduce() when shift and reduce moves are taken by the parser * and produces various other debugging messages. */ public Symbol debug_parse() throws java.lang.Exception { /* the current action code */ int act; /* the Symbol/stack element returned by a reduce */ Symbol lhs_sym = null; /* information about production being reduced with */ short handle_size, lhs_sym_num; /* set up direct reference to tables to drive the parser */ production_tab = production_table(); action_tab = action_table(); reduce_tab = reduce_table(); debug_message("# Initializing parser"); /* initialize the action encapsulation object */ init_actions(); /* do user initialization */ user_init(); /* the current Symbol */ cur_token = scan(); debug_message("# Current Symbol is #" + cur_token.sym); /* push dummy Symbol with start state to get us underway */ stack.removeAllElements(); stack.push(new Symbol(0, start_state())); tos = 0; /* continue until we are told to stop */ for (_done_parsing = false; !_done_parsing; ) { /* Check current token for freshness. */ if (cur_token.used_by_parser) throw new Error("Symbol recycling detected (fix your scanner)."); /* current state is always on the top of the stack */ //debug_stack(); /* look up action out of the current state with the current input */ act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym); /* decode the action -- > 0 encodes shift */ if (act > 0) { /* shift to the encoded state by pushing it on the stack */ cur_token.parse_state = act-1; cur_token.used_by_parser = true; debug_shift(cur_token); stack.push(cur_token); tos++; /* advance to the next Symbol */ cur_token = scan(); debug_message("# Current token is " + cur_token); } /* if its less than zero, then it encodes a reduce action */ else if (act < 0) { /* perform the action for the reduce */ lhs_sym = do_action((-act)-1, this, stack, tos); /* look up information about the production */ lhs_sym_num = production_tab[(-act)-1][0]; handle_size = production_tab[(-act)-1][1]; debug_reduce((-act)-1, lhs_sym_num, handle_size); /* pop the handle off the stack */ for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; } /* look up the state to go to from the one popped back to */ act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num); debug_message("# Reduce rule: top state " + ((Symbol)stack.peek()).parse_state + ", lhs sym " + lhs_sym_num + " -> state " + act); /* shift to that state */ lhs_sym.parse_state = act; lhs_sym.used_by_parser = true; stack.push(lhs_sym); tos++; debug_message("# Goto state #" + act); } /* finally if the entry is zero, we have an error */ else if (act == 0) { /* call user syntax error reporting routine */ syntax_error(cur_token); /* try to error recover */ if (!error_recovery(true)) { /* if that fails give up with a fatal syntax error */ unrecovered_syntax_error(cur_token); /* just in case that wasn't fatal enough, end parse */ done_parsing(); } else { lhs_sym = (Symbol)stack.peek(); } } } return lhs_sym; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /* Error recovery code */ /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Attempt to recover from a syntax error. This returns false if recovery * fails, true if it succeeds. Recovery happens in 4 steps. First we * pop the parse stack down to a point at which we have a shift out * of the top-most state on the error Symbol. This represents the * initial error recovery configuration. If no such configuration is * found, then we fail. Next a small number of "lookahead" or "parse * ahead" Symbols are read into a buffer. The size of this buffer is * determined by error_sync_size() and determines how many Symbols beyond * the error must be matched to consider the recovery a success. Next, * we begin to discard Symbols in attempt to get past the point of error * to a point where we can continue parsing. After each Symbol, we attempt * to "parse ahead" though the buffered lookahead Symbols. The "parse ahead" * process simulates that actual parse, but does not modify the real * parser's configuration, nor execute any actions. If we can parse all * the stored Symbols without error, then the recovery is considered a * success. Once a successful recovery point is determined, we do an * actual parse over the stored input -- modifying the real parse * configuration and executing all actions. Finally, we return the the * normal parser to continue with the overall parse. * * @param debug should we produce debugging messages as we parse. */ protected boolean error_recovery(boolean debug) throws java.lang.Exception { if (debug) debug_message("# Attempting error recovery"); /* first pop the stack back into a state that can shift on error and do that shift (if that fails, we fail) */ if (!find_recovery_config(debug)) { if (debug) debug_message("# Error recovery fails"); return false; } /* read ahead to create lookahead we can parse multiple times */ read_lookahead(); /* repeatedly try to parse forward until we make it the required dist */ for (;;) { /* try to parse forward, if it makes it, bail out of loop */ if (debug) debug_message("# Trying to parse ahead"); if (try_parse_ahead(debug)) { break; } /* if we are now at EOF, we have failed */ if (lookahead[0].sym == EOF_sym()) { if (debug) debug_message("# Error recovery fails at EOF"); return false; } /* otherwise, we consume another Symbol and try again */ // BUG FIX by Bruce Hutton // Computer Science Department, University of Auckland, // Auckland, New Zealand. // It is the first token that is being consumed, not the one // we were up to parsing if (debug) debug_message("# Consuming Symbol #" + lookahead[ 0 ].sym); restart_lookahead(); } /* we have consumed to a point where we can parse forward */ if (debug) debug_message("# Parse-ahead ok, going back to normal parse"); /* do the real parse (including actions) across the lookahead */ parse_lookahead(debug); /* we have success */ return true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Determine if we can shift under the special error Symbol out of the * state currently on the top of the (real) parse stack. */ protected boolean shift_under_error() { /* is there a shift under error Symbol */ return get_action(((Symbol)stack.peek()).parse_state, error_sym()) > 0; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Put the (real) parse stack into error recovery configuration by * popping the stack down to a state that can shift on the special * error Symbol, then doing the shift. If no suitable state exists on * the stack we return false * * @param debug should we produce debugging messages as we parse. */ protected boolean find_recovery_config(boolean debug) { Symbol error_token; int act; if (debug) debug_message("# Finding recovery state on stack"); /* Remember the right-position of the top symbol on the stack */ int right_pos = ((Symbol)stack.peek()).right; int left_pos = ((Symbol)stack.peek()).left; /* pop down until we can shift under error Symbol */ while (!shift_under_error()) { /* pop the stack */ if (debug) debug_message("# Pop stack by one, state was # " + ((Symbol)stack.peek()).parse_state); left_pos = ((Symbol)stack.pop()).left; tos--; /* if we have hit bottom, we fail */ if (stack.empty()) { if (debug) debug_message("# No recovery state found on stack"); return false; } } /* state on top of the stack can shift under error, find the shift */ act = get_action(((Symbol)stack.peek()).parse_state, error_sym()); if (debug) { debug_message("# Recover state found (#" + ((Symbol)stack.peek()).parse_state + ")"); debug_message("# Shifting on error to state #" + (act-1)); } /* build and shift a special error Symbol */ error_token = new Symbol(error_sym(), left_pos, right_pos); error_token.parse_state = act-1; error_token.used_by_parser = true; stack.push(error_token); tos++; return true; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Lookahead Symbols used for attempting error recovery "parse aheads". */ protected Symbol lookahead[]; /** Position in lookahead input buffer used for "parse ahead". */ protected int lookahead_pos; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Read from input to establish our buffer of "parse ahead" lookahead * Symbols. */ protected void read_lookahead() throws java.lang.Exception { /* create the lookahead array */ lookahead = new Symbol[error_sync_size()]; /* fill in the array */ for (int i = 0; i < error_sync_size(); i++) { lookahead[i] = cur_token; cur_token = scan(); } /* start at the beginning */ lookahead_pos = 0; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Return the current lookahead in our error "parse ahead" buffer. */ protected Symbol cur_err_token() { return lookahead[lookahead_pos]; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Advance to next "parse ahead" input Symbol. Return true if we have * input to advance to, false otherwise. */ protected boolean advance_lookahead() { /* advance the input location */ lookahead_pos++; /* return true if we didn't go off the end */ return lookahead_pos < error_sync_size(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Reset the parse ahead input to one Symbol past where we started error * recovery (this consumes one new Symbol from the real input). */ protected void restart_lookahead() throws java.lang.Exception { /* move all the existing input over */ for (int i = 1; i < error_sync_size(); i++) lookahead[i-1] = lookahead[i]; /* read a new Symbol into the last spot */ // BUG Fix by Bruce Hutton // Computer Science Department, University of Auckland, // Auckland, New Zealand. [applied 5-sep-1999 by csa] // The following two lines were out of order!! lookahead[error_sync_size()-1] = cur_token; cur_token = scan(); /* reset our internal position marker */ lookahead_pos = 0; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Do a simulated parse forward (a "parse ahead") from the current * stack configuration using stored lookahead input and a virtual parse * stack. Return true if we make it all the way through the stored * lookahead input without error. This basically simulates the action of * parse() using only our saved "parse ahead" input, and not executing any * actions. * * @param debug should we produce debugging messages as we parse. */ protected boolean try_parse_ahead(boolean debug) throws java.lang.Exception { int act; short lhs, rhs_size; /* create a virtual stack from the real parse stack */ virtual_parse_stack vstack = new virtual_parse_stack(stack); /* parse until we fail or get past the lookahead input */ for (;;) { /* look up the action from the current state (on top of stack) */ act = get_action(vstack.top(), cur_err_token().sym); /* if its an error, we fail */ if (act == 0) return false; /* > 0 encodes a shift */ if (act > 0) { /* push the new state on the stack */ vstack.push(act-1); if (debug) debug_message("# Parse-ahead shifts Symbol #" + cur_err_token().sym + " into state #" + (act-1)); /* advance simulated input, if we run off the end, we are done */ if (!advance_lookahead()) return true; } /* < 0 encodes a reduce */ else { /* if this is a reduce with the start production we are done */ if ((-act)-1 == start_production()) { if (debug) debug_message("# Parse-ahead accepts"); return true; } /* get the lhs Symbol and the rhs size */ lhs = production_tab[(-act)-1][0]; rhs_size = production_tab[(-act)-1][1]; /* pop handle off the stack */ for (int i = 0; i < rhs_size; i++) vstack.pop(); if (debug) debug_message("# Parse-ahead reduces: handle size = " + rhs_size + " lhs = #" + lhs + " from state #" + vstack.top()); /* look up goto and push it onto the stack */ vstack.push(get_reduce(vstack.top(), lhs)); if (debug) debug_message("# Goto state #" + vstack.top()); } } } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Parse forward using stored lookahead Symbols. In this case we have * already verified that parsing will make it through the stored lookahead * Symbols and we are now getting back to the point at which we can hand * control back to the normal parser. Consequently, this version of the * parser performs all actions and modifies the real parse configuration. * This returns once we have consumed all the stored input or we accept. * * @param debug should we produce debugging messages as we parse. */ protected void parse_lookahead(boolean debug) throws java.lang.Exception { /* the current action code */ int act; /* the Symbol/stack element returned by a reduce */ Symbol lhs_sym = null; /* information about production being reduced with */ short handle_size, lhs_sym_num; /* restart the saved input at the beginning */ lookahead_pos = 0; if (debug) { debug_message("# Reparsing saved input with actions"); debug_message("# Current Symbol is #" + cur_err_token().sym); debug_message("# Current state is #" + ((Symbol)stack.peek()).parse_state); } /* continue until we accept or have read all lookahead input */ while(!_done_parsing) { /* current state is always on the top of the stack */ /* look up action out of the current state with the current input */ act = get_action(((Symbol)stack.peek()).parse_state, cur_err_token().sym); /* decode the action -- > 0 encodes shift */ if (act > 0) { /* shift to the encoded state by pushing it on the stack */ cur_err_token().parse_state = act-1; cur_err_token().used_by_parser = true; if (debug) debug_shift(cur_err_token()); stack.push(cur_err_token()); tos++; /* advance to the next Symbol, if there is none, we are done */ if (!advance_lookahead()) { if (debug) debug_message("# Completed reparse"); /* scan next Symbol so we can continue parse */ // BUGFIX by Chris Harris <[email protected]>: // correct a one-off error by commenting out // this next line. /*cur_token = scan();*/ /* go back to normal parser */ return; } if (debug) debug_message("# Current Symbol is #" + cur_err_token().sym); } /* if its less than zero, then it encodes a reduce action */ else if (act < 0) { /* perform the action for the reduce */ lhs_sym = do_action((-act)-1, this, stack, tos); /* look up information about the production */ lhs_sym_num = production_tab[(-act)-1][0]; handle_size = production_tab[(-act)-1][1]; if (debug) debug_reduce((-act)-1, lhs_sym_num, handle_size); /* pop the handle off the stack */ for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; } /* look up the state to go to from the one popped back to */ act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num); /* shift to that state */ lhs_sym.parse_state = act; lhs_sym.used_by_parser = true; stack.push(lhs_sym); tos++; if (debug) debug_message("# Goto state #" + act); } /* finally if the entry is zero, we have an error (shouldn't happen here, but...)*/ else if (act == 0) { report_fatal_error("Syntax error", lhs_sym); return; } } } /*-----------------------------------------------------------*/ /** Utility function: unpacks parse tables from strings */ protected static short[][] unpackFromStrings(String[] sa) { // Concatanate initialization strings. StringBuffer sb = new StringBuffer(sa[0]); for (int i=1; i<sa.length; i++) sb.append(sa[i]); int n=0; // location in initialization string int size1 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2; short[][] result = new short[size1][]; for (int i=0; i<size1; i++) { int size2 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2; result[i] = new short[size2]; for (int j=0; j<size2; j++) result[i][j] = (short) (sb.charAt(n++)-2); } return result; } }
45,377
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Scanner.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/runtime/Scanner.java
package java_cup.runtime; /** * Defines the Scanner interface, which CUP uses in the default * implementation of <code>lr_parser.scan()</code>. Integration * of scanners implementing <code>Scanner</code> is facilitated. * * @version last updated 23-Jul-1999 * @author David MacMahon <[email protected]> */ /* ************************************************* Interface Scanner Declares the next_token() method that should be implemented by scanners. This method is typically called by lr_parser.scan(). End-of-file can be indicated either by returning <code>new Symbol(lr_parser.EOF_sym())</code> or <code>null</code>. ***************************************************/ public interface Scanner { /** Return the next token, or <code>null</code> on end-of-file. */ public Symbol next_token() throws java.lang.Exception; }
887
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Symbol.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/runtime/Symbol.java
package java_cup.runtime; /** * Defines the Symbol class, which is used to represent all terminals * and nonterminals while parsing. The lexer should pass CUP Symbols * and CUP returns a Symbol. * * @version last updated: 7/3/96 * @author Frank Flannery */ /* **************************************************************** Class Symbol what the parser expects to receive from the lexer. the token is identified as follows: sym: the symbol type parse_state: the parse state. value: is the lexical value of type Object left : is the left position in the original input file right: is the right position in the original input file ******************************************************************/ public class Symbol { /******************************* Constructor for l,r values *******************************/ public Symbol(int id, int l, int r, Object o) { this(id); left = l; right = r; value = o; } /******************************* Constructor for no l,r values ********************************/ public Symbol(int id, Object o) { this(id, -1, -1, o); } /***************************** Constructor for no value ***************************/ public Symbol(int id, int l, int r) { this(id, l, r, null); } /*********************************** Constructor for no value or l,r ***********************************/ public Symbol(int sym_num) { this(sym_num, -1); left = -1; right = -1; value = null; } /*********************************** Constructor to give a start state ***********************************/ Symbol(int sym_num, int state) { sym = sym_num; parse_state = state; } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The symbol number of the terminal or non terminal being represented */ public int sym; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The parse state to be recorded on the parse stack with this symbol. * This field is for the convenience of the parser and shouldn't be * modified except by the parser. */ public int parse_state; /** This allows us to catch some errors caused by scanners recycling * symbols. For the use of the parser only. [CSA, 23-Jul-1999] */ boolean used_by_parser = false; /******************************* The data passed to parser *******************************/ public int left, right; public Object value; /***************************** Printing this token out. (Override for pretty-print). ****************************/ public String toString() { return "#"+sym; } }
2,766
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
virtual_parse_stack.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.xml/src/java_cup/runtime/virtual_parse_stack.java
package java_cup.runtime; import java.util.Stack; /** This class implements a temporary or "virtual" parse stack that * replaces the top portion of the actual parse stack (the part that * has been changed by some set of operations) while maintaining its * original contents. This data structure is used when the parse needs * to "parse ahead" to determine if a given error recovery attempt will * allow the parse to continue far enough to consider it successful. Once * success or failure of parse ahead is determined the system then * reverts to the original parse stack (which has not actually been * modified). Since parse ahead does not execute actions, only parse * state is maintained on the virtual stack, not full Symbol objects. * * @see java_cup.runtime.lr_parser * @version last updated: 7/3/96 * @author Frank Flannery */ public class virtual_parse_stack { /*-----------------------------------------------------------*/ /*--- Constructor(s) ----------------------------------------*/ /*-----------------------------------------------------------*/ /** Constructor to build a virtual stack out of a real stack. */ public virtual_parse_stack(Stack shadowing_stack) throws java.lang.Exception { /* sanity check */ if (shadowing_stack == null) throw new Exception( "Internal parser error: attempt to create null virtual stack"); /* set up our internals */ real_stack = shadowing_stack; vstack = new Stack(); real_next = 0; /* get one element onto the virtual portion of the stack */ get_from_real(); } /*-----------------------------------------------------------*/ /*--- (Access to) Instance Variables ------------------------*/ /*-----------------------------------------------------------*/ /** The real stack that we shadow. This is accessed when we move off * the bottom of the virtual portion of the stack, but is always left * unmodified. */ protected Stack real_stack; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Top of stack indicator for where we leave off in the real stack. * This is measured from top of stack, so 0 would indicate that no * elements have been "moved" from the real to virtual stack. */ protected int real_next; /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** The virtual top portion of the stack. This stack contains Integer * objects with state numbers. This stack shadows the top portion * of the real stack within the area that has been modified (via operations * on the virtual stack). When this portion of the stack becomes empty we * transfer elements from the underlying stack onto this stack. */ protected Stack vstack; /*-----------------------------------------------------------*/ /*--- General Methods ---------------------------------------*/ /*-----------------------------------------------------------*/ /** Transfer an element from the real to the virtual stack. This assumes * that the virtual stack is currently empty. */ protected void get_from_real() { Symbol stack_sym; /* don't transfer if the real stack is empty */ if (real_next >= real_stack.size()) return; /* get a copy of the first Symbol we have not transfered */ stack_sym = (Symbol)real_stack.elementAt(real_stack.size()-1-real_next); /* record the transfer */ real_next++; /* put the state number from the Symbol onto the virtual stack */ vstack.push(new Integer(stack_sym.parse_state)); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Indicate whether the stack is empty. */ public boolean empty() { /* if vstack is empty then we were unable to transfer onto it and the whole thing is empty. */ return vstack.empty(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Return value on the top of the stack (without popping it). */ public int top() throws java.lang.Exception { if (vstack.empty()) throw new Exception( "Internal parser error: top() called on empty virtual stack"); return ((Integer)vstack.peek()).intValue(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Pop the stack. */ public void pop() throws java.lang.Exception { if (vstack.empty()) throw new Exception( "Internal parser error: pop from empty virtual stack"); /* pop it */ vstack.pop(); /* if we are now empty transfer an element (if there is one) */ if (vstack.empty()) get_from_real(); } /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/ /** Push a state number onto the stack. */ public void push(int state_num) { vstack.push(new Integer(state_num)); } /*-----------------------------------------------------------*/ }
5,136
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridColumn.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridColumn.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 * Marty Jones<[email protected]> - custom header/footer font in bug 293743 * Cserveny Tamas <[email protected]> - min width in bug 295468 * Benjamin Bortfeldt<[email protected]> - new tooltip support in 300797 * Thomas Halm <[email protected]> - bugfix in 315397 * Cserveny Tamas <[email protected]> - bugfix in 318984 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.nebula.widgets.grid.internal.DefaultCellRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultColumnFooterRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultColumnHeaderRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.TypedListener; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A * PRE-RELEASE ALPHA VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE * VERSIONS. * </p> * Instances of this class represent a column in a grid widget. * <p> * <dl> * <dt><b>Styles:</b></dt> * <dd>SWT.LEFT, SWT.RIGHT, SWT.CENTER, SWT.CHECK</dd> * <dt><b>Events:</b></dt> * <dd>Move, Resize, Selection, Show, Hide</dd> * </dl> * * @author [email protected] */ public class GridColumn extends Item { private GridHeaderEditor controlEditor; /** * Default width of the column. */ private static final int DEFAULT_WIDTH = 10; /** * Parent table. */ private Grid parent; /** * Header renderer. */ private GridHeaderRenderer headerRenderer = new DefaultColumnHeaderRenderer(); private GridFooterRenderer footerRenderer = new DefaultColumnFooterRenderer(); /** * Cell renderer. */ private GridCellRenderer cellRenderer = new DefaultCellRenderer(); /** * Width of column. */ private int width = DEFAULT_WIDTH; /** * Sort style of column. Only used to draw indicator, does not actually sort * data. */ private int sortStyle = SWT.NONE; /** * Determines if this column shows toggles. */ private boolean tree = false; /** * Does this column contain check boxes? Did the user specify SWT.CHECK in * the constructor of the column. */ private boolean check = false; /** * Specifies if this column should display a checkbox because SWT.CHECK was * passed to the parent table (not necessarily the column). */ private boolean tableCheck = false; /** * Is this column resizable? */ private boolean resizeable = true; /** * Is this column moveable? */ private boolean moveable = false; /** * Is a summary column in a column group. Not applicable if this column is * not in a group. */ private boolean summary = true; /** * Is a detail column in a column group. Not applicable if this column is * not in a group. */ private boolean detail = true; private boolean visible = true; private boolean cellSelectionEnabled = true; private GridColumnGroup group; private boolean checkable = true; private Image footerImage; private String footerText = ""; private Font headerFont; private Font footerFont; private int minimumWidth = 0; private String headerTooltip = null; /** * Constructs a new instance of this class given its parent (which must be a * <code>Grid</code>) and a style value describing its behavior and * appearance. The item is added to the end of the items maintained by its * parent. * * @param parent * an Grid control which will be the parent of the new instance * (cannot be null) * @param style * the style of control to construct * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li> * ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridColumn(Grid parent, int style) { this(parent, style, -1); } /** * Constructs a new instance of this class given its parent (which must be a * <code>Grid</code>), a style value describing its behavior and appearance, * and the index at which to place it in the items maintained by its parent. * * @param parent * an Grid control which will be the parent of the new instance * (cannot be null) * @param style * the style of control to construct * @param index * the index to store the receiver in its parent * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li> * ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridColumn(Grid parent, int style, int index) { super(parent, style, index); init(parent, style, index); } /** * Constructs a new instance of this class given its parent column group * (which must be a <code>GridColumnGroup</code>), a style value describing * its behavior and appearance, and the index at which to place it in the * items maintained by its parent. * * @param parent * an Grid control which will be the parent of the new instance * (cannot be null) * @param style * the style of control to construct * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li> * ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridColumn(GridColumnGroup parent, int style) { super(parent.getParent(), style, parent.getNewColumnIndex()); init(parent.getParent(), style, parent.getNewColumnIndex()); group = parent; group.newColumn(this, -1); } private void init(Grid table, int style, int index) { this.parent = table; table.newColumn(this, index); if ((style & SWT.CHECK) == SWT.CHECK) { check = true; } initHeaderRenderer(); initFooterRenderer(); initCellRenderer(); } /** * {@inheritDoc} */ public void dispose() { if (!parent.isDisposing()) { parent.removeColumn(this); if (group != null) group.removeColumn(this); if (controlEditor != null ) { controlEditor.dispose(); } } super.dispose(); } /** * Initialize header renderer. */ private void initHeaderRenderer() { headerRenderer.setDisplay(getDisplay()); } private void initFooterRenderer() { footerRenderer.setDisplay(getDisplay()); } /** * Initialize cell renderer. */ private void initCellRenderer() { cellRenderer.setDisplay(getDisplay()); cellRenderer.setCheck(check); cellRenderer.setTree(tree); cellRenderer.setColumn(parent.indexOf(this)); if ((getStyle() & SWT.RIGHT) == SWT.RIGHT) { cellRenderer.setAlignment(SWT.RIGHT); } if ((getStyle() & SWT.CENTER) == SWT.CENTER) { cellRenderer.setAlignment(SWT.CENTER); } } /** * Returns the header renderer. * * @return header renderer */ public GridHeaderRenderer getHeaderRenderer() { return headerRenderer; } GridFooterRenderer getFooterRenderer() { return footerRenderer; } /** * Returns the cell renderer. * * @return cell renderer. */ public GridCellRenderer getCellRenderer() { return cellRenderer; } /** * Returns the width of the column. * * @return width of column * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getWidth() { checkWidget(); return width; } /** * Sets the width of the column. * * @param width * new width * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setWidth(int width) { checkWidget(); setWidth(width, true); } void setWidth(int width, boolean redraw) { this.width = Math.max(minimumWidth, width); if (redraw) { parent.setScrollValuesObsolete(); parent.redraw(); } } /** * Sets the sort indicator style for the column. This method does not actual * sort the data in the table. Valid values include: SWT.UP, SWT.DOWN, * SWT.NONE. * * @param style * SWT.UP, SWT.DOWN, SWT.NONE * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setSort(int style) { checkWidget(); sortStyle = style; parent.redraw(); } /** * Returns the sort indicator value. * * @return SWT.UP, SWT.DOWN, SWT.NONE * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getSort() { checkWidget(); return sortStyle; } /** * Adds the listener to the collection of listeners who will be notified * when the receiver's is pushed, by sending it one of the messages defined * in the <code>SelectionListener</code> interface. * * @param listener * the listener which should be notified * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void addSelectionListener(SelectionListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } this.addListener(SWT.Selection, new TypedListener(listener)); } /** * Removes the listener from the collection of listeners who will be * notified when the receiver's selection changes. * * @param listener * the listener which should no longer be notified * @see SelectionListener * @see #addSelectionListener(SelectionListener) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void removeSelectionListener(SelectionListener listener) { checkWidget(); this.removeListener(SWT.Selection, listener); } /** * Fires selection listeners. */ void fireListeners() { Event e = new Event(); e.display = this.getDisplay(); e.item = this; e.widget = parent; this.notifyListeners(SWT.Selection, e); } /** * Returns true if the column is visible, false otherwise. If the column is * in a group and the group is not expanded and this is a detail column, * returns false (and vice versa). * * @return true if visible, false otherwise * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean isVisible() { checkWidget(); if (group != null) { if ((group.getExpanded() && !isDetail()) || (!group.getExpanded() && !isSummary())) { return false; } } return visible; } /** * Returns the visibility state as set with {@code setVisible}. * * @return the visible * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getVisible() { checkWidget(); return visible; } /** * Sets the column's visibility. * * @param visible * the visible to set * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setVisible(boolean visible) { checkWidget(); boolean before = isVisible(); this.visible = visible; if (isVisible() != before) { if (visible) { notifyListeners(SWT.Show, new Event()); } else { notifyListeners(SWT.Hide, new Event()); } GridColumn[] colsOrdered = parent.getColumnsInOrder(); boolean fire = false; for (int i = 0; i < colsOrdered.length; i++) { GridColumn column = colsOrdered[i]; if (column == this) { fire = true; } else { if (column.isVisible()) column.fireMoved(); } } parent.redraw(); } } /** * Causes the receiver to be resized to its preferred size. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void pack() { checkWidget(); GC gc = new GC(parent); int newWidth = getHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).x; GridItem[] items = parent.getItems(); for (int i = 0; i < items.length; i++) { GridItem item = items[i]; if (item.isVisible()) { getCellRenderer().setColumn(parent.indexOf(this)); newWidth = Math.max(newWidth, getCellRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, item).x); } } gc.dispose(); setWidth(newWidth); parent.redraw(); } /** * Returns true if this column includes a tree toggle. * * @return true if the column includes the tree toggle. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean isTree() { checkWidget(); return tree; } /** * Returns true if the column includes a check box. * * @return true if the column includes a check box. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean isCheck() { checkWidget(); return check || tableCheck; } /** * Sets the cell renderer. * * @param cellRenderer * The cellRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setCellRenderer(GridCellRenderer cellRenderer) { checkWidget(); this.cellRenderer = cellRenderer; initCellRenderer(); } /** * Sets the header renderer. * * @param headerRenderer * The headerRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setHeaderRenderer(GridHeaderRenderer headerRenderer) { checkWidget(); this.headerRenderer = headerRenderer; initHeaderRenderer(); } /** * Sets the header renderer. * * @param footerRenderer * The footerRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setFooterRenderer(GridFooterRenderer footerRenderer) { checkWidget(); this.footerRenderer = footerRenderer; initFooterRenderer(); } /** * Adds a listener to the list of listeners notified when the column is * moved or resized. * * @param listener * listener * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void addControlListener(ControlListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } TypedListener typedListener = new TypedListener(listener); addListener(SWT.Resize, typedListener); addListener(SWT.Move, typedListener); } /** * Removes the given control listener. * * @param listener * listener. * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void removeControlListener(ControlListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } removeListener(SWT.Resize, listener); removeListener(SWT.Move, listener); } /** * Fires moved event. */ void fireMoved() { Event e = new Event(); e.display = this.getDisplay(); e.item = this; e.widget = parent; this.notifyListeners(SWT.Move, e); } /** * Fires resized event. */ void fireResized() { Event e = new Event(); e.display = this.getDisplay(); e.item = this; e.widget = parent; this.notifyListeners(SWT.Resize, e); } /** * Adds or removes the columns tree toggle. * * @param tree * true to add toggle. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setTree(boolean tree) { checkWidget(); this.tree = tree; cellRenderer.setTree(tree); parent.redraw(); } /** * Returns the column alignment. * * @return SWT.LEFT, SWT.RIGHT, SWT.CENTER * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getAlignment() { checkWidget(); return cellRenderer.getAlignment(); } /** * Sets the column alignment. * * @param alignment * SWT.LEFT, SWT.RIGHT, SWT.CENTER * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setAlignment(int alignment) { checkWidget(); cellRenderer.setAlignment(alignment); } /** * Returns true if this column is moveable. * * @return true if moveable. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getMoveable() { checkWidget(); return moveable; } /** * Sets the column moveable or fixed. * * @param moveable * true to enable column moving * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setMoveable(boolean moveable) { checkWidget(); this.moveable = moveable; parent.redraw(); } /** * Returns true if the column is resizeable. * * @return true if the column is resizeable. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getResizeable() { checkWidget(); return resizeable; } /** * Sets the column resizeable. * * @param resizeable * true to make the column resizeable * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setResizeable(boolean resizeable) { checkWidget(); this.resizeable = resizeable; } /** * Returns the column group if this column was created inside a group, or * {@code null} otherwise. * * @return the column group. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public GridColumnGroup getColumnGroup() { checkWidget(); return group; } /** * Returns true if this column is set as a detail column in a column group. * Detail columns are shown when the group is expanded. * * @return true if the column is a detail column. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean isDetail() { checkWidget(); return detail; } /** * Sets the column as a detail column in a column group. Detail columns are * shown when a column group is expanded. If this column was not created in * a column group, this method has no effect. * * @param detail * true to show this column when the group is expanded. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setDetail(boolean detail) { checkWidget(); this.detail = detail; } /** * Returns true if this column is set as a summary column in a column group. * Summary columns are shown when the group is collapsed. * * @return true if the column is a summary column. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean isSummary() { checkWidget(); return summary; } /** * Sets the column as a summary column in a column group. Summary columns * are shown when a column group is collapsed. If this column was not * created in a column group, this method has no effect. * * @param summary * true to show this column when the group is collapsed. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setSummary(boolean summary) { checkWidget(); this.summary = summary; } /** * Returns the bounds of this column's header. * * @return bounds of the column header */ Rectangle getBounds() { Rectangle bounds = new Rectangle(0, 0, 0, 0); if (!isVisible()) { return bounds; } Point loc = parent.getOrigin(this, null); bounds.x = loc.x; bounds.y = loc.y; bounds.width = getWidth(); bounds.height = parent.getHeaderHeight(); if (getColumnGroup() != null) { bounds.height -= parent.getGroupHeaderHeight(); } return bounds; } /** * @return the tableCheck */ protected boolean isTableCheck() { return tableCheck; } /** * @param tableCheck * the tableCheck to set */ protected void setTableCheck(boolean tableCheck) { this.tableCheck = tableCheck; cellRenderer.setCheck(tableCheck || check); } /** * Returns true if cells in the receiver can be selected. * * @return the cellSelectionEnabled * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getCellSelectionEnabled() { checkWidget(); return cellSelectionEnabled; } /** * Sets whether cells in the receiver can be selected. * * @param cellSelectionEnabled * the cellSelectionEnabled to set * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setCellSelectionEnabled(boolean cellSelectionEnabled) { checkWidget(); this.cellSelectionEnabled = cellSelectionEnabled; } /** * Returns the parent grid. * * @return the parent grid. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Grid getParent() { checkWidget(); return parent; } /** * Returns the checkable state. If false the checkboxes in the column cannot * be checked. * * @return true if the column is checkable (only applicable when style is * SWT.CHECK). * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getCheckable() { checkWidget(); return checkable; } /** * Sets the checkable state. If false the checkboxes in the column cannot be * checked. * * @param checkable * the new checkable state. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setCheckable(boolean checkable) { checkWidget(); this.checkable = checkable; } void setColumnIndex(int newIndex) { cellRenderer.setColumn(newIndex); } /** * Returns the true if the cells in receiver wrap their text. * * @return true if the cells wrap their text. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getWordWrap() { checkWidget(); return cellRenderer.isWordWrap(); } /** * If the argument is true, wraps the text in the receiver's cells. This * feature will not cause the row height to expand to accommodate the * wrapped text. Please use <code>Grid#setItemHeight</code> to change the * height of each row. * * @param wordWrap * true to make cells wrap their text. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setWordWrap(boolean wordWrap) { checkWidget(); cellRenderer.setWordWrap(wordWrap); parent.redraw(); } /** * Sets whether or not text is word-wrapped in the header for this column. * If Grid.setAutoHeight(true) is set, the row height is adjusted to * accommodate word-wrapped text. * * @param wordWrap * Set to true to wrap the text, false otherwise * @see #getHeaderWordWrap() */ public void setHeaderWordWrap(boolean wordWrap) { checkWidget(); headerRenderer.setWordWrap(wordWrap); parent.redraw(); } /** * Returns whether or not text is word-wrapped in the header for this * column. * * @return true if the header wraps its text. * @see GridColumn#setHeaderWordWrap(boolean) */ public boolean getHeaderWordWrap() { checkWidget(); return headerRenderer.isWordWrap(); } /** * Set a new editor at the top of the control. If there's an editor already * set it is disposed. * * @param control * the control to be displayed in the header */ public void setHeaderControl(Control control) { if (this.controlEditor == null) { this.controlEditor = new GridHeaderEditor(this); this.controlEditor.initColumn(); } this.controlEditor.setEditor(control); getParent().recalculateHeader(); if (control != null) { // We need to realign if multiple editors are set it is possible // that // a later one needs more space control.getDisplay().asyncExec(new Runnable() { public void run() { if (GridColumn.this.controlEditor != null && GridColumn.this.controlEditor.getEditor() != null) { GridColumn.this.controlEditor.layout(); } } }); } } /** * @return the current header control */ public Control getHeaderControl() { if (this.controlEditor != null) { return this.controlEditor.getEditor(); } return null; } /** * Returns the tooltip of the column header. * * @return the tooltip text */ public String getHeaderTooltip() { checkWidget(); return headerTooltip; } /** * Sets the tooltip text of the column header. * * @param tooltip the tooltip text */ public void setHeaderTooltip(String tooltip) { checkWidget(); this.headerTooltip = tooltip; } /** * Sets the receiver's footer image to the argument, which may be null * indicating that no image should be displayed. * * @param image * the image to display on the receiver (may be null) * * @exception IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been * disposed</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setFooterImage(Image image) { checkWidget(); if (image != null && image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); this.footerImage = image; } /** * Sets the receiver's footer text. * * @param string * the new text * * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the text is null</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setFooterText(String string) { checkWidget(); if (string == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); this.footerText = string; } /** * Returns the receiver's footer image if it has one, or null if it does * not. * * @return the receiver's image * * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Image getFooterImage() { checkWidget(); return footerImage; } /** * Returns the receiver's footer text, which will be an empty string if it * has never been set. * * @return the receiver's text * * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public String getFooterText() { checkWidget(); return footerText; } /** * Returns the font that the receiver will use to paint textual information * for the header. * * @return the receiver's font * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Font getHeaderFont() { checkWidget(); if (headerFont == null) { return parent.getFont(); } return headerFont; } /** * Sets the Font to be used when displaying the Header text. * * @param font */ public void setHeaderFont(Font font) { checkWidget(); headerFont = font; } /** * Returns the font that the receiver will use to paint textual information * for the footer. * * @return the receiver's font * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Font getFooterFont() { checkWidget(); if (footerFont == null) { return parent.getFont(); } return footerFont; } /** * Sets the Font to be used when displaying the Footer text. * * @param font */ public void setFooterFont(Font font) { checkWidget(); footerFont = font; } /** * @return the minimum width */ public int getMinimumWidth() { return minimumWidth; } /** * Set the minimum width of the column * * @param minimumWidth * the minimum width */ public void setMinimumWidth(int minimumWidth) { this.minimumWidth = Math.max(0, minimumWidth); if( minimumWidth > getWidth() ) { setWidth(minimumWidth, true); } } }
39,444
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridHeaderEditor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridHeaderEditor.java
/******************************************************************************* * Copyright (c) 2009 BestSolution.at * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - bugfix in 257923 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ControlEditor; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * Manager for a Control that appears below the grid column header. Based on * {@link GridEditor}. */ class GridHeaderEditor extends ControlEditor { private Grid table; private GridColumn column; ControlListener columnListener; Listener resizeListener; private final Listener columnVisibleListener; private final Listener columnGroupListener; private final SelectionListener scrollListener; private final Listener mouseOverListener; /** * Creates a TableEditor for the specified Table. * * @param column * the Table Control above which this editor will be displayed */ GridHeaderEditor(final GridColumn column) { super(column.getParent()); this.table = column.getParent(); this.column = column; columnListener = new ControlListener() { public void controlMoved(ControlEvent e) { table.getDisplay().asyncExec(new Runnable() { public void run() { layout(); } }); } public void controlResized(ControlEvent e) { layout(); } }; columnVisibleListener = new Listener() { public void handleEvent(Event event) { getEditor().setVisible(column.isVisible()); // if (getEditor().isVisible()) layout(); } }; resizeListener = new Listener() { public void handleEvent(Event event) { layout(); } }; scrollListener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { layout(); } public void widgetDefaultSelected(SelectionEvent e) { } }; columnGroupListener = new Listener() { public void handleEvent(Event event) { if (getEditor() == null || getEditor().isDisposed()) return; getEditor().setVisible(column.isVisible()); // if (getEditor().isVisible()) layout(); } }; // Reset the mouse cursor when the mouse hovers the control mouseOverListener = new Listener() { public void handleEvent(Event event) { if (table.getCursor() != null) { // We need to reset because it could be that when we left the resizer was active table.hoveringOnColumnResizer=false; table.setCursor(null); } } }; // The following three listeners are workarounds for // Eclipse bug 105764 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=105764 table.addListener(SWT.Resize, resizeListener); if (table.getVerticalScrollBarProxy() != null) { table.getVerticalScrollBarProxy().addSelectionListener( scrollListener); } if (table.getHorizontalScrollBarProxy() != null) { table.getHorizontalScrollBarProxy().addSelectionListener( scrollListener); } // To be consistent with older versions of SWT, grabVertical defaults to // true grabVertical = true; // initColumn(); } /** * Returns the bounds of the editor. * * @return bounds of the editor. */ protected Rectangle internalComputeBounds() { column.getHeaderRenderer().setBounds(column.getBounds()); return column.getHeaderRenderer().getControlBounds(column, true); } /** * Removes all associations between the TableEditor and the cell in the * table. The Table and the editor Control are <b>not</b> disposed. */ public void dispose() { if (!table.isDisposed() && !column.isDisposed()) { column.removeControlListener(columnListener); if (column.getColumnGroup() != null) { column.getColumnGroup().removeListener(SWT.Expand, columnGroupListener); column.getColumnGroup().removeListener(SWT.Collapse, columnGroupListener); } } if (!table.isDisposed()) { table.removeListener(SWT.Resize, resizeListener); if (table.getVerticalScrollBarProxy() != null) table.getVerticalScrollBarProxy().removeSelectionListener( scrollListener); if (table.getHorizontalScrollBarProxy() != null) table.getHorizontalScrollBarProxy().removeSelectionListener( scrollListener); } columnListener = null; resizeListener = null; table = null; super.dispose(); } /** * Sets the zero based index of the column of the cell being tracked by this * editor. * * @param column * the zero based index of the column of the cell being tracked * by this editor */ void initColumn() { column.addControlListener(columnListener); column.addListener(SWT.Show, columnVisibleListener); column.addListener(SWT.Hide, columnVisibleListener); if (column.getColumnGroup() != null) { column.getColumnGroup() .addListener(SWT.Expand, columnGroupListener); column.getColumnGroup().addListener(SWT.Collapse, columnGroupListener); } layout(); } /** * {@inheritDoc} */ public void layout() { if (table.isDisposed()) return; boolean hadFocus = false; if (getEditor() == null || getEditor().isDisposed() || !column.isVisible()) { return; } if (getEditor().getVisible()) { hadFocus = getEditor().isFocusControl(); } Rectangle rect = internalComputeBounds(); if (rect == null || rect.x < 0) { getEditor().setVisible(false); return; } else if(table.getItemHeaderWidth()>0&&table.getItemHeaderWidth()>rect.x){ getEditor().setVisible(false); return; }else { getEditor().setVisible(true); } getEditor().setBounds(rect); if (hadFocus) { if (getEditor() == null || getEditor().isDisposed()) return; getEditor().setFocus(); } } public void setEditor(Control editor) { if (getEditor() != null) { getEditor().removeListener(SWT.MouseEnter, mouseOverListener); } super.setEditor(editor); if (editor != null) { getEditor().addListener(SWT.MouseEnter, mouseOverListener); } } }
6,628
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridColumnGroup.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridColumnGroup.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - bugfix in 244333 * Marty Jones<[email protected]> - custom header/footer font in bug 293743 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.nebula.widgets.grid.internal.DefaultColumnGroupHeaderRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.TypedListener; import java.util.Vector; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * Instances of this class represent a column group in a grid widget. A column group header is * displayed above grouped columns. The column group can optionally be configured to expand and * collapse. A column group in the expanded state shows {@code GridColumn}s whose detail property * is true. A column group in the collapsed state shows {@code GridColumn}s whose summary property * is true. * <p> * <dl> * <dt><b>Styles:</b></dt> * <dd>SWT.TOGGLE</dd> * <dt><b>Events:</b></dt> * <dd>Expand, Collapse</dd> * </dl> * * @author [email protected] */ public class GridColumnGroup extends Item { private Grid parent; private GridColumn[] columns = new GridColumn[] {}; private boolean expanded = true; private Font headerFont; /** * Header renderer. */ private GridHeaderRenderer headerRenderer = new DefaultColumnGroupHeaderRenderer(); /** * Constructs a new instance of this class given its parent (which must be a Table) and a style * value describing its behavior and appearance. * * @param parent the parent table * @param style the style of the group * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> */ public GridColumnGroup(Grid parent, int style) { super(parent, style); this.parent = parent; headerRenderer.setDisplay(getDisplay()); parent.newColumnGroup(this); } /** * Adds the listener to the collection of listeners who will * be notified when an item in the receiver is expanded or collapsed * by sending it one of the messages defined in the <code>TreeListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TreeListener * @see #removeTreeListener */ public void addTreeListener(TreeListener listener) { checkWidget (); if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Expand, typedListener); addListener (SWT.Collapse, typedListener); } /** * Removes the listener from the collection of listeners who will * be notified when items in the receiver are expanded or collapsed. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TreeListener * @see #addTreeListener */ public void removeTreeListener(TreeListener listener) { checkWidget (); if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); removeListener (SWT.Expand, listener); removeListener (SWT.Collapse, listener); } /** * Returns the parent grid. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Grid getParent() { checkWidget(); return parent; } int getNewColumnIndex() { if (columns.length == 0) { return -1; } GridColumn lastCol = columns[columns.length - 1]; return parent.indexOf(lastCol) + 1; } void newColumn(GridColumn column, int index) { GridColumn[] newAllColumns = new GridColumn[columns.length + 1]; System.arraycopy(columns, 0, newAllColumns, 0, columns.length); newAllColumns[newAllColumns.length - 1] = column; columns = newAllColumns; } void removeColumn(GridColumn col) { if (columns.length == 0) return; // widget is disposing GridColumn[] newAllColumns = new GridColumn[columns.length - 1]; int x = 0; for (int i = 0; i < columns.length; i++) { if (columns[i] != col) { newAllColumns[x] = columns[i]; x ++; } } columns = newAllColumns; } /** * Returns the columns within this group. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * @return the columns * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn[] getColumns() { checkWidget(); GridColumn[] newArray = new GridColumn[columns.length]; System.arraycopy (columns, 0, newArray, 0, columns.length); return newArray; } /** * {@inheritDoc} */ public void dispose() { super.dispose(); if (parent.isDisposing()) return; GridColumn[] oldColumns = columns; columns = new GridColumn[0]; for (int i = 0; i < oldColumns.length; i++) { oldColumns[i].dispose(); } parent.removeColumnGroup(this); } /** * Gets the header renderer. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridHeaderRenderer getHeaderRenderer() { checkWidget(); return headerRenderer; } /** * Sets the header renderer. * * @param headerRenderer The headerRenderer to set. * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the renderer is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setHeaderRenderer(GridHeaderRenderer headerRenderer) { if (headerRenderer == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); this.headerRenderer = headerRenderer; headerRenderer.setDisplay(getDisplay()); } /** * Returns true if the receiver is expanded, false otherwise. * * @return the expanded attribute * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getExpanded() { checkWidget(); return expanded; } /** * Sets the expanded state of the receiver. * * @param expanded the expanded to set * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setExpanded(boolean expanded) { checkWidget(); this.expanded = expanded; if (!expanded && getParent().getCellSelectionEnabled()) { Vector collapsedCols = new Vector(); for (int j = 0; j < columns.length; j++) { if (!columns[j].isSummary()) { collapsedCols.add(new Integer(getParent().indexOf(columns[j]))); } } Point[] selection = getParent().getCellSelection(); for (int i = 0; i < selection.length; i++) { if (collapsedCols.contains(new Integer(selection[i].x))) { getParent().deselectCell(selection[i]); } } if (getParent().getFocusColumn() != null && getParent().getFocusColumn().getColumnGroup() == this) { getParent().updateColumnFocus(); } parent.updateColumnSelection(); } if (parent.getCellSelectionEnabled()) parent.refreshHoverState(); parent.setScrollValuesObsolete(); parent.redraw(); } /** * Returns the first visible column in this column group. * * @return first visible column */ GridColumn getFirstVisibleColumn() { GridColumn[] cols = parent.getColumnsInOrder(); for (int i = 0; i < cols.length; i++) { if (cols[i].getColumnGroup() == this && cols[i].isVisible()) { return cols[i]; } } return null; } /** * Returns the last visible column in this column group. * * @return last visible column */ GridColumn getLastVisibleColumn() { GridColumn[] cols = parent.getColumnsInOrder(); GridColumn lastVisible = null; for (int i = 0; i < cols.length; i++) { if (cols[i].getColumnGroup() == this && cols[i].isVisible()) { lastVisible = cols[i]; } } return lastVisible; } Rectangle getBounds() { Rectangle bounds = new Rectangle(0, 0, 0, 0); bounds.height = parent.getGroupHeaderHeight(); boolean foundFirstColumnInGroup = false; GridColumn[] cols = parent.getColumnsInOrder(); for (int i = 0; i < cols.length; i++) { if (cols[i].getColumnGroup() == this) { if (cols[i].isVisible()) { if (!foundFirstColumnInGroup) { bounds.x = parent.getOrigin(cols[i], null).x; foundFirstColumnInGroup = true; } bounds.width += cols[i].getWidth(); } } else { if (foundFirstColumnInGroup) { break; } } } return bounds; } /** * Sets whether or not text is word-wrapped in the header for this column group. If Grid.setAutoHeight(true) is set, the row height * is adjusted to accommodate word-wrapped text. * @param wordWrap Set to true to wrap the text, false otherwise * @see #getHeaderWordWrap() */ public void setHeaderWordWrap(boolean wordWrap) { checkWidget(); headerRenderer.setWordWrap(wordWrap); parent.redraw(); } /** * Returns whether or not text is word-wrapped in the header for this column group. * @return true if the header wraps its text. * @see GridColumn#setHeaderWordWrap(boolean) */ public boolean getHeaderWordWrap() { checkWidget(); return headerRenderer.isWordWrap(); } /** * Returns the font that the receiver will use to paint textual information * for the header. * * @return the receiver's font * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Font getHeaderFont() { checkWidget(); if (headerFont == null) { return parent.getFont(); } return headerFont; } /** * Sets the Font to be used when displaying the Header text. * @param font */ public void setHeaderFont(Font font) { checkWidget(); this.headerFont = font; } }
14,153
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridCellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridCellRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Rectangle; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * The super class for all grid cell renderers. Contains the properties specific * to a grid cell. * * @author [email protected] */ public abstract class GridCellRenderer extends AbstractInternalWidget { private int row = 0; private int column = 0; private int alignment = SWT.LEFT; private boolean tree = false; private boolean check = false; private boolean rowHover = false; private boolean columnHover = false; private boolean rowFocus = false; private boolean cellFocus = false; private boolean cellSelected = false; private boolean wordWrap = false; private boolean dragging = false; /** * @return Returns the row. */ public int getRow() { return row; } /** * @param row The row to set. */ public void setRow(int row) { this.row = row; } /** * @return Returns the alignment. */ public int getAlignment() { return alignment; } /** * @param alignment The alignment to set. */ public void setAlignment(int alignment) { this.alignment = alignment; } /** * @return Returns the check. */ public boolean isCheck() { return check; } /** * @param check The check to set. */ public void setCheck(boolean check) { this.check = check; } /** * @return Returns the tree. */ public boolean isTree() { return tree; } /** * @param tree The tree to set. */ public void setTree(boolean tree) { this.tree = tree; } /** * @return Returns the column. */ public int getColumn() { return column; } /** * @param column The column to set. */ public void setColumn(int column) { this.column = column; } /** * @return Returns the columnHover. */ public boolean isColumnHover() { return columnHover; } /** * @param columnHover The columnHover to set. */ public void setColumnHover(boolean columnHover) { this.columnHover = columnHover; } /** * @return Returns the rowHover. */ public boolean isRowHover() { return rowHover; } /** * @param rowHover The rowHover to set. */ public void setRowHover(boolean rowHover) { this.rowHover = rowHover; } /** * @return Returns the columnFocus. */ public boolean isCellFocus() { return cellFocus; } /** * @param columnFocus The columnFocus to set. */ public void setCellFocus(boolean columnFocus) { this.cellFocus = columnFocus; } /** * @return Returns the rowFocus. */ public boolean isRowFocus() { return rowFocus; } /** * @param rowFocus The rowFocus to set. */ public void setRowFocus(boolean rowFocus) { this.rowFocus = rowFocus; } /** * @return the cellSelected */ public boolean isCellSelected() { return cellSelected; } /** * @param cellSelected the cellSelected to set */ public void setCellSelected(boolean cellSelected) { this.cellSelected = cellSelected; } /** * Returns the bounds of the text in the cell. This is used when displaying in-place tooltips. * If <code>null</code> is returned here, in-place tooltips will not be displayed. If the * <code>preferred</code> argument is <code>true</code> then the returned bounds should be large * enough to show the entire text. If <code>preferred</code> is <code>false</code> then the * returned bounds should be be relative to the current bounds. * * @param item item to calculate text bounds. * @param preferred true if the preferred width of the text should be returned. * @return bounds of the text. */ public Rectangle getTextBounds(GridItem item, boolean preferred) { return null; } /** * @return the wordWrap */ public boolean isWordWrap() { return wordWrap; } /** * @param wordWrap the wordWrap to set */ public void setWordWrap(boolean wordWrap) { this.wordWrap = wordWrap; } /** * Gets the dragging state. * * @return Returns the dragging state. */ public boolean isDragging() { return dragging; } /** * Sets the dragging state. * * @param dragging The state to set. */ public void setDragging(boolean dragging) { this.dragging = dragging; } }
5,587
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridVisibleRangeSupport.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridVisibleRangeSupport.java
package org.eclipse.nebula.widgets.grid; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EventObject; import java.util.Iterator; import org.eclipse.nebula.widgets.grid.Grid.GridVisibleRange; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * This support class adds the possibility to get informed when the visual range * in the grid is modified. E.g. to implement clever resource management * <p> * <b>This support is provisional and may change</b> * </p> */ public class GridVisibleRangeSupport { private Collection rangeChangeListener; private Grid grid; private GridVisibleRange oldRange = new GridVisibleRange(); private Listener paintListener = new Listener() { public void handleEvent(Event event) { calculateChange(); } }; /** * Listener notified when the visible range changes */ public interface VisibleRangeChangedListener { /** * Method called when range is changed * * @param event * the event holding informations about the change */ public void rangeChanged(RangeChangedEvent event); } /** * Event informing about the change */ public static class RangeChangedEvent extends EventObject { /** * */ private static final long serialVersionUID = 1L; /** * Rows new in the visible range */ public GridItem[] addedRows; /** * Rows removed from the range */ public GridItem[] removedRows; /** * Columns added to the range */ public GridColumn[] addedColumns; /** * Columns removed from the range */ public GridColumn[] removedColumns; /** * The current visible range */ public GridVisibleRange visibleRange; RangeChangedEvent(Grid grid, GridVisibleRange visibleRange) { super(grid); this.visibleRange = visibleRange; } } private GridVisibleRangeSupport(Grid grid) { this.grid = grid; this.grid.setSizeOnEveryItemImageChange(true); // FIXME Maybe better to listen to resize, ... ? grid.addListener(SWT.Paint, paintListener); } /** * Add a listener who is informed when the range is changed * * @param listener * the listener to add */ public void addRangeChangeListener(VisibleRangeChangedListener listener) { if (rangeChangeListener == null) { rangeChangeListener = new ArrayList(); } rangeChangeListener.add(listener); } /** * Remove the listener from the ones informed when the range is changed * * @param listener */ public void removeRangeChangeListener(VisibleRangeChangedListener listener) { if (rangeChangeListener != null) { rangeChangeListener.remove(listener); if (rangeChangeListener.size() == 0) { rangeChangeListener = null; } } } private void calculateChange() { // FIXME Add back if (rangeChangeListener != null) { GridVisibleRange range = grid.getVisibleRange(); ArrayList lOrigItems = new ArrayList(); lOrigItems.addAll(Arrays.asList(oldRange.getItems())); ArrayList lNewItems = new ArrayList(); lNewItems.addAll(Arrays.asList(range.getItems())); Iterator it = lNewItems.iterator(); while (it.hasNext()) { if (lOrigItems.remove(it.next())) { it.remove(); } } ArrayList lOrigColumns = new ArrayList(); lOrigColumns.addAll(Arrays.asList(oldRange.getColumns())); ArrayList lNewColumns = new ArrayList(); lNewColumns.addAll(Arrays.asList(range.getColumns())); it = lNewColumns.iterator(); while (it.hasNext()) { if (lOrigColumns.remove(it.next())) { it.remove(); } } if (lOrigItems.size() != 0 || lNewItems.size() != 0 || lOrigColumns.size() != 0 || lNewColumns.size() != 0) { RangeChangedEvent evt = new RangeChangedEvent(grid, range); evt.addedRows = new GridItem[lNewItems.size()]; lNewItems.toArray(evt.addedRows); evt.removedRows = new GridItem[lOrigItems.size()]; lOrigItems.toArray(evt.removedRows); evt.addedColumns = new GridColumn[lNewColumns.size()]; lNewColumns.toArray(evt.addedColumns); evt.removedColumns = new GridColumn[lOrigColumns.size()]; lNewColumns.toArray(evt.removedColumns); it = rangeChangeListener.iterator(); while (it.hasNext()) { ((VisibleRangeChangedListener) it.next()).rangeChanged(evt); } } oldRange = range; } } /** * Create a range support for the given grid instance * * @param grid * the grid instance the range support is created for * @return the created range support */ public static GridVisibleRangeSupport createFor(Grid grid) { return new GridVisibleRangeSupport(grid); } }
4,667
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridDragSourceEffect.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridDragSourceEffect.java
package org.eclipse.nebula.widgets.grid; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEffect; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; /** * This class provides default implementations to display a source image * when a drag is initiated from a <code>Grid</code>. * * <p>Classes that wish to provide their own source image for a <code>Grid</code> can * extend <code>DragSourceAdapter</code> class and override the <code>DragSourceAdapter.dragStart</code> * method and set the field <code>DragSourceEvent.image</code> with their own image.</p> * * Subclasses that override any methods of this class must call the corresponding * <code>super</code> method to get the default drag under effect implementation. * * @see DragSourceAdapter * @see DragSourceEvent * * @since 3.3 * @author mark-oliver.reiser */ public class GridDragSourceEffect extends DragSourceEffect { Image dragSourceImage = null; /** * * @param grid */ public GridDragSourceEffect(Grid grid) { super(grid); } /** * This implementation of <code>dragFinished</code> disposes the image * that was created in <code>GridDragSourceEffect.dragStart</code>. * * Subclasses that override this method should call <code>super.dragFinished(event)</code> * to dispose the image in the default implementation. * * @param event the information associated with the drag finished event */ public void dragFinished(DragSourceEvent event) { if (dragSourceImage != null) dragSourceImage.dispose(); dragSourceImage = null; } /** * This implementation of <code>dragStart</code> will create a default * image that will be used during the drag. The image should be disposed * when the drag is completed in the <code>GridDragSourceEffect.dragFinished</code> * method. * * Subclasses that override this method should call <code>super.dragStart(event)</code> * to use the image from the default implementation. * * @param event the information associated with the drag start event */ public void dragStart(DragSourceEvent event) { event.image = getDragSourceImage(event); } Image getDragSourceImage(DragSourceEvent event) { if (dragSourceImage != null) dragSourceImage.dispose(); dragSourceImage = null; Grid grid = (Grid) getControl(); Display display = grid.getDisplay(); Rectangle empty = new Rectangle(0,0,0,0); // Collect the currently selected items. Point[] selection; if(grid.getCellSelectionEnabled()){ selection = grid.getCellSelection(); } else { List l = new ArrayList(); GridItem[] selItems = grid.getSelection(); for (int i = 0; i < selItems.length; i++){ for (int j = 0; j < grid.getColumnCount() ; j++){ if(grid.getColumn(j).isVisible()){ l.add(new Point(j,grid.indexOf(selItems[i]))); } } } selection = (Point[])l.toArray(new Point[l.size()]); } if (selection.length == 0) return null; Rectangle bounds=null; for (int i = 0; i < selection.length; i++) { GridItem item = grid.getItem(selection[i].y); Rectangle currBounds = item.getBounds(selection[i].x); if(empty.equals(currBounds)){ selection[i]=null; }else { if(bounds==null){ bounds = currBounds; }else { bounds = bounds.union(currBounds); } } } if(bounds==null) return null; if (bounds.width <= 0 || bounds.height <= 0) return null; dragSourceImage = new Image(display,bounds.width,bounds.height); GC gc = new GC(dragSourceImage); for (int i = 0; i < selection.length; i++) { if(selection[i]==null) continue; GridItem item = grid.getItem(selection[i].y); GridColumn column = grid.getColumn(selection[i].x); Rectangle currBounds = item.getBounds(selection[i].x); GridCellRenderer r = column.getCellRenderer(); r.setBounds(currBounds.x-bounds.x, currBounds.y-bounds.y, currBounds.width, currBounds.height); gc.setClipping(currBounds.x-bounds.x-1, currBounds.y-bounds.y-1, currBounds.width+2, currBounds.height+2); r.setColumn(selection[i].x); r.setSelected(false); r.setFocus(false); r.setRowFocus(false); r.setCellFocus(false); r.setRowHover(false); r.setColumnHover(false); r.setCellSelected(false); r.setHoverDetail(""); r.setDragging(true); r.paint(gc, item); gc.setClipping((Rectangle)null); } gc.dispose(); return dragSourceImage; } }
4,771
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridFooterRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridFooterRenderer.java
/******************************************************************************* * Copyright (c) 2009 BestSolution.at * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.graphics.Rectangle; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * The super class for all grid header renderers. Contains the properties specific * to a grid header. * * @author [email protected] */ public abstract class GridFooterRenderer extends AbstractInternalWidget { /** * Returns the bounds of the text in the cell. This is used when displaying in-place tooltips. * If <code>null</code> is returned here, in-place tooltips will not be displayed. If the * <code>preferred</code> argument is <code>true</code> then the returned bounds should be large * enough to show the entire text. If <code>preferred</code> is <code>false</code> then the * returned bounds should be be relative to the current bounds. * * @param value the object being rendered. * @param preferred true if the preferred width of the text should be returned. * @return bounds of the text. */ public Rectangle getTextBounds(Object value, boolean preferred) { return null; } }
1,774
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AbstractInternalWidget.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/AbstractInternalWidget.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * Base implementation of IRenderer and IInternalWidget. Provides management of * a few values. * * @see AbstractRenderer * @author [email protected] */ public abstract class AbstractInternalWidget extends AbstractRenderer implements IInternalWidget { String hoverDetail = ""; /** * @return the hoverDetail */ public String getHoverDetail() { return hoverDetail; } /** * @param hoverDetail the hoverDetail to set */ public void setHoverDetail(String hoverDetail) { this.hoverDetail = hoverDetail; } }
1,352
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IInternalWidget.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/IInternalWidget.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * * TODO fill in. * * @author [email protected] */ public interface IInternalWidget extends IRenderer { // CSOFF: Magic Number // Event type constants /** Hover State. */ int MouseMove = SWT.MouseMove; /** Mouse down state. */ int LeftMouseButtonDown = SWT.MouseDown; /** * Mechanism used to notify the light weight widgets that an event occurred * that it might be interested in. * * @param event Event type. * @param point Location of event. * @param value New value. * @return widget handled the event. */ boolean notify(int event, Point point, Object value); /** * Returns the hover detail object. This detail is used by the renderer to * determine which part or piece of the rendered image is hovered over. * * @return string identifying which part of the image is being hovered over. */ String getHoverDetail(); /** * Sets a string object that represents which part of the rendered image is currently under the * mouse pointer. * * @param detail identifying string. */ void setHoverDetail(String detail); }
2,001
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/IRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * * Renders a single visual unit. A IRenderer implementation can have state (i.e. * is hovered or is selected) that affects the drawing. * * @author [email protected] */ public interface IRenderer { /** * Paints the visual representation of the given value on the given GC. The * actual class of the value object is determined by the use of the * implementing class. * <p> * Implementors need to respect the bounds values that may have been * specified. The bounds values may affect the x and y values for all * drawing operations as well as the width and heights. Implementors may use * a <code>Transform</code> to translate the coordinates of all the * drawing operations, otherwise they will need to offset each draw. * </p> * * @param gc GC to paint with * @param value the value being painted */ void paint(GC gc, Object value); /** * Returns the size of the given value's visual representation. * * @param gc convenience GC for string and text extents * @param wHint given width (or SWT.DEFAULT) * @param hHint given height (or SWT.DEFAULT) * @param value value to be sized * @return the size */ Point computeSize(GC gc, int wHint, int hHint, Object value); /** * Sets the bounds of the drawing. * * @param bounds Bounds. */ void setBounds(Rectangle bounds); /** * Sets the bounds of the drawing. * * @param x X coordinate. * @param y Y coordinate. * @param width Width. * @param height Height. */ void setBounds(int x, int y, int width, int height); /** * Sets the location of the drawing. * * @param location Location. */ void setLocation(Point location); /** * Sets the location of the drawing. * * @param x X. * @param y Y. */ void setLocation(int x, int y); /** * Sets focus state. * * @param focus focus state. */ void setFocus(boolean focus); /** * Sets the hover state. * * @param hover Hover state. */ void setHover(boolean hover); /** * Sets the hover state. * * @param mouseDown Mouse state. */ void setMouseDown(boolean mouseDown); /** * Sets the selected state. * * @param selected Selection state. */ void setSelected(boolean selected); /** * Sets the expanded state. * * @param expanded Expansion state. */ void setExpanded(boolean expanded); /** * Sets the area of the drawing. * * @param width Width. * @param height Height. */ void setSize(int width, int height); /** * Sets the area of the drawing. * * @param size Size. */ void setSize(Point size); /** * Sets the display. * * @param display Display. */ void setDisplay(Display display); }
3,914
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridCellSpanManager.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridCellSpanManager.java
/******************************************************************************* * Copyright (c) 2009 Claes Rosell * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Claes Rosell<[email protected]> - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.graphics.Rectangle; class GridCellSpanManager { List listOfCellSpanRectangles = new ArrayList(); Rectangle lastUsedCellSpanRectangle = null; protected void addCellSpanInfo(int colIndex, int rowIndex, int colSpan, int rowSpan) { Rectangle rect = new Rectangle(colIndex, rowIndex, colSpan + 1, rowSpan + 1); this.listOfCellSpanRectangles.add(rect); } private Rectangle findSpanRectangle(int columnIndex, int rowIndex) { Iterator iter = listOfCellSpanRectangles.iterator(); while (iter.hasNext()) { Rectangle cellSpanRectangle = (Rectangle) iter.next(); if (cellSpanRectangle.contains(columnIndex, rowIndex)) { return cellSpanRectangle; } } return null; } protected boolean skipCell(int columnIndex, int rowIndex) { this.lastUsedCellSpanRectangle = this.findSpanRectangle(columnIndex, rowIndex); return this.lastUsedCellSpanRectangle != null; } protected void consumeCell(int columnIndex, int rowIndex) { Rectangle rectangleToConsume = null; if (this.lastUsedCellSpanRectangle != null && this.lastUsedCellSpanRectangle.contains(columnIndex, rowIndex)) { rectangleToConsume = this.lastUsedCellSpanRectangle; } else { rectangleToConsume = this.findSpanRectangle(columnIndex, rowIndex); } if (rectangleToConsume != null) { if (columnIndex >= rectangleToConsume.x + (rectangleToConsume.width - 1) && rowIndex >= (rectangleToConsume.y + rectangleToConsume.height - 1)) { this.listOfCellSpanRectangles.remove(rectangleToConsume); } } } }
2,227
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Grid.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/Grid.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 * Claes Rosell<[email protected]> - rowspan in bug 272384 * Marco Maccaferri<[email protected]> - fixed arrow scrolling in bug 294767 * [email protected] . fixed selectionEvent.item in bug 286617 * [email protected] - fix in bug 298684 * Enrico Schnepel<[email protected]> - new API in 238729, bugfix in 294952, 322114 * Benjamin Bortfeldt<[email protected]> - new tooltip support in 300797 * Thomas Halm <[email protected]> - bugfix in 315397 * Justin Dolezy <[email protected]> - bugfix in 316598 * Cosmin Ghita <[email protected]> - bugfix in 323687 * Pinard-Legry Guilhaume <[email protected]> - bugfix in 267057 * Thorsten Schenkel <[email protected]> - bugfix in 356803 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.eclipse.nebula.widgets.grid.internal.DefaultBottomLeftRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultColumnGroupHeaderRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultDropPointRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultEmptyCellRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultEmptyColumnFooterRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultEmptyColumnHeaderRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultEmptyRowHeaderRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultFocusRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultInsertMarkRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultRowHeaderRenderer; import org.eclipse.nebula.widgets.grid.internal.DefaultTopLeftRenderer; import org.eclipse.nebula.widgets.grid.internal.GridToolTip; import org.eclipse.nebula.widgets.grid.internal.IScrollBarProxy; import org.eclipse.nebula.widgets.grid.internal.NullScrollBarProxy; import org.eclipse.nebula.widgets.grid.internal.ScrollBarProxyAdapter; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.accessibility.ACC; import org.eclipse.swt.accessibility.Accessible; import org.eclipse.swt.accessibility.AccessibleAdapter; import org.eclipse.swt.accessibility.AccessibleControlAdapter; import org.eclipse.swt.accessibility.AccessibleControlEvent; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.TypedListener; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * Instances of this class implement a selectable user interface object that * displays a list of images and strings and issue notification when selected. * <p> * The item children that may be added to instances of this class must be of * type {@code GridItem}. * </p> * <dl> * <dt><b>Styles:</b></dt> * <dd>SWT.SINGLE, SWT.MULTI, SWT.NO_FOCUS, SWT.CHECK, SWT.VIRTUAL</dd> * <dt><b>Events:</b></dt> * <dd>Selection, DefaultSelection</dd> * </dl> * * @author [email protected] */ public class Grid extends Canvas { //TODO: figure out better way to allow renderers to trigger events //TODO: scroll as necessary when performing drag select (current strategy ok) //TODO: need to refactor the way the range select remembers older selection //TODO: remember why i decided i needed to refactor the way the range select remembers older selection //TODO: need to alter how column drag selection works to allow selection of spanned cells //TODO: JAVADOC! //TODO: column freezing //TODO: Performance - need to cache top index /** * Object holding the visible range */ public static class GridVisibleRange { private GridItem[] items = new GridItem[0]; private GridColumn[] columns = new GridColumn[0]; /** * @return the current items shown */ public GridItem[] getItems() { return items; } /** * @return the current columns shown */ public GridColumn[] getColumns() { return columns; } } /** * Accessibility default action for column headers and column group headers. */ private static final String ACC_COLUMN_DEFAULT_ACTION = "Click"; /** * Accessibility default action for items. */ private static final String ACC_ITEM_DEFAULT_ACTION = "Double Click"; /** * Accessibility expand action for tree items. */ private static final String ACC_ITEM_ACTION_EXPAND = "Expand"; /** * Accessibility collapse action for tree items. */ private static final String ACC_ITEM_ACTION_COLLAPSE = "Collapse"; /** * Accessibility name for the column group header toggle button. */ private static final String ACC_TOGGLE_BUTTON_NAME = "Toggle Button"; /** * Alpha blending value used when drawing the dragged column header. */ private static final int COLUMN_DRAG_ALPHA = 128; /** * Number of pixels below the header to draw the drop point. */ private static final int DROP_POINT_LOWER_OFFSET = 3; /** * Horizontal scrolling increment, in pixels. */ private static final int HORZ_SCROLL_INCREMENT = 5; /** * The area to the left and right of the column boundary/resizer that is * still considered the resizer area. This prevents a user from having to be * *exactly* over the resizer. */ private static final int COLUMN_RESIZER_THRESHOLD = 4; /** * @see #COLUMN_RESIZER_THRESHOLD */ private static final int ROW_RESIZER_THRESHOLD = 3; /** * The minimum width of a column header. */ private static final int MIN_COLUMN_HEADER_WIDTH = 20; /** * The minimum height of a row header. */ private static final int MIN_ROW_HEADER_HEIGHT = 10; /** * The number used when sizing the row header (i.e. size it for '1000') * initially. */ // private static final int INITIAL_ROW_HEADER_SIZING_VALUE = 1000; /** * The factor to multiply the current row header sizing value by when * determining the next sizing value. Used for performance reasons. */ // private static final int ROW_HEADER_SIZING_MULTIPLIER = 10; /** * Tracks whether the scroll values are correct. If not they will be * recomputed in onPaint. This allows us to get a free ride on top of the * OS's paint event merging to assure that we don't perform this expensive * operation when unnecessary. */ private boolean scrollValuesObsolete = false; /** * All items in the table, not just root items. */ private List items = new ArrayList(); /** * All root items. */ private List rootItems = new ArrayList(); /** * List of selected items. */ private List selectedItems = new ArrayList(); /** * Reference to the item in focus. */ private GridItem focusItem; private boolean cellSelectionEnabled = false; private List selectedCells = new ArrayList(); private List selectedCellsBeforeRangeSelect = new ArrayList(); private boolean cellDragSelectionOccuring = false; private boolean cellRowDragSelectionOccuring = false; private boolean cellColumnDragSelectionOccuring = false; private boolean cellDragCTRL = false; private boolean followupCellSelectionEventOwed = false; private boolean cellSelectedOnLastMouseDown; private boolean cellRowSelectedOnLastMouseDown; private boolean cellColumnSelectedOnLastMouseDown; private GridColumn shiftSelectionAnchorColumn; private GridColumn focusColumn; private List selectedColumns = new ArrayList(); /** * This is the column that the user last navigated to, but may not be the focusColumn because * that column may be spanned in the current row. This is only used in situations where the user * has used the keyboard to navigate up or down in the table and the focusColumn has switched to * a new column because the intended column (was maintained in this var) was spanned. The table * will attempt to set focus back to the intended column during subsequent up/down navigations. */ private GridColumn intendedFocusColumn; /** * List of table columns in creation/index order. */ private List columns = new ArrayList(); /** * List of the table columns in the order they are displayed. */ private List displayOrderedColumns = new ArrayList(); private GridColumnGroup[] columnGroups = new GridColumnGroup[0]; /** * Renderer to paint the top left area when both column and row headers are * shown. */ private IRenderer topLeftRenderer = new DefaultTopLeftRenderer(); /** * Renderer to paint the bottom left area when row headers and column footers are shown */ private IRenderer bottomLeftRenderer = new DefaultBottomLeftRenderer(); /** * Renderer used to paint row headers. */ private IRenderer rowHeaderRenderer = new DefaultRowHeaderRenderer(); /** * Renderer used to paint empty column headers, used when the columns don't * fill the horz space. */ private IRenderer emptyColumnHeaderRenderer = new DefaultEmptyColumnHeaderRenderer(); /** * Renderer used to paint empty column footers, used when the columns don't * fill the horz space. */ private IRenderer emptyColumnFooterRenderer = new DefaultEmptyColumnFooterRenderer(); /** * Renderer used to paint empty cells to fill horz and vert space. */ private GridCellRenderer emptyCellRenderer = new DefaultEmptyCellRenderer(); /** * Renderer used to paint empty row headers when the rows don't fill the * vertical space. */ private IRenderer emptyRowHeaderRenderer = new DefaultEmptyRowHeaderRenderer(); /** * Renderers the UI affordance identifying where the dragged column will be * dropped. */ private IRenderer dropPointRenderer = new DefaultDropPointRenderer(); /** * Renderer used to paint on top of an already painted row to denote focus. */ private IRenderer focusRenderer = new DefaultFocusRenderer(); /** * Are row headers visible? */ private boolean rowHeaderVisible = false; /** * Are column headers visible? */ private boolean columnHeadersVisible = false; /** * Are column footers visible? */ private boolean columnFootersVisible = false; /** * Type of selection behavior. Valid values are SWT.SINGLE and SWT.MULTI. */ private int selectionType = SWT.SINGLE; /** * True if selection highlighting is enabled. */ private boolean selectionEnabled = true; /** * Default height of items. This value is used * for <code>GridItem</code>s with a height * of -1. */ private int itemHeight = 1; private boolean userModifiedItemHeight = false; /** * Width of each row header. */ private int rowHeaderWidth = 0; /** * The row header width is variable. The row header width gets larger as * more rows are added to the table to ensure that the row header has enough * room to display the longest string of numbers that display in the row * header. This determination of how wide to make the row header is rather * slow and therefore is only done at every 1000 items (or so). This * variable remembers how many items were last computed and therefore when * the number of items is greater than this value, we need to recalculate * the row header width. See newItem(). */ // private int lastRowHeaderWidthCalculationAt = 0; /** * Height of each column header. */ private int headerHeight = 0; /** * Height of each column footer */ private int footerHeight = 0; /** * True if mouse is hover on a column boundary and can resize the column. */ boolean hoveringOnColumnResizer = false; /** * Reference to the column being resized. */ private GridColumn columnBeingResized; /** * Are this <code>Grid</code>'s rows resizeable? */ private boolean rowsResizeable = false; /** * Is the user currently resizing a column? */ private boolean resizingColumn = false; /** * The mouse X position when the user starts the resize. */ private int resizingStartX = 0; /** * The width of the column when the user starts the resize. This, together * with the resizingStartX determines the current width during resize. */ private int resizingColumnStartWidth = 0; private boolean hoveringOnRowResizer = false; private GridItem rowBeingResized; private boolean resizingRow = false; private int resizingStartY; private int resizingRowStartHeight; /** * Reference to the column whose header is currently in a pushed state. */ private GridColumn columnBeingPushed; /** * Is the user currently pushing a column header? */ private boolean pushingColumn = false; /** * Is the user currently pushing a column header and hovering over that same * header? */ private boolean pushingAndHovering = false; /** * X position of the mouse when the user first pushes a column header. */ private int startHeaderPushX = 0; /** * X position of the mouse when the user has initiated a drag. This is * different than startHeaderPushX because the mouse is allowed some * 'wiggle-room' until the header is put into drag mode. */ private int startHeaderDragX = 0; /** * The current X position of the mouse during a header drag. */ private int currentHeaderDragX = 0; /** * Are we currently dragging a column header? */ private boolean draggingColumn = false; private GridColumn dragDropBeforeColumn = null; private GridColumn dragDropAfterColumn = null; /** * True if the current dragDropPoint is a valid drop point for the dragged * column. This is false if the column groups are involved and a column is * being dropped into or out of its column group. */ private boolean dragDropPointValid = true; /** * Reference to the currently item that the mouse is currently hovering * over. */ private GridItem hoveringItem; /** * Reference to the column that the mouse is currently hovering over. * Includes the header and all cells (all rows) in this column. */ private GridColumn hoveringColumn; private GridColumn hoveringColumnHeader; private GridColumnGroup hoverColumnGroupHeader; /** * String-based detail of what is being hovered over in a cell. This allows * a renderer to differentiate between hovering over different parts of the * cell. For example, hovering over a checkbox in the cell or hovering over * a tree node in the cell. The table does nothing with this string except * to set it back in the renderer when its painted. The renderer sets this * during its notify method (InternalWidget.HOVER) and the table pulls it * back and maintains it so it can be set back when the cell is painted. The * renderer determines what the hover detail means and how it affects * painting. */ private String hoveringDetail = ""; /** * True if the mouse is hovering of a cell's text. */ private boolean hoveringOverText = false; /** * Are the grid lines visible? */ private boolean linesVisible = true; /** * Are tree lines visible? */ private boolean treeLinesVisible = true; /** * Grid line color. */ private Color lineColor; /** * Vertical scrollbar proxy. * <p> * Note: * <ul> * <li>{@link Grid#getTopIndex()} is the only method allowed to call vScroll.getSelection() * (except #updateScrollbars() of course)</li> * <li>{@link Grid#setTopIndex(int)} is the only method allowed to call vScroll.setSelection(int)</li> * </ul> */ private IScrollBarProxy vScroll; /** * Horizontal scrollbar proxy. */ private IScrollBarProxy hScroll; /** * The number of GridItems whose visible = true. Maintained for * performance reasons (rather than iterating over all items). */ private int currentVisibleItems = 0; /** * Item selected when a multiple selection using shift+click first occurs. * This item anchors all further shift+click selections. */ private GridItem shiftSelectionAnchorItem; private boolean columnScrolling = false; private int groupHeaderHeight; private Color cellHeaderSelectionBackground; /** * Dispose listener. This listener is removed during the dispose event to allow re-firing of * the event. */ private Listener disposeListener; /** * The inplace tooltip. */ private GridToolTip inplaceToolTip; private GC sizingGC; private Color backgroundColor; /** * True if the widget is being disposed. When true, events are not fired. */ private boolean disposing = false; /** * True if there is at least one tree node. This is used by accessibility and various * places for optimization. */ private boolean isTree = false; /** * True if there is at least one <code>GridItem</code> with an individual height. * This value is only set to true in {@link GridItem#setHeight(int,boolean)} * and it is never reset to false. */ boolean hasDifferingHeights = false; /** * True if three is at least one cell spanning columns. This is used in various places for * optimizatoin. */ private boolean hasSpanning = false; /** * Index of first visible item. The value must never be read directly. It is cached and * updated when appropriate. #getTopIndex should be called for every client (even internal * callers). A value of -1 indicates that the value is old and will be recomputed. * * @see #bottomIndex */ int topIndex = -1; /** * Index of last visible item. The value must never be read directly. It is cached and * updated when appropriate. #getBottomIndex() should be called for every client (even internal * callers). A value of -1 indicates that the value is old and will be recomputed. * <p> * Note that the item with this index is often only partly visible; maybe only * a single line of pixels is visible. In extreme cases, bottomIndex may be the * same as topIndex. * * @see #topIndex */ int bottomIndex = -1; /** * Index of the first visible column. A value of -1 indicates that the value is old and will be recomputed. */ int startColumnIndex = -1; /** * Index of the the last visible column. A value of -1 indicates that the value is old and will be recomputed. */ int endColumnIndex = -1; /** * True if the last visible item is completely visible. The value must never be read directly. It is cached and * updated when appropriate. #isShown() should be called for every client (even internal * callers). * * @see #bottomIndex */ private boolean bottomIndexShownCompletely = false; /** * Tooltip text - overriden because we have cell specific tooltips */ private String toolTipText = null; /** * Flag that is set to true as soon as one image is set on any one item. * This is used to mimic Table behavior that resizes the rows on the first image added. * See imageSetOnItem. */ private boolean firstImageSet = false; /** * Mouse capture flag. Used for inplace tooltips. This flag must be used to ensure that * we don't setCapture(false) in situations where we didn't do setCapture(true). The OS (SWT?) * will automatically capture the mouse for us during a drag operation. */ private boolean inplaceTooltipCapture; /** * This is the tooltip text currently used. This could be the tooltip text for the currently * hovered cell, or the general grid tooltip. See handleCellHover. */ private String displayedToolTipText; /** * The height of the area at the top and bottom of the * visible grid area in which scrolling is initiated * while dragging over this Grid. */ private static final int DRAG_SCROLL_AREA_HEIGHT = 12; /** * Threshold for the selection border used for drag n drop * in mode (!{@link #dragOnFullSelection}}. */ private static final int SELECTION_DRAG_BORDER_THRESHOLD = 2; private boolean hoveringOnSelectionDragArea = false; private GridItem insertMarkItem = null; private GridColumn insertMarkColumn = null; private boolean insertMarkBefore = false; private IRenderer insertMarkRenderer = new DefaultInsertMarkRenderer(); private boolean sizeOnEveryItemImageChange; private boolean autoHeight = false; private boolean autoWidth = true; private boolean wordWrapRowHeader = false; /** * A range of rows in a <code>Grid</code>. * <p> * A row in this sense exists only for visible items * (i.e. items with {@link GridItem#isVisible()} == true). * Therefore, the items at 'startIndex' and 'endIndex' * are always visible. * * @see Grid#getRowRange(int, int, boolean, boolean) */ private static class RowRange { /** index of first item in range */ public int startIndex; /** index of last item in range */ public int endIndex; /** number of rows (i.e. <em>visible</em> items) in this range */ public int rows; /** height in pixels of this range (including horizontal separator between rows) */ public int height; } /** * Filters out unnecessary styles, adds mandatory styles and generally * manages the style to pass to the super class. * * @param style user specified style. * @return style to pass to the super class. */ private static int checkStyle(int style) { int mask = SWT.BORDER | SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT | SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE | SWT.MULTI | SWT.NO_FOCUS | SWT.CHECK | SWT.VIRTUAL; int newStyle = style & mask; newStyle |= SWT.DOUBLE_BUFFERED; return newStyle; } /** * Constructs a new instance of this class given its parent and a style * value describing its behavior and appearance. * <p> * * @param parent a composite control which will be the parent of the new * instance (cannot be null) * @param style the style of control to construct * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the parent</li> * </ul> * @see SWT#SINGLE * @see SWT#MULTI */ public Grid(Composite parent, int style) { super(parent, checkStyle(style)); // initialize drag & drop support setData("DEFAULT_DRAG_SOURCE_EFFECT", new GridDragSourceEffect(this)); setData("DEFAULT_DROP_TARGET_EFFECT", new GridDropTargetEffect(this)); sizingGC = new GC(this); topLeftRenderer.setDisplay(getDisplay()); bottomLeftRenderer.setDisplay(getDisplay()); rowHeaderRenderer.setDisplay(getDisplay()); emptyColumnHeaderRenderer.setDisplay(getDisplay()); emptyColumnFooterRenderer.setDisplay(getDisplay()); emptyCellRenderer.setDisplay(getDisplay()); dropPointRenderer.setDisplay(getDisplay()); focusRenderer.setDisplay(getDisplay()); emptyRowHeaderRenderer.setDisplay(getDisplay()); insertMarkRenderer.setDisplay(getDisplay()); setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND)); setLineColor(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); if ((style & SWT.MULTI) != 0) { selectionType = SWT.MULTI; } if (getVerticalBar() != null) { getVerticalBar().setVisible(false); vScroll = new ScrollBarProxyAdapter(getVerticalBar()); } else { vScroll = new NullScrollBarProxy(); } if (getHorizontalBar() != null) { getHorizontalBar().setVisible(false); hScroll = new ScrollBarProxyAdapter(getHorizontalBar()); } else { hScroll = new NullScrollBarProxy(); } scrollValuesObsolete = true; initListeners(); initAccessible(); itemHeight = sizingGC.getFontMetrics().getHeight() + 2; RGB sel = getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION).getRGB(); RGB white = getDisplay().getSystemColor(SWT.COLOR_WHITE).getRGB(); RGB cellSel = blend(sel,white,50); cellHeaderSelectionBackground = new Color(getDisplay(),cellSel); setDragDetect(false); } /** * {@inheritDoc} */ public Color getBackground() { checkWidget(); if (backgroundColor == null) return getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND); return backgroundColor; } /** * {@inheritDoc} */ public void setBackground(Color color) { checkWidget(); backgroundColor = color; redraw(); } /** * Returns the background color of column and row headers when a cell in * the row or header is selected. * * @return cell header selection background color * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Color getCellHeaderSelectionBackground() { checkWidget(); return cellHeaderSelectionBackground; } /** * Sets the background color of column and row headers displayed when a cell in * the row or header is selected. * * @param cellSelectionBackground color to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setCellHeaderSelectionBackground(Color cellSelectionBackground) { checkWidget(); this.cellHeaderSelectionBackground = cellSelectionBackground; } /** * Adds the listener to the collection of listeners who will be notified * when the receiver's selection changes, by sending it one of the messages * defined in the {@code SelectionListener} interface. * <p> * Cell selection events may have <code>Event.detail = SWT.DRAG</code> when the * user is drag selecting multiple cells. A follow up selection event will be generated * when the drag is complete. * * @param listener the listener which should be notified * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void addSelectionListener(SelectionListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } addListener(SWT.Selection, new TypedListener(listener)); addListener(SWT.DefaultSelection, new TypedListener(listener)); } /** * Adds the listener to the collection of listeners who will be notified * when the receiver's items changes, by sending it one of the messages * defined in the {@code TreeListener} interface. * * @param listener the listener which should be notified * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see TreeListener * @see #removeTreeListener * @see org.eclipse.swt.events.TreeEvent */ public void addTreeListener(TreeListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } addListener(SWT.Expand, new TypedListener(listener)); addListener(SWT.Collapse, new TypedListener(listener)); } /** * {@inheritDoc} */ public Point computeSize(int wHint, int hHint, boolean changed) { checkWidget(); Point prefSize = null; if (wHint == SWT.DEFAULT || hHint == SWT.DEFAULT) { prefSize = getTableSize(); prefSize.x += 2 * getBorderWidth(); prefSize.y += 2 * getBorderWidth(); } int x = 0; int y = 0; if (wHint == SWT.DEFAULT) { x += prefSize.x; if (getVerticalBar() != null) { x += getVerticalBar().getSize().x; } } else { x = wHint; } if (hHint == SWT.DEFAULT) { y += prefSize.y; if (getHorizontalBar() != null) { y += getHorizontalBar().getSize().y; } } else { y = hHint; } return new Point(x, y); } /** * Deselects the item at the given zero-relative index in the receiver. If * the item at the index was already deselected, it remains deselected. * Indices that are out of range are ignored. * <p> * If cell selection is enabled, all cells in the specified item are deselected. * * @param index the index of the item to deselect * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselect(int index) { checkWidget(); if (index < 0 || index > items.size() - 1) { return; } GridItem item = (GridItem)items.get(index); if (!cellSelectionEnabled) { if (selectedItems.contains(item)) { selectedItems.remove(item); } } else { deselectCells(getCells(item)); } redraw(); } /** * Deselects the items at the given zero-relative indices in the receiver. * If the item at the given zero-relative index in the receiver is selected, * it is deselected. If the item at the index was not selected, it remains * deselected. The range of the indices is inclusive. Indices that are out * of range are ignored. * <p> * If cell selection is enabled, all cells in the given range are deselected. * * @param start the start index of the items to deselect * @param end the end index of the items to deselect * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselect(int start, int end) { checkWidget(); for (int i = start; i <= end; i++) { if (i < 0) { continue; } if (i > items.size() - 1) { break; } GridItem item = (GridItem)items.get(i); if (!cellSelectionEnabled) { if (selectedItems.contains(item)) { selectedItems.remove(item); } } else { deselectCells(getCells(item)); } } redraw(); } /** * Deselects the items at the given zero-relative indices in the receiver. * If the item at the given zero-relative index in the receiver is selected, * it is deselected. If the item at the index was not selected, it remains * deselected. Indices that are out of range and duplicate indices are * ignored. * <p> * If cell selection is enabled, all cells in the given items are deselected. * * @param indices the array of indices for the items to deselect * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the set of indices is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselect(int[] indices) { checkWidget(); if (indices == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } for (int i = 0; i < indices.length; i++) { int j = indices[i]; if (j >= 0 && j < items.size()) { GridItem item = (GridItem)items.get(j); if (!cellSelectionEnabled) { if (selectedItems.contains(item)) { selectedItems.remove(item); } } else { deselectCells(getCells(item)); } } } redraw(); } /** * Deselects all selected items in the receiver. If cell selection is enabled, * all cells are deselected. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselectAll() { checkWidget(); if (!cellSelectionEnabled) { selectedItems.clear(); redraw(); } else { deselectAllCells(); } } /** * Returns the column at the given, zero-relative index in the receiver. * Throws an exception if the index is out of range. If no * {@code GridColumn}s were created by the programmer, this method will * throw {@code ERROR_INVALID_RANGE} despite the fact that a single column * of data may be visible in the table. This occurs when the programmer uses * the table like a list, adding items but never creating a column. * * @param index the index of the column to return * @return the column at the given index * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number * of elements in the list minus 1 (inclusive)</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn getColumn(int index) { checkWidget(); if (index < 0 || index > getColumnCount() - 1) { SWT.error(SWT.ERROR_INVALID_RANGE); } return (GridColumn)columns.get(index); } /** * Returns the column at the given point in the receiver or null if no such * column exists. The point is in the coordinate system of the receiver. * * @param point the point used to locate the column * @return the column at the given point * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn getColumn(Point point) { return getColumn(null, point); } /** * Returns the column at the given point and a known item in the receiver or null if no such * column exists. The point is in the coordinate system of the receiver. * * @param item a known GridItem * @param point the point used to locate the column * @return the column at the given point * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ private GridColumn getColumn(GridItem item, Point point) { checkWidget(); if (point == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } GridColumn overThis = null; int x2 = 0; if (rowHeaderVisible) { if (point.x <= rowHeaderWidth) { return null; } x2 += rowHeaderWidth; } x2 -= getHScrollSelectionInPixels(); for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (!column.isVisible()) { continue; } if (point.x >= x2 && point.x < x2 + column.getWidth()) { overThis = column; break; } x2 += column.getWidth(); } if (overThis == null) { return null; } if (hasSpanning) { // special logic for column spanning if(item == null) { item = getItem(point); } if (item != null) { int displayColIndex = displayOrderedColumns.indexOf(overThis); // track back all previous columns and check their spanning for (int i = 0; i < displayColIndex; i++) { if (!((GridColumn)displayOrderedColumns.get(i)).isVisible()) { continue; } int colIndex = indexOf((GridColumn)displayOrderedColumns.get(i)); int span = item.getColumnSpan(colIndex); if (i + span >= displayColIndex) { overThis = (GridColumn)displayOrderedColumns.get(i); break; } } } } return overThis; } /** * Returns the number of columns contained in the receiver. If no * {@code GridColumn}s were created by the programmer, this value is * zero, despite the fact that visually, one column of items may be visible. * This occurs when the programmer uses the table like a list, adding items * but never creating a column. * * @return the number of columns * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getColumnCount() { checkWidget(); return columns.size(); } /** * Returns an array of zero-relative integers that map the creation order of * the receiver's items to the order in which they are currently being * displayed. * <p> * Specifically, the indices of the returned array represent the current * visual order of the items, and the contents of the array represent the * creation order of the items. * </p> * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the current visual order of the receiver's items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int[] getColumnOrder() { checkWidget(); int[] order = new int[columns.size()]; int i = 0; for (Iterator colIterator = displayOrderedColumns.iterator(); colIterator.hasNext(); ) { GridColumn col = (GridColumn) colIterator.next(); order[i] = columns.indexOf(col); i++; } return order; } /** * Returns the number of column groups contained in the receiver. * * @return the number of column groups * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getColumnGroupCount() { checkWidget(); return columnGroups.length; } /** * Returns an array of {@code GridColumnGroup}s which are the column groups in the * receiver. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the column groups in the receiver * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumnGroup[] getColumnGroups() { checkWidget(); GridColumnGroup[] newArray = new GridColumnGroup[columnGroups.length]; System.arraycopy (columnGroups, 0, newArray, 0, columnGroups.length); return newArray; } /** * Returns the column group at the given, zero-relative index in the receiver. * Throws an exception if the index is out of range. * * @param index the index of the column group to return * @return the column group at the given index * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number * of elements in the list minus 1 (inclusive)</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumnGroup getColumnGroup(int index) { checkWidget(); if (index < 0 || index >= columnGroups.length) SWT.error(SWT.ERROR_INVALID_RANGE); return columnGroups[index]; } /** * Sets the order that the items in the receiver should be displayed in to * the given argument which is described in terms of the zero-relative * ordering of when the items were added. * * @param order the new order to display the items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS -if not called from the thread that * created the receiver</li> * </ul> * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the item order is null</li> * <li>ERROR_INVALID_ARGUMENT - if the order is not the same length as the * number of items, or if an item is listed twice, or if the order splits a * column group</li> * </ul> */ public void setColumnOrder(int[] order) { checkWidget(); if (order == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (order.length != displayOrderedColumns.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } boolean[] seen = new boolean[displayOrderedColumns.size()]; for (int i = 0; i < order.length; i++) { if (order[i] < 0 || order[i] >= displayOrderedColumns.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } if (seen[order[i]]) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } seen[order[i]] = true; } if (columnGroups.length != 0) { GridColumnGroup currentGroup = null; int colsInGroup = 0; for (int i = 0; i < order.length; i++) { GridColumn col = getColumn(order[i]); if (currentGroup != null) { if (col.getColumnGroup() != currentGroup && colsInGroup > 0 ) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } else { colsInGroup--; if (colsInGroup <= 0) { currentGroup = null; } } } else if (col.getColumnGroup() != null) { currentGroup = col.getColumnGroup(); colsInGroup = currentGroup.getColumns().length - 1; } } } GridColumn[] cols = getColumns(); displayOrderedColumns.clear(); for (int i = 0; i < order.length; i++) { displayOrderedColumns.add(cols[order[i]]); } } /** * Returns an array of {@code GridColumn}s which are the columns in the * receiver. If no {@code GridColumn}s were created by the programmer, * the array is empty, despite the fact that visually, one column of items * may be visible. This occurs when the programmer uses the table like a * list, adding items but never creating a column. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the items in the receiver * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn[] getColumns() { checkWidget(); return (GridColumn[])columns.toArray(new GridColumn[columns.size()]); } /** * Returns the empty cell renderer. * * @return Returns the emptyCellRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridCellRenderer getEmptyCellRenderer() { checkWidget(); return emptyCellRenderer; } /** * Returns the empty column header renderer. * * @return Returns the emptyColumnHeaderRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getEmptyColumnHeaderRenderer() { checkWidget(); return emptyColumnHeaderRenderer; } /** * Returns the empty column footer renderer. * * @return Returns the emptyColumnFooterRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getEmptyColumnFooterRenderer() { checkWidget(); return emptyColumnFooterRenderer; } /** * Returns the empty row header renderer. * * @return Returns the emptyRowHeaderRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getEmptyRowHeaderRenderer() { checkWidget(); return emptyRowHeaderRenderer; } /** * Returns the externally managed horizontal scrollbar. * * @return the external horizontal scrollbar. * @see #setHorizontalScrollBarProxy(IScrollBarProxy) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ protected IScrollBarProxy getHorizontalScrollBarProxy() { checkWidget(); return hScroll; } /** * Returns the externally managed vertical scrollbar. * * @return the external vertical scrollbar. * @see #setlVerticalScrollBarProxy(IScrollBarProxy) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ protected IScrollBarProxy getVerticalScrollBarProxy() { checkWidget(); return vScroll; } /** * Gets the focus renderer. * * @return Returns the focusRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getFocusRenderer() { checkWidget(); return focusRenderer; } /** * Returns the height of the column headers. If this table has column * groups, the returned value includes the height of group headers. * * @return height of the column header row * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getHeaderHeight() { checkWidget(); return headerHeight; } /** * Returns the height of the column footers. * * @return height of the column footer row * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getFooterHeight() { checkWidget(); return footerHeight; } /** * Returns the height of the column group headers. * * @return height of column group headers * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getGroupHeaderHeight() { checkWidget(); return groupHeaderHeight; } /** * Returns {@code true} if the receiver's header is visible, and * {@code false} otherwise. * * @return the receiver's header's visibility state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getHeaderVisible() { checkWidget(); return columnHeadersVisible; } /** * Returns {@code true} if the receiver's footer is visible, and {@code false} otherwise * @return the receiver's footer's visibility state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getFooterVisible() { checkWidget(); return columnFootersVisible; } /** * Returns the item at the given, zero-relative index in the receiver. * Throws an exception if the index is out of range. * * @param index the index of the item to return * @return the item at the given index * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the * list minus 1 (inclusive) </li> * * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem getItem(int index) { checkWidget(); if (index < 0 || index >= items.size()) { SWT.error(SWT.ERROR_INVALID_RANGE); } return (GridItem)items.get(index); } /** * Returns the item at the given point in the receiver or null if no such * item exists. The point is in the coordinate system of the receiver. * * @param point the point used to locate the item * @return the item at the given point * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem getItem(Point point) { checkWidget(); if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (point.x < 0 || point.x > getClientArea().width) return null; Point p = new Point(point.x, point.y); int y2=0; if (columnHeadersVisible) { if (p.y <= headerHeight) { return null; } y2 += headerHeight; } GridItem itemToReturn = null; int row=getTopIndex(); while(row<items.size() && y2<=getClientArea().height) { GridItem currItem = (GridItem)items.get(row); if (currItem.isVisible()) { int currItemHeight = currItem.getHeight(); if (p.y >= y2 && p.y < y2+currItemHeight+1) { itemToReturn = currItem; break; } y2 += currItemHeight +1; } row++; } if (hasSpanning) { if (itemToReturn != null) { int itemIndex = this.getIndexOfItem(itemToReturn); GridColumn gridColumn = getColumn(itemToReturn, point); int displayColIndex = displayOrderedColumns.indexOf(gridColumn); // track back all previous columns and check their spanning for (int i = 0; i < itemIndex; i++) { GridItem gridItem = this.getItem(i); if (gridItem.isVisible() == false) { continue; } int span = gridItem.getRowSpan(displayColIndex); if (i + span >= itemIndex) { itemToReturn = gridItem; break; } } } } return itemToReturn; } /** * Returns the number of items contained in the receiver. * * @return the number of items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getItemCount() { checkWidget(); return getItems().length; } /** * Returns the default height of the items * in this <code>Grid</code>. See {@link #setItemHeight(int)} * for details. * * <p>IMPORTANT: The Grid's items need not all have the * height returned by this method, because an * item's height may have been changed by calling * {@link GridItem#setHeight(int)}. * * @return default height of items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see #setItemHeight(int) */ public int getItemHeight() { checkWidget(); return itemHeight; } /** * Sets the default height for this <code>Grid</code>'s items. When * this method is called, all existing items are resized * to the specified height and items created afterwards will be * initially sized to this height. * <p> * As long as no default height was set by the client through this method, * the preferred height of the first item in this <code>Grid</code> is * used as a default for all items (and is returned by {@link #getItemHeight()}). * * @param height default height in pixels * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the height is < 1</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * * @see GridItem#getHeight() * @see GridItem#setHeight(int) */ public void setItemHeight(int height) { checkWidget(); if (height < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); itemHeight = height; userModifiedItemHeight = true; for(int cnt=0;cnt<items.size();cnt++) ((GridItem)items.get(cnt)).setHeight(height); hasDifferingHeights=false; setScrollValuesObsolete(); redraw(); } /** * Returns true if the rows are resizable. * * @return the row resizeable state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see #setRowsResizeable(boolean) */ public boolean getRowsResizeable() { checkWidget(); return rowsResizeable; } /** * Sets the rows resizeable state of this <code>Grid</code>. * The default is 'false'. * <p> * If a row in a <code>Grid</code> is resizeable, * then the user can interactively change its height * by dragging the border of the row header. * <p> * Note that for rows to be resizable the row headers must be visible. * * @param rowsResizeable true if this <code>Grid</code>'s rows should be resizable * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see #setRowHeaderVisible(boolean) */ public void setRowsResizeable(boolean rowsResizeable) { checkWidget(); this.rowsResizeable=rowsResizeable; } /** * Returns a (possibly empty) array of {@code GridItem}s which are the * items in the receiver. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the items in the receiver * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem[] getItems() { checkWidget(); return (GridItem[])items.toArray(new GridItem[items.size()]); } /** * * @param item * @return t */ public int getIndexOfItem(GridItem item) { checkWidget(); return items.indexOf(item); } /** * Returns the line color. * * @return Returns the lineColor. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Color getLineColor() { checkWidget(); return lineColor; } /** * Returns true if the lines are visible. * * @return Returns the linesVisible. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getLinesVisible() { checkWidget(); return linesVisible; } /** * Returns true if the tree lines are visible. * * @return Returns the treeLinesVisible. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getTreeLinesVisible() { checkWidget(); return treeLinesVisible; } /** * Returns the next visible item in the table. * * @param item item * @return next visible item or null * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem getNextVisibleItem(GridItem item) { checkWidget(); int index = items.indexOf(item); if (items.size() == index + 1) { return null; } GridItem nextItem = (GridItem)items.get(index + 1); while (!nextItem.isVisible()) { index++; if (items.size() == index + 1) { return null; } nextItem = (GridItem)items.get(index + 1); } return nextItem; } /** * Returns the previous visible item in the table. Passing null for the item * will return the last visible item in the table. * * @param item item or null * @return previous visible item or if item==null last visible item * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem getPreviousVisibleItem(GridItem item) { checkWidget(); int index = 0; if (item == null) { index = items.size(); } else { index = items.indexOf(item); if (index == 0) { return null; } } GridItem prevItem = (GridItem)items.get(index - 1); while (!prevItem.isVisible()) { index--; if (index == 0) { return null; } prevItem = (GridItem)items.get(index - 1); } return prevItem; } /** * Returns the previous visible column in the table. * * @param column column * @return previous visible column or null * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn getPreviousVisibleColumn(GridColumn column) { checkWidget(); int index = displayOrderedColumns.indexOf(column); if (index == 0) return null; index --; GridColumn previous = (GridColumn)displayOrderedColumns.get(index); while (!previous.isVisible()) { if (index == 0) return null; index --; previous = (GridColumn)displayOrderedColumns.get(index); } return previous; } /** * Returns the next visible column in the table. * * @param column column * @return next visible column or null * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn getNextVisibleColumn(GridColumn column) { checkWidget(); int index = displayOrderedColumns.indexOf(column); if (index == displayOrderedColumns.size() - 1) return null; index ++; GridColumn next = (GridColumn)displayOrderedColumns.get(index); while (!next.isVisible()) { if (index == displayOrderedColumns.size() - 1) return null; index ++; next = (GridColumn)displayOrderedColumns.get(index); } return next; } /** * Returns the number of root items contained in the receiver. * * @return the number of items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getRootItemCount() { checkWidget(); return rootItems.size(); } /** * Returns a (possibly empty) array of {@code GridItem}s which are * the root items in the receiver. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the root items in the receiver * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem[] getRootItems() { checkWidget(); return (GridItem[])rootItems.toArray(new GridItem[rootItems.size()]); } /** * TODO: asl;fj * @param index * @return asdf */ public GridItem getRootItem(int index) { checkWidget(); if (index < 0 || index >= rootItems.size()) { SWT.error(SWT.ERROR_INVALID_RANGE); } return (GridItem)rootItems.get(index); } /** * Gets the row header renderer. * * @return Returns the rowHeaderRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getRowHeaderRenderer() { checkWidget(); return rowHeaderRenderer; } /** * Returns a array of {@code GridItem}s that are currently selected in the * receiver. The order of the items is unspecified. An empty array indicates * that no items are selected. * <p> * Note: This is not the actual structure used by the receiver to maintain * its selection, so modifying the array will not affect the receiver. * <p> * If cell selection is enabled, any items which contain at least one selected * cell are returned. * * @return an array representing the selection * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem[] getSelection() { checkWidget(); if (!cellSelectionEnabled) { return (GridItem[])selectedItems.toArray(new GridItem[selectedItems.size()]); } else { Vector items = new Vector(); int itemCount = getItemCount(); for (Iterator iter = selectedCells.iterator(); iter.hasNext();) { Point cell = (Point)iter.next(); if (cell.y >= 0 && cell.y < itemCount) { GridItem item = getItem(cell.y); if (!items.contains(item)) items.add(item); } } return (GridItem[])items.toArray(new GridItem[]{}); } } /** * Returns the number of selected items contained in the receiver. If cell selection * is enabled, the number of items with at least one selected cell are returned. * * @return the number of selected items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getSelectionCount() { checkWidget(); if (!cellSelectionEnabled) { return selectedItems.size(); } else { Vector items = new Vector(); for (Iterator iter = selectedCells.iterator(); iter.hasNext();) { Point cell = (Point)iter.next(); GridItem item = getItem(cell.y); if (!items.contains(item)) items.add(item); } return items.size(); } } /** * Returns the number of selected cells contained in the receiver. * * @return the number of selected cells * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getCellSelectionCount() { checkWidget(); return selectedCells.size(); } /** * Returns the zero-relative index of the item which is currently selected * in the receiver, or -1 if no item is selected. If cell selection is enabled, * returns the index of first item that contains at least one selected cell. * * @return the index of the selected item * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getSelectionIndex() { checkWidget(); if (!cellSelectionEnabled) { if (selectedItems.size() == 0) { return -1; } return items.indexOf(selectedItems.get(0)); } else { if (selectedCells.size() == 0) return -1; return ((Point)selectedCells.get(0)).y; } } /** * Returns the zero-relative indices of the items which are currently * selected in the receiver. The order of the indices is unspecified. The * array is empty if no items are selected. * <p> * Note: This is not the actual structure used by the receiver to maintain * its selection, so modifying the array will not affect the receiver. * <p> * If cell selection is enabled, returns the indices of any items which * contain at least one selected cell. * * @return the array of indices of the selected items * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int[] getSelectionIndices() { checkWidget(); if (!cellSelectionEnabled) { int[] indices = new int[selectedItems.size()]; int i = 0; for (Iterator itemIterator = selectedItems.iterator(); itemIterator.hasNext(); ) { GridItem item = (GridItem) itemIterator.next(); indices[i] = items.indexOf(item); i++; } return indices; } else { Vector selectedRows = new Vector(); for (Iterator iter = selectedCells.iterator(); iter.hasNext();) { Point cell = (Point)iter.next(); GridItem item = getItem(cell.y); if (!selectedRows.contains(item)) selectedRows.add(item); } int[] indices = new int[selectedRows.size()]; int i = 0; for (Iterator itemIterator = selectedRows.iterator(); itemIterator.hasNext(); ) { GridItem item = (GridItem) itemIterator.next(); indices[i] = items.indexOf(item); i++; } return indices; } } /** * Returns the zero-relative index of the item which is currently at the top * of the receiver. This index can change when items are scrolled or new * items are added or removed. * * @return the index of the top item * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getTopIndex() { checkWidget(); if (topIndex != -1) return topIndex; if (!vScroll.getVisible()) { topIndex = 0; } else { // figure out first visible row and last visible row int firstVisibleIndex = vScroll.getSelection(); if (isTree) { Iterator itemsIter = items.iterator(); int row = firstVisibleIndex + 1; while (row > 0 && itemsIter.hasNext()) { GridItem item = (GridItem)itemsIter.next(); if (item.isVisible()) { row--; if (row == 0) { firstVisibleIndex = items.indexOf(item); } } } } topIndex = firstVisibleIndex; /* * MOPR here lies more potential for increasing performance * for the case (isTree || hasDifferingHeights) * the topIndex could be derived from the previous value * depending on a delta of the vScroll.getSelection() * instead of being calculated completely anew */ } return topIndex; } /** * Returns the zero-relative index of the item which is currently at the bottom * of the receiver. This index can change when items are scrolled, expanded * or collapsed or new items are added or removed. * <p> * Note that the item with this index is often only partly visible; maybe only * a single line of pixels is visible. Use {@link #isShown(GridItem)} to find * out. * <p> * In extreme cases, getBottomIndex() may return the same value as * {@link #getTopIndex()}. * * @return the index of the bottom item * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ int getBottomIndex() { checkWidget(); if (bottomIndex != -1) return bottomIndex; if (items.size() == 0) { bottomIndex = 0; } else if (getVisibleGridHeight()<1) { bottomIndex = getTopIndex(); } else { RowRange range = getRowRange(getTopIndex(),getVisibleGridHeight(),false,false); bottomIndex = range.endIndex; bottomIndexShownCompletely = range.height <= getVisibleGridHeight(); } return bottomIndex; } /** * Returns a {@link RowRange} ranging from * the grid item at startIndex to that at endIndex. * <p> * This is primarily used to measure the height * in pixel of such a range and to count the number * of visible grid items within the range. * * @param startIndex index of the first item in the range or -1 to the first visible item in this grid * @param endIndex index of the last item in the range or -1 to use the last visible item in this grid * @return */ private RowRange getRowRange(int startIndex, int endIndex) { // parameter preparation if (startIndex == -1) { // search frist visible item do startIndex++; while (startIndex < items.size() && !((GridItem)items.get(startIndex)).isVisible()); if (startIndex == items.size()) return null; } if (endIndex == -1) { // search last visible item endIndex = items.size(); do endIndex--; while (endIndex >= 0 && !((GridItem)items.get(endIndex)).isVisible()); if (endIndex == -1) return null; } // fail fast if (startIndex<0 || endIndex<0 || startIndex>=items.size() || endIndex>=items.size() || endIndex < startIndex || ((GridItem)items.get(startIndex)).isVisible()==false || ((GridItem)items.get(endIndex)).isVisible()==false) SWT.error(SWT.ERROR_INVALID_ARGUMENT); RowRange range = new RowRange(); range.startIndex = startIndex; range.endIndex = endIndex; if(isTree || hasDifferingHeights) { for (int idx=startIndex ; idx<=endIndex ; idx++ ) { GridItem currItem = (GridItem)items.get(idx); if(currItem.isVisible()) { if (range.rows>0) range.height++; // height of horizontal row separator range.height += currItem.getHeight(); range.rows++; } } } else { range.rows = range.endIndex - range.startIndex + 1; range.height = ( getItemHeight() + 1 ) * range.rows - 1; } return range; } /** * This method can be used to build a range of grid rows * that is allowed to span a certain height in pixels. * <p> * It returns a {@link RowRange} that contains information * about the range, especially the index of the last * element in the range (or if inverse == true, then the * index of the first element). * <p> * Note: Even if 'forceEndCompletelyInside' is set to * true, the last item will not lie completely within * the availableHeight, if (height of item at startIndex < availableHeight). * * @param startIndex index of the first (if inverse==false) or * last (if inverse==true) item in the range * @param availableHeight height in pixels * @param forceEndCompletelyInside if true, the last item in the range will lie completely * within the availableHeight, otherwise it may lie partly outside this range * @param inverse if true, then the first item in the range will be searched, not the last * @return range of grid rows * @see RowRange */ private RowRange getRowRange(int startIndex, int availableHeight, boolean forceEndCompletelyInside, boolean inverse) { // parameter preparation if (startIndex == -1) { if(!inverse) { // search frist visible item do startIndex++; while (startIndex < items.size() && !((GridItem)items.get(startIndex)).isVisible()); if (startIndex == items.size()) return null; } else { // search last visible item startIndex = items.size(); do startIndex--; while (startIndex >= 0 && !((GridItem)items.get(startIndex)).isVisible()); if (startIndex == -1) return null; } } // fail fast if (startIndex < 0 || startIndex >= items.size() || ((GridItem)items.get(startIndex)).isVisible() == false) SWT.error(SWT.ERROR_INVALID_ARGUMENT); RowRange range = new RowRange(); if (availableHeight <= 0) { // special case: empty range range.startIndex = startIndex; range.endIndex = startIndex; range.rows = 0; range.height = 0; return range; } if (isTree || hasDifferingHeights) { int otherIndex = startIndex; // tentative end index int consumedItems = 0; int consumedHeight = 0; // consume height for startEnd (note: no separator pixel added here) consumedItems++; consumedHeight += ((GridItem)items.get(otherIndex)).getHeight(); // note: we use "+2" in next line, because we only try to add another row if there // is room for the separator line + at least one pixel row for the additional item while (consumedHeight+2 <= availableHeight) { // STEP 1: // try to find a visible item we can add int nextIndex = otherIndex; GridItem nextItem; do { if (!inverse) nextIndex++; else nextIndex--; if (nextIndex >= 0 && nextIndex < items.size()) nextItem = (GridItem)items.get(nextIndex); else nextItem = null; } while (nextItem != null && !nextItem.isVisible()); if (nextItem == null) { // no visible item found break; } if (forceEndCompletelyInside) { // must lie completely within the allowed height if(!(consumedHeight + 1 + nextItem.getHeight() <= availableHeight)) break; } // we found one !! // STEP 2: // Consume height for this item consumedItems++; consumedHeight += 1; // height of separator line consumedHeight += nextItem.getHeight(); // STEP 3: // make this item it the current guess for the other end otherIndex = nextIndex; } range.startIndex = !inverse ? startIndex : otherIndex; range.endIndex = !inverse ? otherIndex : startIndex; range.rows = consumedItems; range.height = consumedHeight; } else { int availableRows = ( availableHeight + 1 ) / ( getItemHeight() + 1 ); if ((( getItemHeight() + 1 ) * range.rows - 1) + 1 < availableHeight) { // not all available space used yet // - so add another row if it need not be completely within availableHeight if (!forceEndCompletelyInside) availableRows++; } int otherIndex = startIndex + ((availableRows - 1) * (!inverse ? 1 : -1)); if (otherIndex<0) otherIndex = 0; if (otherIndex>=items.size()) otherIndex = items.size() - 1 ; range.startIndex = !inverse ? startIndex : otherIndex; range.endIndex = !inverse ? otherIndex : startIndex; range.rows = range.endIndex - range.startIndex + 1; range.height = ( getItemHeight() + 1 ) * range.rows - 1; } return range; } /** * Returns the height of the plain grid in pixels. * <p> * This includes all rows for visible items (i.e. items that return true * on {@link GridItem#isVisible()} ; not only those currently visible on * screen) and the 1 pixel separator between rows. * <p> * This does <em>not</em> include the height of the column headers. * * @return height of plain grid */ int getGridHeight() { RowRange range = getRowRange(-1,-1); return range != null ? range.height : 0; /* * MOPR currently this method is only used in #getTableSize() ; * if it will be used for more important things in the future * (e.g. the max value for vScroll.setValues() when doing pixel-by-pixel * vertical scrolling) then this value should at least be cached or * even updated incrementally when grid items are added/removed or * expaned/collapsed (similar as #currentVisibleItems). * (this is only necessary in the case (isTree || hasDifferingHeights)) */ } /** * Returns the height of the on-screen area that is available * for showing the grid's rows, i.e. the client area of the * scrollable minus the height of the column headers (if shown). * * @return height of visible grid in pixels */ int getVisibleGridHeight() { return getClientArea().height - (columnHeadersVisible ? headerHeight : 0) - (columnFootersVisible ? footerHeight : 0); } /** * Returns the height of the screen area that is available for showing the grid columns * @return */ int getVisibleGridWidth() { return getClientArea().width - ( rowHeaderVisible ? rowHeaderWidth : 0 ); } /** * Gets the top left renderer. * * @return Returns the topLeftRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getTopLeftRenderer() { checkWidget(); return topLeftRenderer; } /** * Gets the bottom left renderer. * * @return Returns the bottomLeftRenderer. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public IRenderer getBottomLeftRenderer() { checkWidget(); return bottomLeftRenderer; } /** * Searches the receiver's list starting at the first column (index 0) until * a column is found that is equal to the argument, and returns the index of * that column. If no column is found, returns -1. * * @param column the search column * @return the index of the column * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the column is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int indexOf(GridColumn column) { checkWidget(); if (column == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (column.getParent() != this) return -1; return columns.indexOf(column); } /** * Searches the receiver's list starting at the first item (index 0) until * an item is found that is equal to the argument, and returns the index of * that item. If no item is found, returns -1. * * @param item the search item * @return the index of the item * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int indexOf(GridItem item) { checkWidget(); if (item == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (item.getParent() != this) return -1; return items.indexOf(item); } /** * Returns {@code true} if the receiver's row header is visible, and * {@code false} otherwise. * <p> * * @return the receiver's row header's visibility state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean isRowHeaderVisible() { checkWidget(); return rowHeaderVisible; } /** * Returns {@code true} if the item is selected, and {@code false} * otherwise. Indices out of range are ignored. If cell selection is * enabled, returns true if the item at the given index contains at * least one selected cell. * * @param index the index of the item * @return the visibility state of the item at the index * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean isSelected(int index) { checkWidget(); if (index < 0 || index >= items.size()) return false; if (!cellSelectionEnabled) { return isSelected((GridItem)items.get(index)); } else { for (Iterator iter = selectedCells.iterator(); iter.hasNext();) { Point cell = (Point)iter.next(); if (cell.y == index) return true; } return false; } } /** * Returns true if the given item is selected. If cell selection is enabled, * returns true if the given item contains at least one selected cell. * * @param item item * @return true if the item is selected. * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean isSelected(GridItem item) { checkWidget(); if (!cellSelectionEnabled) { return selectedItems.contains(item); } else { int index = indexOf(item); if (index == -1) return false; for (Iterator iter = selectedCells.iterator(); iter.hasNext();) { Point cell = (Point)iter.next(); if (cell.y == index) return true; } return false; } } /** * Returns true if the given cell is selected. * * @param cell cell * @return true if the cell is selected. * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the cell is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean isCellSelected(Point cell) { checkWidget(); if (cell == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); return selectedCells.contains(cell); } /** * Removes the item from the receiver at the given zero-relative index. * * @param index the index for the item * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number * of elements in the list minus 1 (inclusive)</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void remove(int index) { checkWidget(); if (index < 0 || index > items.size() - 1) { SWT.error(SWT.ERROR_INVALID_RANGE); } GridItem item = (GridItem)items.get(index); item.dispose(); redraw(); } /** * Removes the items from the receiver which are between the given * zero-relative start and end indices (inclusive). * * @param start the start of the range * @param end the end of the range * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if either the start or end are not between 0 * and the number of elements in the list minus 1 (inclusive)</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void remove(int start, int end) { checkWidget(); for (int i = end; i >= start; i--) { if (i < 0 || i > items.size() - 1) { SWT.error(SWT.ERROR_INVALID_RANGE); } GridItem item = (GridItem)items.get(i); item.dispose(); } redraw(); } /** * Removes the items from the receiver's list at the given zero-relative * indices. * * @param indices the array of indices of the items * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number * of elements in the list minus 1 (inclusive)</li> * <li>ERROR_NULL_ARGUMENT - if the indices array is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void remove(int[] indices) { checkWidget(); if (indices == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } GridItem[] removeThese = new GridItem[indices.length]; for (int i = 0; i < indices.length; i++) { int j = indices[i]; if (j < items.size() && j >= 0) { removeThese[i] = (GridItem)items.get(j); } else { SWT.error(SWT.ERROR_INVALID_RANGE); } } for (int i = 0; i < removeThese.length; i++) { GridItem item = removeThese[i]; item.dispose(); } redraw(); } /** * Removes all of the items from the receiver. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void removeAll() { checkWidget(); while (items.size() > 0) { ((GridItem)items.get(0)).dispose(); } deselectAll(); redraw(); } /** * Removes the listener from the collection of listeners who will be * notified when the receiver's selection changes. * * @param listener the listener which should no longer be notified * @see SelectionListener * @see #addSelectionListener(SelectionListener) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void removeSelectionListener(SelectionListener listener) { checkWidget(); removeListener(SWT.Selection, listener); removeListener(SWT.DefaultSelection, listener); } /** * Removes the listener from the collection of listeners who will be * notified when the receiver's items changes. * * @param listener the listener which should no longer be notified * @see TreeListener * @see #addTreeListener(TreeListener) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void removeTreeListener(TreeListener listener) { checkWidget(); removeListener(SWT.Expand, listener); removeListener(SWT.Collapse, listener); } /** * Selects the item at the given zero-relative index in the receiver. If the * item at the index was already selected, it remains selected. Indices that * are out of range are ignored. * <p> * If cell selection is enabled, selects all cells at the given index. * * @param index the index of the item to select * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void select(int index) { checkWidget(); if (!selectionEnabled) return; if (index < 0 || index >= items.size()) return; GridItem item = (GridItem)items.get(index); if (!cellSelectionEnabled) { if (selectionType == SWT.MULTI && selectedItems.contains(item)) return; if (selectionType == SWT.SINGLE) selectedItems.clear(); selectedItems.add(item); } else { selectCells(getCells(item)); } redraw(); } /** * Selects the items in the range specified by the given zero-relative * indices in the receiver. The range of indices is inclusive. The current * selection is not cleared before the new items are selected. * <p> * If an item in the given range is not selected, it is selected. If an item * in the given range was already selected, it remains selected. Indices * that are out of range are ignored and no items will be selected if start * is greater than end. If the receiver is single-select and there is more * than one item in the given range, then all indices are ignored. * <p> * If cell selection is enabled, all cells within the given range are selected. * * @param start the start of the range * @param end the end of the range * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see Grid#setSelection(int,int) */ public void select(int start, int end) { checkWidget(); if (!selectionEnabled) return; if (selectionType == SWT.SINGLE && start != end) return; if (!cellSelectionEnabled) { if (selectionType == SWT.SINGLE) selectedItems.clear(); } for (int i = start; i <= end; i++) { if (i < 0) { continue; } if (i > items.size() - 1) { break; } GridItem item = (GridItem)items.get(i); if (!cellSelectionEnabled) { if (!selectedItems.contains(item)) selectedItems.add(item); } else { selectCells(getCells(item)); } } redraw(); } /** * Selects the items at the given zero-relative indices in the receiver. The * current selection is not cleared before the new items are selected. * <p> * If the item at a given index is not selected, it is selected. If the item * at a given index was already selected, it remains selected. Indices that * are out of range and duplicate indices are ignored. If the receiver is * single-select and multiple indices are specified, then all indices are * ignored. * <p> * If cell selection is enabled, all cells within the given indices are * selected. * * @param indices the array of indices for the items to select * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the array of indices is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see Grid#setSelection(int[]) */ public void select(int[] indices) { checkWidget(); if (indices == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (!selectionEnabled) return; if (selectionType == SWT.SINGLE && indices.length > 1) return; if (!cellSelectionEnabled) if (selectionType == SWT.SINGLE) selectedItems.clear(); for (int i = 0; i < indices.length; i++) { int j = indices[i]; if (j >= 0 && j < items.size()) { GridItem item = (GridItem)items.get(j); if (!cellSelectionEnabled) { if (!selectedItems.contains(item)) selectedItems.add(item); } else { selectCells(getCells(item)); } } } redraw(); } /** * Selects all of the items in the receiver. * <p> * If the receiver is single-select, do nothing. If cell selection is enabled, * all cells are selected. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectAll() { checkWidget(); if (!selectionEnabled) return; if (selectionType == SWT.SINGLE) return; if (cellSelectionEnabled) { selectAllCells(); return; } selectedItems.clear(); selectedItems.addAll(items); redraw(); } /** * Sets the empty cell renderer. * * @param emptyCellRenderer The emptyCellRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setEmptyCellRenderer(GridCellRenderer emptyCellRenderer) { checkWidget(); emptyCellRenderer.setDisplay(getDisplay()); this.emptyCellRenderer = emptyCellRenderer; } /** * Sets the empty column header renderer. * * @param emptyColumnHeaderRenderer The emptyColumnHeaderRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setEmptyColumnHeaderRenderer(IRenderer emptyColumnHeaderRenderer) { checkWidget(); emptyColumnHeaderRenderer.setDisplay(getDisplay()); this.emptyColumnHeaderRenderer = emptyColumnHeaderRenderer; } /** * Sets the empty column footer renderer. * * @param emptyColumnFooterRenderer The emptyColumnFooterRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setEmptyColumnFooterRenderer(IRenderer emptyColumnFooterRenderer) { checkWidget(); emptyColumnFooterRenderer.setDisplay(getDisplay()); this.emptyColumnFooterRenderer = emptyColumnFooterRenderer; } /** * Sets the empty row header renderer. * * @param emptyRowHeaderRenderer The emptyRowHeaderRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setEmptyRowHeaderRenderer(IRenderer emptyRowHeaderRenderer) { checkWidget(); emptyRowHeaderRenderer.setDisplay(getDisplay()); this.emptyRowHeaderRenderer = emptyRowHeaderRenderer; } /** * Sets the external horizontal scrollbar. Allows the scrolling to be * managed externally from the table. This functionality is only intended * when SWT.H_SCROLL is not given. * <p> * Using this feature, a ScrollBar could be instantiated outside the table, * wrapped in IScrollBar and thus be 'connected' to the table. * * @param scroll The horizontal scrollbar to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ protected void setHorizontalScrollBarProxy(IScrollBarProxy scroll) { checkWidget(); if (getHorizontalBar() != null) { return; } hScroll = scroll; hScroll.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { onScrollSelection(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } /** * Sets the external vertical scrollbar. Allows the scrolling to be managed * externally from the table. This functionality is only intended when * SWT.V_SCROLL is not given. * <p> * Using this feature, a ScrollBar could be instantiated outside the table, * wrapped in IScrollBar and thus be 'connected' to the table. * * @param scroll * The vertical scrollbar to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ protected void setlVerticalScrollBarProxy(IScrollBarProxy scroll) { checkWidget(); if (getVerticalBar() != null) { return; } vScroll = scroll; vScroll.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { onScrollSelection(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } /** * Sets the focus renderer. * * @param focusRenderer The focusRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setFocusRenderer(IRenderer focusRenderer) { checkWidget(); this.focusRenderer = focusRenderer; } /** * Marks the receiver's header as visible if the argument is {@code true}, * and marks it invisible otherwise. * * @param show the new visibility state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setHeaderVisible(boolean show) { checkWidget(); this.columnHeadersVisible = show; redraw(); } /** * Marks the receiver's footer as visible if the argument is {@code true}, * and marks it invisible otherwise. * * @param show the new visibility state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setFooterVisible(boolean show) { checkWidget(); this.columnFootersVisible = show; redraw(); } /** * Sets the line color. * * @param lineColor The lineColor to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setLineColor(Color lineColor) { checkWidget(); this.lineColor = lineColor; } /** * Sets the line visibility. * * @param linesVisible Te linesVisible to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setLinesVisible(boolean linesVisible) { checkWidget(); this.linesVisible = linesVisible; redraw(); } /** * Sets the tree line visibility. * * @param treeLinesVisible * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setTreeLinesVisible(boolean treeLinesVisible) { checkWidget(); this.treeLinesVisible = treeLinesVisible; redraw(); } /** * Sets the row header renderer. * * @param rowHeaderRenderer The rowHeaderRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setRowHeaderRenderer(IRenderer rowHeaderRenderer) { checkWidget(); rowHeaderRenderer.setDisplay(getDisplay()); this.rowHeaderRenderer = rowHeaderRenderer; } /** * Marks the receiver's row header as visible if the argument is * {@code true}, and marks it invisible otherwise. When row headers are * visible, horizontal scrolling is always done by column rather than by * pixel. * * @param show the new visibility state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setRowHeaderVisible(boolean show) { checkWidget(); this.rowHeaderVisible = show; setColumnScrolling(true); if (show && isAutoWidth()) { rowHeaderWidth = 1; for (Iterator iter = items.iterator(); iter.hasNext();) { GridItem iterItem = (GridItem)iter.next(); rowHeaderWidth = Math.max(rowHeaderWidth,rowHeaderRenderer.computeSize(sizingGC, SWT.DEFAULT,SWT.DEFAULT,iterItem).x); } } redraw(); } /** * Selects the item at the given zero-relative index in the receiver. The * current selection is first cleared, then the new item is selected. * <p> * If cell selection is enabled, all cells within the item at the given index * are selected. * * @param index the index of the item to select * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setSelection(int index) { checkWidget(); if (!selectionEnabled) return; if (index >= 0 && index < items.size()) { if (!cellSelectionEnabled) { selectedItems.clear(); selectedItems.add((GridItem)items.get(index)); redraw(); } else { selectedCells.clear(); selectCells(getCells((GridItem)items.get(index))); } } } /** * Selects the items in the range specified by the given zero-relative * indices in the receiver. The range of indices is inclusive. The current * selection is cleared before the new items are selected. * <p> * Indices that are out of range are ignored and no items will be selected * if start is greater than end. If the receiver is single-select and there * is more than one item in the given range, then all indices are ignored. * <p> * If cell selection is enabled, all cells within the given range are selected. * * @param start the start index of the items to select * @param end the end index of the items to select * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see Grid#deselectAll() * @see Grid#select(int,int) */ public void setSelection(int start, int end) { checkWidget(); if (!selectionEnabled) return; if (selectionType == SWT.SINGLE && start != end) return; if (!cellSelectionEnabled) { selectedItems.clear(); } else { selectedCells.clear(); } for (int i = start; i <= end; i++) { if (i < 0) { continue; } if (i > items.size() - 1) { break; } GridItem item = (GridItem)items.get(i); if (!cellSelectionEnabled) { selectedItems.add(item); } else { selectCells(getCells(item)); } } redraw(); } /** * Selects the items at the given zero-relative indices in the receiver. The * current selection is cleared before the new items are selected. * <p> * Indices that are out of range and duplicate indices are ignored. If the * receiver is single-select and multiple indices are specified, then all * indices are ignored. * <p> * If cell selection is enabled, all cells within the given indices are selected. * * @param indices the indices of the items to select * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the array of indices is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see Grid#deselectAll() * @see Grid#select(int[]) */ public void setSelection(int[] indices) { checkWidget(); if (!selectionEnabled) return; if (selectionType == SWT.SINGLE && indices.length > 1) return; if (!cellSelectionEnabled) { selectedItems.clear(); } else { selectedCells.clear(); } for (int i = 0; i < indices.length; i++) { int j = indices[i]; if (j < 0) { continue; } if (j > items.size() - 1) { break; } GridItem item = (GridItem)items.get(j); if (!cellSelectionEnabled) { selectedItems.add(item); } else { selectCells(getCells(item)); } } redraw(); } /** * Sets the receiver's selection to be the given array of items. The current * selection is cleared before the new items are selected. * <p> * Items that are not in the receiver are ignored. If the receiver is * single-select and multiple items are specified, then all items are * ignored. If cell selection is enabled, all cells within the given items * are selected. * * @param _items the array of items * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the array of items is null</li> * <li>ERROR_INVALID_ARGUMENT - if one of the items has been disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> * @see Grid#deselectAll() * @see Grid#select(int[]) * @see Grid#setSelection(int[]) */ public void setSelection(GridItem[] _items) { checkWidget(); if (!selectionEnabled) return; if (_items == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (selectionType == SWT.SINGLE && _items.length > 1) return; if (!cellSelectionEnabled) { selectedItems.clear(); } else { selectedCells.clear(); } for (int i = 0; i < _items.length; i++) { GridItem item = _items[i]; if (item == null) continue; if (item.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if (item.getParent() != this) continue; if (!cellSelectionEnabled) { selectedItems.add(item); } else { selectCells(getCells(item)); } } redraw(); } /** * Sets the zero-relative index of the item which is currently at the top of * the receiver. This index can change when items are scrolled or new items * are added and removed. * * @param index the index of the top item * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setTopIndex(int index) { checkWidget(); if (index < 0 || index >= items.size()) { return; } GridItem item = (GridItem)items.get(index); if (!item.isVisible()) { return; } if (!vScroll.getVisible()) { return; } int vScrollAmount = 0; for (int i = 0; i < index; i++) { if (((GridItem)items.get(i)).isVisible()) { vScrollAmount++; } } vScroll.setSelection(vScrollAmount); topIndex = -1; bottomIndex = -1; redraw(); } /** * Sets the top left renderer. * * @param topLeftRenderer The topLeftRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setTopLeftRenderer(IRenderer topLeftRenderer) { checkWidget(); topLeftRenderer.setDisplay(getDisplay()); this.topLeftRenderer = topLeftRenderer; } /** * Sets the bottom left renderer. * * @param bottomLeftRenderer The topLeftRenderer to set. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setBottomLeftRenderer(IRenderer bottomLeftRenderer) { checkWidget(); bottomLeftRenderer.setDisplay(getDisplay()); this.bottomLeftRenderer = bottomLeftRenderer; } /** * Shows the column. If the column is already showing in the receiver, this * method simply returns. Otherwise, the columns are scrolled until the * column is visible. * * @param col the column to be shown * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void showColumn(GridColumn col) { checkWidget(); if (!col.isVisible()) { GridColumnGroup group = col.getColumnGroup(); group.setExpanded(!group.getExpanded()); if (group.getExpanded()) { group.notifyListeners(SWT.Expand,new Event()); } else { group.notifyListeners(SWT.Collapse,new Event()); } } if (!hScroll.getVisible()) { return; } int x = getColumnHeaderXPosition(col); int firstVisibleX = 0; if (rowHeaderVisible) { firstVisibleX = rowHeaderWidth; } // if its visible just return if (x >= firstVisibleX && (x + col.getWidth()) <= (firstVisibleX + (getClientArea().width - firstVisibleX))) { return; } if (!getColumnScrolling()) { if (x < firstVisibleX) { hScroll.setSelection(getHScrollSelectionInPixels() - (firstVisibleX - x)); } else { if (col.getWidth() > getClientArea().width - firstVisibleX) { hScroll.setSelection(getHScrollSelectionInPixels() + (x - firstVisibleX)); } else { x -= getClientArea().width - firstVisibleX - col.getWidth(); hScroll.setSelection(getHScrollSelectionInPixels() + (x - firstVisibleX)); } } } else { if (x < firstVisibleX || col.getWidth() > getClientArea().width - firstVisibleX) { int sel = displayOrderedColumns.indexOf(col); hScroll.setSelection(sel); } else { int availableWidth = getClientArea().width - firstVisibleX - col.getWidth(); GridColumn prevCol = getPreviousVisibleColumn(col); GridColumn currentScrollTo = col; while (true) { if (prevCol == null || prevCol.getWidth() > availableWidth) { int sel = displayOrderedColumns.indexOf(currentScrollTo); hScroll.setSelection(sel); break; } else { availableWidth -= prevCol.getWidth(); currentScrollTo = prevCol; prevCol = getPreviousVisibleColumn(prevCol); } } } } redraw(); } /** * Returns true if 'item' is currently being <em>completely</em> * shown in this <code>Grid</code>'s visible on-screen area. * * <p>Here, "completely" only refers to the item's height, not its * width. This means this method returns true also if some cells * are horizontally scrolled away. * * @param item * @return true if 'item' is shown * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * <li>ERROR_INVALID_ARGUMENT - if 'item' is not contained in the receiver</li> * </ul> */ boolean isShown(GridItem item) { checkWidget(); if(!item.isVisible()) return false; int itemIndex = items.indexOf(item); if (itemIndex == -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); int firstVisibleIndex = getTopIndex(); int lastVisibleIndex = getBottomIndex(); return (itemIndex >= firstVisibleIndex && itemIndex < lastVisibleIndex) || (itemIndex == lastVisibleIndex && bottomIndexShownCompletely); } /** * Shows the item. If the item is already showing in the receiver, this * method simply returns. Otherwise, the items are scrolled until the item * is visible. * * @param item the item to be shown * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * <li>ERROR_INVALID_ARGUMENT - if 'item' is not contained in the receiver</li> * </ul> */ public void showItem(GridItem item) { checkWidget(); updateScrollbars(); // if no items are visible on screen then abort if (getVisibleGridHeight()<1) { return; } // if its visible just return if (isShown(item)) { return; } if (!item.isVisible()) { GridItem parent = item.getParentItem(); do { if (!parent.isExpanded()) { parent.setExpanded(true); parent.fireEvent(SWT.Expand); } parent = parent.getParentItem(); } while (parent != null); } int newTopIndex = items.indexOf(item); if (newTopIndex >= getBottomIndex()) { RowRange range = getRowRange(newTopIndex,getVisibleGridHeight(),true,true); // note: inverse==true newTopIndex = range.startIndex; // note: use startIndex because of inverse==true } setTopIndex(newTopIndex); } /** * Shows the selection. If the selection is already showing in the receiver, * this method simply returns. Otherwise, the items are scrolled until the * selection is visible. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void showSelection() { checkWidget(); if (scrollValuesObsolete) updateScrollbars(); GridItem item = null; if (!cellSelectionEnabled) { if (selectedItems.size() == 0) { return; } item = (GridItem)selectedItems.get(0); showItem(item); } else { if (selectedCells.size() == 0) return; Point cell = (Point)selectedCells.get(0); item = getItem(cell.y); showItem(item); GridColumn col = getColumn(cell.x); showColumn(col); } } /** * Enables selection highlighting if the argument is <code>true</code>. * * @param selectionEnabled the selection enabled state * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setSelectionEnabled(boolean selectionEnabled) { checkWidget(); if (!selectionEnabled) { selectedItems.clear(); redraw(); } this.selectionEnabled = selectionEnabled; } /** * Returns <code>true</code> if selection is enabled, false otherwise. * * @return the selection enabled state * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getSelectionEnabled() { checkWidget(); return selectionEnabled; } /** * Computes and sets the height of the header row. This method will ask for * the preferred size of all the column headers and use the max. * * @param gc GC for font metrics, etc. */ private void computeHeaderHeight(GC gc) { int colHeaderHeight = 0; for (Iterator columnsIterator = columns.iterator(); columnsIterator.hasNext(); ) { GridColumn column = (GridColumn) columnsIterator.next(); colHeaderHeight = Math .max(column.getHeaderRenderer().computeSize(gc, column.getWidth(), SWT.DEFAULT, column).y, colHeaderHeight); } int groupHeight = 0; for (int groupIndex = 0; groupIndex < columnGroups.length; groupIndex++) { GridColumnGroup group = (GridColumnGroup) columnGroups[groupIndex]; groupHeight = Math.max(group.getHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, group).y, groupHeight); } headerHeight = colHeaderHeight + groupHeight; groupHeaderHeight = groupHeight; } private void computeFooterHeight(GC gc) { int colFooterHeight = 0; for (Iterator columnsIterator = columns.iterator(); columnsIterator.hasNext(); ) { GridColumn column = (GridColumn) columnsIterator.next(); colFooterHeight = Math .max(column.getFooterRenderer().computeSize(gc, column.getWidth(), SWT.DEFAULT, column).y, colFooterHeight); } footerHeight = colFooterHeight; } /** * Returns the computed default item height. Currently this method just gets the * preferred size of all the cells in the given row and returns that (it is * then used as the height of all rows with items having a height of -1). * * @param item item to use for sizing * @param gc GC used to perform font metrics,etc. * @return the row height */ private int computeItemHeight(GridItem item, GC gc) { int height = 1; if (columns.size() == 0 || items.size() == 0) { return height; } for (Iterator columnsIterator = columns.iterator(); columnsIterator.hasNext(); ) { GridColumn column = (GridColumn) columnsIterator.next(); column.getCellRenderer().setColumn(indexOf(column)); height = Math.max(height, column.getCellRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, item).y); } if( rowHeaderVisible && rowHeaderRenderer != null ) { height = Math.max(height, rowHeaderRenderer.computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, item).y); } return height <= 0 ? 16 : height; } /** * Returns the x position of the given column. Takes into account scroll * position. * * @param column given column * @return x position */ private int getColumnHeaderXPosition(GridColumn column) { if (!column.isVisible()) { return -1; } int x = 0; x -= getHScrollSelectionInPixels(); if (rowHeaderVisible) { x += rowHeaderWidth; } for (Iterator column2Iterator = displayOrderedColumns.iterator(); column2Iterator.hasNext(); ) { GridColumn column2 = (GridColumn) column2Iterator.next(); if (!column2.isVisible()) { continue; } if (column2 == column) { break; } x += column2.getWidth(); } return x; } /** * Returns the hscroll selection in pixels. This method abstracts away the * differences between column by column scrolling and pixel based scrolling. * * @return the horizontal scroll selection in pixels */ private int getHScrollSelectionInPixels() { int selection = hScroll.getSelection(); if (columnScrolling) { int pixels = 0; for (int i = 0; i < selection; i++) { pixels += ((GridColumn)displayOrderedColumns.get(i)).getWidth(); } selection = pixels; } return selection; } /** * Returns the size of the preferred size of the inner table. * * @return the preferred size of the table. */ private Point getTableSize() { int x = 0; int y = 0; if (columnHeadersVisible) { y += headerHeight; } if(columnFootersVisible) { y += footerHeight; } y += getGridHeight(); if (rowHeaderVisible) { x += rowHeaderWidth; } for (Iterator columnIterator = columns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (column.isVisible()) { x += column.getWidth(); } } return new Point(x, y); } /** * Manages the header column dragging and calculates the drop point, * triggers a redraw. * * @param x mouse x * @return true if this event has been consumed. */ private boolean handleColumnDragging(int x) { GridColumn local_dragDropBeforeColumn = null; GridColumn local_dragDropAfterColumn = null; int x2 = 1; if (rowHeaderVisible) { x2 += rowHeaderWidth + 1; } x2 -= getHScrollSelectionInPixels(); int i = 0; GridColumn previousVisibleCol = null; boolean nextVisibleColumnIsBeforeCol = false; GridColumn firstVisibleCol = null; GridColumn lastVisibleCol = null; if (x < x2) { for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (!column.isVisible()) { continue; } local_dragDropBeforeColumn = column; break; } local_dragDropAfterColumn = null; } else { for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (!column.isVisible()) { continue; } i++; if (firstVisibleCol == null) { firstVisibleCol = column; } lastVisibleCol = column; if (nextVisibleColumnIsBeforeCol) { local_dragDropBeforeColumn = column; nextVisibleColumnIsBeforeCol = false; } if (x >= x2 && x <= (x2 + column.getWidth())) { if (x <= (x2 + column.getWidth() / 2)) { local_dragDropBeforeColumn = column; local_dragDropAfterColumn = previousVisibleCol; } else { local_dragDropAfterColumn = column; // the next visible column is the before col nextVisibleColumnIsBeforeCol = true; } } x2 += column.getWidth(); previousVisibleCol = column; } if (local_dragDropBeforeColumn == null) { local_dragDropAfterColumn = lastVisibleCol; } } currentHeaderDragX = x; if (local_dragDropBeforeColumn != dragDropBeforeColumn || (dragDropBeforeColumn == null && dragDropAfterColumn == null)) { dragDropPointValid = true; // Determine if valid drop point if (columnGroups.length != 0) { if (columnBeingPushed.getColumnGroup() == null) { if (local_dragDropBeforeColumn != null && local_dragDropAfterColumn != null && local_dragDropBeforeColumn.getColumnGroup() != null && local_dragDropBeforeColumn.getColumnGroup() == local_dragDropAfterColumn .getColumnGroup()) { // Dont move a column w/o a group in between two columns // in the same group dragDropPointValid = false; } } else { if (!(local_dragDropBeforeColumn != null && local_dragDropBeforeColumn .getColumnGroup() == columnBeingPushed.getColumnGroup()) && !(local_dragDropAfterColumn != null && local_dragDropAfterColumn .getColumnGroup() == columnBeingPushed.getColumnGroup())) { // Dont move a column with a group dragDropPointValid = false; } } } else { dragDropPointValid = true; } } dragDropBeforeColumn = local_dragDropBeforeColumn; dragDropAfterColumn = local_dragDropAfterColumn; Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); return true; } /** * Handles the moving of columns after a column is dropped. */ private void handleColumnDrop() { draggingColumn = false; if ((dragDropBeforeColumn != columnBeingPushed && dragDropAfterColumn != columnBeingPushed) && (columnGroups.length == 0 || dragDropPointValid)) { int notifyFrom = displayOrderedColumns.indexOf(columnBeingPushed); int notifyTo = notifyFrom; displayOrderedColumns.remove(columnBeingPushed); if (dragDropBeforeColumn == null) { notifyTo = displayOrderedColumns.size(); displayOrderedColumns.add(columnBeingPushed); } else if (dragDropAfterColumn == null) { displayOrderedColumns.add(0, columnBeingPushed); notifyFrom = 0; } else { int insertAtIndex = 0; if (columnGroups.length != 0) { // ensure that we aren't putting this column into a group, // this is possible if // there are invisible columns between the after and before // cols if (dragDropBeforeColumn.getColumnGroup() == columnBeingPushed.getColumnGroup()) { insertAtIndex = displayOrderedColumns.indexOf(dragDropBeforeColumn); } else if (dragDropAfterColumn.getColumnGroup() == columnBeingPushed .getColumnGroup()) { insertAtIndex = displayOrderedColumns.indexOf(dragDropAfterColumn) + 1; } else { if (dragDropBeforeColumn.getColumnGroup() == null) { insertAtIndex = displayOrderedColumns.indexOf(dragDropBeforeColumn); } else { GridColumnGroup beforeGroup = dragDropBeforeColumn.getColumnGroup(); insertAtIndex = displayOrderedColumns.indexOf(dragDropBeforeColumn); while (insertAtIndex > 0 && ((GridColumn)displayOrderedColumns.get(insertAtIndex -1)).getColumnGroup() == beforeGroup) { insertAtIndex--; } } } } else { insertAtIndex = displayOrderedColumns.indexOf(dragDropBeforeColumn); } displayOrderedColumns.add(insertAtIndex, columnBeingPushed); notifyFrom = Math.min(notifyFrom, insertAtIndex); notifyTo = Math.max(notifyTo, insertAtIndex); } for (int i = notifyFrom; i <= notifyTo; i++) { ((GridColumn)displayOrderedColumns.get(i)).fireMoved(); } } redraw(); } /** * Determines if the mouse is pushing the header but has since move out of * the header bounds and therefore should be drawn unpushed. Also initiates * a column header drag when appropriate. * * @param x mouse x * @param y mouse y * @return true if this event has been consumed. */ private boolean handleColumnHeaderHoverWhilePushing(int x, int y) { GridColumn overThis = overColumnHeader(x, y); if ((overThis == columnBeingPushed) != pushingAndHovering) { pushingAndHovering = (overThis == columnBeingPushed); redraw(); } if (columnBeingPushed.getMoveable()) { if (pushingAndHovering && Math.abs(startHeaderPushX - x) > 3) { // stop pushing pushingColumn = false; columnBeingPushed.getHeaderRenderer().setMouseDown(false); columnBeingPushed.getHeaderRenderer().setHover(false); // now dragging draggingColumn = true; columnBeingPushed.getHeaderRenderer().setMouseDown(false); startHeaderDragX = x; dragDropAfterColumn = null; dragDropBeforeColumn = null; dragDropPointValid = true; handleColumnDragging(x); } } return true; } /** * Determines if a column group header has been clicked and forwards the * event to the header renderer. * * @param x mouse x * @param y mouse y * @return true if this event has been consumed. */ private boolean handleColumnGroupHeaderClick(int x, int y) { if (!columnHeadersVisible) { return false; } GridColumnGroup overThis = overColumnGroupHeader(x, y); if (overThis == null) { return false; } int headerX = 0; if (rowHeaderVisible) { headerX += rowHeaderWidth; } int width = 0; boolean firstCol = false; for (Iterator colIterator = displayOrderedColumns.iterator(); colIterator.hasNext(); ) { GridColumn col = (GridColumn) colIterator.next(); if (col.getColumnGroup() == overThis && col.isVisible()) { firstCol = true; width += col.getWidth(); } if (!firstCol && col.isVisible()) { headerX += col.getWidth(); } } overThis.getHeaderRenderer().setBounds(headerX - getHScrollSelectionInPixels(), 0, width, groupHeaderHeight); return overThis.getHeaderRenderer() .notify(IInternalWidget.LeftMouseButtonDown, new Point(x, y), overThis); } /** * Determines if a column header has been clicked, updates the renderer * state and triggers a redraw if necesary. * * @param x mouse x * @param y mouse y * @return true if this event has been consumed. */ private boolean handleColumnHeaderPush(int x, int y) { if (!columnHeadersVisible) { return false; } GridColumn overThis = overColumnHeader(x, y); if (overThis == null) { return false; } columnBeingPushed = overThis; // draw pushed columnBeingPushed.getHeaderRenderer().setMouseDown(true); columnBeingPushed.getHeaderRenderer().setHover(true); pushingAndHovering = true; redraw(); startHeaderPushX = x; pushingColumn = true; setCapture(true); return true; } private boolean handleColumnFooterPush(int x, int y) { if(!columnFootersVisible) { return false; } GridColumn overThis = overColumnFooter(x, y); if (overThis == null) { return false; } return true; } /** * Sets the new width of the column being resized and fires the appropriate * listeners. * * @param x mouse x */ private void handleColumnResizerDragging(int x) { int newWidth = resizingColumnStartWidth + (x - resizingStartX); if (newWidth < MIN_COLUMN_HEADER_WIDTH) { newWidth = MIN_COLUMN_HEADER_WIDTH; } if (columnScrolling) { int maxWidth = getClientArea().width; if (rowHeaderVisible) maxWidth -= rowHeaderWidth; if (newWidth > maxWidth) newWidth = maxWidth; } if (newWidth == columnBeingResized.getWidth()) { return; } columnBeingResized.setWidth(newWidth,false); scrollValuesObsolete = true; Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); columnBeingResized.fireResized(); for (int index = displayOrderedColumns.indexOf(columnBeingResized) + 1; index < displayOrderedColumns.size(); index ++) { GridColumn col = (GridColumn)displayOrderedColumns.get(index); if (col.isVisible()) col.fireMoved(); } } /** * Sets the new height of the item of the row being resized and fires the appropriate * listeners. * * @param x mouse x */ private void handleRowResizerDragging(int y) { int newHeight = resizingRowStartHeight + (y - resizingStartY); if (newHeight < MIN_ROW_HEADER_HEIGHT) { newHeight = MIN_ROW_HEADER_HEIGHT; } if (newHeight > getClientArea().height) { newHeight = getClientArea().height; } if (newHeight == rowBeingResized.getHeight()) { return; } Event e = new Event(); e.item = rowBeingResized; e.widget = this; e.detail = newHeight; rowBeingResized.notifyListeners(SWT.Resize, e); if (e.doit == false) return; newHeight = e.detail; if (newHeight < MIN_ROW_HEADER_HEIGHT) { newHeight = MIN_ROW_HEADER_HEIGHT; } if (newHeight > getClientArea().height) { newHeight = getClientArea().height; } rowBeingResized.setHeight(newHeight); scrollValuesObsolete = true; Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); } /** * Determines if the mouse is hovering on a column resizer and changes the * pointer and sets field appropriately. * * @param x mouse x * @param y mouse y * @return true if this event has been consumed. */ private boolean handleHoverOnColumnResizer(int x, int y) { boolean over = false; if (y <= headerHeight) { int x2 = 0; if (rowHeaderVisible) { x2 += rowHeaderWidth; } x2 -= getHScrollSelectionInPixels(); for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (!column.isVisible()) { continue; } x2 += column.getWidth(); if (x2 >= (x - COLUMN_RESIZER_THRESHOLD) && x2 <= (x + COLUMN_RESIZER_THRESHOLD)) { if (column.getResizeable()) { if (column.getColumnGroup() != null && y <= groupHeaderHeight) { // if this is not the last column if (column != column.getColumnGroup().getLastVisibleColumn()) { break; } } over = true; columnBeingResized = column; } break; } } } if (over != hoveringOnColumnResizer) { if (over) { setCursor(getDisplay().getSystemCursor(SWT.CURSOR_SIZEWE)); } else { columnBeingResized = null; setCursor(null); } hoveringOnColumnResizer = over; } return over; } /** * Determines if the mouse is hovering on a row resizer and changes the * pointer and sets field appropriately. * * @param x mouse x * @param y mouse y * @return true if this event has been consumed. */ private boolean handleHoverOnRowResizer(int x, int y) { rowBeingResized = null; boolean over = false; if (x <= rowHeaderWidth) { int y2 = 0; if (columnHeadersVisible) { y2 += headerHeight; } int row=getTopIndex(); while(row<items.size() && y2<=getClientArea().height) { GridItem currItem = (GridItem)items.get(row); if (currItem.isVisible()) { y2 += currItem.getHeight() +1; if (y2 >= (y - ROW_RESIZER_THRESHOLD) && y2 <= (y + ROW_RESIZER_THRESHOLD)) { // if (currItem.isResizeable()) { over = true; rowBeingResized = currItem; } // do not brake here, because in case of overlapping // row resizers we need to find the last one } else { if(rowBeingResized != null) { // we have passed all (overlapping) row resizers, so break break; } } } row++; } } if (over != hoveringOnRowResizer) { if (over) { setCursor(getDisplay().getSystemCursor(SWT.CURSOR_SIZENS)); } else { rowBeingResized = null; setCursor(null); } hoveringOnRowResizer = over; } return over; } /** * Returns the cell at the given point in the receiver or null if no such * cell exists. The point is in the coordinate system of the receiver. * * @param point the point used to locate the item * @return the cell at the given point * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Point getCell(Point point) { checkWidget(); if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (point.x < 0 || point.x > getClientArea().width) return null; GridItem item = getItem(point); GridColumn column = getColumn(point); if (item!=null && column!=null) { return new Point(columns.indexOf(column),items.indexOf(item)); } else { return null; } } /** * Paints. * * @param e paint event */ private void onPaint(PaintEvent e) { int insertMarkPosX1 = -1; // we will populate these values while drawing the cells int insertMarkPosX2 = -1; int insertMarkPosY = -1; boolean insertMarkPosFound = false; GridCellSpanManager cellSpanManager = new GridCellSpanManager(); e.gc.setBackground(getBackground()); this.drawBackground(e.gc,0,0,getSize().x,getSize().y); if (scrollValuesObsolete) { updateScrollbars(); scrollValuesObsolete = false; } int x = 0; int y = 0; if (columnHeadersVisible) { paintHeader(e.gc); y += headerHeight; } int availableHeight = getClientArea().height-y; int visibleRows = availableHeight / getItemHeight() + 1; if (items.size()>0 && availableHeight>0) { RowRange range = getRowRange(getTopIndex(),availableHeight,false,false); if (range.height >= availableHeight) visibleRows = range.rows; else visibleRows = range.rows + (availableHeight-range.height) / getItemHeight() + 1; } int firstVisibleIndex = getTopIndex(); int firstItemToDraw = firstVisibleIndex; if(hasSpanning) { // We need to find the first Item to draw. An earlier item can row-span the first visible item. for(int rowIndex = 0; rowIndex < firstVisibleIndex; rowIndex++) { GridItem itemForRow = (GridItem)items.get(rowIndex); int colIndex = 0; int maxRowSpanForItem = 0; for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (!column.isVisible()) { colIndex++; continue; } int rowSpan = itemForRow.getRowSpan(colIndex); maxRowSpanForItem = rowSpan > maxRowSpanForItem ? rowSpan : maxRowSpanForItem; } if(rowIndex + maxRowSpanForItem >= firstVisibleIndex) { firstItemToDraw = rowIndex; break; } else { rowIndex += maxRowSpanForItem; } } for(int rowIndex = firstItemToDraw; rowIndex < firstVisibleIndex; rowIndex++) { GridItem itemForRow = (GridItem)items.get(rowIndex); y = y - itemForRow.getHeight() - 1; } } int row = firstItemToDraw; for (int i = 0; i < visibleRows + (firstVisibleIndex - firstItemToDraw); i++) { x = 0; x -= getHScrollSelectionInPixels(); // get the item to draw GridItem item = null; if (row < items.size()) { item = (GridItem)items.get(row); while (!item.isVisible() && row < items.size() - 1) { row++; item = (GridItem)items.get(row); } } if (item != null && !item.isVisible()) { item = null; } if (item != null) { boolean cellInRowSelected = false; if (rowHeaderVisible) { // row header is actually painted later x += rowHeaderWidth; } int focusY = y; int colIndex = 0; // draw regular cells for each column for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); boolean skipCell = cellSpanManager.skipCell(colIndex, row); int indexOfColumn = indexOf(column); if (!column.isVisible()) { colIndex++; if(skipCell) { cellSpanManager.consumeCell(colIndex, row); } continue; } int width = item.getCellSize(indexOfColumn).x; if(skipCell == false) { int nrRowsToSpan = item.getRowSpan(indexOfColumn); int nrColumnsToSpan = item.getColumnSpan(indexOfColumn); if(nrRowsToSpan > 0 || nrColumnsToSpan > 0) { cellSpanManager.addCellSpanInfo(colIndex, row, nrColumnsToSpan, nrRowsToSpan); } if (x + width >= 0 && x < getClientArea().width ) { Point sizeOfColumn = item.getCellSize(indexOfColumn); column.getCellRenderer().setBounds(x, y, width, sizeOfColumn.y); int cellInHeaderDelta = columnHeadersVisible ? headerHeight - y : 0; if(cellInHeaderDelta > 0) { e.gc.setClipping(new Rectangle(x -1,y + cellInHeaderDelta, width +1, sizeOfColumn.y + 2 - cellInHeaderDelta)); } else { e.gc.setClipping(new Rectangle(x -1,y -1,width +1, sizeOfColumn.y + 2)); } column.getCellRenderer().setRow(i + 1); column.getCellRenderer().setSelected(selectedItems.contains(item)); column.getCellRenderer().setFocus(this.isFocusControl()); column.getCellRenderer().setRowFocus(focusItem == item); column.getCellRenderer().setCellFocus(cellSelectionEnabled && focusItem == item && focusColumn == column); column.getCellRenderer().setRowHover(hoveringItem == item); column.getCellRenderer().setColumnHover(hoveringColumn == column); column.getCellRenderer().setColumn(indexOfColumn); if (selectedCells.contains(new Point(indexOfColumn,row))) { column.getCellRenderer().setCellSelected(true); cellInRowSelected = true; } else { column.getCellRenderer().setCellSelected(false); } if (hoveringItem == item && hoveringColumn == column) { column.getCellRenderer().setHoverDetail(hoveringDetail); } else { column.getCellRenderer().setHoverDetail(""); } column.getCellRenderer().paint(e.gc, item); e.gc.setClipping((Rectangle)null); // collect the insertMark position if (!insertMarkPosFound && insertMarkItem == item && (insertMarkColumn == null || insertMarkColumn == column)) { // y-pos insertMarkPosY = y - 1; if (!insertMarkBefore) insertMarkPosY += item.getHeight() + 1; // x1-pos insertMarkPosX1 = x; if (column.isTree()) { insertMarkPosX1 += Math.min( width, column.getCellRenderer().getTextBounds(item, false).x); } // x2-pos if (insertMarkColumn == null) { insertMarkPosX2 = getClientArea().x + getClientArea().width; } else { insertMarkPosX2 = x + width; } insertMarkPosFound = true; } } } else { cellSpanManager.consumeCell(colIndex, row); } x += column.getWidth(); colIndex++; } if (x < getClientArea().width) { // insertMarkPos needs correction if(insertMarkPosFound && insertMarkColumn == null) insertMarkPosX2 = x; emptyCellRenderer.setSelected(selectedItems.contains(item)); emptyCellRenderer.setFocus(this.isFocusControl()); emptyCellRenderer.setRow(i + 1); emptyCellRenderer.setBounds(x, y, getClientArea().width - x + 1, item.getHeight()); emptyCellRenderer.setColumn(getColumnCount()); emptyCellRenderer.paint(e.gc, item); } x = 0; if (rowHeaderVisible) { if (!cellSelectionEnabled) { rowHeaderRenderer.setSelected(selectedItems.contains(item)); } else { rowHeaderRenderer.setSelected(cellInRowSelected); } if(y >= headerHeight) { rowHeaderRenderer.setBounds(0, y, rowHeaderWidth, item.getHeight() + 1); rowHeaderRenderer.paint(e.gc, item); } x += rowHeaderWidth; } // focus if (isFocusControl() && !cellSelectionEnabled) { if (item == focusItem) { if (focusRenderer != null) { int focusX = 0; if (rowHeaderVisible) { focusX = rowHeaderWidth; } focusRenderer .setBounds(focusX, focusY - 1, getClientArea().width - focusX - 1, item.getHeight() + 1); focusRenderer.paint(e.gc, item); } } } y += item.getHeight() + 1; } else { if (rowHeaderVisible) { //row header is actually painted later x += rowHeaderWidth; } emptyCellRenderer.setBounds(x, y, getClientArea().width - x, getItemHeight()); emptyCellRenderer.setFocus(false); emptyCellRenderer.setSelected(false); emptyCellRenderer.setRow(i + 1); for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { GridColumn column = (GridColumn) columnIterator.next(); if (column.isVisible()) { emptyCellRenderer.setBounds(x, y, column.getWidth(), getItemHeight()); emptyCellRenderer.setColumn(indexOf(column)); emptyCellRenderer.paint(e.gc, this); x += column.getWidth(); } } if (x < getClientArea().width) { emptyCellRenderer.setBounds(x, y, getClientArea().width - x + 1, getItemHeight()); emptyCellRenderer.setColumn(getColumnCount()); emptyCellRenderer.paint(e.gc, this); } x = 0; if (rowHeaderVisible) { emptyRowHeaderRenderer.setBounds(x, y, rowHeaderWidth, getItemHeight() + 1); emptyRowHeaderRenderer.paint(e.gc, this); x += rowHeaderWidth; } y += getItemHeight() + 1; } row++; } // draw drop point if (draggingColumn) { if ((dragDropAfterColumn != null || dragDropBeforeColumn != null) && (dragDropAfterColumn != columnBeingPushed && dragDropBeforeColumn != columnBeingPushed) && dragDropPointValid) { if (dragDropBeforeColumn != null) { x = getColumnHeaderXPosition(dragDropBeforeColumn); } else { x = getColumnHeaderXPosition(dragDropAfterColumn) + dragDropAfterColumn.getWidth(); } Point size = dropPointRenderer.computeSize(e.gc, SWT.DEFAULT, SWT.DEFAULT, null); x -= size.x / 2; if (x < 0) { x = 0; } dropPointRenderer.setBounds(x - 1, headerHeight + DROP_POINT_LOWER_OFFSET, size.x, size.y); dropPointRenderer.paint(e.gc, null); } } // draw insertion mark if (insertMarkPosFound) { e.gc.setClipping( rowHeaderVisible ? rowHeaderWidth : 0, columnHeadersVisible ? headerHeight : 0, getClientArea().width, getClientArea().height); insertMarkRenderer.paint(e.gc, new Rectangle(insertMarkPosX1, insertMarkPosY, insertMarkPosX2 - insertMarkPosX1, 0)); } if (columnFootersVisible) { paintFooter(e.gc); } } /** * Returns a column reference if the x,y coordinates are over a column * header (header only). * * @param x mouse x * @param y mouse y * @return column reference which mouse is over, or null. */ private GridColumn overColumnHeader(int x, int y) { GridColumn col = null; if (y <= headerHeight && y > 0) { col = getColumn(new Point(x, y)); if (col != null && col.getColumnGroup() != null) { if (y <= groupHeaderHeight) { return null; } } } return col; } /** * Returns a column reference if the x,y coordinates are over a column * header (header only). * * @param x mouse x * @param y mouse y * @return column reference which mouse is over, or null. */ private GridColumn overColumnFooter(int x, int y) { GridColumn col = null; if (y >= getClientArea().height - footerHeight ) { col = getColumn(new Point(x, y)); } return col; } /** * Returns a column group reference if the x,y coordinates are over a column * group header (header only). * * @param x mouse x * @param y mouse y * @return column group reference which mouse is over, or null. */ private GridColumnGroup overColumnGroupHeader(int x, int y) { GridColumnGroup group = null; if (y <= groupHeaderHeight && y > 0) { GridColumn col = getColumn(new Point(x, y)); if (col != null) { group = col.getColumnGroup(); } } return group; } /** * Paints the header. * * @param gc gc from paint event */ private void paintHeader(GC gc) { int x = 0; int y = 0; x -= getHScrollSelectionInPixels(); if (rowHeaderVisible) { // paint left corner // topLeftRenderer.setBounds(0, y, rowHeaderWidth, headerHeight); // topLeftRenderer.paint(gc, null); x += rowHeaderWidth; } GridColumnGroup previousPaintedGroup = null; for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { if (x > getClientArea().width) break; GridColumn column = (GridColumn) columnIterator.next(); int height = 0; if (!column.isVisible()) { continue; } if (column.getColumnGroup() != null) { if (column.getColumnGroup() != previousPaintedGroup) { int width = column.getWidth(); GridColumn nextCol = null; if (displayOrderedColumns.indexOf(column) + 1 < displayOrderedColumns.size()) { nextCol = (GridColumn)displayOrderedColumns .get(displayOrderedColumns.indexOf(column) + 1); } while (nextCol != null && nextCol.getColumnGroup() == column.getColumnGroup()) { if ((nextCol.getColumnGroup().getExpanded() && !nextCol.isDetail()) || (!nextCol.getColumnGroup().getExpanded() && !nextCol.isSummary())) { } else if( nextCol.isVisible() ) { width += nextCol.getWidth(); } if (displayOrderedColumns.indexOf(nextCol) + 1 < displayOrderedColumns .size()) { nextCol = (GridColumn)displayOrderedColumns.get(displayOrderedColumns .indexOf(nextCol) + 1); } else { nextCol = null; } } boolean selected = true; for (int i = 0; i < column.getColumnGroup().getColumns().length; i++) { GridColumn col = column.getColumnGroup().getColumns()[i]; if (col.isVisible() && (column.getMoveable() || !selectedColumns.contains(col))) { selected = false; break; } } column.getColumnGroup().getHeaderRenderer().setSelected(selected); column.getColumnGroup().getHeaderRenderer() .setHover(hoverColumnGroupHeader == column.getColumnGroup()); column.getColumnGroup().getHeaderRenderer().setHoverDetail(hoveringDetail); column.getColumnGroup().getHeaderRenderer().setBounds(x, 0, width, groupHeaderHeight); column.getColumnGroup().getHeaderRenderer().paint(gc, column.getColumnGroup()); previousPaintedGroup = column.getColumnGroup(); } height = headerHeight - groupHeaderHeight; y = groupHeaderHeight; } else { height = headerHeight; y = 0; } if (pushingColumn) { column.getHeaderRenderer().setHover( columnBeingPushed == column && pushingAndHovering); } else { column.getHeaderRenderer().setHover(hoveringColumnHeader == column); } column.getHeaderRenderer().setHoverDetail(hoveringDetail); column.getHeaderRenderer().setBounds(x, y, column.getWidth(), height); if (cellSelectionEnabled) column.getHeaderRenderer().setSelected(selectedColumns.contains(column)); if (x + column.getWidth() >= 0) { column.getHeaderRenderer().paint(gc, column); } x += column.getWidth(); } if (x < getClientArea().width) { emptyColumnHeaderRenderer.setBounds(x, 0, getClientArea().width - x, headerHeight); emptyColumnHeaderRenderer.paint(gc, null); } x = 0; if (rowHeaderVisible) { // paint left corner topLeftRenderer.setBounds(0, 0, rowHeaderWidth, headerHeight); topLeftRenderer.paint(gc, this); x += rowHeaderWidth; } if (draggingColumn) { gc.setAlpha(COLUMN_DRAG_ALPHA); columnBeingPushed.getHeaderRenderer().setSelected(false); int height = 0; if (columnBeingPushed.getColumnGroup() != null) { height = headerHeight - groupHeaderHeight; y = groupHeaderHeight; } else { height = headerHeight; y = 0; } columnBeingPushed.getHeaderRenderer() .setBounds( getColumnHeaderXPosition(columnBeingPushed) + (currentHeaderDragX - startHeaderDragX), y, columnBeingPushed.getWidth(), height); columnBeingPushed.getHeaderRenderer().paint(gc, columnBeingPushed); columnBeingPushed.getHeaderRenderer().setSelected(false); gc.setAlpha(-1); gc.setAdvanced(false); } } private void paintFooter(GC gc) { int x = 0; int y = 0; x -= getHScrollSelectionInPixels(); if (rowHeaderVisible) { // paint left corner // topLeftRenderer.setBounds(0, y, rowHeaderWidth, headerHeight); // topLeftRenderer.paint(gc, null); x += rowHeaderWidth; } for (Iterator columnIterator = displayOrderedColumns.iterator(); columnIterator.hasNext(); ) { if (x > getClientArea().width) break; GridColumn column = (GridColumn) columnIterator.next(); int height = 0; if (!column.isVisible()) { continue; } height = footerHeight; y = getClientArea().height - height; column.getFooterRenderer().setBounds(x, y, column.getWidth(), height); if (x + column.getWidth() >= 0) { column.getFooterRenderer().paint(gc, column); } x += column.getWidth(); } if (x < getClientArea().width) { emptyColumnFooterRenderer.setBounds(x, getClientArea().height - footerHeight, getClientArea().width - x, footerHeight); emptyColumnFooterRenderer.paint(gc, null); } if (rowHeaderVisible) { // paint left corner bottomLeftRenderer.setBounds(0, getClientArea().height-footerHeight, rowHeaderWidth, footerHeight); bottomLeftRenderer.paint(gc, this); x += rowHeaderWidth; } } /** * Manages the state of the scrollbars when new items are added or the * bounds are changed. */ private void updateScrollbars() { Point preferredSize = getTableSize(); Rectangle clientArea = getClientArea(); // First, figure out if the scrollbars should be visible and turn them // on right away // this will allow the computations further down to accommodate the // correct client // area // Turn the scrollbars on if necessary and do it all over again if // necessary. This ensures // that if a scrollbar is turned on/off, the other scrollbar's // visibility may be affected (more // area may have been added/removed. for (int doublePass = 1; doublePass <= 2; doublePass++) { if (preferredSize.y > clientArea.height) { vScroll.setVisible(true); } else { vScroll.setVisible(false); vScroll.setValues(0, 0, 1, 1, 1, 1); } if (preferredSize.x > clientArea.width) { hScroll.setVisible(true); } else { hScroll.setVisible(false); hScroll.setValues(0, 0, 1, 1, 1, 1); } // get the clientArea again with the now visible/invisible // scrollbars clientArea = getClientArea(); } // if the scrollbar is visible set its values if (vScroll.getVisible()) { int max = currentVisibleItems; int thumb = 1; if(!hasDifferingHeights) { // in this case, the number of visible rows on screen is constant, // so use this as thumb thumb = ( getVisibleGridHeight() + 1 ) / ( getItemHeight() + 1 ); } else { // in this case, the number of visible rows on screen is variable, // so we have to use 1 as thumb and decrease max by the number of // rows on the last page if(getVisibleGridHeight()>=1) { RowRange range = getRowRange(-1,getVisibleGridHeight(),true,true); max -= range.rows - 1; } } // if possible, remember selection, if selection is too large, just // make it the max you can int selection = Math.min(vScroll.getSelection(), max); vScroll.setValues(selection, 0, max, thumb, 1, thumb); } // if the scrollbar is visible set its values if (hScroll.getVisible()) { if (!columnScrolling) { // horizontal scrolling works pixel by pixel int hiddenArea = preferredSize.x - clientArea.width + 1; // if possible, remember selection, if selection is too large, // just // make it the max you can int selection = Math.min(hScroll.getSelection(), hiddenArea - 1); hScroll.setValues(selection, 0, hiddenArea + clientArea.width - 1, clientArea.width, HORZ_SCROLL_INCREMENT, clientArea.width); } else { // horizontal scrolling is column by column int hiddenArea = preferredSize.x - clientArea.width + 1; int max = 0; int i = 0; while (hiddenArea > 0 && i < getColumnCount()) { GridColumn col = (GridColumn)displayOrderedColumns.get(i); i++; if (col.isVisible()) { hiddenArea -= col.getWidth(); max++; } } max++; // max should never be greater than the number of visible cols int visCols = 0; for (Iterator iter = columns.iterator(); iter.hasNext();) { GridColumn element = (GridColumn)iter.next(); if (element.isVisible()) { visCols++; } } max = Math.min(visCols, max); // if possible, remember selection, if selection is too large, // just // make it the max you can int selection = Math.min(hScroll.getSelection(), max); hScroll.setValues(selection, 0, max, 1, 1, 1); } } } /** * Adds/removes items from the selected items list based on the * selection/deselection of the given item. * * @param item item being selected/unselected * @param stateMask key state during selection * * @return selection event that needs to be fired or null */ private Event updateSelection(GridItem item, int stateMask) { if (!selectionEnabled) { return null; } Event selectionEvent = null; if (selectionType == SWT.SINGLE) { if (selectedItems.contains(item)) { // Deselect when pressing CTRL if ((stateMask & SWT.MOD1) == SWT.MOD1) { selectedItems.clear(); } } else { selectedItems.clear(); selectedItems.add(item); } Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); selectionEvent = new Event(); selectionEvent.item = item; } else if (selectionType == SWT.MULTI) { boolean shift = false; boolean ctrl = false; if ((stateMask & SWT.MOD2) == SWT.MOD2) { shift = true; } if ((stateMask & SWT.MOD1) == SWT.MOD1) { ctrl = true; } if (!shift && !ctrl) { if (selectedItems.size() == 1 && selectedItems.contains(item)) return null; selectedItems.clear(); selectedItems.add(item); Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); shiftSelectionAnchorItem = null; selectionEvent = new Event(); selectionEvent.item = item; } else if (shift) { if (shiftSelectionAnchorItem == null) { shiftSelectionAnchorItem = focusItem; } // if (shiftSelectionAnchorItem == item) // { // return; // } boolean maintainAnchorSelection = false; if (!ctrl) { if (selectedItems.contains(shiftSelectionAnchorItem)) { maintainAnchorSelection = true; } selectedItems.clear(); } int anchorIndex = items.indexOf(shiftSelectionAnchorItem); int itemIndex = items.indexOf(item); int min = 0; int max = 0; if (anchorIndex < itemIndex) { if (maintainAnchorSelection) { min = anchorIndex; } else { min = anchorIndex + 1; } max = itemIndex; } else { if (maintainAnchorSelection) { max = anchorIndex; } else { max = anchorIndex - 1; } min = itemIndex; } for (int i = min; i <= max; i++) { if (!selectedItems.contains(items.get(i)) && ((GridItem)items.get(i)).isVisible()) { selectedItems.add((GridItem)items.get(i)); } } Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); selectionEvent = new Event(); } else if (ctrl) { if (selectedItems.contains(item)) { selectedItems.remove(item); } else { selectedItems.add(item); } Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); shiftSelectionAnchorItem = null; selectionEvent = new Event(); selectionEvent.item = item; } } Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); return selectionEvent; } /** * Updates cell selection. * * @param newCell newly clicked, navigated to cell. * @param stateMask statemask during preceeding mouse or key event. * @param dragging true if the user is dragging. * @param reverseDuplicateSelections true if the user is reversing selection rather than adding to. * * @return selection event that will need to be fired or null. */ private Event updateCellSelection(Point newCell, int stateMask, boolean dragging, boolean reverseDuplicateSelections) { Vector v = new Vector(); v.add(newCell); return updateCellSelection(v, stateMask, dragging, reverseDuplicateSelections); } /** * Updates cell selection. * * @param newCell newly clicked, navigated to cells. * @param stateMask statemask during preceeding mouse or key event. * @param dragging true if the user is dragging. * @param reverseDuplicateSelections true if the user is reversing selection rather than adding to. * * @return selection event that will need to be fired or null. */ private Event updateCellSelection(Vector newCells, int stateMask, boolean dragging, boolean reverseDuplicateSelections) { boolean shift = false; boolean ctrl = false; if ((stateMask & SWT.MOD2) == SWT.MOD2) { shift = true; } else { shiftSelectionAnchorColumn = null; shiftSelectionAnchorItem = null; } if ((stateMask & SWT.MOD1) == SWT.MOD1) { ctrl = true; } if (!shift && !ctrl) { if (newCells.equals(selectedCells)) return null; selectedCells.clear(); for (int i = 0; i < newCells.size(); i++) { addToCellSelection((Point)newCells.get(i)); } } else if (shift) { Point newCell = (Point)newCells.get(0); //shift selection should only occur with one //cell, ignoring others if ((focusColumn == null) || (focusItem == null)) { return null; } shiftSelectionAnchorColumn = getColumn(newCell.x); shiftSelectionAnchorItem = getItem(newCell.y); if (ctrl) { selectedCells.clear(); selectedCells.addAll(selectedCellsBeforeRangeSelect); } else { selectedCells.clear(); } GridColumn currentColumn = focusColumn; GridItem currentItem = focusItem; GridColumn endColumn = getColumn(newCell.x); GridItem endItem = getItem(newCell.y); Point newRange = getSelectionRange(currentItem,currentColumn,endItem,endColumn); currentColumn = getColumn(newRange.x); endColumn = getColumn(newRange.y); GridColumn startCol = currentColumn; if (indexOf(currentItem) > indexOf(endItem)) { GridItem temp = currentItem; currentItem = endItem; endItem = temp; } boolean firstLoop = true; do { if (!firstLoop) { currentItem = getNextVisibleItem(currentItem); } firstLoop = false; boolean firstLoop2 = true; currentColumn = startCol; do { if (!firstLoop2) { int index = displayOrderedColumns.indexOf(currentColumn) + 1; if (index < displayOrderedColumns.size()) { currentColumn = getVisibleColumn_DegradeRight(currentItem,(GridColumn)displayOrderedColumns.get(index)); } else { currentColumn = null; } if (currentColumn!= null) if (displayOrderedColumns.indexOf(currentColumn) > displayOrderedColumns.indexOf(endColumn)) currentColumn = null; } firstLoop2 = false; if (currentColumn != null) { Point cell = new Point(indexOf(currentColumn),indexOf(currentItem)); addToCellSelection(cell); } } while (currentColumn != endColumn && currentColumn != null); } while (currentItem != endItem); } else if (ctrl) { boolean reverse = reverseDuplicateSelections; if (!selectedCells.containsAll(newCells)) reverse = false; if (dragging) { selectedCells.clear(); selectedCells.addAll(selectedCellsBeforeRangeSelect); } if (reverse) { selectedCells.removeAll(newCells); } else { for (int i = 0; i < newCells.size(); i++) { addToCellSelection((Point)newCells.get(i)); } } } updateColumnSelection(); Event e = new Event(); if (dragging) { e.detail = SWT.DRAG; followupCellSelectionEventOwed = true; } Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); return e; } private void addToCellSelection(Point newCell) { if (newCell.x < 0 || newCell.x >= columns.size()) return; if (newCell.y < 0 || newCell.y >= items.size()) return; if (getColumn(newCell.x).getCellSelectionEnabled()) { Iterator it = selectedCells.iterator(); boolean found = false; while( it.hasNext() ) { Point p = (Point) it.next(); if( newCell.equals(p) ) { found = true; break; } } if( ! found ) { selectedCells.add(newCell); } } } void updateColumnSelection() { //Update the list of which columns have all their cells selected selectedColumns.clear(); for (Iterator iter = selectedCells.iterator(); iter.hasNext();) { Point cell = (Point)iter.next(); GridColumn col = getColumn(cell.x); selectedColumns.add(col); } } /** * Initialize all listeners. */ private void initListeners() { disposeListener = new Listener() { public void handleEvent(Event e) { onDispose(e); } }; addListener(SWT.Dispose,disposeListener); addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { onPaint(e); } }); addListener(SWT.Resize, new Listener() { public void handleEvent(Event e) { onResize(); } }); if (getVerticalBar() != null) { getVerticalBar().addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { onScrollSelection(); } }); } if (getHorizontalBar() != null) { getHorizontalBar().addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { onScrollSelection(); } }); } addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { onKeyDown(e); } }); addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent e) { e.doit = true; } }); addMouseListener(new MouseListener() { public void mouseDoubleClick(MouseEvent e) { onMouseDoubleClick(e); } public void mouseDown(MouseEvent e) { onMouseDown(e); } public void mouseUp(MouseEvent e) { onMouseUp(e); } }); addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { onMouseMove(e); } }); addMouseTrackListener(new MouseTrackListener() { public void mouseEnter(MouseEvent e) { } public void mouseExit(MouseEvent e) { onMouseExit(e); } public void mouseHover(MouseEvent e) { } }); addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { onFocusIn(); redraw(); } public void focusLost(FocusEvent e) { redraw(); } }); // Special code to reflect mouse wheel events if using an external // scroller addListener(SWT.MouseWheel, new Listener() { public void handleEvent(Event e) { onMouseWheel(e); } }); } private void onFocusIn() { if (!items.isEmpty() && focusItem == null) { focusItem = (GridItem) items.get(0); } } private void onDispose(Event event) { //We only want to dispose of our items and such *after* anybody else who may have been //listening to the dispose has had a chance to do whatever. removeListener(SWT.Dispose, disposeListener); notifyListeners(SWT.Dispose, event); event.type = SWT.None; disposing = true; cellHeaderSelectionBackground.dispose(); for (Iterator iterator = items.iterator(); iterator.hasNext();) { GridItem item = (GridItem)iterator.next(); item.dispose(); } for (int i = 0; i < columnGroups.length; i++) { columnGroups[i].dispose(); } for (Iterator iterator = columns.iterator(); iterator.hasNext();) { GridColumn col = (GridColumn)iterator.next(); col.dispose(); } sizingGC.dispose(); } /** * Mouse wheel event handler. * * @param e event */ private void onMouseWheel(Event e) { if (vScroll.getVisible()) { vScroll.handleMouseWheel(e); if (getVerticalBar() == null) e.doit = false; } else if (hScroll.getVisible()) { hScroll.handleMouseWheel(e); if (getHorizontalBar() == null) e.doit = false; } } /** * Mouse down event handler. * * @param e event */ private void onMouseDown(MouseEvent e) { // for some reason, SWT prefers the children to get focus if // there are any children // the setFocus method on Composite will not set focus to the // Composite if one of its // children can get focus instead. This only affects the table // when an editor is open // and therefore the table has a child. The solution is to // forceFocus() if ((getStyle() & SWT.NO_FOCUS) != SWT.NO_FOCUS) { forceFocus(); } hideToolTip(); //if populated will be fired at end of method. Event selectionEvent = null; cellSelectedOnLastMouseDown = false; cellRowSelectedOnLastMouseDown = false; cellColumnSelectedOnLastMouseDown = false; if (hoveringOnColumnResizer) { if (e.button == 1) { resizingColumn = true; resizingStartX = e.x; resizingColumnStartWidth = columnBeingResized.getWidth(); } return; } if (rowsResizeable && hoveringOnRowResizer) { if (e.button == 1) { resizingRow = true; resizingStartY = e.y; resizingRowStartHeight = rowBeingResized.getHeight(); } return; } if (e.button == 1 && handleColumnHeaderPush(e.x, e.y)) { return; } if (e.button == 1 && handleColumnGroupHeaderClick(e.x, e.y)) { return; } if(e.button == 1 && handleColumnFooterPush(e.x,e.y)) { return; } GridItem item = getItem(new Point(e.x, e.y)); if (e.button == 1 && item != null && handleCellClick(item,e.x, e.y)) { return; } if (isListening(SWT.DragDetect)) { if ((cellSelectionEnabled && hoveringOnSelectionDragArea) || (!cellSelectionEnabled && item != null && selectedItems.contains(item))) { if(dragDetect(e)) { return; } } } if (item != null) { if (cellSelectionEnabled) { GridColumn col = getColumn(new Point(e.x, e.y)); boolean isSelectedCell = false; if (col != null) isSelectedCell = selectedCells.contains(new Point(indexOf(col),indexOf(item))); if (e.button == 1 || (e.button == 3 && col != null && !isSelectedCell)) { if (col != null) { selectionEvent = updateCellSelection(new Point(indexOf(col),indexOf(item)), e.stateMask, false, true); cellSelectedOnLastMouseDown = (getCellSelectionCount() > 0); if (e.stateMask != SWT.MOD2) { focusColumn = col; focusItem = item; } //showColumn(col); showItem(item); redraw(); } else if (rowHeaderVisible) { if (e.x <= rowHeaderWidth) { boolean shift = ((e.stateMask & SWT.MOD2) != 0); boolean ctrl = false; if (!shift) { ctrl = ((e.stateMask & SWT.MOD1) != 0); } Vector cells = new Vector(); if (shift) { getCells(item,focusItem,cells); } else { getCells(item,cells); } int newStateMask = SWT.NONE; if (ctrl) newStateMask = SWT.MOD1; selectionEvent = updateCellSelection(cells, newStateMask, shift, ctrl); cellRowSelectedOnLastMouseDown = (getCellSelectionCount() > 0); if (!shift) { //set focus back to the first visible column focusColumn = getColumn(new Point(rowHeaderWidth + 1,e.y)); focusItem = item; } showItem(item); redraw(); } } intendedFocusColumn = focusColumn; } } else { if (e.button == 2 || e.button > 3) { return; } if (e.button == 3 && selectionType == SWT.MULTI) { if ((e.stateMask & SWT.MOD2) == SWT.MOD2) { return; } if ((e.stateMask & SWT.MOD1) == SWT.MOD1) { return; } if (selectedItems.contains(item)) { return; } } selectionEvent = updateSelection(item, e.stateMask); focusItem = item; showItem(item); redraw(); } } else if (e.button == 1 && rowHeaderVisible && e.x <= rowHeaderWidth && e.y < headerHeight) { // Nothing to select if(items.size() == 0) { return; } if (cellSelectionEnabled) { //click on the top left corner means select everything selectionEvent = selectAllCellsInternal(); focusColumn = getColumn(new Point(rowHeaderWidth + 1,1)); } else { //click on the top left corner means select everything selectionEvent = selectAllRowsInternal(); } focusItem = getItem(getTopIndex()); } else if (cellSelectionEnabled && e.button == 1 && columnHeadersVisible && e.y <= headerHeight) { //column cell selection GridColumn col = getColumn(new Point(e.x,e.y)); if (col == null) return; if (getItemCount() == 0) return; Vector cells = new Vector(); GridColumnGroup group = col.getColumnGroup(); if (group != null && e.y < groupHeaderHeight) { getCells(group, cells); } else { getCells(col, cells); } selectionEvent = updateCellSelection(cells, e.stateMask, false, true); cellColumnSelectedOnLastMouseDown = (getCellSelectionCount() > 0); GridItem newFocusItem = getItem(0); while (newFocusItem != null && getSpanningColumn(newFocusItem, col) != null) { newFocusItem = getNextVisibleItem(newFocusItem); } if (newFocusItem != null) { focusColumn = col; focusItem = newFocusItem; } showColumn(col); redraw(); } if (selectionEvent != null) { selectionEvent.stateMask = e.stateMask; selectionEvent.button = e.button; selectionEvent.item = item; selectionEvent.x = e.x; selectionEvent.y = e.y; notifyListeners(SWT.Selection, selectionEvent); if (!cellSelectionEnabled) { if (isListening(SWT.DragDetect)) { dragDetect(e); } } } } /** * Mouse double click event handler. * * @param e event */ private void onMouseDoubleClick(MouseEvent e) { if (e.button == 1) { if (hoveringOnColumnResizer) { columnBeingResized.pack(); columnBeingResized.fireResized(); for (int index = displayOrderedColumns.indexOf(columnBeingResized) + 1; index < displayOrderedColumns.size(); index ++) { GridColumn col = (GridColumn)displayOrderedColumns.get(index); if (col.isVisible()) col.fireMoved(); } resizingColumn = false; handleHoverOnColumnResizer(e.x, e.y); return; } else if (rowsResizeable && hoveringOnRowResizer) { List sel = Arrays.asList(getSelection()); if(sel.contains(rowBeingResized)) { // the user double-clicked a row resizer of a selected row // so update all selected rows for(int cnt=0;cnt<sel.size();cnt++) ((GridItem)sel.get(cnt)).pack(); redraw(); } else { // otherwise only update the row the user double-clicked rowBeingResized.pack(); } resizingRow = false; handleHoverOnRowResizer(e.x, e.y); return; } GridItem item = getItem(new Point(e.x, e.y)); if (item != null) { if (isListening(SWT.DefaultSelection)) { Event newEvent = new Event(); newEvent.item = item; notifyListeners(SWT.DefaultSelection, newEvent); } else if (item.getItemCount() > 0) { item.setExpanded(!item.isExpanded()); if (item.isExpanded()) { item.fireEvent(SWT.Expand); } else { item.fireEvent(SWT.Collapse); } } } } } /** * Mouse up handler. * * @param e event */ private void onMouseUp(MouseEvent e) { cellSelectedOnLastMouseDown = false; if (resizingColumn) { resizingColumn = false; handleHoverOnColumnResizer(e.x, e.y); // resets cursor if // necessary return; } if (resizingRow) { resizingRow = false; handleHoverOnRowResizer(e.x, e.y); // resets cursor if // necessary return; } if (pushingColumn) { pushingColumn = false; columnBeingPushed.getHeaderRenderer().setMouseDown(false); columnBeingPushed.getHeaderRenderer().setHover(false); redraw(); if (pushingAndHovering) { columnBeingPushed.fireListeners(); } setCapture(false); return; } if (draggingColumn) { handleColumnDrop(); return; } if (cellDragSelectionOccuring || cellRowDragSelectionOccuring || cellColumnDragSelectionOccuring) { cellDragSelectionOccuring = false; cellRowDragSelectionOccuring = false; cellColumnDragSelectionOccuring = false; setCursor(null); if (followupCellSelectionEventOwed) { Event se = new Event(); se.button = e.button; se.item = getItem(new Point(e.x, e.y)); se.stateMask = e.stateMask; se.x = e.x; se.y = e.y; notifyListeners(SWT.Selection, se); followupCellSelectionEventOwed = false; } } } /** * Mouse move event handler. * * @param e event */ private void onMouseMove(MouseEvent e) { //check to see if the mouse is outside the grid //this should only happen when the mouse is captured for inplace //tooltips - see bug 203364 if (inplaceTooltipCapture && (e.x < 0 || e.y < 0 || e.x >= getBounds().width || e.y >= getBounds().height)) { setCapture(false); inplaceTooltipCapture = false; return; //a mouseexit event should occur immediately } //if populated will be fired at end of method. Event selectionEvent = null; if ((e.stateMask & SWT.BUTTON1) == 0) { handleHovering(e.x, e.y); } else { if (draggingColumn) { handleColumnDragging(e.x); return; } if (resizingColumn) { handleColumnResizerDragging(e.x); return; } if (resizingRow) { handleRowResizerDragging(e.y); return; } if (pushingColumn) { handleColumnHeaderHoverWhilePushing(e.x, e.y); return; } if (cellSelectionEnabled) { if (!cellDragSelectionOccuring && cellSelectedOnLastMouseDown) { cellDragSelectionOccuring = true; //XXX: make this user definable setCursor(getDisplay().getSystemCursor(SWT.CURSOR_CROSS)); cellDragCTRL = ((e.stateMask & SWT.MOD1) != 0); if (cellDragCTRL) { selectedCellsBeforeRangeSelect.clear(); selectedCellsBeforeRangeSelect.addAll(selectedCells); } } if (!cellRowDragSelectionOccuring && cellRowSelectedOnLastMouseDown) { cellRowDragSelectionOccuring = true; setCursor(getDisplay().getSystemCursor(SWT.CURSOR_CROSS)); cellDragCTRL = ((e.stateMask & SWT.MOD1) != 0); if (cellDragCTRL) { selectedCellsBeforeRangeSelect.clear(); selectedCellsBeforeRangeSelect.addAll(selectedCells); } } if (!cellColumnDragSelectionOccuring && cellColumnSelectedOnLastMouseDown) { cellColumnDragSelectionOccuring = true; setCursor(getDisplay().getSystemCursor(SWT.CURSOR_CROSS)); cellDragCTRL = ((e.stateMask & SWT.MOD1) != 0); if (cellDragCTRL) { selectedCellsBeforeRangeSelect.clear(); selectedCellsBeforeRangeSelect.addAll(selectedCells); } } int ctrlFlag = (cellDragCTRL ? SWT.MOD1 : SWT.NONE); if (cellDragSelectionOccuring && handleCellHover(e.x, e.y)) { GridColumn intentColumn = hoveringColumn; GridItem intentItem = hoveringItem; if (hoveringItem == null) { if (e.y > headerHeight) { //then we must be hovering way to the bottom intentItem = getPreviousVisibleItem(null); } else { intentItem = (GridItem)items.get(0); } } if (hoveringColumn == null) { if (e.x > rowHeaderWidth) { //then we must be hovering way to the right intentColumn = getVisibleColumn_DegradeLeft(intentItem,(GridColumn)displayOrderedColumns.get(displayOrderedColumns.size() - 1)); } else { GridColumn firstCol = (GridColumn)displayOrderedColumns.get(0); if (!firstCol.isVisible()) { firstCol = getNextVisibleColumn(firstCol); } intentColumn = firstCol; } } showColumn(intentColumn); showItem(intentItem); selectionEvent = updateCellSelection(new Point(indexOf(intentColumn),indexOf(intentItem)),ctrlFlag | SWT.MOD2, true, false); } if (cellRowDragSelectionOccuring && handleCellHover(e.x, e.y)) { GridItem intentItem = hoveringItem; if (hoveringItem == null) { if (e.y > headerHeight) { //then we must be hovering way to the bottom intentItem = getPreviousVisibleItem(null); } else { if (getTopIndex() > 0) { intentItem = getPreviousVisibleItem((GridItem)items.get(getTopIndex())); } else { intentItem = (GridItem)items.get(0); } } } Vector cells = new Vector(); getCells(intentItem,focusItem,cells); showItem(intentItem); selectionEvent = updateCellSelection(cells,ctrlFlag, true, false); } if (cellColumnDragSelectionOccuring && handleCellHover(e.x, e.y)) { GridColumn intentCol = hoveringColumn; if (intentCol == null) { if (e.y < rowHeaderWidth) { //TODO: get the first col to the left } else { //TODO: get the first col to the right } } if (intentCol == null) return; //temporary GridColumn iterCol = intentCol; Vector newSelected = new Vector(); boolean decreasing = (displayOrderedColumns.indexOf(iterCol) > displayOrderedColumns.indexOf(focusColumn)); do { getCells(iterCol, newSelected); if (iterCol == focusColumn) { break; } if (decreasing) { iterCol = getPreviousVisibleColumn(iterCol); } else { iterCol = getNextVisibleColumn(iterCol); } } while (true); selectionEvent = updateCellSelection(newSelected, ctrlFlag, true, false); } } } if (selectionEvent != null) { selectionEvent.stateMask = e.stateMask; selectionEvent.button = e.button; selectionEvent.item = getItem(new Point(e.x, e.y)); selectionEvent.x = e.x; selectionEvent.y = e.y; notifyListeners(SWT.Selection, selectionEvent); } } /** * Handles the assignment of the correct values to the hover* field * variables that let the painting code now what to paint as hovered. * * @param x mouse x coordinate * @param y mouse y coordinate */ private void handleHovering(int x, int y) { // TODO: need to clean up and refactor hover code handleCellHover(x, y); // Is this Grid a DragSource ?? if (cellSelectionEnabled && getData("DragSource") != null) { if (handleHoverOnSelectionDragArea(x, y)) { return; } } if (columnHeadersVisible) { if (handleHoverOnColumnResizer(x, y)) { // if (hoveringItem != null || !hoveringDetail.equals("") || hoveringColumn != null // || hoveringColumnHeader != null || hoverColumnGroupHeader != null) // { // hoveringItem = null; // hoveringDetail = ""; // hoveringColumn = null; // hoveringColumnHeader = null; // hoverColumnGroupHeader = null; // // Rectangle clientArea = getClientArea(); // redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); // } return; } } if (rowsResizeable && rowHeaderVisible) { if (handleHoverOnRowResizer(x, y)) { return; } } // handleCellHover(x, y); } /** * Refreshes the hover* variables according to the mouse location and * current state of the table. This is useful is some method call, caused * the state of the table to change and therefore the hover effects may have * become out of date. */ protected void refreshHoverState() { Point p = getDisplay().map(null, this, getDisplay().getCursorLocation()); handleHovering(p.x, p.y); } /** * Mouse exit event handler. * * @param e event */ private void onMouseExit(MouseEvent e) { hoveringItem = null; hoveringDetail = ""; hoveringColumn = null; hoveringOverText = false; hideToolTip(); redraw(); } /** * Key down event handler. * * @param e event */ private void onKeyDown(Event e) { if (focusColumn == null || focusColumn.isDisposed()) { if (columns.size() == 0) return; focusColumn = getColumn(0); intendedFocusColumn = focusColumn; } if (e.character == '\r' && focusItem != null) { Event newEvent = new Event(); newEvent.item = focusItem; notifyListeners(SWT.DefaultSelection, newEvent); return; } int attemptExpandCollapse = 0; if ((e.character == '-' || (!cellSelectionEnabled && e.keyCode == SWT.ARROW_LEFT)) && focusItem != null && focusItem.isExpanded()) { attemptExpandCollapse = SWT.Collapse; } else if ((e.character == '+' || (!cellSelectionEnabled && e.keyCode == SWT.ARROW_RIGHT)) && focusItem != null && !focusItem.isExpanded()) { attemptExpandCollapse = SWT.Expand; } if (attemptExpandCollapse != 0 && focusItem != null && focusItem.hasChildren()) { int performExpandCollapse = 0; if (cellSelectionEnabled && focusColumn != null && focusColumn.isTree()) { performExpandCollapse = attemptExpandCollapse; } else if (!cellSelectionEnabled) { performExpandCollapse = attemptExpandCollapse; } if (performExpandCollapse == SWT.Expand) { focusItem.setExpanded(true); focusItem.fireEvent(SWT.Expand); return; } if (performExpandCollapse == SWT.Collapse) { focusItem.setExpanded(false); focusItem.fireEvent(SWT.Collapse); return; } } if (e.character == ' ') { handleSpaceBarDown(e); } GridItem newSelection = null; GridColumn newColumnFocus = null; //These two variables are used because the key navigation when the shift key is down is //based, not off the focus item/column, but rather off the implied focus (i.e. where the //keyboard has extended focus to). GridItem impliedFocusItem = focusItem; GridColumn impliedFocusColumn = focusColumn; if (cellSelectionEnabled && e.stateMask == SWT.MOD2) { if (shiftSelectionAnchorColumn != null) { impliedFocusItem = shiftSelectionAnchorItem; impliedFocusColumn = shiftSelectionAnchorColumn; } } switch (e.keyCode) { case SWT.ARROW_RIGHT : if (cellSelectionEnabled) { if (impliedFocusItem != null && impliedFocusColumn != null) { newSelection = impliedFocusItem; int index = displayOrderedColumns.indexOf(impliedFocusColumn); int jumpAhead = impliedFocusItem.getColumnSpan(indexOf(impliedFocusColumn)); jumpAhead ++; while (jumpAhead > 0) { index ++; if (index < displayOrderedColumns.size()) { if (((GridColumn)displayOrderedColumns.get(index)).isVisible()) jumpAhead --; } else { break; } } if (index < displayOrderedColumns.size()) { newColumnFocus = (GridColumn)displayOrderedColumns.get(index); } else { newColumnFocus = impliedFocusColumn; } } intendedFocusColumn = newColumnFocus; } else { if (impliedFocusItem != null && impliedFocusItem.hasChildren()) { newSelection = impliedFocusItem.getItem(0); } } break; case SWT.ARROW_LEFT : if (cellSelectionEnabled) { if (impliedFocusItem != null && impliedFocusColumn != null) { newSelection = impliedFocusItem; int index = displayOrderedColumns.indexOf(impliedFocusColumn); if (index != 0) { newColumnFocus = (GridColumn)displayOrderedColumns.get(index -1); newColumnFocus = getVisibleColumn_DegradeLeft(impliedFocusItem, newColumnFocus); } else { newColumnFocus = impliedFocusColumn; } } intendedFocusColumn = newColumnFocus; } else { if (impliedFocusItem != null && impliedFocusItem.getParentItem() != null) { newSelection = impliedFocusItem.getParentItem(); } } break; case SWT.ARROW_UP : if (impliedFocusItem != null) { newSelection = getPreviousVisibleItem(impliedFocusItem); } if (impliedFocusColumn != null) { if (newSelection != null) { newColumnFocus = getVisibleColumn_DegradeLeft(newSelection, intendedFocusColumn); } else { newColumnFocus = impliedFocusColumn; } } break; case SWT.ARROW_DOWN : if (impliedFocusItem != null) { newSelection = getNextVisibleItem(impliedFocusItem); } else { if (items.size() > 0) { newSelection = (GridItem)items.get(0); } } if (impliedFocusColumn != null) { if (newSelection != null) { newColumnFocus = getVisibleColumn_DegradeLeft(newSelection, intendedFocusColumn); } else { newColumnFocus = impliedFocusColumn; } } break; case SWT.HOME : if (!cellSelectionEnabled) { if (items.size() > 0) { newSelection = (GridItem)items.get(0); } } else { newSelection = impliedFocusItem; newColumnFocus = getVisibleColumn_DegradeRight(newSelection,(GridColumn)displayOrderedColumns.get(0)); } break; case SWT.END : if (!cellSelectionEnabled) { if (items.size() > 0) { newSelection = getPreviousVisibleItem(null); } } else { newSelection = impliedFocusItem; newColumnFocus = getVisibleColumn_DegradeLeft(newSelection,(GridColumn)displayOrderedColumns.get(displayOrderedColumns.size() - 1)); } break; case SWT.PAGE_UP : int topIndex = getTopIndex(); newSelection = (GridItem)items.get(topIndex); if (focusItem == newSelection) { RowRange range = getRowRange(getTopIndex(),getVisibleGridHeight(),false,true); newSelection = (GridItem)items.get(range.startIndex); } newColumnFocus = focusColumn; break; case SWT.PAGE_DOWN : int bottomIndex = getBottomIndex(); newSelection = (GridItem)items.get(bottomIndex); if(!isShown(newSelection)) { // the item at bottom index is not shown completely GridItem tmpItem = getPreviousVisibleItem(newSelection); if(tmpItem!=null) newSelection = tmpItem; } if (focusItem == newSelection) { RowRange range = getRowRange(getBottomIndex(),getVisibleGridHeight(),true,false); newSelection = (GridItem)items.get(range.endIndex); } newColumnFocus = focusColumn; break; default : break; } if (newSelection == null) { return; } if (cellSelectionEnabled) { if (e.stateMask != SWT.MOD2) focusColumn = newColumnFocus; showColumn(newColumnFocus); if (e.stateMask != SWT.MOD2) focusItem = newSelection; showItem(newSelection); if (e.stateMask != SWT.MOD1) { Event selEvent = updateCellSelection(new Point(indexOf(newColumnFocus),indexOf(newSelection)),e.stateMask, false, false); if (selEvent != null) { selEvent.stateMask = e.stateMask; selEvent.character = e.character; selEvent.keyCode = e.keyCode; notifyListeners(SWT.Selection, selEvent); } } redraw(); } else { Event selectionEvent = null; if (selectionType == SWT.SINGLE || e.stateMask != SWT.MOD1) { selectionEvent = updateSelection(newSelection, e.stateMask); if (selectionEvent != null) { selectionEvent.stateMask = e.stateMask; selectionEvent.character = e.character; selectionEvent.keyCode = e.keyCode; } } focusItem = newSelection; showItem(newSelection); redraw(); if (selectionEvent != null) notifyListeners(SWT.Selection, selectionEvent); } } private void handleSpaceBarDown(Event event) { if (focusItem == null) return; if (selectionEnabled && !cellSelectionEnabled && !selectedItems.contains(focusItem)) { selectedItems.add(focusItem); redraw(); Event e = new Event(); e.item = focusItem; e.stateMask = event.stateMask; e.character = event.character; e.keyCode = event.keyCode; notifyListeners(SWT.Selection, e); } if (!cellSelectionEnabled) { boolean checkFirstCol = false; boolean first = true; for (Iterator iter = columns.iterator(); iter.hasNext();) { GridColumn col = (GridColumn)iter.next(); if (first) { if (!col.isCheck()) break; first = false; checkFirstCol = true; } else { if (col.isCheck()) { checkFirstCol = false; break; } } } if (checkFirstCol) { focusItem.setChecked(!focusItem.getChecked()); redraw(); focusItem.fireCheckEvent(0); } } } /** * Resize event handler. */ private void onResize() { //CGross 1/2/08 - I don't really want to be doing this.... //I shouldn't be changing something you user configured... //leaving out for now // if (columnScrolling) // { // int maxWidth = getClientArea().width; // if (rowHeaderVisible) // maxWidth -= rowHeaderWidth; // // for (Iterator cols = columns.iterator(); cols.hasNext();) { // GridColumn col = (GridColumn) cols.next(); // if (col.getWidth() > maxWidth) // col.setWidth(maxWidth); // } // } scrollValuesObsolete = true; topIndex = -1; bottomIndex = -1; } /** * Scrollbar selection event handler. */ private void onScrollSelection() { topIndex = -1; bottomIndex = -1; refreshHoverState(); redraw(getClientArea().x, getClientArea().y, getClientArea().width, getClientArea().height, false); } /** * Returns the intersection of the given column and given item. * * @param column column * @param item item * @return x,y of top left corner of the cell */ Point getOrigin(GridColumn column, GridItem item) { int x = 0; if (rowHeaderVisible) { x += rowHeaderWidth; } x -= getHScrollSelectionInPixels(); for (Iterator colIterIterator = displayOrderedColumns.iterator(); colIterIterator.hasNext(); ) { GridColumn colIter = (GridColumn) colIterIterator.next(); if (colIter == column) { break; } if (colIter.isVisible()) { x += colIter.getWidth(); } } int y = 0; if (item != null) { if (columnHeadersVisible) { y += headerHeight; } int currIndex=getTopIndex(); int itemIndex=items.indexOf(item); if (itemIndex == -1) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } while(currIndex!=itemIndex) { if(currIndex<itemIndex) { GridItem currItem = (GridItem)items.get(currIndex); if(currItem.isVisible()) { y += currItem.getHeight() + 1; } currIndex++; } else if(currIndex>itemIndex) { currIndex--; GridItem currItem = (GridItem)items.get(currIndex); if(currItem.isVisible()) { y -= currItem.getHeight() + 1; } } } } else { if (column.getColumnGroup() != null) { y += groupHeaderHeight; } } return new Point(x, y); } /** * Determines (which cell/if a cell) has been clicked (mouse down really) * and notifies the appropriate renderer. Returns true when a cell has * responded to this event in some way and prevents the event from * triggering an action further down the chain (like a selection). * * @param item item clicked * @param x mouse x * @param y mouse y * @return true if this event has been consumed. */ private boolean handleCellClick(GridItem item, int x, int y) { // if(!isTree) // return false; GridColumn col = getColumn(new Point(x, y)); if (col == null) { return false; } col.getCellRenderer().setBounds(item.getBounds(indexOf(col))); return col.getCellRenderer().notify(IInternalWidget.LeftMouseButtonDown, new Point(x, y), item); } /** * Sets the hovering variables (hoverItem,hoveringColumn) as well as * hoverDetail by talking to the cell renderers. Triggers a redraw if * necessary. * * @param x mouse x * @param y mouse y * @return true if a new section of the table is now being hovered */ private boolean handleCellHover(int x, int y) { String detail = ""; boolean overText = false; final GridColumn col = getColumn(new Point(x, y)); final GridItem item = getItem(new Point(x, y)); GridColumnGroup hoverColGroup = null; GridColumn hoverColHeader = null; if (col != null) { if (item != null) { if( y < getClientArea().height - footerHeight ) { col.getCellRenderer().setBounds(item.getBounds(columns.indexOf(col))); if (col.getCellRenderer().notify(IInternalWidget.MouseMove, new Point(x, y), item)) { detail = col.getCellRenderer().getHoverDetail(); } Rectangle textBounds = col.getCellRenderer().getTextBounds(item,false); if (textBounds != null) { Point p = new Point(x - col.getCellRenderer().getBounds().x, y - col.getCellRenderer().getBounds().y); overText = textBounds.contains(p); } } } else { if (y < headerHeight) { if (columnGroups.length != 0 && y < groupHeaderHeight && col.getColumnGroup() != null) { hoverColGroup = col.getColumnGroup(); hoverColGroup.getHeaderRenderer().setBounds(hoverColGroup.getBounds()); if (hoverColGroup.getHeaderRenderer() .notify(IInternalWidget.MouseMove, new Point(x, y), hoverColGroup)) { detail = hoverColGroup.getHeaderRenderer().getHoverDetail(); } Rectangle textBounds = hoverColGroup.getHeaderRenderer().getTextBounds(hoverColGroup,false); if (textBounds != null) { Point p = new Point(x - hoverColGroup.getHeaderRenderer().getBounds().x, y - hoverColGroup.getHeaderRenderer().getBounds().y); overText = textBounds.contains(p); } } else { // on col header hoverColHeader = col; col.getHeaderRenderer().setBounds(col.getBounds()); if (col.getHeaderRenderer().notify(IInternalWidget.MouseMove, new Point(x, y), col)) { detail = col.getHeaderRenderer().getHoverDetail(); } Rectangle textBounds = col.getHeaderRenderer().getTextBounds(col,false); if (textBounds != null) { Point p = new Point(x - col.getHeaderRenderer().getBounds().x, y - col.getHeaderRenderer().getBounds().y); overText = textBounds.contains(p); } } } } } boolean hoverChange = false; if (hoveringItem != item || !hoveringDetail.equals(detail) || hoveringColumn != col || hoverColGroup != hoverColumnGroupHeader || hoverColHeader != hoveringColumnHeader) { hoveringItem = item; hoveringDetail = detail; hoveringColumn = col; hoveringColumnHeader = hoverColHeader; hoverColumnGroupHeader = hoverColGroup; Rectangle clientArea = getClientArea(); redraw(clientArea.x,clientArea.y,clientArea.width,clientArea.height,false); hoverChange = true; } //do inplace toolTip stuff if (hoverChange || hoveringOverText != overText) { hoveringOverText = overText; if (overText){ Rectangle cellBounds = null; Rectangle textBounds = null; Rectangle preferredTextBounds = null; if (hoveringItem != null && hoveringItem.getToolTipText(indexOf(col)) == null && //no inplace tooltips when regular tooltip !col.getWordWrap()) //dont show inplace tooltips for cells with wordwrap { cellBounds = col.getCellRenderer().getBounds(); if (cellBounds.x + cellBounds.width > getSize().x) { cellBounds.width = getSize().x - cellBounds.x; } textBounds = col.getCellRenderer().getTextBounds(item,false); preferredTextBounds = col.getCellRenderer().getTextBounds(item,true); } else if (hoveringColumnHeader != null && hoveringColumnHeader.getHeaderTooltip() == null) //no inplace tooltips when regular tooltip { cellBounds = hoveringColumnHeader.getHeaderRenderer().getBounds(); if (cellBounds.x + cellBounds.width > getSize().x) { cellBounds.width = getSize().x - cellBounds.x; } textBounds = hoveringColumnHeader.getHeaderRenderer().getTextBounds(col,false); preferredTextBounds = hoveringColumnHeader.getHeaderRenderer().getTextBounds(col,true); } else if (hoverColumnGroupHeader != null) { cellBounds = hoverColumnGroupHeader.getHeaderRenderer().getBounds(); if (cellBounds.x + cellBounds.width > getSize().x) { cellBounds.width = getSize().x - cellBounds.x; } textBounds = hoverColumnGroupHeader.getHeaderRenderer().getTextBounds(hoverColumnGroupHeader,false); preferredTextBounds = hoverColumnGroupHeader.getHeaderRenderer().getTextBounds(hoverColumnGroupHeader,true); } //if we are truncated if (textBounds != null && textBounds.width < preferredTextBounds.width) { showToolTip(item,col, hoverColumnGroupHeader, new Point(cellBounds.x + textBounds.x,cellBounds.y + textBounds.y)); //the following 2 lines are done here rather than in showToolTip to allow //that method to be overridden yet still capture the mouse. setCapture(true); inplaceTooltipCapture = true; } } else { hideToolTip(); } } //do normal cell specific tooltip stuff if (hoverChange) { String newTip = null; if ((hoveringItem != null) && (hoveringColumn != null)) { // get cell specific tooltip newTip = hoveringItem.getToolTipText(indexOf(hoveringColumn)); } else if ((hoveringColumn != null) && (hoveringColumnHeader != null)) { // get column header specific tooltip newTip = hoveringColumn.getHeaderTooltip(); } if (newTip == null) { // no cell or column header specific tooltip then use base Grid tooltip newTip = getToolTipText(); } //Avoid unnecessarily resetting tooltip - this will cause the tooltip to jump around if (newTip != null && !newTip.equals(displayedToolTipText)) { updateToolTipText(newTip); } else if(newTip == null && displayedToolTipText != null) { updateToolTipText(null); } displayedToolTipText = newTip; } return hoverChange; } /** * Sets the tooltip for the whole Grid to the given text. This method is made available * for subclasses to override, when a subclass wants to display a different than the standard * SWT/OS tooltip. Generally, those subclasses would override this event and use this tooltip * text in their own tooltip or just override this method to prevent the SWT/OS tooltip from * displaying. * * @param text */ protected void updateToolTipText(String text) { super.setToolTipText(text); } /** * Marks the scroll values obsolete so they will be recalculated. */ protected void setScrollValuesObsolete() { this.scrollValuesObsolete = true; redraw(); } /** * Inserts a new column into the table. * * @param column new column * @param index index to insert new column * @return current number of columns */ int newColumn(GridColumn column, int index) { if (index == -1) { columns.add(column); displayOrderedColumns.add(column); } else { columns.add(index, column); displayOrderedColumns.add(index, column); for (int i = 0; i < columns.size(); i++) { ((GridColumn) columns.get(i)).setColumnIndex(i); } } computeHeaderHeight(sizingGC); computeFooterHeight(sizingGC); updatePrimaryCheckColumn(); for (Iterator iterator = items.iterator(); iterator.hasNext();) { GridItem item = (GridItem)iterator.next(); item.columnAdded(index); } scrollValuesObsolete = true; redraw(); return columns.size() - 1; } /** * Removes the given column from the table. * * @param column column to remove */ void removeColumn(GridColumn column) { boolean selectionModified = false; int index = indexOf(column); if (cellSelectionEnabled) { Vector removeSelectedCells = new Vector(); for (Iterator iterator = selectedCells.iterator(); iterator.hasNext();) { Point cell = (Point)iterator.next(); if (cell.x == index) { removeSelectedCells.add(cell); } } if (removeSelectedCells.size() > 0) { selectedCells.removeAll(removeSelectedCells); selectionModified = true; } for (Iterator iterator = selectedCells.iterator(); iterator.hasNext();) { Point cell = (Point)iterator.next(); if (cell.x >= index) { cell.x--; selectionModified = true; } } } columns.remove(column); displayOrderedColumns.remove(column); updatePrimaryCheckColumn(); scrollValuesObsolete = true; redraw(); for (Iterator iterator = items.iterator(); iterator.hasNext();) { GridItem item = (GridItem)iterator.next(); item.columnRemoved(index); } int i = 0; for (Iterator iterator = columns.iterator(); iterator.hasNext();) { GridColumn col = (GridColumn)iterator.next(); col.setColumnIndex(i); i++; } if (selectionModified && !disposing) { updateColumnSelection(); } } /** * Manages the setting of the checkbox column when the SWT.CHECK style was given to the * table. This method will ensure that the first column of the table always has a checkbox * when SWT.CHECK is given to the table. */ private void updatePrimaryCheckColumn() { if ((getStyle() & SWT.CHECK) == SWT.CHECK) { boolean firstCol = true; for (Iterator iter = columns.iterator(); iter.hasNext();) { GridColumn col = (GridColumn)iter.next(); col.setTableCheck(firstCol); firstCol = false; } } } void newRootItem(GridItem item, int index) { if (index == -1 || index >= rootItems.size()) { rootItems.add(item); } else { rootItems.add(index,item); } } void removeRootItem(GridItem item) { rootItems.remove(item); } /** * Creates the new item at the given index. Only called from GridItem * constructor. * * @param item new item * @param index index to insert the item at * @return the index where the item was insert */ int newItem(GridItem item, int index, boolean root) { int row = 0; if (!isTree) { if (item.getParentItem() != null) { isTree = true; } } //Have to convert indexes, this method needs a flat index, the method is called with indexes //that are relative to the level if (root && index != -1) { if (index >= rootItems.size()) { index = -1; } else { index = items.indexOf(rootItems.get(index)); } } else if (!root) { if (index >= item.getParentItem().getItems().length || index == -1) { GridItem rightMostDescendent = item.getParentItem(); while (rightMostDescendent.getItems().length > 0) { rightMostDescendent = rightMostDescendent.getItems()[rightMostDescendent .getItems().length - 1]; } index = indexOf(rightMostDescendent) + 1; } else { index = indexOf(item.getParentItem().getItems()[index]); } } if (index == -1) { items.add(item); row = items.size() - 1; } else { items.add(index, item); row = index; } if (items.size() == 1 && !userModifiedItemHeight) itemHeight = computeItemHeight(item,sizingGC); item.initializeHeight(itemHeight); if (isRowHeaderVisible() && isAutoWidth()) { rowHeaderWidth = Math.max(rowHeaderWidth,rowHeaderRenderer .computeSize(sizingGC, SWT.DEFAULT, SWT.DEFAULT, item).x); } scrollValuesObsolete = true; topIndex = -1; bottomIndex = -1; currentVisibleItems++; redraw(); return row; } /** * Removes the given item from the table. This method is only called from * the item's dispose method. * * @param item item to remove */ void removeItem(GridItem item) { Point[] cells = getCells(item); boolean selectionModified = false; items.remove(item); if (disposing) return; if (selectedItems.remove(item)) selectionModified = true; for (int i = 0; i < cells.length; i++) { if (selectedCells.remove(cells[i])) selectionModified = true; } if (focusItem == item) { focusItem = null; } scrollValuesObsolete = true; topIndex = -1; bottomIndex = -1; if (item.isVisible()) { currentVisibleItems--; } if (selectionModified && !disposing) { updateColumnSelection(); } redraw(); } /** * Creates the given column group at the given index. This method is only * called from the {@code GridColumnGroup}'s constructor. * * @param group group to add. */ void newColumnGroup(GridColumnGroup group) { GridColumnGroup[] newColumnGroups = new GridColumnGroup[columnGroups.length + 1]; System.arraycopy(columnGroups, 0, newColumnGroups, 0, columnGroups.length); newColumnGroups[newColumnGroups.length - 1] = group; columnGroups = newColumnGroups; // if we just added the first col group, then we need to up the row // height if (columnGroups.length == 1) { computeHeaderHeight(sizingGC); } scrollValuesObsolete = true; redraw(); } /** * Removes the given column group from the table. This method is only called * from the {@code GridColumnGroup}'s dispose method. * * @param group group to remove. */ void removeColumnGroup(GridColumnGroup group) { GridColumnGroup[] newColumnGroups = new GridColumnGroup[columnGroups.length - 1]; int newIndex = 0; for (int i = 0; i < columnGroups.length; i++) { if (columnGroups[i] != group) { newColumnGroups[newIndex] = columnGroups[i]; newIndex++; } } columnGroups = newColumnGroups; if (columnGroups.length == 0) { computeHeaderHeight(sizingGC); } scrollValuesObsolete = true; redraw(); } /** * Updates the cached number of visible items by the given amount. * * @param amount amount to update cached total */ void updateVisibleItems(int amount) { currentVisibleItems += amount; } /** * Returns the current item in focus. * * @return item in focus or {@code null}. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridItem getFocusItem() { checkWidget(); return focusItem; } /** * Returns the current cell in focus. If cell selection is disabled, this method returns null. * * @return cell in focus or {@code null}. x represents the column and y the row the cell is in * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Point getFocusCell() { checkWidget(); if (!cellSelectionEnabled) return null; int x = -1; int y = -1; if (focusColumn != null) x = indexOf(focusColumn); if (focusItem != null) y = indexOf(focusItem); return new Point(x,y); } /** * Sets the focused item to the given item. * * @param item item to focus. * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if item is disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setFocusItem(GridItem item) { checkWidget(); //TODO: check and make sure this item is valid for focus if (item == null || item.isDisposed() || item.getParent() != this) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } focusItem = item; } /** * Sets the focused item to the given column. Column focus is only applicable when cell * selection is enabled. * * @param column column to focus. * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if item is disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setFocusColumn(GridColumn column) { checkWidget(); //TODO: check and make sure this item is valid for focus if (column == null || column.isDisposed() || column.getParent() != this || !column.isVisible()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } focusColumn = column; intendedFocusColumn = column; } /** * Returns an array of the columns in their display order. * * @return columns in display order */ GridColumn[] getColumnsInOrder() { checkWidget(); return (GridColumn[])displayOrderedColumns.toArray(new GridColumn[columns.size()]); } /** * Returns true if the table is set to horizontally scroll column-by-column * rather than pixel-by-pixel. * * @return true if the table is scrolled horizontally by column * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getColumnScrolling() { checkWidget(); return columnScrolling; } /** * Sets the table scrolling method to either scroll column-by-column (true) * or pixel-by-pixel (false). * * @param columnScrolling true to horizontally scroll by column, false to * scroll by pixel * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setColumnScrolling(boolean columnScrolling) { checkWidget(); if (rowHeaderVisible && !columnScrolling) { return; } this.columnScrolling = columnScrolling; scrollValuesObsolete = true; redraw(); } /** * Returns the first visible column that is not spanned by any other column that is either the * given column or any of the columns displaying to the left of the given column. If the * given column and subsequent columns to the right are either not visible or spanned, this * method will return null. * * @param item * @param col * @return */ private GridColumn getVisibleColumn_DegradeLeft(GridItem item, GridColumn col) { int index = displayOrderedColumns.indexOf(col); GridColumn prevCol = col; int i = 0; while (!prevCol.isVisible()) { i ++; if (index - i < 0) return null; prevCol = (GridColumn)displayOrderedColumns.get(index - i); } index = displayOrderedColumns.indexOf(prevCol); for (int j = 0; j < index; j++) { GridColumn tempCol = (GridColumn)displayOrderedColumns.get(j); if (!tempCol.isVisible()) { continue; } if (item.getColumnSpan(indexOf(tempCol)) >= index - j) { prevCol = tempCol; break; } } return prevCol; } /** * Returns the first visible column that is not spanned by any other column that is either the * given column or any of the columns displaying to the right of the given column. If the * given column and subsequent columns to the right are either not visible or spanned, this * method will return null. * * @param item * @param col * @return */ private GridColumn getVisibleColumn_DegradeRight(GridItem item, GridColumn col) { int index = displayOrderedColumns.indexOf(col); int i = 0; GridColumn nextCol = col; while (!nextCol.isVisible()) { i ++; if (index + i == displayOrderedColumns.size()) return null; nextCol = (GridColumn)displayOrderedColumns.get(index + i); } index = displayOrderedColumns.indexOf(nextCol); int startIndex = index; while (index > 0) { index --; GridColumn prevCol = (GridColumn)displayOrderedColumns.get(index); if (item.getColumnSpan(indexOf(prevCol)) >= startIndex - index) { if (startIndex == displayOrderedColumns.size() - 1) { return null; } else { return getVisibleColumn_DegradeRight(item, (GridColumn)displayOrderedColumns.get(startIndex + 1)); } } } return nextCol; } /** * Returns true if the cells are selectable in the reciever. * * @return cell selection enablement status. * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getCellSelectionEnabled() { checkWidget(); return cellSelectionEnabled; } /** * Sets whether cells are selectable in the receiver. * * @param cellSelection the cellSelection to set * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setCellSelectionEnabled(boolean cellSelection) { checkWidget(); if (!cellSelection) { selectedCells.clear(); redraw(); } else { selectedItems.clear(); redraw(); } this.cellSelectionEnabled = cellSelection; } /** * @return <code>true</code> if cell selection is enabled */ public boolean isCellSelectionEnabled() { return cellSelectionEnabled; } /** * Deselects the given cell in the receiver. If the given cell is already * deselected it remains deselected. Invalid cells are ignored. * * @param cell cell to deselect. * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the cell is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselectCell(Point cell) { checkWidget(); if (cell == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); selectedCells.remove(cell); updateColumnSelection(); redraw(); } /** * Deselects the given cells. Invalid cells are ignored. * * @param cells the cells to deselect. * * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the set of cells or any cell is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselectCells(Point[] cells) { checkWidget(); if (cells == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); for (int i = 0; i < cells.length; i++) { if (cells[i] == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); } for (int i = 0; i < cells.length; i++) { selectedCells.remove(cells[i]); } updateColumnSelection(); redraw(); } /** * Deselects all selected cells in the receiver. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void deselectAllCells() { checkWidget(); selectedCells.clear(); updateColumnSelection(); redraw(); } /** * Selects the given cell. Invalid cells are ignored. * * @param cell point whose x values is a column index and y value is an item index * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectCell(Point cell) { checkWidget(); if (!cellSelectionEnabled) return; if (cell == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); addToCellSelection(cell); updateColumnSelection(); redraw(); } /** * Selects the given cells. Invalid cells are ignored. * * @param cells an arry of points whose x value is a column index and y value is an item index * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the set of cells or an individual cell is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectCells(Point[] cells) { checkWidget(); if (!cellSelectionEnabled) return; if (cells == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); for (int i = 0; i < cells.length; i++) { if (cells[i] == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); } for (int i = 0; i < cells.length; i++) { addToCellSelection(cells[i]); } updateColumnSelection(); redraw(); } /** * Selects all cells in the receiver. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectAllCells() { checkWidget(); selectAllCellsInternal(); } /** * Selects all cells in the receiver. * * @return An Event object * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ private Event selectAllCellsInternal() { if (!cellSelectionEnabled) return selectAllRowsInternal(); if (columns.size() == 0) return null; if(items.size() == 0) return null; int index = 0; GridColumn column = (GridColumn)displayOrderedColumns.get(index); while (!column.isVisible()) { index ++; if (index >= columns.size()) return null; column = (GridColumn)displayOrderedColumns.get(index); } GridColumn oldFocusColumn = focusColumn; GridItem oldFocusItem = focusItem; focusColumn = column; focusItem = (GridItem)items.get(0); GridItem lastItem = getPreviousVisibleItem(null); GridColumn lastCol = getVisibleColumn_DegradeLeft(lastItem,(GridColumn)displayOrderedColumns.get(displayOrderedColumns.size() -1)); Event event = updateCellSelection(new Point(indexOf(lastCol),indexOf(lastItem)),SWT.MOD2, true, false); focusColumn = oldFocusColumn; focusItem = oldFocusItem; updateColumnSelection(); redraw(); return event; } /** * Selects rows in the receiver. * * @return An Event object * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ private Event selectAllRowsInternal() { if (cellSelectionEnabled) return selectAllCellsInternal(); if (SWT.MULTI != selectionType) return null; if(items.size() == 0) return null; deselectAll(); GridItem oldFocusItem = focusItem; GridItem firstItem = getItem(getTopIndex()); GridItem lastItem = getPreviousVisibleItem(null); setFocusItem(firstItem); updateSelection(firstItem, SWT.NONE); Event event = updateSelection(lastItem, SWT.MOD2); setFocusItem(oldFocusItem); redraw(); return event; } /** * Selects all cells in the given column in the receiver. * * @param col * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectColumn(int col) { checkWidget(); Vector cells = new Vector(); getCells(getColumn(col), cells); selectCells((Point[])cells.toArray(new Point[0])); } /** * Selects all cells in the given column group in the receiver. * * @param colGroup the column group * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectColumnGroup(int colGroup) { selectColumnGroup(getColumnGroup(colGroup)); } /** * Selects all cells in the given column group in the receiver. * * @param colGroup the column group * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void selectColumnGroup(GridColumnGroup colGroup) { checkWidget(); Vector cells = new Vector(); getCells(colGroup, cells); selectCells((Point[])cells.toArray(new Point[0])); } /** * Selects the selection to the given cell. The existing selection is cleared before * selecting the given cell. * * @param cell point whose x values is a column index and y value is an item index * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the cell is invalid</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setCellSelection(Point cell) { checkWidget(); if (!cellSelectionEnabled) return; if (cell == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (!isValidCell(cell)) SWT.error(SWT.ERROR_INVALID_ARGUMENT); selectedCells.clear(); addToCellSelection(cell); updateColumnSelection(); redraw(); } /** * Selects the selection to the given set of cell. The existing selection is cleared before * selecting the given cells. * * @param cells point array whose x values is a column index and y value is an item index * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the cell array or an individual cell is null</li> * <li>ERROR_INVALID_ARGUMENT - if the a cell is invalid</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setCellSelection(Point[] cells) { checkWidget(); if (!cellSelectionEnabled) return; if (cells == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); for (int i = 0; i < cells.length; i++) { if (cells[i] == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (!isValidCell(cells[i])) SWT.error(SWT.ERROR_INVALID_ARGUMENT); } selectedCells.clear(); for (int i = 0; i < cells.length; i++) { addToCellSelection(cells[i]); } updateColumnSelection(); redraw(); } /** * Returns an array of cells that are currently selected in the * receiver. The order of the items is unspecified. An empty array indicates * that no items are selected. * <p> * Note: This is not the actual structure used by the receiver to maintain * its selection, so modifying the array will not affect the receiver. * </p> * * @return an array representing the cell selection * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Point[] getCellSelection() { checkWidget(); return (Point[])selectedCells.toArray(new Point[selectedCells.size()]); } GridColumn getFocusColumn() { return focusColumn; } void updateColumnFocus() { if (!focusColumn.isVisible()) { int index = displayOrderedColumns.indexOf(focusColumn); if (index > 0) { GridColumn prev = (GridColumn)displayOrderedColumns.get(index - 1); prev = getVisibleColumn_DegradeLeft(focusItem,prev); if (prev == null) { prev = getVisibleColumn_DegradeRight(focusItem,focusColumn); } focusColumn = prev; } else { focusColumn = getVisibleColumn_DegradeRight(focusItem,focusColumn); } } } private void getCells(GridColumn col, Vector cells) { int colIndex = indexOf(col); int columnAtPosition = 0; for (Iterator iter = displayOrderedColumns.iterator(); iter.hasNext();) { GridColumn nextCol = (GridColumn)iter.next(); if (!nextCol.isVisible()) continue; if (nextCol == col) break; columnAtPosition ++; } GridItem item = null; if (getItemCount() > 0) item = getItem(0); while (item != null) { //is cell spanned int position = -1; boolean spanned = false; for (Iterator iter = displayOrderedColumns.iterator(); iter.hasNext();) { GridColumn nextCol = (GridColumn)iter.next(); if (!nextCol.isVisible()) continue; if (nextCol == col) break; int span = item.getColumnSpan(indexOf(nextCol)); if (position + span >= columnAtPosition){ spanned = true; break; } } if (!spanned && item.getColumnSpan(colIndex) == 0) { cells.add(new Point(colIndex,indexOf(item))); } item = getNextVisibleItem(item); } } private void getCells(GridColumnGroup colGroup, Vector cells) { GridColumn[] cols = colGroup.getColumns(); for (int i = 0; i < cols.length; i++) { getCells(cols[i], cells); } } private void getCells(GridItem item, Vector cells) { int itemIndex = indexOf(item); int span = 0; for (Iterator iter = displayOrderedColumns.iterator(); iter.hasNext();) { GridColumn nextCol = (GridColumn)iter.next(); if (span > 0) { span --; continue; } if (!nextCol.isVisible()) continue; span = item.getColumnSpan(indexOf(nextCol)); cells.add(new Point(indexOf(nextCol),itemIndex)); } } private Point[] getCells(GridItem item) { Vector cells = new Vector(); int itemIndex = indexOf(item); int span = 0; for (Iterator iter = displayOrderedColumns.iterator(); iter.hasNext();) { GridColumn nextCol = (GridColumn)iter.next(); if (span > 0) { span --; continue; } if (!nextCol.isVisible()) continue; span = item.getColumnSpan(indexOf(nextCol)); cells.add(new Point(indexOf(nextCol),itemIndex)); } return (Point[])cells.toArray(new Point[]{}); } private void getCells(GridItem fromItem, GridItem toItem, Vector cells) { boolean descending = (indexOf(fromItem) < indexOf(toItem)); GridItem iterItem = toItem; do { getCells(iterItem,cells); if (iterItem == fromItem) break; if (descending) { iterItem = getPreviousVisibleItem(iterItem); } else { iterItem = getNextVisibleItem(iterItem); } } while (true); } private int blend(int v1, int v2, int ratio) { return (ratio*v1 + (100-ratio)*v2)/100; } private RGB blend(RGB c1, RGB c2, int ratio) { int r = blend(c1.red, c2.red, ratio); int g = blend(c1.green, c2.green, ratio); int b = blend(c1.blue, c2.blue, ratio); return new RGB(r, g, b); } /** * Returns a point whose x and y values are the to and from column indexes of the new selection * range inclusive of all spanned columns. * * @param fromItem * @param fromColumn * @param toItem * @param toColumn * @return */ private Point getSelectionRange(GridItem fromItem, GridColumn fromColumn, GridItem toItem, GridColumn toColumn) { if (displayOrderedColumns.indexOf(fromColumn) > displayOrderedColumns.indexOf(toColumn)) { GridColumn temp = fromColumn; fromColumn = toColumn; toColumn = temp; } if (indexOf(fromItem) > indexOf(toItem)) { GridItem temp = fromItem; fromItem = toItem; toItem = temp; } boolean firstTime = true; GridItem iterItem = fromItem; int fromIndex = indexOf(fromColumn); int toIndex = indexOf(toColumn); do { if (!firstTime) { iterItem = getNextVisibleItem(iterItem); } else { firstTime = false; } Point cols = getRowSelectionRange(iterItem, fromColumn, toColumn); //check and see if column spanning means that the range increased if (cols.x != fromIndex || cols.y != toIndex) { GridColumn newFrom = getColumn(cols.x); GridColumn newTo = getColumn(cols.y); //Unfortunately we have to start all over again from the top with the new range return getSelectionRange(fromItem, newFrom, toItem, newTo); } } while (iterItem != toItem); return new Point(indexOf(fromColumn),indexOf(toColumn)); } /** * Returns a point whose x and y value are the to and from column indexes of the new selection * range inclusive of all spanned columns. * * @param item * @param fromColumn * @param toColumn * @return */ private Point getRowSelectionRange(GridItem item, GridColumn fromColumn, GridColumn toColumn) { int newFrom = indexOf(fromColumn); int newTo = indexOf(toColumn); int span = 0; int spanningColIndex = -1; boolean spanningBeyondToCol = false; for (Iterator iter = displayOrderedColumns.iterator(); iter.hasNext();) { GridColumn col = (GridColumn)iter.next(); if (!col.isVisible()) { if (span > 0) span --; continue; } if (span > 0) { if (col == fromColumn) { newFrom = spanningColIndex; } else if (col == toColumn && span > 1) { spanningBeyondToCol = true; } span --; if (spanningBeyondToCol && span == 0) { newTo = indexOf(col); break; } } else { int index = indexOf(col); span = item.getColumnSpan(index); if (span > 0) spanningColIndex = index; if (col == toColumn && span > 0) spanningBeyondToCol = true; } if (col == toColumn && !spanningBeyondToCol) break; } return new Point(newFrom,newTo); } /** * Returns the column which is spanning the given column for the given item or null if it is not * being spanned. * * @param item * @param column * @return */ private GridColumn getSpanningColumn(GridItem item, GridColumn column) { int span = 0; GridColumn spanningCol = null; for (Iterator iter = displayOrderedColumns.iterator(); iter.hasNext();) { GridColumn col = (GridColumn)iter.next(); if (col == column) { return spanningCol; } if (span > 0) { span --; if (span == 0) spanningCol = null; } else { int index = indexOf(col); span = item.getColumnSpan(index); if (span > 0) spanningCol = col; } } return spanningCol; } /** * Returns true if the given cell's x and y values are valid column and * item indexes respectively. * * @param cell * @return */ private boolean isValidCell(Point cell) { if (cell.x < 0 || cell.x >= columns.size()) return false; if (cell.y < 0 || cell.y >= items.size()) return false; return true; } /** * Shows the inplace tooltip for the given item and column. The location is the x and y origin * of the text in the cell. * <p> * This method may be overriden to provide their own custom tooltips. * * @param item the item currently hovered over or null. * @param column the column currently hovered over or null. * @param group the group currently hovered over or null. * @param location the x,y origin of the text in the hovered object. */ protected void showToolTip(GridItem item, GridColumn column, GridColumnGroup group, Point location) { if (inplaceToolTip == null) { inplaceToolTip = new GridToolTip(this); } if (group != null) { inplaceToolTip.setFont(getFont()); inplaceToolTip.setText(group.getText()); } else if (item != null) { inplaceToolTip.setFont(item.getFont(item.getParent().indexOf(column))); inplaceToolTip.setText(item.getText(item.getParent().indexOf(column))); } else if (column != null) { inplaceToolTip.setFont(getFont()); inplaceToolTip.setText(column.getText()); } Point p = getDisplay().map(this, null, location); inplaceToolTip.setLocation(p); inplaceToolTip.setVisible(true); } /** * Hides the inplace tooltip. * <p> * This method must be overriden when showToolTip is overriden. Subclasses must * call super when overriding this method. */ protected void hideToolTip() { if (inplaceToolTip != null) { inplaceToolTip.setVisible(false); } if (inplaceTooltipCapture) { setCapture(false); inplaceTooltipCapture = false; } } void recalculateRowHeaderHeight(GridItem item,int oldHeight, int newHeight) { checkWidget(); if( newHeight > itemHeight ) { itemHeight = newHeight; userModifiedItemHeight = false; hasDifferingHeights=false; itemHeight = computeItemHeight((GridItem) items.get(0), sizingGC); for(int cnt=0;cnt<items.size();cnt++) ((GridItem)items.get(cnt)).setHeight(itemHeight); setScrollValuesObsolete(); redraw(); } } void recalculateRowHeaderWidth(GridItem item,int oldWidth, int newWidth) { if (!isAutoWidth()) return; if (newWidth > rowHeaderWidth) { rowHeaderWidth = newWidth; } else if (newWidth < rowHeaderWidth && oldWidth == rowHeaderWidth) { //if the changed width is smaller, and the previous width of that rows header was equal //to the current row header width then its possible that we may need to make the new //row header width smaller, but to do that we need to ask all the rows all over again for (Iterator iter = items.iterator(); iter.hasNext();) { GridItem iterItem = (GridItem)iter.next(); newWidth = Math.max(newWidth,rowHeaderRenderer.computeSize(sizingGC, SWT.DEFAULT,SWT.DEFAULT,iterItem).x); } rowHeaderWidth = newWidth; } redraw(); } /** * {@inheritDoc} */ public void setFont(Font font) { super.setFont(font); sizingGC.setFont(font); } /** * Returns the row header width or 0 if row headers are not visible. * * @return the width of the row headers * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public int getItemHeaderWidth() { checkWidget(); if (!rowHeaderVisible) return 0; return rowHeaderWidth; } /** * Sets the row header width to the specified value. This automatically disables the auto width feature of the grid. * @param width the width of the row header * @see #getItemHeaderWidth() * @see #setAutoWidth(boolean) */ public void setItemHeaderWidth(int width) { checkWidget(); rowHeaderWidth = width; setAutoWidth(false); redraw(); } /** * Sets the number of items contained in the receiver. * * @param count the number of items * * @exception org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setItemCount(int count) { checkWidget(); setRedraw(false); if (count < 0) count = 0; if (count < items.size()) { //TODO delete and clear items if necessary } while (count > items.size()) { new GridItem(this,SWT.NONE); } setRedraw(true); } /** * Initialize accessibility. */ private void initAccessible() { final Accessible accessible = getAccessible(); accessible.addAccessibleListener(new AccessibleAdapter() { public void getDescription(AccessibleEvent e) { int childID = e.childID; if (childID >= 0 && childID < items.size()) { String descrption = ""; for (int i = 0; i < columns.size(); i++) { if (i != 0) { descrption += ((GridColumn)columns.get(i)).getText() + " : "; descrption += ((GridItem)items.get(childID)).getText(i) + " "; } } e.result = descrption; } } public void getName(AccessibleEvent e) { int childID = e.childID; if (childID >= 0 && childID < items.size()) { // Name of the items e.result = ((GridItem)items.get(childID)).getText(); } else if (childID >= items.size() && childID < items.size() + columns.size()) { // Name of the column headers e.result = ((GridColumn)columns.get(childID - items.size())).getText(); } else if (childID >= items.size() + columns.size() && childID < items.size() + columns.size() + columnGroups.length) { // Name of the column group headers e.result = ((GridColumnGroup)columnGroups[childID - items.size() - columns.size()]).getText(); } else if (childID >= items.size() + columns.size() + columnGroups.length && childID < items.size() + columns.size() + columnGroups.length + columnGroups.length) { // Name of the toggle button for column group headers e.result = ACC_TOGGLE_BUTTON_NAME; } } }); accessible.addAccessibleControlListener(new AccessibleControlAdapter() { public void getChildAtPoint(AccessibleControlEvent e) { Point location = toControl(e.x, e.y); e.childID = ACC.CHILDID_SELF; // Grid Items GridItem item = getItem(location); if (item != null) { for (int i = 0; i < getItems().length; i++) { if (item.equals(getItem(i))) { e.childID = i; return; } } } else { // Column Headers GridColumn column = overColumnHeader(location.x, location.y); if (column != null) { for (int i = 0; i < getColumns().length; i++) { if (column.equals(getColumn(i))) { e.childID = getItems().length + i; return; } } } else { // Column Group headers GridColumnGroup columnGroup = overColumnGroupHeader(location.x, location.y); if (columnGroup != null) { for (int i = 0; i < getColumnGroups().length; i++) { if (columnGroup.equals(getColumnGroup(i))) { Rectangle toggle = ((DefaultColumnGroupHeaderRenderer)columnGroup .getHeaderRenderer()).getToggleBounds(); if (toggle.contains(location.x, location.y)) { // Toggle button for column group // header e.childID = getItems().length + getColumns().length + getColumnGroups().length + i; } else { // Column Group header e.childID = getItems().length + getColumns().length + i; } return; } } } } } } public void getChildCount(AccessibleControlEvent e) { if (e.childID == ACC.CHILDID_SELF) { int length = items.size(); if (isTree) { // Child count for parent. Here if the item parent // is not an other item, // it is consider as children of Grid for (int i = 0; i < items.size(); i++) { if (((GridItem)items.get(i)).getParentItem() != null) { length--; } } } e.detail = length; } } public void getChildren(AccessibleControlEvent e) { if (e.childID == ACC.CHILDID_SELF) { int length = items.size(); if (isTree) { for (int i = 0; i < items.size(); i++) { if (((GridItem)items.get(i)).getParentItem() != null) { length--; } } Object[] children = new Object[length]; int j = 0; for (int i = 0; i < items.size(); i++) { if (((GridItem)items.get(i)).getParentItem() == null) { children[j] = new Integer(i); j++; } } e.children = children; } else { Object[] children = new Object[length]; for (int i = 0; i < items.size(); i++) { children[i] = new Integer(i); } e.children = children; } } } public void getDefaultAction(AccessibleControlEvent e) { int childID = e.childID; if (childID >= 0 && childID < items.size()) { if (getItem(childID).hasChildren()) { // Action of tree items if (getItem(childID).isExpanded()) { e.result = ACC_ITEM_ACTION_COLLAPSE; } else { e.result = ACC_ITEM_ACTION_EXPAND; } } else { // action of default items e.result = ACC_ITEM_DEFAULT_ACTION; } } else if (childID >= items.size() && childID < items.size() + columns.size() + columnGroups.length) { // action of column and column group header e.result = ACC_COLUMN_DEFAULT_ACTION; } else if (childID >= items.size() + columns.size() + columnGroups.length && childID < items.size() + columns.size() + columnGroups.length + columnGroups.length) { // action of toggle button of column group header e.result = SWT.getMessage("SWT_Press"); } } public void getLocation(AccessibleControlEvent e) { // location of parent Rectangle location = getBounds(); location.x = 0; location.y = 0; int childID = e.childID; if (childID >= 0 && childID < items.size()) { // location of items GridItem item = getItem(childID); if (item != null) { Point p = getOrigin((GridColumn)columns.get(0), item); location.y = p.y; location.height = item.getHeight(); } } else if (childID >= items.size() && childID < items.size() + columns.size()) { // location of columns headers GridColumn column = getColumn(childID - items.size()); if (column != null) { location.x = getColumnHeaderXPosition(column); if (column.getColumnGroup() == null) { location.y = 0; } else { location.y = groupHeaderHeight; } location.height = headerHeight; location.width = column.getWidth(); } } else if (childID >= items.size() + columns.size() && childID < items.size() + columns.size() + columnGroups.length) { // location of column group header GridColumnGroup columnGroup = getColumnGroup(childID - items.size() - columns.size()); if (columnGroup != null) { location.y = 0; location.height = groupHeaderHeight; location.x = getColumnHeaderXPosition(columnGroup.getFirstVisibleColumn()); int width = 0; for (int i = 0; i < columnGroup.getColumns().length; i++) { if (columnGroup.getColumns()[i].isVisible()) { width += columnGroup.getColumns()[i].getWidth(); } } location.width = width; } } else if (childID >= items.size() + columns.size() + columnGroups.length && childID < items.size() + columns.size() + columnGroups.length + columnGroups.length) { // location of toggle button of column group header GridColumnGroup columnGroup = getColumnGroup(childID - items.size() - columns.size() - columnGroups.length); location = ((DefaultColumnGroupHeaderRenderer)columnGroup.getHeaderRenderer()) .getToggleBounds(); } if (location != null) { Point pt = toDisplay(location.x, location.y); e.x = pt.x; e.y = pt.y; e.width = location.width; e.height = location.height; } } public void getRole(AccessibleControlEvent e) { int childID = e.childID; if (childID >= 0 && childID < items.size()) { // role of items if (isTree) { e.detail = ACC.ROLE_TREEITEM; } else { e.detail = ACC.ROLE_LISTITEM; } } else if (childID >= items.size() && childID < items.size() + columns.size() + columnGroups.length) { // role of columns headers and column group headers e.detail = ACC.ROLE_TABLECOLUMNHEADER; } else if (childID >= items.size() + columns.size() + columnGroups.length && childID < items.size() + columns.size() + columnGroups.length + columnGroups.length) { // role of toggle button of column group headers e.detail = ACC.ROLE_PUSHBUTTON; } else if (childID == ACC.CHILDID_SELF) { // role of parent if (isTree) { e.detail = ACC.ROLE_TREE; } else { e.detail = ACC.ROLE_TABLE; } } } public void getSelection(AccessibleControlEvent e) { e.childID = ACC.CHILDID_NONE; if (selectedItems.size() == 1) { // Single selection e.childID = indexOf(((GridItem)selectedItems.get(0))); } else if (selectedItems.size() > 1) { // multiple selection e.childID = ACC.CHILDID_MULTIPLE; int length = selectedItems.size(); Object[] children = new Object[length]; for (int i = 0; i < length; i++) { GridItem item = (GridItem)selectedItems.get(i); children[i] = new Integer(indexOf(item)); } e.children = children; } } public void getState(AccessibleControlEvent e) { int childID = e.childID; if (childID >= 0 && childID < items.size()) { // state of items e.detail = ACC.STATE_SELECTABLE; if (getDisplay().getActiveShell() == getParent().getShell()) { e.detail |= ACC.STATE_FOCUSABLE; } if (selectedItems.contains(getItem(childID))) { e.detail |= ACC.STATE_SELECTED; if (getDisplay().getActiveShell() == getParent().getShell()) { e.detail |= ACC.STATE_FOCUSED; } } if (getItem(childID).getChecked()) { e.detail |= ACC.STATE_CHECKED; } // only for tree type items if (getItem(childID).hasChildren()) { if (getItem(childID).isExpanded()) { e.detail |= ACC.STATE_EXPANDED; } else { e.detail |= ACC.STATE_COLLAPSED; } } if (!getItem(childID).isVisible()) { e.detail |= ACC.STATE_INVISIBLE; } } else if (childID >= items.size() && childID < items.size() + columns.size() + columnGroups.length) { // state of column headers and column group headers e.detail = ACC.STATE_READONLY; } else if (childID >= items.size() + columns.size() + columnGroups.length && childID < items.size() + columns.size() + columnGroups.length + columnGroups.length) { // state of toggle button of column group headers if (getColumnGroup( childID - items.size() - columns.size() - columnGroups.length).getExpanded()) { e.detail = ACC.STATE_EXPANDED; } else { e.detail = ACC.STATE_COLLAPSED; } } } public void getValue(AccessibleControlEvent e) { int childID = e.childID; if (childID >= 0 && childID < items.size()) { // value for tree items if (isTree) { e.result = "" + getItem(childID).getLevel(); } } } }); addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (selectedItems.size() > 0) { accessible.setFocus(items.indexOf(selectedItems.get(selectedItems.size() - 1))); } } }); addTreeListener(new TreeListener() { public void treeCollapsed(TreeEvent e) { if (getFocusItem() != null) { accessible.setFocus(items.indexOf(getFocusItem())); } } public void treeExpanded(TreeEvent e) { if (getFocusItem() != null) { accessible.setFocus(items.indexOf(getFocusItem())); } } }); } /** * @return the disposing */ boolean isDisposing() { return disposing; } /** * @param hasSpanning the hasSpanning to set */ void setHasSpanning(boolean hasSpanning) { this.hasSpanning = hasSpanning; } /** * Returns the receiver's tool tip text, or null if it has * not been set. * * @return the receiver's tool tip text * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getToolTipText() { checkWidget(); return toolTipText; } /** * Sets the receiver's tool tip text to the argument, which * may be null indicating that no tool tip text should be shown. * * @param string the new tool tip text (or null) * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setToolTipText(String string) { checkWidget(); toolTipText = string; } /** * Updates the row height when the first image is set on an item. * @param column the column the image is change * @param item item which images has just been set on. */ void imageSetOnItem(int column, GridItem item) { if( sizeOnEveryItemImageChange ) { if( item == null || item.getImage(column) == null ) return; int height = item.getImage(column).getBounds().height; //FIXME Needs better algorithm if( height + 20 > getItemHeight() ) { height = computeItemHeight(item,sizingGC); setItemHeight(height); } } else { if (firstImageSet || userModifiedItemHeight) return; int height = computeItemHeight(item,sizingGC); setItemHeight(height); firstImageSet = true; } } /** * Determines if the mouse is hovering on the selection drag area and changes the * pointer and sets field appropriately. * <p> * Note: The 'selection drag area' is that part of the selection, * on which a drag event can be initiated. This is either the border * of the selection (i.e. a cell border between a slected and a non-selected * cell) or the complete selection (i.e. anywhere on a selected cell). * What area serves as drag area is determined by {@link #setDragOnFullSelection(boolean)}. * * @param x * @param y * @return * @see #setDragOnFullSelection(boolean) */ private boolean handleHoverOnSelectionDragArea(int x, int y) { boolean over = false; // Point inSelection = null; if ( (!rowHeaderVisible || x > rowHeaderWidth-SELECTION_DRAG_BORDER_THRESHOLD) && (!columnHeadersVisible || y > headerHeight-SELECTION_DRAG_BORDER_THRESHOLD) ) { // not on a header // if(!dragOnFullSelection) // { // // drag area is the border of the selection // // if(cellSelectionEnabled) // { // Point neP = new Point( x-SELECTION_DRAG_BORDER_THRESHOLD, y-SELECTION_DRAG_BORDER_THRESHOLD ); // Point ne = getCell(neP); // Point nwP = new Point( x+SELECTION_DRAG_BORDER_THRESHOLD, y-SELECTION_DRAG_BORDER_THRESHOLD ); // Point nw = getCell(nwP); // Point swP = new Point( x+SELECTION_DRAG_BORDER_THRESHOLD, y+SELECTION_DRAG_BORDER_THRESHOLD ); // Point sw = getCell(swP); // Point seP = new Point( x-SELECTION_DRAG_BORDER_THRESHOLD, y+SELECTION_DRAG_BORDER_THRESHOLD ); // Point se = getCell(seP); // // boolean neSel = ne != null && isCellSelected(ne); // boolean nwSel = nw != null && isCellSelected(nw); // boolean swSel = sw != null && isCellSelected(sw); // boolean seSel = se != null && isCellSelected(se); // // over = (neSel || nwSel || swSel || seSel) && (!neSel || !nwSel || !swSel || !seSel); //// inSelection = neSel ? neP : nwSel ? nwP : swSel ? swP : seSel ? seP : null; // } // else // { // Point nP = new Point( x, y-SELECTION_DRAG_BORDER_THRESHOLD ); // GridItem n = getItem(nP); // Point sP = new Point( x, y+SELECTION_DRAG_BORDER_THRESHOLD ); // GridItem s = getItem(sP); // // boolean nSel = n != null && isSelected(n); // boolean sSel = s != null && isSelected(s); // // over = nSel != sSel; //// inSelection = nSel ? nP : sSel ? sP : null; // } // } // else // { // drag area is the entire selection if(cellSelectionEnabled) { Point p = new Point(x,y); Point cell = getCell(p); over = cell !=null && isCellSelected(cell); // inSelection = over ? p : null; } else { Point p = new Point(x,y); GridItem item = getItem(p); over = item != null && isSelected(item); // inSelection = over ? p : null; } } // } if (over != hoveringOnSelectionDragArea) { // if (over) // { // // use drag cursor only in border mode // if (!dragOnFullSelection) // setCursor(getDisplay().getSystemCursor(SWT.CURSOR_SIZEALL)); //// potentialDragStart = inSelection; // } // else // { // setCursor(null); //// potentialDragStart = null; // } hoveringOnSelectionDragArea = over; } return over; } /** * Display a mark indicating the point at which an item will be inserted. * This is used as a visual hint to show where a dragged item will be * inserted when dropped on the grid. This method should not be called * directly, instead {@link DND#FEEDBACK_INSERT_BEFORE} or * {@link DND#FEEDBACK_INSERT_AFTER} should be set in * {@link DropTargetEvent#feedback} from within a {@link DropTargetListener}. * * @param item the insert item. Null will clear the insertion mark. * @param column the column of the cell. Null will make the insertion mark span all columns. * @param before true places the insert mark above 'item'. false places * the insert mark below 'item'. * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the item or column has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ void setInsertMark (GridItem item, GridColumn column, boolean before) { checkWidget (); if (item != null) { if (item.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); } if (column != null) { if (column.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); } insertMarkItem = item; insertMarkColumn = column; insertMarkBefore = before; redraw(); } /** * A helper method for {@link GridDropTargetEffect#dragOver(DropTargetEvent)}. * * @param point * @return true if point is near the top or bottom border of the visible grid area */ boolean isInDragScrollArea(Point point) { int rhw = rowHeaderVisible ? rowHeaderWidth : 0; int chh = columnHeadersVisible ? headerHeight : 0; Rectangle top = new Rectangle(rhw, chh, getClientArea().width - rhw, DRAG_SCROLL_AREA_HEIGHT); Rectangle bottom = new Rectangle(rhw, getClientArea().height - DRAG_SCROLL_AREA_HEIGHT, getClientArea().width - rhw, DRAG_SCROLL_AREA_HEIGHT); return top.contains(point) || bottom.contains(point); } /** * Clears the item at the given zero-relative index in the receiver. * The text, icon and other attributes of the item are set to the default * value. If the table was created with the <code>SWT.VIRTUAL</code> style, * these attributes are requested again as needed. * * @param index the index of the item to clear * @param allChildren <code>true</code> if all child items of the indexed item should be * cleared recursively, and <code>false</code> otherwise * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SWT#VIRTUAL * @see SWT#SetData */ public void clear(int index, boolean allChildren) { checkWidget(); if (index < 0 || index >= items.size()) { SWT.error(SWT.ERROR_INVALID_RANGE); } GridItem item = getItem(index); item.clear(allChildren); redraw(); } /** * Clears the items in the receiver which are between the given * zero-relative start and end indices (inclusive). The text, icon * and other attributes of the items are set to their default values. * If the table was created with the <code>SWT.VIRTUAL</code> style, * these attributes are requested again as needed. * * @param start the start index of the item to clear * @param end the end index of the item to clear * @param allChildren <code>true</code> if all child items of the range of items should be * cleared recursively, and <code>false</code> otherwise * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_RANGE - if either the start or end are not between 0 and the number of elements in the list minus 1 (inclusive)</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SWT#VIRTUAL * @see SWT#SetData */ public void clear(int start, int end, boolean allChildren) { checkWidget(); if (start > end) return; int count = items.size(); if (!(0 <= start && start <= end && end < count)) { SWT.error(SWT.ERROR_INVALID_RANGE); } for (int i=start; i<=end; i++) { GridItem item = (GridItem)items.get(i); item.clear(allChildren); } redraw(); } /** * Clears the items at the given zero-relative indices in the receiver. * The text, icon and other attributes of the items are set to their default * values. If the table was created with the <code>SWT.VIRTUAL</code> style, * these attributes are requested again as needed. * * @param indices the array of indices of the items * @param allChildren <code>true</code> if all child items of the indexed items should be * cleared recursively, and <code>false</code> otherwise * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li> * <li>ERROR_NULL_ARGUMENT - if the indices array is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SWT#VIRTUAL * @see SWT#SetData */ public void clear(int [] indices, boolean allChildren) { checkWidget(); if (indices == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (indices.length == 0) return; int count = items.size(); for (int i=0; i<indices.length; i++) { if (!(0 <= indices[i] && indices[i] < count)) { SWT.error(SWT.ERROR_INVALID_RANGE); } } for (int i=0; i<indices.length; i++) { GridItem item = (GridItem)items.get(indices[i]); item.clear(allChildren); } redraw(); } /** * Clears all the items in the receiver. The text, icon and other * attributes of the items are set to their default values. If the * table was created with the <code>SWT.VIRTUAL</code> style, these * attributes are requested again as needed. * * @param allChildren <code>true</code> if all child items of each item should be * cleared recursively, and <code>false</code> otherwise * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SWT#VIRTUAL * @see SWT#SetData */ public void clearAll(boolean allChildren) { checkWidget(); if (items.size() > 0) clear(0, items.size()-1, allChildren); } /** * Recalculate the height of the header */ public void recalculateHeader() { int previous = getHeaderHeight(); computeHeaderHeight(sizingGC); if( previous != getHeaderHeight() ) { scrollValuesObsolete = true; redraw(); } } /** * Query the grid for all currently visible rows and columns * <p> * <b>This support is provisional and may change</b> * </p> * @return all currently visible rows and columns */ public GridVisibleRange getVisibleRange() { //FIXME I think we should remember the topIndex in the onPaint-method int topIndex = getTopIndex(); int bottomIndex = getBottomIndex(); int startColumnIndex = getStartColumnIndex(); int endColumnIndex = getEndColumnIndex(); GridVisibleRange range = new GridVisibleRange(); range.items = new GridItem[0]; range.columns = new GridColumn[0]; if( topIndex <= bottomIndex ) { if( items.size() > 0 ) { range.items = new GridItem[bottomIndex - topIndex + 1]; for( int i = topIndex; i <= bottomIndex; i++ ) { range.items[i - topIndex] = (GridItem) items.get(i); } } } if( startColumnIndex <= endColumnIndex ) { if( displayOrderedColumns.size() > 0 ) { ArrayList cols = new ArrayList(); for( int i = startColumnIndex; i <= endColumnIndex; i++ ) { GridColumn col = (GridColumn) displayOrderedColumns.get(i); if( col.isVisible() ) { cols.add(col); } } range.columns = new GridColumn[cols.size()]; cols.toArray(range.columns); } } return range; } int getStartColumnIndex() { checkWidget(); if( startColumnIndex != -1 ) { return startColumnIndex; } if( !hScroll.getVisible() ) { startColumnIndex = 0; } startColumnIndex = hScroll.getSelection(); return startColumnIndex; } int getEndColumnIndex() { checkWidget(); if( endColumnIndex != -1 ) { return endColumnIndex; } if( displayOrderedColumns.size() == 0 ) { endColumnIndex = 0; } else if( getVisibleGridWidth() < 1 ) { endColumnIndex = getStartColumnIndex(); } else { int x = 0; x -= getHScrollSelectionInPixels(); if (rowHeaderVisible) { //row header is actually painted later x += rowHeaderWidth; } int startIndex = getStartColumnIndex(); GridColumn[] columns = new GridColumn[displayOrderedColumns.size()]; displayOrderedColumns.toArray(columns); for (int i = startIndex; i < columns.length; i++) { endColumnIndex = i; GridColumn column = columns[i]; if (column.isVisible()) { x += column.getWidth(); } if (x > getClientArea().width) { break; } } } endColumnIndex = Math.max(0, endColumnIndex); return endColumnIndex; } void setSizeOnEveryItemImageChange(boolean sizeOnEveryItemImageChange) { this.sizeOnEveryItemImageChange = sizeOnEveryItemImageChange; } /** * Returns the width of the row headers. * * @return width of the column header row * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getRowHeaderWidth() { checkWidget(); return rowHeaderWidth; } /** * Sets the value of the auto-height feature. When enabled, this feature resizes the height of rows to * reflect the content of cells with word-wrapping enabled. Cell word-wrapping is enabled via the GridColumn.setWordWrap(boolean) method. * If column headers have word-wrapping enabled, this feature will also resize the height of the column headers as necessary. * @param enabled Set to true to enable this feature, false (default) otherwise. */ public void setAutoHeight(boolean enabled) { if (autoHeight == enabled) return; checkWidget(); autoHeight = enabled; setRowsResizeable(false); // turn of resizing of row height since it conflicts with this property redraw(); } /** * Returns the value of the auto-height feature, which resizes row heights and column header heights based on word-wrapped content. * @return Returns whether or not the auto-height feature is enabled. * @see #setAutoHeight(boolean) */ public boolean isAutoHeight() { return autoHeight; } /** * Sets the value of the auto-width feature. When enabled, this feature resizes the width of the row headers to * reflect the content of row headers. * @param enabled Set to true to enable this feature, false (default) otherwise. * @see #isAutoWidth() */ public void setAutoWidth(boolean enabled) { if (autoWidth == enabled) return; checkWidget(); autoWidth = enabled; redraw(); } /** * Returns the value of the auto-height feature, which resizes row header width based on content. * @return Returns whether or not the auto-width feature is enabled. * @see #setAutoWidth(boolean) */ public boolean isAutoWidth() { return autoWidth; } /** * Sets the value of the word-wrap feature for row headers. When enabled, this feature will word-wrap the contents of row headers. * @param enabled Set to true to enable this feature, false (default) otherwise. * @see #isWordWrapHeader() */ public void setWordWrapHeader(boolean enabled) { if (wordWrapRowHeader == enabled) return; checkWidget(); wordWrapRowHeader = enabled; redraw(); } /** * Returns the value of the row header word-wrap feature, which word-wraps the content of row headers. * @return Returns whether or not the row header word-wrap feature is enabled. * @see #setWordWrapHeader(boolean) */ public boolean isWordWrapHeader() { return wordWrapRowHeader; } }
338,421
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridItem.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridItem.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * Claes Rosell<[email protected]> - rowspan in bug 272384 * Stefan Widmaier<[email protected]> - rowspan in 304797 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.TypedListener; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A * PRE-RELEASE ALPHA VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE * VERSIONS. * </p> * Instances of this class represent a selectable user interface object that * represents an item in a grid. * <p> * <dl> * <dt><b>Styles:</b></dt> * <dd>(none)</dd> * <dt><b>Events:</b></dt> * <dd>(none)</dd> * </dl> * * @author [email protected] */ public class GridItem extends Item { /** * List of background colors for each column. */ private ArrayList backgrounds = new ArrayList(); /** * Lists of check states for each column. */ private ArrayList checks = new ArrayList(); /** * Lists of checkable states for each column. */ private ArrayList checkable = new ArrayList(); /** * List of children. */ private ArrayList children = new ArrayList(); /** * List of column spaning. */ private ArrayList columnSpans = new ArrayList(); /** * List of row spaning. */ private ArrayList rowSpans = new ArrayList(); /** * Default background color. */ private Color defaultBackground; /** * Default font. */ private Font defaultFont; /** * Default foreground color. */ private Color defaultForeground; /** * The height of this <code>GridItem</code>. */ private int height = 1; /** * Is expanded? */ private boolean expanded = false; /** * Lists of fonts for each column. */ private ArrayList fonts = new ArrayList(); /** * List of foreground colors for each column. */ private ArrayList foregrounds = new ArrayList(); /** * Lists of grayed (3rd check state) for each column. */ private ArrayList grayeds = new ArrayList(); /** * True if has children. */ private boolean hasChildren = false; /** * List of images for each column. */ private ArrayList images = new ArrayList(); /** * Level of item in a tree. */ private int level = 0; /** * Parent grid instance. */ private Grid parent; /** * Parent item (if a child item). */ private GridItem parentItem; /** * List of text for each column. */ private ArrayList texts = new ArrayList(); /** * List of tooltips for each column. */ private ArrayList tooltips = new ArrayList(); /** * Is visible? */ private boolean visible = true; /** * Row header text. */ private String headerText = null; /** * Row header image */ private Image headerImage = null; /** * Background color of the header */ private Color headerBackground = null; /** * Foreground color of the header */ public Color headerForeground = null; /** * (SWT.VIRTUAL only) Flag that specifies whether the client has already * been sent a SWT.SetData event. */ private boolean hasSetData = false; /** * Creates a new instance of this class and places the item at the end of * the grid. * * @param parent * parent grid * @param style * item style * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridItem(Grid parent, int style) { this(parent, style, -1); } /** * Creates a new instance of this class and places the item in the grid at * the given index. * * @param parent * parent grid * @param style * item style * @param index * index where to insert item * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridItem(Grid parent, int style, int index) { super(parent, style, index); this.parent = parent; init(); parent.newItem(this, index, true); parent.newRootItem(this, index); } /** * Creates a new instance of this class as a child node of the given * GridItem and places the item at the end of the parents items. * * @param parent * parent item * @param style * item style * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridItem(GridItem parent, int style) { this(parent, style, -1); } /** * Creates a new instance of this class as a child node of the given Grid * and places the item at the given index in the parent items list. * * @param parent * parent item * @param style * item style * @param index * index to place item * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed * subclass</li> * </ul> */ public GridItem(GridItem parent, int style, int index) { super(parent, style, index); parentItem = parent; this.parent = parentItem.getParent(); init(); this.parent.newItem(this, index, false); level = parentItem.getLevel() + 1; parentItem.newItem(this, index); if (parent.isVisible() && parent.isExpanded()) { setVisible(true); } else { setVisible(false); } } /** * {@inheritDoc} */ public void dispose() { if (!parent.isDisposing()) { parent.removeItem(this); if (parentItem != null) { parentItem.remove(this); } else { parent.removeRootItem(this); } for (int i = children.size() - 1; i >= 0; i--) { ((GridItem) children.get(i)).dispose(); } } super.dispose(); } /** * Adds the listener to the collection of listeners who will be notified * when the row is resized, by sending it one of the messages defined in the * <code>ControlListener</code> interface. * <p> * Clients who wish to override the standard row resize logic should use the * untyped listener mechanisms. The untyped <code>Event</code> object passed * to an untyped listener will have its <code>detail</code> field populated * with the new row height. Clients may alter this value to, for example, * enforce minimum or maximum row sizes. Clients may also set the * <code>doit</code> field to false to prevent the entire resize operation. * * @param listener * the listener which should be notified * * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not * called from the thread that created the receiver</li> * </ul> */ public void addControlListener(ControlListener listener) { checkWidget(); if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener(listener); addListener(SWT.Resize, typedListener); } /** * Removes the listener from the collection of listeners who will be * notified when the row is resized. * * @param listener * the listener which should no longer be notified * * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void removeControlListener(ControlListener listener) { checkWidget(); if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); removeListener(SWT.Resize, listener); } /** * Fires the given event type on the parent Grid instance. This method * should only be called from within a cell renderer. Any other use is not * intended. * * @param eventId * SWT event constant * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void fireEvent(int eventId) { checkWidget(); Event e = new Event(); e.display = getDisplay(); e.widget = this; e.item = this; e.type = eventId; getParent().notifyListeners(eventId, e); } /** * Fires the appropriate events in response to a user checking/unchecking an * item. Checking an item fires both a selection event (with event.detail of * SWT.CHECK) if the checkbox is in the first column and the seperate check * listener (all columns). This method manages that behavior. This method * should only be called from within a cell renderer. Any other use is not * intended. * * @param column * the column where the checkbox resides * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void fireCheckEvent(int column) { checkWidget(); Event selectionEvent = new Event(); selectionEvent.display = getDisplay(); selectionEvent.widget = this; selectionEvent.item = this; selectionEvent.type = SWT.Selection; selectionEvent.detail = SWT.CHECK; selectionEvent.index = column; getParent().notifyListeners(SWT.Selection, selectionEvent); } /** * Returns the receiver's background color. * * @return the background color * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Color getBackground() { checkWidget(); if (defaultBackground == null) { return parent.getBackground(); } return defaultBackground; } /** * Returns the background color at the given column index in the receiver. * * @param index * the column index * @return the background color * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Color getBackground(int index) { checkWidget(); handleVirtual(); Color c = (Color) backgrounds.get(index); // if (c == null) // { // c = getBackground(); // } return c; } /** * Returns a rectangle describing the receiver's size and location relative * to its parent at a column in the table. * * @param columnIndex * the index that specifies the column * @return the receiver's bounding column rectangle * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Rectangle getBounds(int columnIndex) { checkWidget(); // HACK: The -1000,-1000 xy coordinates below are a hack to deal with // GridEditor issues. In // normal SWT Table, when an editor is created on Table and its // positioned in the header area // the header overlays the editor. Because Grid (header and everything) // is drawn on one // composite, when an editor is positioned in the header area the editor // overlays the header. // So to fix this, when the editor is anywhere its not supposed to be // seen (the editor // coordinates are determined by this getBounds) we position it out in // timbuktu. if (!isVisible()) return new Rectangle(-1000, -1000, 0, 0); if (!parent.isShown(this)) return new Rectangle(-1000, -1000, 0, 0); Point origin = parent.getOrigin(parent.getColumn(columnIndex), this); if (origin.x < 0 && parent.isRowHeaderVisible()) return new Rectangle(-1000, -1000, 0, 0); Point cellSize = this.getCellSize(columnIndex); return new Rectangle(origin.x, origin.y, cellSize.x, cellSize.y); } /** * * @param columnIndex * @return width and height */ protected Point getCellSize(int columnIndex) { int width = 0; int span = getColumnSpan(columnIndex); for (int i = 0; i <= span; i++) { if (parent.getColumnCount() <= columnIndex + i) { break; } width += parent.getColumn(columnIndex + i).getWidth(); } int indexOfCurrentItem = parent.getIndexOfItem(this); GridItem item = parent.getItem(indexOfCurrentItem); int height = item.getHeight(); span = getRowSpan(columnIndex); for (int i = 1; i <= span; i++) { /* We will probably need another escape condition here */ if (parent.getItems().length <= indexOfCurrentItem + i) { break; } item = parent.getItem(indexOfCurrentItem + i); if (item.isVisible()) { height += item.getHeight() + 1; } } return new Point(width, height); } /** * Returns the checked state at the first column in the receiver. * * @return the checked state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getChecked() { checkWidget(); return getChecked(0); } /** * Returns the checked state at the given column index in the receiver. * * @param index * the column index * @return the checked state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getChecked(int index) { checkWidget(); handleVirtual(); Boolean b = (Boolean) checks.get(index); if (b == null) { return false; } return b.booleanValue(); } /** * Returns the column span for the given column index in the receiver. * * @param index * the column index * @return the number of columns spanned (0 equals no columns spanned) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getColumnSpan(int index) { checkWidget(); Integer i = (Integer) columnSpans.get(index); if (i == null) { return 0; } return i.intValue(); } /** * Returns the row span for the given column index in the receiver. * * @param index * the row index * @return the number of row spanned (0 equals no row spanned) * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getRowSpan(int index) { checkWidget(); if (index >= 0 && index < rowSpans.size()) { Integer i = (Integer) rowSpans.get(index); if (i != null) { return i.intValue(); } } return 0; } /** * Returns the font that the receiver will use to paint textual information * for this item. * * @return the receiver's font * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Font getFont() { if (defaultFont == null) { return parent.getFont(); } return defaultFont; } /** * Returns the font that the receiver will use to paint textual information * for the specified cell in this item. * * @param index * the column index * @return the receiver's font * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Font getFont(int index) { checkWidget(); handleVirtual(); Font f = (Font) fonts.get(index); if (f == null) { f = getFont(); } return f; } /** * Returns the foreground color that the receiver will use to draw. * * @return the receiver's foreground color * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Color getForeground() { if (defaultForeground == null) { return parent.getForeground(); } return defaultForeground; } /** * Returns the foreground color at the given column index in the receiver. * * @param index * the column index * @return the foreground color * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Color getForeground(int index) { checkWidget(); handleVirtual(); Color c = (Color) foregrounds.get(index); if (c == null) { c = getForeground(); } return c; } /** * Returns <code>true</code> if the first column in the receiver is grayed, * and false otherwise. When the GridColumn does not have the * <code>CHECK</code> style, return false. * * @return the grayed state of the checkbox * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getGrayed() { return getGrayed(0); } /** * Returns <code>true</code> if the column at the given index in the * receiver is grayed, and false otherwise. When the GridColumn does not * have the <code>CHECK</code> style, return false. * * @param index * the column index * @return the grayed state of the checkbox * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getGrayed(int index) { checkWidget(); handleVirtual(); Boolean b = (Boolean) grayeds.get(index); if (b == null) { return false; } return b.booleanValue(); } /** * Returns the height of this <code>GridItem</code>. * * @return height of this <code>GridItem</code> */ public int getHeight() { checkWidget(); return height; } /** * {@inheritDoc} */ public Image getImage() { checkWidget(); return getImage(0); } /** * Returns the image stored at the given column index in the receiver, or * null if the image has not been set or if the column does not exist. * * @param index * the column index * @return the image stored at the given column index in the receiver * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Image getImage(int index) { checkWidget(); handleVirtual(); return (Image) images.get(index); } /** * Returns the item at the given, zero-relative index in the receiver. * Throws an exception if the index is out of range. * * @param index * the index of the item to return * @return the item at the given index * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and * the number of elements in the list minus 1 (inclusive)</li> * </ul> * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public GridItem getItem(int index) { checkWidget(); return (GridItem) children.get(index); } /** * Returns the number of items contained in the receiver that are direct * item children of the receiver. * * @return the number of items * * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getItemCount() { checkWidget(); return children.size(); } /** * Searches the receiver's list starting at the first item (index 0) until * an item is found that is equal to the argument, and returns the index of * that item. If no item is found, returns -1. * * @param item * the search item * @return the index of the item * * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed * </li> * </ul> * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int indexOf(GridItem item) { checkWidget(); if (item == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); return children.indexOf(item); } /** * Returns a (possibly empty) array of <code>GridItem</code>s which are the * direct item children of the receiver. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the receiver's items * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public GridItem[] getItems() { return (GridItem[]) children.toArray(new GridItem[children.size()]); } /** * Returns the level of this item in the tree. * * @return the level of the item in the tree * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getLevel() { checkWidget(); return level; } /** * Returns the receiver's parent, which must be a <code>Grid</code>. * * @return the receiver's parent * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Grid getParent() { checkWidget(); return parent; } /** * Returns the receiver's parent item, which must be a <code>GridItem</code> * or null when the receiver is a root. * * @return the receiver's parent item * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public GridItem getParentItem() { checkWidget(); return parentItem; } /** * {@inheritDoc} */ public String getText() { checkWidget(); return getText(0); } /** * Returns the text stored at the given column index in the receiver, or * empty string if the text has not been set. * * @param index * the column index * @return the text stored at the given column index in the receiver * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public String getText(int index) { checkWidget(); handleVirtual(); String s = (String) texts.get(index); // SWT TableItem returns empty if never set // so we return empty to ensure API compatibility if (s == null) { return ""; } return s; } /** * Returns true if this item has children. * * @return true if this item has children * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean hasChildren() { checkWidget(); return hasChildren; } /** * Returns <code>true</code> if the receiver is expanded, and false * otherwise. * <p> * * @return the expanded state * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> <li>ERROR_THREAD_INVALID_ACCESS - if not called from * the thread that created the receiver</li> * </ul> */ public boolean isExpanded() { checkWidget(); return expanded; } /** * Sets the receiver's background color to the color specified by the * argument, or to the default system color for the item if the argument is * null. * * @param background * the new color (or null) * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been * disposed</li> * </ul> * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setBackground(Color background) { checkWidget(); if (background != null && background.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } defaultBackground = background; parent.redraw(); } /** * Sets the background color at the given column index in the receiver to * the color specified by the argument, or to the default system color for * the item if the argument is null. * * @param index * the column index * @param background * the new color (or null) * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been * disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setBackground(int index, Color background) { checkWidget(); if (background != null && background.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } backgrounds.set(index, background); parent.redraw(); } /** * Sets the checked state at the first column in the receiver. * * @param checked * the new checked state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setChecked(boolean checked) { checkWidget(); setChecked(0, checked); parent.redraw(); } /** * Sets the checked state at the given column index in the receiver. * * @param index * the column index * @param checked * the new checked state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setChecked(int index, boolean checked) { checkWidget(); checks.set(index, new Boolean(checked)); parent.redraw(); } /** * Sets the column spanning for the column at the given index to span the * given number of subsequent columns. * * @param index * column index that should span * @param span * number of subsequent columns to span * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setColumnSpan(int index, int span) { checkWidget(); columnSpans.set(index, new Integer(span)); parent.setHasSpanning(true); parent.redraw(); } /** * Sets the row spanning for the row at the given index to span the given * number of subsequent rows. * * @param index * row index that should span * @param span * number of subsequent rows to span * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setRowSpan(int index, int span) { checkWidget(); rowSpans.set(index, new Integer(span)); parent.setHasSpanning(true); parent.redraw(); } /** * Sets the expanded state of the receiver. * <p> * * @param expanded * the new expanded state * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> <li>ERROR_THREAD_INVALID_ACCESS - if not called from * the thread that created the receiver</li> * </ul> */ public void setExpanded(boolean expanded) { checkWidget(); this.expanded = expanded; // We must unselect any items that are becoming invisible // and thus if we change the selection we have to fire a selection event boolean unselected = false; for (Iterator itemIterator = children.iterator(); itemIterator .hasNext();) { GridItem item = (GridItem) itemIterator.next(); item.setVisible(expanded && visible); if (!expanded) { if (!getParent().getCellSelectionEnabled()) { if (getParent().isSelected(item)) { unselected = true; getParent().deselect(getParent().indexOf(item)); } if (deselectChildren(item)) { unselected = true; } } else { if (deselectCells(item)) { unselected = true; } } } } this.getParent().topIndex = -1; this.getParent().bottomIndex = -1; this.getParent().setScrollValuesObsolete(); if (unselected) { Event e = new Event(); e.item = this; getParent().notifyListeners(SWT.Selection, e); } if (getParent().getFocusItem() != null && !getParent().getFocusItem().isVisible()) { getParent().setFocusItem(this); } if (getParent().getCellSelectionEnabled()) { getParent().updateColumnSelection(); } } private boolean deselectCells(GridItem item) { boolean flag = false; int index = getParent().indexOf(item); GridColumn[] columns = getParent().getColumns(); for (int i = 0; i < columns.length; i++) { Point cell = new Point(getParent().indexOf(columns[i]), index); if (getParent().isCellSelected(cell)) { flag = true; getParent().deselectCell(cell); } } GridItem[] kids = item.getItems(); for (int i = 0; i < kids.length; i++) { if (deselectCells(kids[i])) { flag = true; } } return flag; } /** * Deselects the given item's children recursively. * * @param item * item to deselect children. * @return true if an item was deselected */ private boolean deselectChildren(GridItem item) { boolean flag = false; GridItem[] kids = item.getItems(); for (int i = 0; i < kids.length; i++) { if (getParent().isSelected(kids[i])) { flag = true; } getParent().deselect(getParent().indexOf(kids[i])); if (deselectChildren(kids[i])) { flag = true; } } return flag; } /** * Sets the font that the receiver will use to paint textual information for * this item to the font specified by the argument, or to the default font * for that kind of control if the argument is null. * * @param f * the new font (or null) * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been * disposed</li> * </ul> * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setFont(Font f) { checkWidget(); if (f != null && f.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } defaultFont = f; parent.redraw(); } /** * Sets the font that the receiver will use to paint textual information for * the specified cell in this item to the font specified by the argument, or * to the default font for that kind of control if the argument is null. * * @param index * the column index * @param font * the new font (or null) * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been * disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setFont(int index, Font font) { checkWidget(); if (font != null && font.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } fonts.set(index, font); parent.redraw(); } /** * Sets the receiver's foreground color to the color specified by the * argument, or to the default system color for the item if the argument is * null. * * @param foreground * the new color (or null) * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been * disposed</li> * </ul> * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setForeground(Color foreground) { checkWidget(); if (foreground != null && foreground.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } defaultForeground = foreground; parent.redraw(); } /** * Sets the foreground color at the given column index in the receiver to * the color specified by the argument, or to the default system color for * the item if the argument is null. * * @param index * the column index * @param foreground * the new color (or null) * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been * disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setForeground(int index, Color foreground) { checkWidget(); if (foreground != null && foreground.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } foregrounds.set(index, foreground); parent.redraw(); } /** * Sets the grayed state of the checkbox for the first column. This state * change only applies if the GridColumn was created with the SWT.CHECK * style. * * @param grayed * the new grayed state of the checkbox; * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setGrayed(boolean grayed) { checkWidget(); setGrayed(0, grayed); parent.redraw(); } /** * Sets the grayed state of the checkbox for the given column index. This * state change only applies if the GridColumn was created with the * SWT.CHECK style. * * @param index * the column index * @param grayed * the new grayed state of the checkbox; * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setGrayed(int index, boolean grayed) { checkWidget(); grayeds.set(index, new Boolean(grayed)); parent.redraw(); } /** * Sets the height of this <code>GridItem</code>. * * @param newHeight * new height in pixels * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setHeight(int newHeight) { checkWidget(); if (newHeight < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); height = newHeight; parent.hasDifferingHeights = true; if (isVisible()) { int myIndex = parent.indexOf(this); if (parent.getTopIndex() <= myIndex && myIndex <= parent.getBottomIndex()) // note: cannot use // Grid#isShown() // here, because // that returns // false for // partially shown // items parent.bottomIndex = -1; } parent.setScrollValuesObsolete(); parent.redraw(); } /** * Sets this <code>GridItem</code> to its preferred height. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void pack() { checkWidget(); int maxPrefHeight = 2; GridColumn[] columns = parent.getColumns(); GC gc = new GC(parent); for (int cnt = 0; cnt < columns.length; cnt++) { if (!columns[cnt].isVisible()) continue; // invisible columns do not affect item/row height GridCellRenderer renderer = columns[cnt].getCellRenderer(); renderer.setAlignment(columns[cnt].getAlignment()); renderer.setCheck(columns[cnt].isCheck()); renderer.setColumn(cnt); renderer.setTree(columns[cnt].isTree()); renderer.setWordWrap(columns[cnt].getWordWrap()); Point size = renderer.computeSize(gc, columns[cnt].getWidth(), SWT.DEFAULT, this); if (size != null) maxPrefHeight = Math.max(maxPrefHeight, size.y); } gc.dispose(); setHeight(maxPrefHeight); } /** * {@inheritDoc} */ public void setImage(Image image) { setImage(0, image); parent.redraw(); } /** * Sets the receiver's image at a column. * * @param index * the column index * @param image * the new image * @throws IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setImage(int index, Image image) { checkWidget(); if (image != null && image.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } images.set(index, image); parent.imageSetOnItem(index, this); parent.redraw(); } /** * Sets the receiver's text at a column. * * @param index * the column index * @param text * the new text * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the text is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setText(int index, String text) { checkWidget(); if (text == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } texts.set(index, text); parent.redraw(); } /** * {@inheritDoc} */ public void setText(String string) { setText(0, string); parent.redraw(); } /** * Adds items to the given list to ensure the list is large enough to hold a * value for each column. * * @param al * list */ private void ensureSize(ArrayList al) { int count = Math.max(1, parent.getColumnCount()); al.ensureCapacity(count); while (al.size() <= count) { al.add(null); } } /** * Removes the given child item from the list of children. * * @param child * child to remove */ private void remove(GridItem child) { children.remove(child); hasChildren = children.size() > 0; } /** * Returns true if the item is visible because its parent items are all * expanded. This method does not determine if the item is in the currently * visible range. * * @return Returns the visible. */ boolean isVisible() { return visible; } /** * Creates a new child item in this item at the given index. * * @param item * new child item * @param index * index */ void newItem(GridItem item, int index) { setHasChildren(true); if (index == -1) { children.add(item); } else { children.add(index, item); } } /** * Sets whether this item has children. * * @param hasChildren * true if this item has children */ void setHasChildren(boolean hasChildren) { this.hasChildren = hasChildren; } /** * Sets the visible state of this item. The visible state is determined by * the expansion state of all of its parent items. If all parent items are * expanded it is visible. * * @param visible * The visible to set. */ void setVisible(boolean visible) { if (this.visible == visible) { return; } this.visible = visible; if (visible) { parent.updateVisibleItems(1); } else { parent.updateVisibleItems(-1); } if (hasChildren) { boolean childrenVisible = visible; if (visible) { childrenVisible = expanded; } for (Iterator itemIterator = children.iterator(); itemIterator .hasNext();) { GridItem item = (GridItem) itemIterator.next(); item.setVisible(childrenVisible); } } } /** * Returns the receiver's row header text. If the text is <code>null</code> * the row header will display the row number. * * @return the text stored for the row header or code <code>null</code> if * the default has to be displayed * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public String getHeaderText() { checkWidget(); // handleVirtual(); return headerText; } /** * Returns the receiver's row header image. * * @return the image stored for the header or <code>null</code> if none has * to be displayed * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Image getHeaderImage() { checkWidget(); return headerImage; } /** * Returns the receiver's row header background color * * @return the color or <code>null</code> if none * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Color getHeaderBackground() { checkWidget(); return headerBackground; } /** * Returns the receiver's row header foreground color * * @return the color or <code>null</code> if none * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public Color getHeaderForeground() { checkWidget(); return headerForeground; } /** * Sets the receiver's row header text. If the text is <code>null</code> the * row header will display the row number. * * @param text * the new text * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the text is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setHeaderText(String text) { checkWidget(); // if (text == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (text != headerText) { GC gc = new GC(parent); int oldWidth = parent.getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).x; this.headerText = text; int newWidth = parent.getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).x; gc.dispose(); parent.recalculateRowHeaderWidth(this, oldWidth, newWidth); } parent.redraw(); } /** * Sets the receiver's row header image. If the image is <code>null</code> * none is shown in the header * * @param image * the new image * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setHeaderImage(Image image) { checkWidget(); // if (text == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); if (image != headerImage) { GC gc = new GC(parent); int oldWidth = parent.getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).x; int oldHeight = parent.getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).y; this.headerImage = image; int newWidth = parent.getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).x; int newHeight = parent.getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, this).y; gc.dispose(); parent.recalculateRowHeaderWidth(this, oldWidth, newWidth); parent.recalculateRowHeaderHeight(this, oldHeight, newHeight); } parent.redraw(); } /** * Set the new header background * * @param headerBackground * the color or <code>null</code> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setHeaderBackground(Color headerBackground) { checkWidget(); this.headerBackground = headerBackground; parent.redraw(); } /** * Set the new header foreground * * @param headerForeground * the color or <code>null</code> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setHeaderForeground(Color headerForeground) { checkWidget(); this.headerForeground = headerForeground; parent.redraw(); } /** * Returns the checkable state at the given column index in the receiver. If * the column at the given index is not checkable then this will return * false regardless of the individual cell's checkable state. * * @param index * the column index * @return the checked state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public boolean getCheckable(int index) { checkWidget(); if (!parent.getColumn(index).getCheckable()) return false; Boolean b = (Boolean) checkable.get(index); if (b == null) { return true; } return b.booleanValue(); } /** * Sets the checkable state at the given column index in the receiver. A * checkbox which is uncheckable will not be modifiable by the user but * still make be modified programmatically. If the column at the given index * is not checkable then individual cell will not be checkable regardless. * * @param index * the column index * @param checked * the new checked state * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setCheckable(int index, boolean checked) { checkWidget(); checkable.set(index, new Boolean(checked)); } /** * Returns the tooltip for the given cell. * * @param index * the column index * @return the tooltip * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public String getToolTipText(int index) { checkWidget(); handleVirtual(); String s = (String) tooltips.get(index); return s; } /** * Sets the tooltip for the given column index. * * @param index * the column index * @param tooltip * the tooltip text * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * </li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void setToolTipText(int index, String tooltip) { checkWidget(); tooltips.set(index, tooltip); } private void init() { ensureSize(backgrounds); ensureSize(checks); ensureSize(checkable); ensureSize(fonts); ensureSize(foregrounds); ensureSize(grayeds); ensureSize(images); ensureSize(texts); ensureSize(columnSpans); ensureSize(rowSpans); ensureSize(tooltips); } /** * Notifies the item that a column has been removed. * * @param index * index of column removed. */ void columnRemoved(int index) { removeValue(index, backgrounds); removeValue(index, checks); removeValue(index, checkable); removeValue(index, fonts); removeValue(index, foregrounds); removeValue(index, grayeds); removeValue(index, images); removeValue(index, texts); removeValue(index, columnSpans); removeValue(index, rowSpans); removeValue(index, tooltips); } void columnAdded(int index) { insertValue(index, backgrounds); insertValue(index, checks); insertValue(index, checkable); insertValue(index, fonts); insertValue(index, foregrounds); insertValue(index, grayeds); insertValue(index, images); insertValue(index, texts); insertValue(index, columnSpans); insertValue(index, rowSpans); insertValue(index, tooltips); hasSetData = false; } private void insertValue(int index, List list) { if (index == -1) { list.add(null); } else { list.add(index, null); } } private void removeValue(int index, List list) { if (list.size() > index) { list.remove(index); } } private void handleVirtual() { if ((getParent().getStyle() & SWT.VIRTUAL) != 0 && !hasSetData) { hasSetData = true; Event event = new Event(); event.item = this; if (parentItem == null) { event.index = getParent().indexOf(this); } else { event.index = parentItem.indexOf(this); } getParent().notifyListeners(SWT.SetData, event); } } /** * Sets the initial item height for this item. * * @param height * initial height. */ void initializeHeight(int height) { this.height = height; } /** * Clears all properties of this item and resets values to their defaults. * * @param allChildren * <code>true</code> if all child items should be cleared * recursively, and <code>false</code> otherwise */ void clear(boolean allChildren) { backgrounds.clear(); checks.clear(); checkable.clear(); columnSpans.clear(); rowSpans.clear(); fonts.clear(); foregrounds.clear(); grayeds.clear(); images.clear(); texts.clear(); tooltips.clear(); defaultForeground = null; defaultBackground = null; defaultFont = null; hasSetData = false; headerText = null; headerImage = null; headerBackground = null; headerForeground = null; // Recursively clear children if requested. if (allChildren) { for (int i = children.size() - 1; i >= 0; i--) { ((GridItem) children.get(i)).clear(true); } } init(); } }
60,507
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AbstractRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/AbstractRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * Base implementation of IRenderer. Provides management of a few values. * * @author [email protected] */ public abstract class AbstractRenderer implements IRenderer { /** Hover state. */ private boolean hover; /** Renderer has focus. */ private boolean focus; /** Mouse down on the renderer area. */ private boolean mouseDown; /** Selection state. */ private boolean selected; /** Expansion state. */ private boolean expanded; /** The bounds the renderer paints on. */ private Rectangle bounds = new Rectangle(0, 0, 0, 0); /** Display used to create GC to perform painting. */ private Display display; /** Dragging state. */ private boolean dragging; /** * Returns the bounds. * * @return Rectangle describing the bounds. */ public Rectangle getBounds() { return bounds; } /** * {@inheritDoc} */ public void setBounds(int x, int y, int width, int height) { setBounds(new Rectangle(x, y, width, height)); } /** * {@inheritDoc} */ public void setBounds(Rectangle bounds) { this.bounds = bounds; } /** * Returns the size. * * @return size of the renderer. */ public Point getSize() { return new Point(bounds.width, bounds.height); } /** * {@inheritDoc} */ public void setLocation(int x, int y) { setBounds(new Rectangle(x, y, bounds.width, bounds.height)); } /** * {@inheritDoc} */ public void setLocation(Point location) { setBounds(new Rectangle(location.x, location.y, bounds.width, bounds.height)); } /** * {@inheritDoc} */ public void setSize(int width, int height) { setBounds(new Rectangle(bounds.x, bounds.y, width, height)); } /** * {@inheritDoc} */ public void setSize(Point size) { setBounds(new Rectangle(bounds.x, bounds.y, size.x, size.y)); } /** * Returns a boolean value indicating if this renderer has focus. * * @return True/false if has focus. */ public boolean isFocus() { return focus; } /** * {@inheritDoc} */ public void setFocus(boolean focus) { this.focus = focus; } /** * Returns the hover state. * * @return Is the renderer in the hover state. */ public boolean isHover() { return hover; } /** * {@inheritDoc} */ public void setHover(boolean hover) { this.hover = hover; } /** * Returns the boolean value indicating if the renderer has the mouseDown * state. * * @return mouse down state. */ public boolean isMouseDown() { return mouseDown; } /** * {@inheritDoc} */ public void setMouseDown(boolean mouseDown) { this.mouseDown = mouseDown; } /** * Returns the boolean state indicating if the selected state is set. * * @return selected state. */ public boolean isSelected() { return selected; } /** * {@inheritDoc} */ public void setSelected(boolean selected) { this.selected = selected; } /** * Returns the expansion state. * * @return Returns the expanded. */ public boolean isExpanded() { return expanded; } /** * Sets the expansion state of this renderer. * * @param expanded The expanded to set. */ public void setExpanded(boolean expanded) { this.expanded = expanded; } /** * Sets the display for the renderer. * * @return Returns the display. */ public Display getDisplay() { return display; } /** * {@inheritDoc} */ public void setDisplay(Display display) { this.display = display; } }
4,899
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridEditor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridEditor.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ControlEditor; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * * A GridEditor is a manager for a Control that appears above a cell in a Grid * and tracks with the moving and resizing of that cell. It can be used to * display a text widget above a cell in a Grid so that the user can edit the * contents of that cell. It can also be used to display a button that can * launch a dialog for modifying the contents of the associated cell. * <p> * @see org.eclipse.swt.custom.TableEditor */ public class GridEditor extends ControlEditor { Grid table; GridItem item; int column = -1; ControlListener columnListener; Listener resizeListener; private Listener columnVisibleListener; private Listener columnGroupListener; private SelectionListener scrollListener; private TreeListener treeListener; /** * Creates a TableEditor for the specified Table. * * @param table the Table Control above which this editor will be displayed */ public GridEditor(final Grid table) { super(table); this.table = table; treeListener = new TreeListener () { final Runnable runnable = new Runnable() { public void run() { if (getEditor() == null || getEditor().isDisposed()) return; if (table.isDisposed()) return; layout(); getEditor().setVisible(true); } }; public void treeCollapsed(TreeEvent e) { if (getEditor() == null || getEditor().isDisposed ()) return; getEditor().setVisible(false); e.display.asyncExec(runnable); } public void treeExpanded(TreeEvent e) { if (getEditor() == null || getEditor().isDisposed ()) return; getEditor().setVisible(false); e.display.asyncExec(runnable); } }; table.addTreeListener(treeListener); columnListener = new ControlListener() { public void controlMoved(ControlEvent e) { layout(); } public void controlResized(ControlEvent e) { layout(); } }; columnVisibleListener = new Listener() { public void handleEvent(Event event) { getEditor().setVisible(((GridColumn)event.widget).isVisible()); if (getEditor().isVisible()) layout(); } }; resizeListener = new Listener() { public void handleEvent(Event event) { layout(); } }; scrollListener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { layout(); } public void widgetDefaultSelected(SelectionEvent e) { } }; columnGroupListener = new Listener() { public void handleEvent(Event event) { if (getEditor() == null || getEditor().isDisposed()) return; getEditor().setVisible(table.getColumn(getColumn()).isVisible()); if (getEditor().isVisible()) layout(); } }; // The following three listeners are workarounds for // Eclipse bug 105764 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=105764 table.addListener(SWT.Resize, resizeListener); if (table.getVerticalScrollBarProxy() != null) { table.getVerticalScrollBarProxy().addSelectionListener(scrollListener); } if (table.getHorizontalScrollBarProxy() != null) { table.getHorizontalScrollBarProxy().addSelectionListener(scrollListener); } // To be consistent with older versions of SWT, grabVertical defaults to // true grabVertical = true; } /** * Returns the bounds of the editor. * * @return bounds of the editor. */ protected Rectangle computeBounds() { if (item == null || column == -1 || item.isDisposed()) return new Rectangle(0, 0, 0, 0); Rectangle cell = item.getBounds(column); Rectangle area = table.getClientArea(); if (cell.x < area.x + area.width) { if (cell.x + cell.width > area.x + area.width) { cell.width = area.x + area.width - cell.x; } } Rectangle editorRect = new Rectangle(cell.x, cell.y, minimumWidth, minimumHeight); if (grabHorizontal) { editorRect.width = Math.max(cell.width, minimumWidth); } if (grabVertical) { editorRect.height = Math.max(cell.height, minimumHeight); } if (horizontalAlignment == SWT.RIGHT) { editorRect.x += cell.width - editorRect.width; } else if (horizontalAlignment == SWT.LEFT) { // do nothing - cell.x is the right answer } else { // default is CENTER editorRect.x += (cell.width - editorRect.width) / 2; } if (verticalAlignment == SWT.BOTTOM) { editorRect.y += cell.height - editorRect.height; } else if (verticalAlignment == SWT.TOP) { // do nothing - cell.y is the right answer } else { // default is CENTER editorRect.y += (cell.height - editorRect.height) / 2; } GridColumn c = table.getColumn(column); if( c != null && c.isTree() ) { int x = c.getCellRenderer().getTextBounds(item, false).x; editorRect.x += x; editorRect.width -= x; } return editorRect; } /** * Removes all associations between the TableEditor and the cell in the * table. The Table and the editor Control are <b>not</b> disposed. */ public void dispose() { if (!table.isDisposed() && this.column > -1 && this.column < table.getColumnCount()) { GridColumn tableColumn = table.getColumn(this.column); tableColumn.removeControlListener(columnListener); if (tableColumn.getColumnGroup() != null){ tableColumn.getColumnGroup().removeListener(SWT.Expand, columnGroupListener); tableColumn.getColumnGroup().removeListener(SWT.Collapse, columnGroupListener); } } if (!table.isDisposed()) { table.removeListener(SWT.Resize, resizeListener); if (table.getVerticalScrollBarProxy() != null) table.getVerticalScrollBarProxy().removeSelectionListener(scrollListener); if (table.getHorizontalScrollBarProxy() != null) table.getHorizontalScrollBarProxy().removeSelectionListener(scrollListener); } columnListener = null; resizeListener = null; table = null; item = null; column = -1; super.dispose(); } /** * Returns the zero based index of the column of the cell being tracked by * this editor. * * @return the zero based index of the column of the cell being tracked by * this editor */ public int getColumn() { return column; } /** * Returns the TableItem for the row of the cell being tracked by this * editor. * * @return the TableItem for the row of the cell being tracked by this * editor */ public GridItem getItem() { return item; } /** * Sets the zero based index of the column of the cell being tracked by this * editor. * * @param column the zero based index of the column of the cell being * tracked by this editor */ public void setColumn(int column) { int columnCount = table.getColumnCount(); // Separately handle the case where the table has no TableColumns. // In this situation, there is a single default column. if (columnCount == 0) { this.column = (column == 0) ? 0 : -1; layout(); return; } if (this.column > -1 && this.column < columnCount) { GridColumn tableColumn = table.getColumn(this.column); tableColumn.removeControlListener(columnListener); tableColumn.removeListener(SWT.Show, columnVisibleListener); tableColumn.removeListener(SWT.Hide, columnVisibleListener); this.column = -1; } if (column < 0 || column >= table.getColumnCount()) return; this.column = column; GridColumn tableColumn = table.getColumn(this.column); tableColumn.addControlListener(columnListener); tableColumn.addListener(SWT.Show, columnVisibleListener); tableColumn.addListener(SWT.Hide, columnVisibleListener); if (tableColumn.getColumnGroup() != null){ tableColumn.getColumnGroup().addListener(SWT.Expand, columnGroupListener); tableColumn.getColumnGroup().addListener(SWT.Collapse, columnGroupListener); } layout(); } /** * Sets the item that this editor will function over. * * @param item editing item. */ public void setItem(GridItem item) { this.item = item; layout(); } /** * Specify the Control that is to be displayed and the cell in the table * that it is to be positioned above. * <p> * Note: The Control provided as the editor <b>must</b> be created with its * parent being the Table control specified in the TableEditor constructor. * * @param editor the Control that is displayed above the cell being edited * @param item the TableItem for the row of the cell being tracked by this * editor * @param column the zero based index of the column of the cell being * tracked by this editor */ public void setEditor(Control editor, GridItem item, int column) { setItem(item); setColumn(column); setEditor(editor); layout(); } /** * {@inheritDoc} */ public void layout() { if (table.isDisposed()) return; if (item == null || item.isDisposed()) return; int columnCount = table.getColumnCount(); if (columnCount == 0 && column != 0) return; if (columnCount > 0 && (column < 0 || column >= columnCount)) return; boolean hadFocus = false; if (getEditor() == null || getEditor().isDisposed()) return; if (getEditor().getVisible()) { hadFocus = getEditor().isFocusControl(); } // this doesn't work because // resizing the column takes the focus away // before we get here getEditor().setBounds(computeBounds()); if (hadFocus) { if (getEditor() == null || getEditor().isDisposed()) return; getEditor().setFocus(); } } }
12,652
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridHeaderRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridHeaderRenderer.java
/******************************************************************************* * Copyright (c) 2008 BestSolution.at and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.graphics.Rectangle; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * The super class for all grid header renderers. Contains the properties specific * to a grid header. * * @author [email protected] */ public abstract class GridHeaderRenderer extends AbstractInternalWidget { private boolean wordWrap = false; /** * Returns the bounds of the text in the cell. This is used when displaying in-place tooltips. * If <code>null</code> is returned here, in-place tooltips will not be displayed. If the * <code>preferred</code> argument is <code>true</code> then the returned bounds should be large * enough to show the entire text. If <code>preferred</code> is <code>false</code> then the * returned bounds should be be relative to the current bounds. * * @param value the object being rendered. * @param preferred true if the preferred width of the text should be returned. * @return bounds of the text. */ public Rectangle getTextBounds(Object value, boolean preferred) { return null; } /** * Returns the bounds of the toggle within the header (typically only group headers have toggles) * or null. * * @return toggle bounds or null if no toggle exists. */ public Rectangle getToggleBounds() { return null; } /** * Returns the bounds of the control to display * * @return the bounds for the control or <code>null</code> if no control is * rendered */ protected Rectangle getControlBounds(Object value, boolean preferred) { return null; } /** * Returns whether or not text will be word-wrapped during the render * @return the wordWrap True if word wrapping is enabled */ public boolean isWordWrap() { return wordWrap; } /** * Sets whether or not text should be word-wrapped during the render * @param wordWrap True to wrap text, false otherwise */ public void setWordWrap(boolean wordWrap) { this.wordWrap = wordWrap; } }
2,911
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridDropTargetEffect.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/GridDropTargetEffect.java
package org.eclipse.nebula.widgets.grid; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEffect; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Widget; /** * This class provides a default drag under effect (eg. select, insert, scroll and expand) * when a drag occurs over a <code>Grid</code>. * * <p>Classes that wish to provide their own drag under effect for a <code>Grid</code> * can extend the <code>DropTargetAdapter</code> class and override any applicable methods * in <code>DropTargetAdapter</code> to display their own drag under effect.</p> * * Subclasses that override any methods of this class must call the corresponding * <code>super</code> method to get the default drag under effect implementation. * * <p>The feedback value is either one of the FEEDBACK constants defined in * class <code>DND</code> which is applicable to instances of this class, * or it must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>DND</code> effect constants. * </p> * <p> * <dl> * <dt><b>Feedback:</b></dt> * <dd>FEEDBACK_SELECT, FEEDBACK_INSERT_BEFORE, FEEDBACK_INSERT_AFTER, FEEDBACK_EXPAND, FEEDBACK_SCROLL</dd> * </dl> * </p><p> * Note: Only one of the styles FEEDBACK_SELECT, FEEDBACK_INSERT_BEFORE or * FEEDBACK_INSERT_AFTER may be specified. * </p> * * @see DropTargetAdapter * @see DropTargetEvent * * @since 3.3 * @author mark-oliver.reiser */ public class GridDropTargetEffect extends DropTargetEffect { static final int SCROLL_HYSTERESIS = 200; // milli seconds static final int EXPAND_HYSTERESIS = 1000; // milli seconds private Grid grid; private boolean ignoreCellSelection = false; private GridItem scrollItem; private long scrollBeginTime; private GridItem expandItem; private long expandBeginTime; private Point insertCell; private boolean insertBefore; private Point selectedCell; /** * Creates a new <code>GridDropTargetEffect</code> to handle the drag under effect on the specified * <code>Grid</code>. * * @param grid the <code>Grid</code> over which the user positions the cursor to drop the data */ public GridDropTargetEffect(Grid grid) { super(grid); this.grid = grid; } /** * Set this value to true to make drop feedback in <code>Grid</code> * always behave like the Grid was <em>not</em> in cell selection mode. * The default is false. * * <p>A value of true, means that for {@link DND#FEEDBACK_SELECT} full rows will * be selected instead of cells and for {@link DND#FEEDBACK_INSERT_AFTER} and * {@link DND#FEEDBACK_INSERT_BEFORE} the insert mark will span all columns. * * @param ignore */ public void setIgnoreCellSelection(boolean ignore) { ignoreCellSelection = ignore; } /** * * @return true if cell selection mode is ignored * @see #setIgnoreCellSelection(boolean) */ public boolean getIgnoreCellSelection() { return ignoreCellSelection; } int checkEffect(int effect) { // Some effects are mutually exclusive. Make sure that only one of the mutually exclusive effects has been specified. if ((effect & DND.FEEDBACK_SELECT) != 0) effect = effect & ~DND.FEEDBACK_INSERT_AFTER & ~DND.FEEDBACK_INSERT_BEFORE; if ((effect & DND.FEEDBACK_INSERT_BEFORE) != 0) effect = effect & ~DND.FEEDBACK_INSERT_AFTER; return effect; } /** * {@inheritDoc} */ public Widget getItem(int x, int y) { Point coordinates = new Point(x, y); coordinates = grid.toControl(coordinates); return grid.getItem(coordinates); } /** * This implementation of <code>dragEnter</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dragEnter</code>. * * Subclasses that override this method should call <code>super.dragEnter(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drag enter event * * @see DropTargetAdapter * @see DropTargetEvent */ public void dragEnter(DropTargetEvent event) { expandBeginTime = 0; expandItem = null; scrollBeginTime = 0; scrollItem = null; insertCell = null; selectedCell = null; } /** * This implementation of <code>dragLeave</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dragLeave</code>. * * Subclasses that override this method should call <code>super.dragLeave(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drag leave event * * @see DropTargetAdapter * @see DropTargetEvent */ public void dragLeave(DropTargetEvent event) { if (selectedCell != null) { deselect(selectedCell); selectedCell = null; } if (insertCell != null) { setInsertMark(null, false); insertCell = null; } expandBeginTime = 0; expandItem = null; scrollBeginTime = 0; scrollItem = null; } /** * This implementation of <code>dragOver</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dragOver</code>. * * Subclasses that override this method should call <code>super.dragOver(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drag over event * * @see DropTargetAdapter * @see DropTargetEvent * @see DND#FEEDBACK_SELECT * @see DND#FEEDBACK_INSERT_BEFORE * @see DND#FEEDBACK_INSERT_AFTER * @see DND#FEEDBACK_SCROLL * @see DND#FEEDBACK_EXPAND */ public void dragOver(DropTargetEvent event) { int effect = checkEffect(event.feedback); Point coordinates = new Point(event.x, event.y); coordinates = grid.toControl(coordinates); GridItem hoverItem = grid.getItem(coordinates); GridColumn hoverColumn = grid.getColumn(coordinates); Point hoverCell = grid.getCell(coordinates); if (hoverItem == null || hoverColumn == null || hoverCell == null) { hoverItem = null; hoverColumn = null; hoverCell = null; } // handle scrolling if ((effect & DND.FEEDBACK_SCROLL) == 0) { scrollBeginTime = 0; scrollItem = null; } else { if (hoverItem != null && scrollItem == hoverItem && scrollBeginTime != 0) { if (System.currentTimeMillis() >= scrollBeginTime) { GridItem topItem = grid.getItem(grid.getTopIndex()); GridItem nextItem = hoverItem == topItem ? grid.getPreviousVisibleItem(hoverItem) : grid.getNextVisibleItem(hoverItem); boolean scroll = nextItem != null && grid.isInDragScrollArea(coordinates); if (scroll) { grid.showItem(nextItem); } scrollBeginTime = 0; scrollItem = null; } } else { scrollBeginTime = System.currentTimeMillis() + SCROLL_HYSTERESIS; scrollItem = hoverItem; } } // handle expand if ((effect & DND.FEEDBACK_EXPAND) == 0) { expandBeginTime = 0; expandItem = null; } else { if (hoverItem != null && expandItem == hoverItem && expandBeginTime != 0) { if (System.currentTimeMillis() >= expandBeginTime) { if(hoverColumn.isTree() && !hoverItem.isExpanded()) { hoverItem.setExpanded(true); //Manually fire the expand event, otherwise if it hasn't been previously //expanded, you'll see the dummy child node instead of actual contents. //Also, if we don't check hasChildren and just fire the event, then the //content provider ends up being called and it asks for children of //something that says it doesn't have children. if (hoverItem.hasChildren()) { hoverItem.fireEvent(SWT.Expand); } } expandBeginTime = 0; expandItem = null; } } else { expandBeginTime = System.currentTimeMillis() + EXPAND_HYSTERESIS; expandItem = hoverItem; } } // handle select if ((effect & DND.FEEDBACK_SELECT) != 0 && hoverCell != null) { if (!hoverCell.equals(selectedCell)) { if (selectedCell != null) deselect(selectedCell); select(hoverCell); selectedCell = new Point(hoverCell.x,hoverCell.y); } } if ((effect & DND.FEEDBACK_SELECT) == 0 && selectedCell != null) { deselect(selectedCell); selectedCell = null; } // handle insert mark if ((effect & DND.FEEDBACK_INSERT_BEFORE) != 0 || (effect & DND.FEEDBACK_INSERT_AFTER) != 0) { boolean before = (effect & DND.FEEDBACK_INSERT_BEFORE) != 0; if (hoverCell != null) { if (!hoverCell.equals(insertCell) || before != insertBefore) { setInsertMark(hoverCell, before); } insertCell = new Point(hoverCell.x,hoverCell.y); insertBefore = before; } else { if (insertCell != null) { setInsertMark(null, false); } insertCell = null; } } else { if (insertCell != null) { setInsertMark(null, false); } insertCell = null; } } private void select(Point cell) { if(grid.getCellSelectionEnabled() && !ignoreCellSelection) grid.selectCell(cell); else grid.select(cell.y); } private void deselect(Point cell) { if(grid.getCellSelectionEnabled() && !ignoreCellSelection) grid.deselectCell(cell); else grid.deselect(cell.y); } private void setInsertMark(Point cell, boolean before) { if(cell!=null) { if(grid.getCellSelectionEnabled() && !ignoreCellSelection) grid.setInsertMark(grid.getItem(cell.y), grid.getColumn(cell.x), before); else grid.setInsertMark(grid.getItem(cell.y), null, before); } else { grid.setInsertMark(null, null, false); } } }
9,979
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultInsertMarkRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultInsertMarkRenderer.java
package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; /** * A renderer which paints the insert mark feedback during drag & drop. * * @author mark-olver.reiser * @since 3.3 */ public class DefaultInsertMarkRenderer extends AbstractRenderer { /** * Renders the insertion mark. The bounds of the renderer * need not be set. * * @param gc * @param value must be a {@link Rectangle} with height == 0. */ public void paint(GC gc, Object value) { Rectangle r = (Rectangle)value; gc.setLineStyle(SWT.LINE_SOLID); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.drawLine(r.x, r.y-1, r.x+r.width, r.y-1); gc.drawLine(r.x, r.y , r.x+r.width, r.y ); gc.drawLine(r.x, r.y+1, r.x+r.width, r.y+1); gc.drawLine(r.x-1, r.y-2, r.x-1, r.y+2); gc.drawLine(r.x-2, r.y-3, r.x-2, r.y+3); } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(9, 7); } }
1,260
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultBottomLeftRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultBottomLeftRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The renderer for the empty top left area when both column and row headers are * visible. * * @author [email protected] * @since 2.0.0 */ public class DefaultBottomLeftRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(wHint, hHint); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor( SWT.COLOR_WIDGET_BACKGROUND)); gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height + 1); gc.setForeground(getDisplay().getSystemColor( SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x, getBounds().y, getBounds().x + getBounds().width, getBounds().y); } }
1,555
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultEmptyColumnFooterRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultEmptyColumnFooterRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * A renderer for the last empty column header. * * @author [email protected] * @since 2.0.0 */ public class DefaultEmptyColumnFooterRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(wHint, hHint); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width + 1, getBounds().height + 1); gc.drawLine(getBounds().x, getBounds().y, getBounds().x + getBounds().width, getBounds().y); } }
1,526
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultColumnHeaderRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultColumnHeaderRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 * Marty Jones<[email protected]> - custom header/footer font in bug 293743 *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridHeaderRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.widgets.Display; /** * The column header renderer. * * @author [email protected] * @since 2.0.0 */ public class DefaultColumnHeaderRenderer extends GridHeaderRenderer { int leftMargin = 6; int rightMargin = 6; int topMargin = 3; int bottomMargin = 3; int arrowMargin = 6; int imageSpacing = 3; private SortArrowRenderer arrowRenderer = new SortArrowRenderer(); private TextLayout textLayout; /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridColumn column = (GridColumn)value; gc.setFont(column.getHeaderFont()); int x = leftMargin; int y = topMargin + gc.getFontMetrics().getHeight() + bottomMargin; if (column.getImage() != null) { x += column.getImage().getBounds().width + imageSpacing; y = Math.max(y, topMargin + column.getImage().getBounds().height + bottomMargin); } if (!isWordWrap()) { x += gc.stringExtent(column.getText()).x + rightMargin; } else { int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin; else plainTextWidth = wHint - x - rightMargin; getTextLayout(gc, column); textLayout.setText(column.getText()); textLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; int textHeight = topMargin; textHeight += textLayout.getBounds().height; textHeight += bottomMargin; y = Math.max(y, textHeight); } y += computeControlSize(column).y; return new Point(x, y); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridColumn column = (GridColumn)value; // set the font to be used to display the text. gc.setFont(column.getHeaderFont()); boolean flat = (column.getParent().getCellSelectionEnabled() && !column.getMoveable()); boolean drawSelected = ((isMouseDown() && isHover())); gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); if (flat && isSelected()) { gc.setBackground(column.getParent().getCellHeaderSelectionBackground()); } gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); int pushedDrawingOffset = 0; if (drawSelected) { pushedDrawingOffset = 1; } int x = leftMargin; if (column.getImage() != null) { int y = bottomMargin; if( column.getHeaderControl() == null ) { y = getBounds().y + pushedDrawingOffset + getBounds().height - bottomMargin - column.getImage().getBounds().height; } gc.drawImage(column.getImage(), getBounds().x + x + pushedDrawingOffset, y); x += column.getImage().getBounds().width + imageSpacing; } int width = getBounds().width - x; if (column.getSort() == SWT.NONE) { width -= rightMargin; } else { width -= arrowMargin + arrowRenderer.getSize().x + arrowMargin; } gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); int y = bottomMargin; if( column.getHeaderControl() == null ) { y = getBounds().y + getBounds().height - bottomMargin - gc.getFontMetrics().getHeight(); } else { y = getBounds().y + getBounds().height - bottomMargin - gc.getFontMetrics().getHeight() - computeControlSize(column).y; } String text = column.getText(); if (!isWordWrap()) { text = TextUtils.getShortString(gc, text, width); //y -= gc.getFontMetrics().getHeight(); } if (column.getAlignment() == SWT.RIGHT) { int len = gc.stringExtent(text).x; if (len < width) { x += width - len; } } else if (column.getAlignment() == SWT.CENTER) { int len = gc.stringExtent(text).x; if (len < width) { x += (width - len) / 2; } } if (!isWordWrap()) { gc.drawString(text, getBounds().x + x + pushedDrawingOffset, y + pushedDrawingOffset,true); } else { getTextLayout(gc, column); textLayout.setWidth(width < 1 ? 1 : width); textLayout.setText(text); y -= textLayout.getBounds().height; if (column.getParent().isAutoHeight()) { column.getParent().recalculateHeader(); } textLayout.draw(gc, getBounds().x + x + pushedDrawingOffset, y + pushedDrawingOffset); } if (column.getSort() != SWT.NONE) { if( column.getHeaderControl() == null ) { y = getBounds().y + ((getBounds().height - arrowRenderer.getBounds().height) / 2) + 1; } else { y = getBounds().y + ((getBounds().height - computeControlSize(column).y - arrowRenderer.getBounds().height) / 2) + 1; } arrowRenderer.setSelected(column.getSort() == SWT.UP); if (drawSelected) { arrowRenderer .setLocation( getBounds().x + getBounds().width - arrowMargin - arrowRenderer.getBounds().width + 1,y ); } else { if( column.getHeaderControl() == null ) { y = getBounds().y + ((getBounds().height - arrowRenderer.getBounds().height) / 2); } else { y = getBounds().y + ((getBounds().height - computeControlSize(column).y - arrowRenderer.getBounds().height) / 2); } arrowRenderer .setLocation( getBounds().x + getBounds().width - arrowMargin - arrowRenderer.getBounds().width,y); } arrowRenderer.paint(gc, null); } if (!flat) { if (drawSelected) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); } gc.drawLine(getBounds().x, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y); gc.drawLine(getBounds().x, getBounds().y, getBounds().x, getBounds().y + getBounds().height - 1); if (!drawSelected) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW)); gc.drawLine(getBounds().x + 1, getBounds().y + 1, getBounds().x + getBounds().width - 2, getBounds().y + 1); gc.drawLine(getBounds().x + 1, getBounds().y + 1, getBounds().x + 1, getBounds().y + getBounds().height - 2); } if (drawSelected) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); if (!drawSelected) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 2, getBounds().y + 1, getBounds().x + getBounds().width - 2, getBounds().y + getBounds().height - 2); gc.drawLine(getBounds().x + 1, getBounds().y + getBounds().height - 2, getBounds().x + getBounds().width - 2, getBounds().y + getBounds().height - 2); } } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); } } /** * {@inheritDoc} */ public void setDisplay(Display display) { super.setDisplay(display); arrowRenderer.setDisplay(display); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { return false; } /** * {@inheritDoc} */ public Rectangle getTextBounds(Object value, boolean preferred) { GridColumn column = (GridColumn)value; int x = leftMargin; if (column.getImage() != null) { x += column.getImage().getBounds().width + imageSpacing; } GC gc = new GC(column.getParent()); gc.setFont(column.getParent().getFont()); int y = getBounds().height - bottomMargin - gc.getFontMetrics().getHeight(); Rectangle bounds = new Rectangle(x,y,0,0); Point p = gc.stringExtent(column.getText()); bounds.height = p.y; if (preferred) { bounds.width = p.x; } else { int width = getBounds().width - x; if (column.getSort() == SWT.NONE) { width -= rightMargin; } else { width -= arrowMargin + arrowRenderer.getSize().x + arrowMargin; } bounds.width = width; } gc.dispose(); return bounds; } /** * @return the bounds reserved for the control */ protected Rectangle getControlBounds(Object value, boolean preferred) { Rectangle bounds = getBounds(); GridColumn column = (GridColumn) value; Point controlSize = computeControlSize(column); int y = getBounds().y + getBounds().height - bottomMargin - controlSize.y; return new Rectangle(bounds.x+3,y,bounds.width-6,controlSize.y); } private Point computeControlSize(GridColumn column) { if( column.getHeaderControl() != null ) { return column.getHeaderControl().computeSize(SWT.DEFAULT, SWT.DEFAULT); } return new Point(0,0); } private void getTextLayout(GC gc, GridColumn column) { if (textLayout == null) { textLayout = new TextLayout(gc.getDevice()); textLayout.setFont(gc.getFont()); column.getParent().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { textLayout.dispose(); } }); } textLayout.setAlignment(column.getAlignment()); } }
13,490
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultRowHeaderRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultRowHeaderRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.TextLayout; /** * The row header renderer. * * @author [email protected] * @since 2.0.0 */ public class DefaultRowHeaderRenderer extends AbstractRenderer { int leftMargin = 6; int rightMargin = 8; int topMargin = 3; int bottomMargin = 3; private TextLayout textLayout; /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem) value; String text = getHeaderText(item); gc.setFont(getDisplay().getSystemFont()); Color background = getHeaderBackground(item); if( background == null ) { background = getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); } gc.setBackground(background); if (isSelected() && item.getParent().getCellSelectionEnabled()) { gc.setBackground(item.getParent().getCellHeaderSelectionBackground()); } gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height + 1); if (!item.getParent().getCellSelectionEnabled()) { if (isSelected()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); } gc.drawLine(getBounds().x, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y); gc.drawLine(getBounds().x, getBounds().y, getBounds().x, getBounds().y + getBounds().height - 1); if (!isSelected()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW)); gc.drawLine(getBounds().x + 1, getBounds().y + 1, getBounds().x + getBounds().width - 2, getBounds().y + 1); gc.drawLine(getBounds().x + 1, getBounds().y + 1, getBounds().x + 1, getBounds().y + getBounds().height - 2); } if (isSelected()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); if (!isSelected()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 2, getBounds().y + 1, getBounds().x + getBounds().width - 2, getBounds().y + getBounds().height - 2); gc.drawLine(getBounds().x + 1, getBounds().y + getBounds().height - 2, getBounds().x + getBounds().width - 2, getBounds().y + getBounds().height - 2); } } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); } int x = leftMargin; Image image = getHeaderImage(item); if( image != null ) { if( isSelected() && !item.getParent().getCellSelectionEnabled() ) { gc.drawImage(image, x + 1, getBounds().y + 1 + (getBounds().height - image.getBounds().height)/2); x += 1; } else { gc.drawImage(image, x, getBounds().y + (getBounds().height - image.getBounds().height)/2); } x += image.getBounds().width + 5; } int width = getBounds().width - x; width -= rightMargin; Color foreground = getHeaderForeground(item); if( foreground == null ) { foreground = getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND); } gc.setForeground(foreground); int y = getBounds().y; int selectionOffset = 0; if (isSelected() && !item.getParent().getCellSelectionEnabled()) { selectionOffset = 1; } if (!item.getParent().isWordWrapHeader()) { y += (getBounds().height - gc.stringExtent(text).y) / 2; gc.drawString(TextUtils.getShortString(gc, text, width), getBounds().x + x + selectionOffset, y + selectionOffset, true); } else { getTextLayout(gc, item); textLayout.setWidth(width < 1 ? 1 : width); textLayout.setText(text); if (item.getParent().isAutoHeight()) { // Look through all columns to get the max height needed for this item int columnCount = item.getParent().getColumnCount(); int maxHeight = textLayout.getBounds().height + topMargin + bottomMargin; for (int i=0; i<columnCount; i++) { GridColumn column = item.getParent().getColumn(i); if (column.getWordWrap()) { int height = column.getCellRenderer().computeSize(gc, column.getWidth(), SWT.DEFAULT, item).y; maxHeight = Math.max(maxHeight, height); } } if (maxHeight != item.getHeight()) { item.setHeight(maxHeight); } } textLayout.draw(gc, getBounds().x + x + selectionOffset, y + selectionOffset); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridItem item = (GridItem) value; String text = getHeaderText(item); Image image = getHeaderImage(item); int x = 0; x += leftMargin; if( image != null ) { x += image.getBounds().width + 5; } x += gc.stringExtent(text).x + rightMargin; int y = 0; y += topMargin; if( image != null ) { y += Math.max(gc.getFontMetrics().getHeight(),image.getBounds().height); } else { y += gc.getFontMetrics().getHeight(); } y += bottomMargin; return new Point(x, y); } private Image getHeaderImage(GridItem item) { return item.getHeaderImage(); } private String getHeaderText(GridItem item) { String text = item.getHeaderText(); if (text == null) { text = (item.getParent().indexOf(item) + 1) + ""; } return text; } private Color getHeaderBackground(GridItem item) { return item.getHeaderBackground(); } private Color getHeaderForeground(GridItem item) { return item.getHeaderForeground(); } private void getTextLayout(GC gc, GridItem gridItem) { if (textLayout == null) { textLayout = new TextLayout(gc.getDevice()); textLayout.setFont(gc.getFont()); gridItem.getParent().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { textLayout.dispose(); } }); } } }
9,606
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultFocusRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultFocusRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The focus item renderer - renders over the completely drawn table. * * @author [email protected] * @since 2.0.0 */ public class DefaultFocusRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem)value; if (item.getParent().isSelected(item)) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT)); } else { gc.setBackground(item.getBackground()); gc.setForeground(item.getForeground()); } gc.drawFocus(getBounds().x, getBounds().y, getBounds().width + 1, getBounds().height + 1); } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return null; } }
1,758
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IScrollBarProxy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/IScrollBarProxy.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Event; /** * Used by Grid to externalize the scrollbars from the table itself. * * @author [email protected] * @version 1.0.0 */ public interface IScrollBarProxy { /** * Returns the scrollbar's visibility. * * @return true if the scrollbar is visible. */ public boolean getVisible(); /** * Sets the scrollbar's visibility. * * @param visible visibilty */ public void setVisible(boolean visible); /** * Returns the selection. * * @return the selection. */ public int getSelection(); /** * Sets the selection. * * @param selection selection to set */ public void setSelection(int selection); /** * Sets the receiver's selection, minimum value, maximum value, thumb, * increment and page increment all at once. * * @param selection selection * @param min minimum * @param max maximum * @param thumb thumb * @param increment increment * @param pageIncrement page increment */ public void setValues(int selection, int min, int max, int thumb, int increment, int pageIncrement); /** * @param e */ public void handleMouseWheel(Event e); /** * @param min */ public void setMinimum(int min); /** * @return min */ public int getMinimum(); /** * @param max */ public void setMaximum(int max); /** * @return max */ public int getMaximum(); /** * @param thumb */ public void setThumb(int thumb); /** * @return thumb */ public int getThumb(); /** * @param increment */ public void setIncrement(int increment); /** * @return increment */ public int getIncrement(); /** * @param page */ public void setPageIncrement(int page); /** * @return page increment */ public int getPageIncrement(); /** * @param listener */ public void addSelectionListener(SelectionListener listener); /** * @param listener */ public void removeSelectionListener(SelectionListener listener); }
2,940
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultDropPointRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultDropPointRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * A renderer which displays the drop point location affordance when dragging columns. * * @author [email protected] * @since 2.0.0 */ public class DefaultDropPointRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); gc.fillPolygon(new int[] {getBounds().x + 0, getBounds().y + 4, getBounds().x + 4, getBounds().y + 0, getBounds().x + 8, getBounds().y + 4, getBounds().x + 7, getBounds().y + 5, getBounds().x + 6, getBounds().y + 5, getBounds().x + 4, getBounds().y + 3, getBounds().x + 2, getBounds().y + 5, getBounds().x + 1, getBounds().y + 5 }); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.drawPolyline(new int[] {getBounds().x + 0, getBounds().y + 4, getBounds().x + 4, getBounds().y + 0, getBounds().x + 8, getBounds().y + 4, getBounds().x + 7, getBounds().y + 5, getBounds().x + 6, getBounds().y + 5, getBounds().x + 4, getBounds().y + 3, getBounds().x + 2, getBounds().y + 5, getBounds().x + 1, getBounds().y + 5 }); } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(9, 7); } }
2,422
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultTopLeftRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultTopLeftRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The renderer for the empty top left area when both column and row headers are visible. * * @author [email protected] * @since 2.0.0 */ public class DefaultTopLeftRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(wHint, hHint); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width - 1, getBounds().height + 1); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width, getBounds().y + getBounds().height - 1); } }
2,029
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TextUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/TextUtils.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.swt.graphics.GC; /** * Utility class to provide common operations on strings not supported by the * base java API. * * @author [email protected] * @since 2.0.0 */ public class TextUtils { /** * Shortens a supplied string so that it fits within the area specified by * the width argument. Strings that have been shorted have an "..." attached * to the end of the string. The width is computed using the * {@link GC#textExtent(String)}. * * @param gc GC used to perform calculation. * @param t text to modify. * @param width Pixels to display. * @return shortened string that fits in area specified. */ public static String getShortText(GC gc, String t, int width) { if (t == null) { return null; } if (t.equals("")) { return ""; } if (width >= gc.textExtent(t).x) { return t; } int w = gc.textExtent("...").x; String text = t; int l = text.length(); int pivot = l / 2; int s = pivot; int e = pivot + 1; while (s >= 0 && e < l) { String s1 = text.substring(0, s); String s2 = text.substring(e, l); int l1 = gc.textExtent(s1).x; int l2 = gc.textExtent(s2).x; if (l1 + w + l2 < width) { text = s1 + "..." + s2; break; } s--; e++; } if (s == 0 || e == l) { text = text.substring(0, 1) + "..." + text.substring(l - 1, l); } return text; } /** * Shortens a supplied string so that it fits within the area specified by * the width argument. Strings that have been shorted have an "..." attached * to the end of the string. The width is computed using the * {@link GC#stringExtent(String)}. * * @param gc GC used to perform calculation. * @param t text to modify. * @param width Pixels to display. * @return shortened string that fits in area specified. */ public static String getShortString(GC gc, String t, int width) { if (t == null) { return null; } if (t.equals("")) { return ""; } if (width >= gc.stringExtent(t).x) { return t; } int w = gc.stringExtent("...").x; String text = t; int l = text.length(); int pivot = l / 2; int s = pivot; int e = pivot + 1; while (s >= 0 && e < l) { String s1 = text.substring(0, s); String s2 = text.substring(e, l); int l1 = gc.stringExtent(s1).x; int l2 = gc.stringExtent(s2).x; if (l1 + w + l2 < width) { text = s1 + "..." + s2; break; } s--; e++; } if (s == 0 || e == l) { text = text.substring(0, 1) + "..." + text.substring(l - 1, l); } return text; } /** * Protected constructor to prevent instantiation. */ protected TextUtils() { } }
3,903
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SortArrowRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/SortArrowRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The column header sort arrow renderer. * * @author [email protected] * @since 2.0.0 */ public class SortArrowRenderer extends AbstractRenderer { /** * Default constructor. */ public SortArrowRenderer() { super(); setSize(7, 4); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); if (isSelected()) { gc .drawLine(getBounds().x + 0, getBounds().y + 0, getBounds().x + 6, getBounds().y + 00); gc.drawLine(getBounds().x + 1, getBounds().y + 01, getBounds().x + 5, getBounds().y + 01); gc.drawLine(getBounds().x + 2, getBounds().y + 02, getBounds().x + 4, getBounds().y + 02); gc.drawPoint(getBounds().x + 3, getBounds().y + 03); } else { gc.drawPoint(getBounds().x + 3, getBounds().y + 0); gc.drawLine(getBounds().x + 2, getBounds().y + 01, getBounds().x + 4, getBounds().y + 01); gc.drawLine(getBounds().x + 1, getBounds().y + 02, getBounds().x + 5, getBounds().y + 02); gc.drawLine(getBounds().x + 0, getBounds().y + 03, getBounds().x + 6, getBounds().y + 03); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(7, 4); } }
2,372
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GroupToggleRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/GroupToggleRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The renderer for the expand/collapse toggle on a column group header. * * @author [email protected] * @since 2.0.0 */ public class GroupToggleRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.fillArc(getBounds().x, getBounds().y, 8, getBounds().height + -1, 90, 180); gc.drawArc(getBounds().x, getBounds().y, 8, getBounds().height + -1, 90, 180); gc.fillRectangle(getBounds().x + 4, getBounds().y, getBounds().width - 4, getBounds().height); int yMid = ((getBounds().height - 1) / 2); if (isHover()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); } if (isExpanded()) { gc.drawLine(getBounds().x + 5, getBounds().y + yMid, getBounds().x + 8, getBounds().y + yMid - 3); gc.drawLine(getBounds().x + 6, getBounds().y + yMid, getBounds().x + 8, getBounds().y + yMid - 2); gc.drawLine(getBounds().x + 5, getBounds().y + yMid, getBounds().x + 8, getBounds().y + yMid + 3); gc.drawLine(getBounds().x + 6, getBounds().y + yMid, getBounds().x + 8, getBounds().y + yMid + 2); gc.drawLine(getBounds().x + 9, getBounds().y + yMid, getBounds().x + 12, getBounds().y + yMid - 3); gc.drawLine(getBounds().x + 10, getBounds().y + yMid, getBounds().x + 12, getBounds().y + yMid - 2); gc.drawLine(getBounds().x + 9, getBounds().y + yMid, getBounds().x + 12, getBounds().y + yMid + 3); gc.drawLine(getBounds().x + 10, getBounds().y + yMid, getBounds().x + 12, getBounds().y + yMid + 2); } else { gc.drawLine(getBounds().x + getBounds().width - 5, getBounds().y + yMid, getBounds().x + getBounds().width - 8, getBounds().y + yMid - 3); gc.drawLine(getBounds().x + getBounds().width - 6, getBounds().y + yMid, getBounds().x + getBounds().width - 8, getBounds().y + yMid - 2); gc.drawLine(getBounds().x + getBounds().width - 5, getBounds().y + yMid, getBounds().x + getBounds().width - 8, getBounds().y + yMid + 3); gc.drawLine(getBounds().x + getBounds().width - 6, getBounds().y + yMid, getBounds().x + getBounds().width - 8, getBounds().y + yMid + 2); gc.drawLine(getBounds().x + getBounds().width - 9, getBounds().y + yMid, getBounds().x + getBounds().width - 12, getBounds().y + yMid - 3); gc.drawLine(getBounds().x + getBounds().width - 10, getBounds().y + yMid, getBounds().x + getBounds().width - 12, getBounds().y + yMid - 2); gc.drawLine(getBounds().x + getBounds().width - 9, getBounds().y + yMid, getBounds().x + getBounds().width - 12, getBounds().y + yMid + 3); gc.drawLine(getBounds().x + getBounds().width - 10, getBounds().y + yMid, getBounds().x + getBounds().width - 12, getBounds().y + yMid + 2); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(0, 0); } }
5,043
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridToolTip.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/GridToolTip.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Widget; /** * An in-place tooltip. * * @author cgross */ public class GridToolTip extends Widget { private Shell shell; private String text; private int ymargin = 2; private int xmargin = 3; /** * Creates an inplace tooltip. * * @param parent parent control. */ public GridToolTip(final Control parent) { super(parent, SWT.NONE); shell = new Shell(parent.getShell(), SWT.NO_TRIM | SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL); shell.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); shell.setForeground(shell.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); parent.addListener(SWT.Dispose, new Listener() { public void handleEvent(Event arg0) { shell.dispose(); dispose(); } }); shell.addListener(SWT.Paint, new Listener() { public void handleEvent(Event e) { onPaint(e.gc); } }); } /** * Paints the tooltip. * * @param gc */ private void onPaint(GC gc) { gc.drawRectangle(0, 0, shell.getSize().x - 1, shell.getSize().y - 1); gc.drawString(text, xmargin, ymargin, true); } /** * Sets the location of the tooltip. * * @param location */ public void setLocation(Point location) { shell.setLocation(location.x - xmargin, location.y - ymargin); } /** * Shows or hides the tooltip. * * @param visible */ public void setVisible(boolean visible) { if (visible && shell.getVisible()) { shell.redraw(); } else { shell.setVisible(visible); } } /** * @param font */ public void setFont(Font font) { shell.setFont(font); } /** * @return the text */ public String getText() { return text; } /** * @param text the text to set */ public void setText(String text) { this.text = text; GC gc = new GC(shell); Point size = gc.stringExtent(text); gc.dispose(); size.x += xmargin + xmargin; size.y += ymargin + ymargin; shell.setSize(size); } /** * {@inheritDoc} */ protected void checkSubclass() { } }
3,332
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultColumnFooterRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultColumnFooterRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * Marty Jones<[email protected]> - custom header/footer font in bug 293743 *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridFooterRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; /** * The column footer renderer. * * @author Tom Schindl - [email protected] * @since 2.0.0 */ public class DefaultColumnFooterRenderer extends GridFooterRenderer { int leftMargin = 6; int rightMargin = 6; int topMargin = 3; int bottomMargin = 3; int arrowMargin = 6; int imageSpacing = 3; /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridColumn column = (GridColumn)value; gc.setFont(column.getFooterFont()); int x = 0; x += leftMargin; x += gc.stringExtent(column.getText()).x + rightMargin; int y = 0; y += topMargin; y += gc.getFontMetrics().getHeight(); y += bottomMargin; if (column.getFooterImage() != null) { x += column.getFooterImage().getBounds().width + imageSpacing; y = Math.max(y, topMargin + column.getFooterImage().getBounds().height + bottomMargin); } return new Point(x, y); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridColumn column = (GridColumn)value; // set the font to be used to display the text. gc.setFont(column.getFooterFont()); gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); gc.drawLine(getBounds().x, getBounds().y, getBounds().x + getBounds().width, getBounds().y); int x = leftMargin; if (column.getFooterImage() != null) { gc.drawImage(column.getFooterImage(), getBounds().x + x, getBounds().y + getBounds().height - bottomMargin - column.getFooterImage().getBounds().height); x += column.getFooterImage().getBounds().width + imageSpacing; } int width = getBounds().width - x; if (column.getSort() == SWT.NONE) { width -= rightMargin; } gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); int y = getBounds().y + getBounds().height - bottomMargin - gc.getFontMetrics().getHeight(); String text = TextUtils.getShortString(gc, column.getFooterText(), width); if (column.getAlignment() == SWT.RIGHT) { int len = gc.stringExtent(text).x; if (len < width) { x += width - len; } } else if (column.getAlignment() == SWT.CENTER) { int len = gc.stringExtent(text).x; if (len < width) { x += (width - len) / 2; } } gc.drawString(text, getBounds().x + x, y,true); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { return false; } /** * {@inheritDoc} */ public Rectangle getTextBounds(Object value, boolean preferred) { GridColumn column = (GridColumn)value; int x = leftMargin; if (column.getImage() != null) { x += column.getImage().getBounds().width + imageSpacing; } GC gc = new GC(column.getParent()); gc.setFont(column.getFooterFont()); int y = getBounds().height - bottomMargin - gc.getFontMetrics().getHeight(); Rectangle bounds = new Rectangle(x,y,0,0); Point p = gc.stringExtent(column.getText()); bounds.height = p.y; if (preferred) { bounds.width = p.x; } else { int width = getBounds().width - x; if (column.getSort() == SWT.NONE) { width -= rightMargin; } bounds.width = width; } gc.dispose(); return bounds; } }
5,044
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultColumnGroupHeaderRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultColumnGroupHeaderRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 * Marty Jones<[email protected]> - custom header/footer font in bug 293743 *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.GridColumnGroup; import org.eclipse.nebula.widgets.grid.GridHeaderRenderer; import org.eclipse.nebula.widgets.grid.IInternalWidget; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; /** * The column group header renderer in Grid. * * @author [email protected] * @since 2.0.0 */ public class DefaultColumnGroupHeaderRenderer extends GridHeaderRenderer { int leftMargin = 6; int rightMargin = 6; int topMargin = 3; int bottomMargin = 3; int imageSpacing = 3; private ExpandToggleRenderer toggleRenderer = new ExpandToggleRenderer(); private TextLayout textLayout; /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridColumnGroup group = (GridColumnGroup)value; // set the font to be used to display the text. gc.setFont(group.getHeaderFont()); if (isSelected()) { gc.setBackground(group.getParent().getCellHeaderSelectionBackground()); } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width + 1, getBounds().height + 1); int x = leftMargin; if (group.getImage() != null) { gc.drawImage(group.getImage(), getBounds().x + x, getBounds().y + topMargin); x += group.getImage().getBounds().width + imageSpacing; } int width = getBounds().width - x - rightMargin; if ((group.getStyle() & SWT.TOGGLE) != 0) { width -= toggleRenderer.getSize().x; } gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); if (!isWordWrap()) { gc.drawString(TextUtils.getShortString(gc, group.getText(), width), getBounds().x + x, getBounds().y + topMargin); } else { getTextLayout(gc, group); textLayout.setWidth(width < 1 ? 1 : width); textLayout.setText(group.getText()); if (group.getParent().isAutoHeight()) { group.getParent().recalculateHeader(); } textLayout.draw(gc, getBounds().x + x, getBounds().y + topMargin); } if ((group.getStyle() & SWT.TOGGLE) != 0) { toggleRenderer.setHover(isHover() && getHoverDetail().equals("toggle")); toggleRenderer.setExpanded(group.getExpanded()); toggleRenderer.setBounds(getToggleBounds()); toggleRenderer.paint(gc, null); } gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridColumnGroup group = (GridColumnGroup)value; gc.setFont(group.getHeaderFont()); int x = leftMargin; int y = topMargin + gc.getFontMetrics().getHeight() + bottomMargin; if (group.getImage() != null) { x += group.getImage().getBounds().width + imageSpacing; y = Math.max(y, topMargin + group.getImage().getBounds().height + bottomMargin); } if (!isWordWrap()) { x += gc.stringExtent(group.getText()).x + rightMargin; } else { int toggleWidth = 0; if ((group.getStyle() & SWT.TOGGLE) != 0) toggleWidth = toggleRenderer.getSize().x; int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin - toggleWidth; else plainTextWidth = wHint - x - rightMargin - toggleWidth; getTextLayout(gc, group); textLayout.setText(group.getText()); textLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; int textHeight = topMargin; textHeight += textLayout.getBounds().height; textHeight += bottomMargin; y = Math.max(y, textHeight); } return new Point(x, y); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { GridColumnGroup group = (GridColumnGroup)value; if ((group.getStyle() & SWT.TOGGLE) != 0) { if (event == IInternalWidget.LeftMouseButtonDown) { if (getToggleBounds().contains(point)) { group.setExpanded(!group.getExpanded()); if (group.getExpanded()) { group.notifyListeners(SWT.Expand,new Event()); } else { group.notifyListeners(SWT.Collapse,new Event()); } return true; } } else { if (getToggleBounds().contains(point)) { setHoverDetail("toggle"); return true; } } } return false; } /** * {@inheritDoc} */ public Rectangle getToggleBounds() { int x = getBounds().x + getBounds().width - toggleRenderer.getBounds().width - rightMargin; int y = getBounds().y + (getBounds().height - toggleRenderer.getBounds().height) / 2; return new Rectangle(x, y, toggleRenderer.getBounds().width, toggleRenderer.getBounds().height); } /** * {@inheritDoc} */ public void setDisplay(Display display) { super.setDisplay(display); toggleRenderer.setDisplay(display); } /** * {@inheritDoc} */ public Rectangle getTextBounds(Object value, boolean preferred) { GridColumnGroup group = (GridColumnGroup)value; int x = leftMargin; if (group.getImage() != null) { x += group.getImage().getBounds().width + imageSpacing; } Rectangle bounds = new Rectangle(x, topMargin, 0, 0); GC gc = new GC(group.getParent()); gc.setFont(group.getHeaderFont()); Point p = gc.stringExtent(group.getText()); bounds.height = p.y; if (preferred) { bounds.width = p.x; } else { int width = getBounds().width - x - rightMargin; if ((group.getStyle() & SWT.TOGGLE) != 0) { width -= toggleRenderer.getSize().x; } bounds.width = width; } gc.dispose(); return bounds; } private void getTextLayout(GC gc, GridColumnGroup group) { if (textLayout == null) { textLayout = new TextLayout(gc.getDevice()); textLayout.setFont(gc.getFont()); group.getParent().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { textLayout.dispose(); } }); } } }
8,912
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultEmptyColumnHeaderRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultEmptyColumnHeaderRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * A renderer for the last empty column header. * * @author [email protected] * @since 2.0.0 */ public class DefaultEmptyColumnHeaderRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(wHint, hHint); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width + 1, getBounds().height + 1); } }
1,410
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ToggleRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/ToggleRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The renderer for tree item plus/minus expand/collapse toggle. * * @author [email protected] * @since 2.0.0 */ public class ToggleRenderer extends AbstractRenderer { /** * Default constructor. */ public ToggleRenderer() { this.setSize(9, 9); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); gc.fillRectangle(getBounds()); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.drawRectangle(getBounds().x, getBounds().y, getBounds().width - 1, getBounds().height - 1); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); gc.drawLine(getBounds().x + 2, getBounds().y + 4, getBounds().x + 6, getBounds().y + 4); if (!isExpanded()) { gc.drawLine(getBounds().x + 4, getBounds().y + 2, getBounds().x + 4, getBounds().y + 6); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(9, 9); } }
1,972
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultEmptyCellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultEmptyCellRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridCellRenderer; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The empty cell renderer. * * @author [email protected] * @since 2.0.0 */ public class DefaultEmptyCellRenderer extends GridCellRenderer { /** * {@inheritDoc} */ public void paint(GC gc, Object value) { Grid table = null; if (value instanceof Grid) table = (Grid)value; GridItem item; if (value instanceof GridItem) { item = (GridItem)value; table = item.getParent(); } boolean drawBackground = true; if (isSelected()) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT)); } else { if (table.isEnabled()) { drawBackground = false; } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } gc.setForeground(table.getForeground()); } if (drawBackground) gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width + 1, getBounds().height); if (table.getLinesVisible()) { gc.setForeground(table.getLineColor()); gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width, getBounds().y + getBounds().height); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(wHint, hHint); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { return false; } }
3,099
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CheckBoxRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/CheckBoxRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * A checkbox renderer. * * @author [email protected] * @since 2.0.0 */ public class CheckBoxRenderer extends AbstractRenderer { private boolean checked = false; private boolean grayed = false; /** * */ public CheckBoxRenderer() { super(); this.setSize(13, 13); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { if (isGrayed()) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); } gc.fillRectangle(getBounds()); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND)); gc.drawRectangle(getBounds().x, getBounds().y, getBounds().width - 1, getBounds().height - 1); gc.drawRectangle(getBounds().x + 1, getBounds().y + 1, getBounds().width - 3, getBounds().height - 3); if (isGrayed()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); } if (isChecked()) { gc.drawLine(getBounds().x + 3, getBounds().y + 5, getBounds().x + 6, getBounds().y + 8); gc.drawLine(getBounds().x + 3, getBounds().y + 6, getBounds().x + 5, getBounds().y + 8); gc.drawLine(getBounds().x + 3, getBounds().y + 7, getBounds().x + 5, getBounds().y + 9); gc.drawLine(getBounds().x + 9, getBounds().y + 3, getBounds().x + 6, getBounds().y + 6); gc.drawLine(getBounds().x + 9, getBounds().y + 4, getBounds().x + 6, getBounds().y + 7); gc.drawLine(getBounds().x + 9, getBounds().y + 5, getBounds().x + 7, getBounds().y + 7); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return getSize(); } /** * @return Returns the checked. */ public boolean isChecked() { return checked; } /** * @param checked The checked to set. */ public void setChecked(boolean checked) { this.checked = checked; } /** * @return Returns the grayed. */ public boolean isGrayed() { return grayed; } /** * @param grayed The grayed to set. */ public void setGrayed(boolean grayed) { this.grayed = grayed; } }
3,289
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ScrollBarProxyAdapter.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/ScrollBarProxyAdapter.java
package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.ScrollBar; /** * Adapts a normal scrollbar to the IScrollBar proxy. * * @author [email protected] * @since 2.0.0 */ public class ScrollBarProxyAdapter implements IScrollBarProxy { /** * Delegates to this scrollbar. */ private ScrollBar scrollBar; /** * Contructs this adapter by delegating to the given scroll bar. * * @param scrollBar delegate */ public ScrollBarProxyAdapter(ScrollBar scrollBar) { super(); this.scrollBar = scrollBar; } /** * {@inheritDoc} */ public int getIncrement() { return scrollBar.getIncrement(); } /** * {@inheritDoc} */ public int getMaximum() { return scrollBar.getMaximum(); } /** * {@inheritDoc} */ public int getMinimum() { return scrollBar.getMinimum(); } /** * {@inheritDoc} */ public int getPageIncrement() { return scrollBar.getPageIncrement(); } /** * {@inheritDoc} */ public int getSelection() { return scrollBar.getSelection(); } /** * {@inheritDoc} */ public int getThumb() { return scrollBar.getThumb(); } /** * {@inheritDoc} */ public boolean getVisible() { return scrollBar.getVisible(); } /** * {@inheritDoc} */ public void setIncrement(int value) { scrollBar.setIncrement(value); } /** * {@inheritDoc} */ public void setMaximum(int value) { scrollBar.setMaximum(value); } /** * {@inheritDoc} */ public void setMinimum(int value) { scrollBar.setMinimum(value); } /** * {@inheritDoc} */ public void setPageIncrement(int value) { scrollBar.setPageIncrement(value); } /** * {@inheritDoc} */ public void setSelection(int selection) { scrollBar.setSelection(selection); } /** * {@inheritDoc} */ public void setThumb(int value) { scrollBar.setThumb(value); } /** * {@inheritDoc} */ public void setValues(int selection, int minimum, int maximum, int thumb, int increment, int pageIncrement) { scrollBar.setValues(selection, minimum, maximum, thumb, increment, pageIncrement); } /** * {@inheritDoc} */ public void setVisible(boolean visible) { scrollBar.setVisible(visible); } /** * {@inheritDoc} */ public void handleMouseWheel(Event e) { //do nothing } /** * {@inheritDoc} */ public void addSelectionListener(SelectionListener listener) { scrollBar.addSelectionListener(listener); } /** * {@inheritDoc} */ public void removeSelectionListener(SelectionListener listener) { scrollBar.removeSelectionListener(listener); } }
3,194
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultEmptyRowHeaderRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultEmptyRowHeaderRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * The empty row header renderer. * * @author [email protected] * @since 2.0.0 */ public class DefaultEmptyRowHeaderRenderer extends AbstractRenderer { /** * {@inheritDoc} */ public void paint(GC gc, Object value) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height + 1); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); Grid grid = (Grid) value; if (!grid.getCellSelectionEnabled()) { gc.drawLine(getBounds().x, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y); gc.drawLine(getBounds().x, getBounds().y, getBounds().x, getBounds().y + getBounds().height - 1); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW)); gc.drawLine(getBounds().x + 1, getBounds().y + 1, getBounds().x + getBounds().width - 2, getBounds().y + 1); gc.drawLine(getBounds().x + 1, getBounds().y + 1, getBounds().x + 1, getBounds().y + getBounds().height - 2); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 2, getBounds().y + 1, getBounds().x + getBounds().width - 2, getBounds().y + getBounds().height - 2); gc.drawLine(getBounds().x + 1, getBounds().y + getBounds().height - 2, getBounds().x + getBounds().width - 2, getBounds().y + getBounds().height - 2); } else { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); gc.drawLine(getBounds().x, getBounds().y + getBounds().height - 1, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height - 1); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(wHint, hHint); } }
4,173
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultCellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/DefaultCellRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - wordwrapping in bug 222280 * [email protected] - wordwrapping in bug 222280 * Claes Rosell<[email protected]> - rowspan in bug 272384 *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridCellRenderer; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.nebula.widgets.grid.IInternalWidget; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; /** * The renderer for a cell in Grid. * * @author [email protected] * @since 2.0.0 */ public class DefaultCellRenderer extends GridCellRenderer { int leftMargin = 4; int rightMargin = 4; int topMargin = 0; int bottomMargin = 0; int textTopMargin = 1; int textBottomMargin = 2; private int insideMargin = 3; int treeIndent = 20; private ToggleRenderer toggleRenderer; private BranchRenderer branchRenderer; private CheckBoxRenderer checkRenderer; private TextLayout textLayout; /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem)value; gc.setFont(item.getFont(getColumn())); boolean drawAsSelected = isSelected(); boolean drawBackground = true; if (isCellSelected()) { drawAsSelected = true;//(!isCellFocus()); } if (drawAsSelected) { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT)); } else { if (item.getParent().isEnabled()) { Color back = item.getBackground(getColumn()); if (back != null) { gc.setBackground(back); } else { drawBackground = false; } } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } gc.setForeground(item.getForeground(getColumn())); } if (drawBackground) gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); int x = leftMargin; if (isTree()) { boolean renderBranches = item.getParent().getTreeLinesVisible(); if(renderBranches) { branchRenderer.setBranches(getBranches(item)); branchRenderer.setIndent(treeIndent); branchRenderer.setBounds( getBounds().x + x, getBounds().y, getToggleIndent(item), getBounds().height + 1); // Take into account border } x += getToggleIndent(item); toggleRenderer.setExpanded(item.isExpanded()); toggleRenderer.setHover(getHoverDetail().equals("toggle")); toggleRenderer.setLocation(getBounds().x + x, (getBounds().height - toggleRenderer .getBounds().height) / 2 + getBounds().y); if (item.hasChildren()) toggleRenderer.paint(gc, null); if (renderBranches) { branchRenderer.setToggleBounds(toggleRenderer.getBounds()); branchRenderer.paint(gc, null); } x += toggleRenderer.getBounds().width + insideMargin; } if (isCheck()) { checkRenderer.setChecked(item.getChecked(getColumn())); checkRenderer.setGrayed(item.getGrayed(getColumn())); if (!item.getParent().isEnabled()) { checkRenderer.setGrayed(true); } checkRenderer.setHover(getHoverDetail().equals("check")); if (isCenteredCheckBoxOnly(item)) { //Special logic if this column only has a checkbox and is centered checkRenderer.setBounds(getBounds().x + ((getBounds().width - checkRenderer.getBounds().width) /2), (getBounds().height - checkRenderer.getBounds().height) / 2 + getBounds().y, checkRenderer .getBounds().width, checkRenderer.getBounds().height); } else { checkRenderer.setBounds(getBounds().x + x, (getBounds().height - checkRenderer .getBounds().height) / 2 + getBounds().y, checkRenderer .getBounds().width, checkRenderer.getBounds().height); x += checkRenderer.getBounds().width + insideMargin; } checkRenderer.paint(gc, null); } Image image = item.getImage(getColumn()); if (image != null) { int y = getBounds().y; y += (getBounds().height - image.getBounds().height)/2; gc.drawImage(image, getBounds().x + x, y); x += image.getBounds().width + insideMargin; } int width = getBounds().width - x - rightMargin; if (drawAsSelected) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT)); } else { gc.setForeground(item.getForeground(getColumn())); } if (!isWordWrap()) { String text = TextUtils.getShortString(gc, item.getText(getColumn()), width); if (getAlignment() == SWT.RIGHT) { int len = gc.stringExtent(text).x; if (len < width) { x += width - len; } } else if (getAlignment() == SWT.CENTER) { int len = gc.stringExtent(text).x; if (len < width) { x += (width - len) / 2; } } gc.drawString(text, getBounds().x + x, getBounds().y + textTopMargin + topMargin, true); } else { if (textLayout == null) { textLayout = new TextLayout(gc.getDevice()); item.getParent().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { textLayout.dispose(); } }); } textLayout.setFont(gc.getFont()); textLayout.setText(item.getText(getColumn())); textLayout.setAlignment(getAlignment()); textLayout.setWidth(width < 1 ? 1 : width); if (item.getParent().isAutoHeight()) { // Look through all columns (except this one) to get the max height needed for this item int columnCount = item.getParent().getColumnCount(); int maxHeight = textLayout.getBounds().height + textTopMargin + textBottomMargin; for (int i=0; i<columnCount; i++) { GridColumn column = item.getParent().getColumn(i); if (i != getColumn() && column.getWordWrap()) { int height = column.getCellRenderer().computeSize(gc, column.getWidth(), SWT.DEFAULT, item).y; maxHeight = Math.max(maxHeight, height); } } // Also look at the row header if necessary if (item.getParent().isWordWrapHeader()) { int height = item.getParent().getRowHeaderRenderer().computeSize(gc, SWT.DEFAULT, SWT.DEFAULT, item).y; maxHeight = Math.max(maxHeight, height); } if (maxHeight != item.getHeight()) { item.setHeight(maxHeight); } } textLayout.draw(gc, getBounds().x + x, getBounds().y + textTopMargin + topMargin); } if (item.getParent().getLinesVisible()) { if (isCellSelected()) { //XXX: should be user definable? gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } else { gc.setForeground(item.getParent().getLineColor()); } gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width -1, getBounds().y + getBounds().height); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); } if (isCellFocus()) { Rectangle focusRect = new Rectangle(getBounds().x, getBounds().y, getBounds().width - 1, getBounds().height); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND)); gc.drawRectangle(focusRect); if (isFocus()) { focusRect.x ++; focusRect.width -= 2; focusRect.y ++; focusRect.height -= 2; gc.drawRectangle(focusRect); } } } /** * Calculates the sequence of branch lines which should be rendered for the provided item * @param item * @return an array of integers composed using the constants in {@link BranchRenderer} */ private int[] getBranches(GridItem item) { int[] branches = new int[item.getLevel() + 1]; GridItem[] roots = item.getParent().getRootItems(); // Is this a node or a leaf? if (item.getParentItem() == null) { // Add descender if not last item if (!item.isExpanded() && roots[roots.length-1].equals(item)) { if (item.hasChildren()) branches[item.getLevel()] = BranchRenderer.LAST_ROOT; else branches[item.getLevel()] = BranchRenderer.SMALL_L; } else { if (item.hasChildren()) branches[item.getLevel()] = BranchRenderer.ROOT; else branches[item.getLevel()] = BranchRenderer.SMALL_T; } } else if (item.hasChildren()) if (item.isExpanded()) branches[item.getLevel()] = BranchRenderer.NODE; else branches[item.getLevel()] = BranchRenderer.NONE; else branches[item.getLevel()] = BranchRenderer.LEAF; // Branch for current item GridItem parent = item.getParentItem(); if (parent == null) return branches; // Are there siblings below this item? if (parent.indexOf(item) < parent.getItemCount() - 1) branches[item.getLevel() - 1] = BranchRenderer.T; // Is the next node a root? else if (parent.getParentItem() == null && !parent.equals(roots[roots.length - 1])) branches[item.getLevel() - 1] = BranchRenderer.T; // This must be the last element at this level else branches[item.getLevel() - 1] = BranchRenderer.L; Grid grid = item.getParent(); item = parent; parent = item.getParentItem(); // Branches for parent items while(item.getLevel() > 0) { if (parent.indexOf(item) == parent.getItemCount() - 1) { if (parent.getParentItem() == null && !grid.getRootItem(grid.getRootItemCount() - 1).equals(parent)) branches[item.getLevel() - 1] = BranchRenderer.I; else branches[item.getLevel() - 1] = BranchRenderer.NONE; } else branches[item.getLevel() - 1] = BranchRenderer.I; item = parent; parent = item.getParentItem(); } // item should be null at this point return branches; } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridItem item = (GridItem)value; gc.setFont(item.getFont(getColumn())); int x = 0; x += leftMargin; if (isTree()) { x += getToggleIndent(item); x += toggleRenderer.getBounds().width + insideMargin; } if (isCheck()) { x += checkRenderer.getBounds().width + insideMargin; } int y = 0; Image image = item.getImage(getColumn()); if (image != null) { y = topMargin + image.getBounds().height + bottomMargin; x += image.getBounds().width + insideMargin; } // MOPR-DND // MOPR: replaced this code (to get correct preferred height for cells in word-wrap columns) // // x += gc.stringExtent(item.getText(column)).x + rightMargin; // // y = Math.max(y,topMargin + gc.getFontMetrics().getHeight() + bottomMargin); // // with this code: int textHeight = 0; if(!isWordWrap()) { x += gc.textExtent(item.getText(getColumn())).x + rightMargin; textHeight = topMargin + textTopMargin + gc.getFontMetrics().getHeight() + textBottomMargin + bottomMargin; } else { int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin; else plainTextWidth = wHint - x - rightMargin; TextLayout currTextLayout = new TextLayout(gc.getDevice()); currTextLayout.setFont(gc.getFont()); currTextLayout.setText(item.getText(getColumn())); currTextLayout.setAlignment(getAlignment()); currTextLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; textHeight += topMargin + textTopMargin; for(int cnt=0;cnt<currTextLayout.getLineCount();cnt++) textHeight += currTextLayout.getLineBounds(cnt).height; textHeight += textBottomMargin + bottomMargin; currTextLayout.dispose(); } y = Math.max(y, textHeight); return new Point(x, y); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { GridItem item = (GridItem)value; if (isCheck()) { if (event == IInternalWidget.MouseMove) { if (overCheck(item, point)) { setHoverDetail("check"); return true; } } if (event == IInternalWidget.LeftMouseButtonDown) { if (overCheck(item, point)) { if (!item.getCheckable(getColumn())) { return false; } item.setChecked(getColumn(), !item.getChecked(getColumn())); item.getParent().redraw(); item.fireCheckEvent(getColumn()); return true; } } } if (isTree() && item.hasChildren()) { if (event == IInternalWidget.MouseMove) { if (overToggle(item, point)) { setHoverDetail("toggle"); return true; } } if (event == IInternalWidget.LeftMouseButtonDown) { if (overToggle(item, point)) { item.setExpanded(!item.isExpanded()); item.getParent().redraw(); if (item.isExpanded()) { item.fireEvent(SWT.Expand); } else { item.fireEvent(SWT.Collapse); } return true; } } } return false; } private boolean overCheck(GridItem item, Point point) { if (isCenteredCheckBoxOnly(item)) { point = new Point(point.x, point.y); point.x -= getBounds().x; point.y -= getBounds().y; Rectangle checkBounds = new Rectangle(0,0,0,0); checkBounds.x = (getBounds().width - checkRenderer.getBounds().width)/2; checkBounds.y = ((getBounds().height - checkRenderer.getBounds().height) / 2); checkBounds.width = checkRenderer.getBounds().width; checkBounds.height = checkRenderer.getBounds().height; return checkBounds.contains(point); } else { point = new Point(point.x, point.y); point.x -= getBounds().x; point.y -= getBounds().y; int x = leftMargin; if (isTree()) { x += getToggleIndent(item); x += toggleRenderer.getSize().x + insideMargin; } if (point.x >= x && point.x < (x + checkRenderer.getSize().x)) { int yStart = ((getBounds().height - checkRenderer.getBounds().height) / 2); if (point.y >= yStart && point.y < yStart + checkRenderer.getSize().y) { return true; } } return false; } } private int getToggleIndent(GridItem item) { return item.getLevel() * treeIndent; } private boolean overToggle(GridItem item, Point point) { point = new Point(point.x, point.y); point.x -= getBounds().x - 1; point.y -= getBounds().y - 1; int x = leftMargin; x += getToggleIndent(item); if (point.x >= x && point.x < (x + toggleRenderer.getSize().x)) { // return true; int yStart = ((getBounds().height - toggleRenderer.getBounds().height) / 2); if (point.y >= yStart && point.y < yStart + toggleRenderer.getSize().y) { return true; } } return false; } /** * {@inheritDoc} */ public void setTree(boolean tree) { super.setTree(tree); if (tree) { toggleRenderer = new ToggleRenderer(); toggleRenderer.setDisplay(getDisplay()); branchRenderer = new BranchRenderer(); branchRenderer.setDisplay(getDisplay()); } } /** * {@inheritDoc} */ public void setCheck(boolean check) { super.setCheck(check); if (check) { checkRenderer = new CheckBoxRenderer(); checkRenderer.setDisplay(getDisplay()); } else { checkRenderer = null; } } /** * {@inheritDoc} */ public Rectangle getTextBounds(GridItem item, boolean preferred) { int x = leftMargin; if (isTree()) { x += getToggleIndent(item); x += toggleRenderer.getBounds().width + insideMargin; } if (isCheck()) { x += checkRenderer.getBounds().width + insideMargin; } Image image = item.getImage(getColumn()); if (image != null) { x += image.getBounds().width + insideMargin; } Rectangle bounds = new Rectangle(x,topMargin + textTopMargin,0,0); GC gc = new GC(item.getParent()); gc.setFont(item.getFont(getColumn())); Point size = gc.stringExtent(item.getText(getColumn())); bounds.height = size.y; if (preferred) { bounds.width = size.x - 1; } else { bounds.width = getBounds().width - x - rightMargin; } gc.dispose(); return bounds; } private boolean isCenteredCheckBoxOnly(GridItem item) { return !isTree() && item.getImage(getColumn()) == null && item.getText(getColumn()).equals("") && getAlignment() == SWT.CENTER; } }
20,842
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NullScrollBarProxy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/NullScrollBarProxy.java
package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Event; /** * A null-op scrollbar proxy. Used when the grid is not showing scrollbars. * * @author [email protected] * @since 2.0.0 */ public class NullScrollBarProxy implements IScrollBarProxy { /** * {@inheritDoc} */ public boolean getVisible() { return false; } /** * {@inheritDoc} */ public void setVisible(boolean visible) { } /** * {@inheritDoc} */ public int getSelection() { return 0; } /** * {@inheritDoc} */ public void setSelection(int selection) { } /** * {@inheritDoc} */ public void setValues(int selection, int min, int max, int thumb, int increment, int pageIncrement) { } /** * {@inheritDoc} */ public void handleMouseWheel(Event e) { } /** * {@inheritDoc} */ public void setMinimum(int min) { } /** * {@inheritDoc} */ public int getMinimum() { return 0; } /** * {@inheritDoc} */ public void setMaximum(int max) { } /** * {@inheritDoc} */ public int getMaximum() { return 0; } /** * {@inheritDoc} */ public void setThumb(int thumb) { } /** * {@inheritDoc} */ public int getThumb() { return 0; } /** * {@inheritDoc} */ public void setIncrement(int increment) { } /** * {@inheritDoc} */ public int getIncrement() { return 0; } /** * {@inheritDoc} */ public void setPageIncrement(int page) { } /** * {@inheritDoc} */ public int getPageIncrement() { return 0; } /** * {@inheritDoc} */ public void addSelectionListener(SelectionListener listener) { } /** * {@inheritDoc} */ public void removeSelectionListener(SelectionListener listener) { } }
2,190
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ExpandToggleRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/ExpandToggleRenderer.java
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; /** * @author [email protected] * @since 2.0.0 */ public class ExpandToggleRenderer extends AbstractRenderer { /** * */ public ExpandToggleRenderer() { super(); setSize(11, 9); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { Color innerColor = null; Color outerColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); if (isHover()) { innerColor = getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND); } else { innerColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND); } if (isExpanded()) { drawLeftPointingLine(gc, innerColor, outerColor, 0); drawLeftPointingLine(gc, innerColor, outerColor, 5); } else { drawRightPointingLine(gc, innerColor, outerColor, 0); drawRightPointingLine(gc, innerColor, outerColor, 5); } } private void drawRightPointingLine(GC gc, Color innerColor, Color outerColor, int xOffset) { gc.setForeground(outerColor); gc.drawLine(getBounds().x + 1 + xOffset, getBounds().y, getBounds().x + 5 + xOffset, getBounds().y + 4); gc.drawLine(getBounds().x + 4 + xOffset, getBounds().y + 5, getBounds().x + 1 + xOffset, getBounds().y + 8); gc.drawPoint(getBounds().x + xOffset, getBounds().y + 7); gc.drawLine(getBounds().x + xOffset, getBounds().y + 6, getBounds().x + 2 + xOffset, getBounds().y + 4); gc.drawLine(getBounds().x + 1 + xOffset, getBounds().y + 3, getBounds().x + xOffset, getBounds().y + 2); gc.drawPoint(getBounds().x + xOffset, getBounds().y + 1); gc.setForeground(innerColor); gc.drawLine(getBounds().x + 1 + xOffset, getBounds().y + 1, getBounds().x + 4 + xOffset, getBounds().y + 4); gc.drawLine(getBounds().x + 1 + xOffset, getBounds().y + 2, getBounds().x + 3 + xOffset, getBounds().y + 4); gc.drawLine(getBounds().x + 3 + xOffset, getBounds().y + 5, getBounds().x + 1 + xOffset, getBounds().y + 7); gc.drawLine(getBounds().x + 2 + xOffset, getBounds().y + 5, getBounds().x + 1 + xOffset, getBounds().y + 6); } private void drawLeftPointingLine(GC gc, Color innerColor, Color outerColor, int xOffset) { gc.setForeground(outerColor); gc.drawLine(getBounds().x + xOffset, getBounds().y + 4, getBounds().x + 4 + xOffset, getBounds().y); gc.drawPoint(getBounds().x + 5 + xOffset, getBounds().y + 1); gc.drawLine(getBounds().x + 5 + xOffset, getBounds().y + 2, getBounds().x + 3 + xOffset, getBounds().y + 4); gc.drawPoint(getBounds().x + 4 + xOffset, getBounds().y + 5); gc.drawLine(getBounds().x + 5 + xOffset, getBounds().y + 6, getBounds().x + 5 + xOffset, getBounds().y + 7); gc.drawLine(getBounds().x + 4 + xOffset, getBounds().y + 8, getBounds().x + 1 + xOffset, getBounds().y + 5); gc.setForeground(innerColor); gc.drawLine(getBounds().x + 1 + xOffset, getBounds().y + 4, getBounds().x + 4 + xOffset, getBounds().y + 1); gc.drawLine(getBounds().x + 2 + xOffset, getBounds().y + 4, getBounds().x + 4 + xOffset, getBounds().y + 2); gc.drawLine(getBounds().x + 2 + xOffset, getBounds().y + 5, getBounds().x + 4 + xOffset, getBounds().y + 7); gc.drawLine(getBounds().x + 2 + xOffset, getBounds().y + 4, getBounds().x + 4 + xOffset, getBounds().y + 6); } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { return new Point(11, 9); } }
4,793
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
BranchRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/BranchRenderer.java
/******************************************************************************* * Copyright (c) 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Michael Houston <[email protected]> - initial implementation * [email protected] - bugfix in 269563 *******************************************************************************/ package org.eclipse.nebula.widgets.grid.internal; import org.eclipse.nebula.widgets.grid.AbstractRenderer; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; /** * Renders the tree branch hierarchy for a {@link GridColumn} * @author Michael Houston <[email protected]> */ public class BranchRenderer extends AbstractRenderer { private static final int[] LINE_STYLE = new int[] {1,1}; // Line segments /** A full-width horizontal bar */ public static final int H_FULL = 1; /** A horizontal bar from the centre to the right */ public static final int H_RIGHT = 1 << 1; /** A horizontal bar from the centre to the toggle */ public static final int H_CENTRE_TOGGLE = 1 << 2; /** A horizontal bar from the left to the toggle */ public static final int H_LEFT_TOGGLE = 1 << 3; /** A full-height vertical bar */ public static final int V_FULL = 1 << 4; /** A vertical bar from the top to the middle */ public static final int V_TOP = 1 << 5; /** A vertical bar from the toggle to the bottom */ public static final int DESCENDER = 1 << 6; /** A vertical bar from the top to the toggle */ public static final int ASCENDER = 1 << 7; // Predefined combinations /** Indicates that a branch should not be rendered. */ public static final int NONE = 0; /** Indicates that a branch should be rendered as a 'T' shape. This * is used for normal children with following siblings */ public static final int T = V_FULL | H_RIGHT; /** Indicates that a branch should be rendered as an 'L' shape. This * is used for the last child element */ public static final int L = V_TOP | H_RIGHT; /** Indicates that a branch should be rendered as a 'I' shape. This * is used for connecting children when intermediate children are shown. */ public static final int I = V_FULL; /** Indicates that the toggle decoration for an expanded parent should be drawn */ public static final int NODE = DESCENDER; /** Indicates that the decoration for a leaf node should be drawn */ public static final int LEAF = H_LEFT_TOGGLE; /** Indicates that the decoration for a root node should be drawn */ public static final int ROOT = ASCENDER | DESCENDER; /** Indicates that the decoration for the last root node should be drawn */ public static final int LAST_ROOT = ASCENDER; /** A half-width T used on roots with no children */ public static final int SMALL_T = V_FULL | H_CENTRE_TOGGLE; /** A half-width L used on roots with no children */ public static final int SMALL_L = V_TOP | H_CENTRE_TOGGLE; private int indent; private int[] branches; private Rectangle toggleBounds; /** * {@inheritDoc} */ public Point computeSize(GC gc, int hint, int hint2, Object value) { return new Point(getBounds().width, getBounds().height); } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { Rectangle bounds = getBounds(); int xLeft = bounds.x; int yTop = bounds.y - 1; int yBottom = yTop + bounds.height; int yMiddle = toggleBounds.y + toggleBounds.height / 2; int yToggleBottom = toggleBounds.y + toggleBounds.height - 1; int yToggleTop = toggleBounds.y; int oldStyle = gc.getLineStyle(); Color oldForeground = gc.getForeground(); int[] oldLineDash = gc.getLineDash(); gc.setForeground(getDisplay().getSystemColor( isSelected() ? SWT.COLOR_LIST_SELECTION_TEXT : SWT.COLOR_WIDGET_NORMAL_SHADOW)); int dy = bounds.y % 2; // Set line style to dotted gc.setLineDash(LINE_STYLE); // Adjust line positions by a few pixels to create correct effect yToggleTop --; yTop ++; yToggleBottom ++; // Adjust full height // If height is even, we shorten to an odd number of pixels, and start at the original y offset if (bounds.height % 2 == 0) { yBottom -= 1; } // If height is odd, we alternate based on the row offset else { yTop += dy; yBottom -= dy; } // Adjust ascender and descender yToggleBottom += dy; if ((yToggleTop - yTop + 1) % 2 == 0) yToggleTop -= 1; if ((yToggleBottom - yBottom + 1) % 2 == 0) yToggleBottom += dy == 1 ? -1 : 1; for (int i = 0; i < branches.length; i++) { // Calculate offsets for this branch int xRight = xLeft + indent; int xMiddle = xLeft + toggleBounds.width / 2; int xMiddleBranch = xMiddle; int xToggleRight = xLeft + toggleBounds.width; int dx = 0; xRight --; xMiddleBranch += 2; xToggleRight --; if (indent % 2 == 0) { xRight -= 1; } else { dx = xLeft % 2; xLeft += dx; xRight -= dx; } // Render line segments if ((branches[i] & H_FULL) == H_FULL) gc.drawLine(xLeft, yMiddle, xRight, yMiddle); if ((branches[i] & H_RIGHT) == H_RIGHT) gc.drawLine(xMiddleBranch, yMiddle, xRight, yMiddle); if ((branches[i] & H_CENTRE_TOGGLE) == H_CENTRE_TOGGLE) gc.drawLine(xMiddleBranch, yMiddle, xToggleRight, yMiddle); if ((branches[i] & H_LEFT_TOGGLE) == H_LEFT_TOGGLE) gc.drawLine(xLeft, yMiddle, xToggleRight, yMiddle); if ((branches[i] & V_FULL) == V_FULL) gc.drawLine(xMiddle, yTop, xMiddle, yBottom); if ((branches[i] & V_TOP) == V_TOP) gc.drawLine(xMiddle, yTop, xMiddle, yMiddle); if ((branches[i] & ASCENDER) == ASCENDER) gc.drawLine(xMiddle, yTop, xMiddle, yToggleTop); if ((branches[i] & DESCENDER) == DESCENDER) gc.drawLine(xMiddle, yToggleBottom, xMiddle, yBottom); xLeft += indent - dx; } gc.setLineDash(oldLineDash); gc.setLineStyle(oldStyle); gc.setForeground(oldForeground); } /** * Sets the branches that will be used. The values are taken from the constants in this class such as * I, L, T, NODE, LEAF and NONE, which represent the branch type to be used for each level. * @param branches an array of branch types */ public void setBranches(int[] branches) { this.branches = branches; } /** * Sets the indent used for rendering the tree branches * @param toggleIndent the indent used for the tree */ public void setIndent(int toggleIndent) { this.indent = toggleIndent; } /** * Sets bounds of the toggle control. This is used to position the downwards branches * @param toggleBounds the bounds of the toggle control */ public void setToggleBounds(Rectangle toggleBounds) { this.toggleBounds = toggleBounds; } }
7,086
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CheckEditingSupport.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/CheckEditingSupport.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ColumnViewer; import org.eclipse.jface.viewers.EditingSupport; /** * . */ public abstract class CheckEditingSupport extends EditingSupport { /** * Checkbox editing support. * * @param viewer column to add check box support for. */ public CheckEditingSupport(ColumnViewer viewer) { super(viewer); } /** {@inheritDoc} */ protected boolean canEdit(Object element) { return false; } /** {@inheritDoc} */ protected CellEditor getCellEditor(Object element) { return null; } /** {@inheritDoc} */ protected Object getValue(Object element) { return null; } /** {@inheritDoc} */ public abstract void setValue(Object element, Object value); }
1,431
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridViewerColumn.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/GridViewerColumn.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * Tom Schindl <[email protected]> - various significant contributions * Mark-Oliver Reiser <[email protected]> - support for differing row heights ; fix in bug 191216 *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import org.eclipse.jface.viewers.ColumnViewer; import org.eclipse.jface.viewers.EditingSupport; import org.eclipse.jface.viewers.ViewerColumn; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * The concrete implementation of the ColumnViewer for the grid. */ public final class GridViewerColumn extends ViewerColumn { /** This is either a GridTableViewer or a GridTreeViewer. */ private ColumnViewer viewer; /** The concrete grid column that is being represented by the {@code ViewerColumn}.*/ private GridColumn column; /** Editor support for handling check events. */ private CheckEditingSupport checkEditingSupport; /** Listener used to get informed when the colum resizes */ protected Listener columnResizeListener = null; /** * Create a new column in the {@link GridTableViewer} * * @param viewer * the viewer the column belongs to * @param style * the style used to create the column for style bits see * {@link GridColumn} * @see GridColumn#GridColumn(Grid, int) */ public GridViewerColumn(GridTableViewer viewer, int style) { this(viewer, style, -1); } /** * Create a new column in the {@link GridTreeViewer} * * @param viewer * the viewer the column belongs to * @param style * the style used to create the column for style bits see * {@link GridColumn} * @see GridColumn#GridColumn(Grid, int) */ public GridViewerColumn(GridTreeViewer viewer, int style) { this(viewer, style, -1); } /** * Create a new column in the {@link GridTableViewer} * * @param viewer * the viewer the column belongs to * @param style * the style used to create the column for style bits see * {@link GridColumn} * @param index * the index of the newly created column * @see GridColumn#GridColumn(Grid, int, int) */ public GridViewerColumn(GridTableViewer viewer, int style, int index) { this(viewer, createColumn((Grid) viewer.getControl(), style, index)); } /** * Create a new column in the {@link GridTreeViewer} * * @param viewer * the viewer the column belongs to * @param style * the style used to create the column for style bits see * {@link GridColumn} * @param index * the index of the newly created column * @see GridColumn#GridColumn(Grid, int, int) */ public GridViewerColumn(GridTreeViewer viewer, int style, int index) { this(viewer, createColumn((Grid) viewer.getControl(), style, index)); } /** * * @param viewer * the viewer the column belongs to * @param column * the column the viewer is attached to */ public GridViewerColumn(GridTreeViewer viewer, GridColumn column) { this((ColumnViewer)viewer,column); } /** * * @param viewer * the viewer the column belongs to * @param column * the column the viewer is attached to */ public GridViewerColumn(GridTableViewer viewer, GridColumn column) { this((ColumnViewer)viewer,column); } GridViewerColumn(ColumnViewer viewer, GridColumn column) { super(viewer, column); this.viewer = viewer; this.column = column; hookColumnResizeListener(); } private static GridColumn createColumn(Grid table, int style, int index) { if (index >= 0) { return new GridColumn(table, style, index); } return new GridColumn(table, style); } /** * Returns the underlying column. * * @return the underlying Nebula column */ public GridColumn getColumn() { return column; } /** {@inheritDoc} */ public void setEditingSupport(EditingSupport editingSupport) { if (editingSupport instanceof CheckEditingSupport) { if (checkEditingSupport == null) { final int colIndex = getColumn().getParent().indexOf(getColumn()); getColumn().getParent().addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (event.detail == SWT.CHECK && event.index == colIndex) { GridItem item = (GridItem)event.item; Object element = item.getData(); checkEditingSupport.setValue(element, new Boolean(item.getChecked(colIndex))); } } }); } checkEditingSupport = (CheckEditingSupport)editingSupport; } else { super.setEditingSupport(editingSupport); } } private void hookColumnResizeListener() { if (columnResizeListener == null) { columnResizeListener = new Listener() { public void handleEvent(Event event) { boolean autoPreferredSize=false; if(viewer instanceof GridTableViewer) autoPreferredSize = ((GridTableViewer)viewer).getAutoPreferredHeight(); if(viewer instanceof GridTreeViewer) autoPreferredSize = ((GridTreeViewer)viewer).getAutoPreferredHeight(); if(autoPreferredSize && column.getWordWrap()) { Grid grid = column.getParent(); for(int cnt=0;cnt<grid.getItemCount();cnt++) grid.getItem(cnt).pack(); grid.redraw(); } } }; column.addListener(SWT.Resize, columnResizeListener); column.addListener(SWT.Hide, columnResizeListener); column.addListener(SWT.Show, columnResizeListener); } } private void unhookColumnResizeListener() { if (columnResizeListener != null) { column.removeListener(SWT.Resize, columnResizeListener); columnResizeListener = null; } } /** * {@inheritDoc} */ protected void handleDispose() { unhookColumnResizeListener(); super.handleDispose(); } }
7,714
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridViewerEditor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/GridViewerEditor.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * Tom Schindl <[email protected]> - various significant contributions * bug fix in: 191216 * Jake fisher<[email protected]> - fixed minimum height (bug 263489) *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import org.eclipse.jface.viewers.ColumnViewer; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerRow; import org.eclipse.jface.viewers.CellEditor.LayoutData; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridEditor; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Item; /** * FIXME */ public class GridViewerEditor extends ColumnViewerEditor { /** Editor support for tables. */ private GridEditor gridEditor; /** * The selection follows the editor */ public static final int SELECTION_FOLLOWS_EDITOR = 1 << 30; private boolean selectionFollowsEditor = false; GridViewerEditor(ColumnViewer viewer, ColumnViewerEditorActivationStrategy editorActivationStrategy, int feature) { super(viewer, editorActivationStrategy, feature); this.selectionFollowsEditor = (feature & SELECTION_FOLLOWS_EDITOR) == SELECTION_FOLLOWS_EDITOR; this.gridEditor = new GridEditor((Grid) viewer.getControl()); } /** * FIXME * {@inheritDoc} */ protected void setEditor(Control w, Item item, int fColumnNumber) { gridEditor.setEditor(w, (GridItem) item, fColumnNumber); } /** * FIXME * {@inheritDoc} */ protected void setLayoutData(LayoutData layoutData) { gridEditor.grabHorizontal = layoutData.grabHorizontal; gridEditor.horizontalAlignment = layoutData.horizontalAlignment; gridEditor.minimumWidth = layoutData.minimumWidth; gridEditor.verticalAlignment = layoutData.verticalAlignment; if (layoutData.minimumHeight != SWT.DEFAULT) { gridEditor.minimumHeight = layoutData.minimumHeight; } else { gridEditor.minimumHeight = SWT.DEFAULT; } } /** * FIXME * {@inheritDoc} */ public ViewerCell getFocusCell() { Grid grid = (Grid)getViewer().getControl(); if( grid.getCellSelectionEnabled() ) { Point p = grid.getFocusCell(); if( p.x >= 0 && p.y >= 0 ) { GridItem item = grid.getItem(p.y); if( item != null ) { ViewerRow row = getViewerRowFromItem(item); return row.getCell(p.x); } } } return null; } private ViewerRow getViewerRowFromItem(GridItem item) { if( getViewer() instanceof GridTableViewer ) { return ((GridTableViewer)getViewer()).getViewerRowFromItem(item); } else { return ((GridTreeViewer)getViewer()).getViewerRowFromItem(item); } } /** * {@inheritDoc} */ protected void updateFocusCell(ViewerCell focusCell, ColumnViewerEditorActivationEvent event) { Grid grid = ((Grid)getViewer().getControl()); if (event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC || event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL) { grid.setFocusColumn(grid.getColumn(focusCell.getColumnIndex())); grid.setFocusItem((GridItem) focusCell.getItem()); if( selectionFollowsEditor ) { grid.setCellSelection(new Point(focusCell.getColumnIndex(),grid.indexOf((GridItem)focusCell.getItem()))); } } grid.showColumn(grid.getColumn(focusCell.getColumnIndex())); grid.showItem((GridItem) focusCell.getItem()); } /** * FIXME * @param viewer * @param editorActivationStrategy * @param feature */ public static void create(GridTableViewer viewer, ColumnViewerEditorActivationStrategy editorActivationStrategy, int feature) { viewer.setColumnViewerEditor(new GridViewerEditor(viewer,editorActivationStrategy,feature)); } /** * FIXME * @param viewer * @param editorActivationStrategy * @param feature */ public static void create(GridTreeViewer viewer, ColumnViewerEditorActivationStrategy editorActivationStrategy, int feature) { viewer.setColumnViewerEditor(new GridViewerEditor(viewer,editorActivationStrategy,feature)); } }
4,948
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridColumnLabelProvider.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/GridColumnLabelProvider.java
/******************************************************************************* * Copyright (c) 2007 Tom Schindl and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tom Schindl - initial API and implementation * Claes Rosell<[email protected]> - rowspan in bug 272384 *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridItem; /** * A label provider that provides hooks for extra functionality in the {@link Grid}. This is currently * limited to supplying the row header text. * <p> * <b> Only one from all {@link GridColumnLabelProvider} in a viewer should * return a none <code>null</code></b> * </p> */ public class GridColumnLabelProvider extends ColumnLabelProvider { /** * Returns the row header text for this element. * * @param element * the model element * @return the text displayed in the row-header or <code>null</code> if * this label provider would not like to modify the default text */ public String getRowHeaderText(Object element) { return null; } /** * Returns the number of columns this element should span * * @param element * the model element * @return colSpan */ public int getColumnSpan(Object element) { return 0; } /** * Returns the number of rows this element should span * * @param element * the model element * @return rowSpan */ public int getRowSpan(Object element) { return 0; } /** * {@inheritDoc} */ public void update(ViewerCell cell) { super.update(cell); Object element = cell.getElement(); String rowText = getRowHeaderText(element); int colSpan = getColumnSpan(element); int rowSpan = getRowSpan(element); GridItem gridItem = (GridItem)cell.getViewerRow().getItem(); if (rowText != null) { gridItem.setHeaderText(rowText); } gridItem.setColumnSpan(cell.getColumnIndex(), colSpan); gridItem.setRowSpan(cell.getColumnIndex(), rowSpan); } }
2,430
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridTreeViewer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/GridTreeViewer.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Michael Houston <[email protected]> - initial API and implementation * Tom Schindl <[email protected]> - bug fix in: 191216 *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerRow; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.swt.widgets.Widget; /** * A concrete viewer based on an Grid control. * <p> * This class is not intended to be subclassed outside the viewer framework. It * is designed to be instantiated with a pre-existing Grid control and * configured with a domain-specific content provider, label provider, element * filter (optional), and element sorter (optional). * <p> * Content providers for grid tree viewers must implement the * {@link ITreeContentProvider} interface. * <p><b>The current implementation does not support lazy content providers.</b></p> */ public class GridTreeViewer extends AbstractTreeViewer { /** This viewer's grid control. */ private Grid grid; private GridViewerRow cachedRow; /** * If true, this grid viewer will ensure that the grid's * rows / GridItems are always sized to their preferred height. */ private boolean autoPreferredHeight = false; private CellLabelProvider rowHeaderLabelProvider; /** * Creates a grid tree viewer on a newly-created grid control under the given * parent. The grid control is created using the SWT style bits * <code>MULTI, H_SCROLL, V_SCROLL,</code> and <code>BORDER</code>. The * viewer has no input, no content provider, a default label provider, no * sorter, and no filters. * * @param parent * the parent control */ public GridTreeViewer(Composite parent) { this(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); } /** * Creates a grid tree viewer on a newly-created grid control under the given * parent. The grid control is created using the given SWT style bits. The * viewer has no input, no content provider, a default label provider, no * sorter, and no filters. * * @param parent * the parent control * @param style * the SWT style bits used to create the grid. */ public GridTreeViewer(Composite parent, int style) { this(new Grid(parent, style)); } /** * Creates a grid tree viewer on the given grid control. The viewer has no * input, no content provider, a default label provider, no sorter, and no * filters. * * @param grid * the grid control */ public GridTreeViewer(Grid grid) { this.grid = grid; hookControl(grid); } /** * Returns the underlying {@link Grid} Control. * * @return grid control. */ public Grid getGrid() { return grid; } /** {@inheritDoc} */ protected Item getItemAt(Point point) { return grid.getItem(point); } /** {@inheritDoc} */ protected ColumnViewerEditor createViewerEditor() { return new GridViewerEditor(this, new ColumnViewerEditorActivationStrategy(this), ColumnViewerEditor.DEFAULT); } /** {@inheritDoc} */ protected void addTreeListener(Control control, TreeListener listener) { ((Grid) control).addTreeListener(listener); } /** {@inheritDoc} */ protected Item[] getChildren(Widget o) { if (o instanceof GridItem) { return ((GridItem) o).getItems(); } if (o instanceof Grid) { return ((Grid) o).getRootItems(); } return null; } /** {@inheritDoc} */ protected boolean getExpanded(Item item) { return ((GridItem) item).isExpanded(); } /** {@inheritDoc} */ protected int getItemCount(Control control) { return ((Grid) control).getItemCount(); } /** {@inheritDoc} */ protected int getItemCount(Item item) { return ((GridItem) item).getItemCount(); } /** {@inheritDoc} */ protected Item[] getItems(Item item) { return ((GridItem) item).getItems(); } /** {@inheritDoc} */ protected Item getParentItem(Item item) { return ((GridItem) item).getParentItem(); } /** {@inheritDoc} */ protected Item[] getSelection(Control control) { return ((Grid) control).getSelection(); } /** {@inheritDoc} */ protected Item newItem(Widget parent, int style, int index) { GridItem item; if (parent instanceof GridItem) { item = (GridItem) createNewRowPart(getViewerRowFromItem(parent), style, index).getItem(); } else { item = (GridItem) createNewRowPart(null, style, index).getItem(); } return item; } /** * Create a new ViewerRow at rowIndex * * @param parent * the parent row * @param style * the style bits to use for the new row * @param rowIndex * the index at which the new row should be created under the parent * @return ViewerRow * the new row */ private ViewerRow createNewRowPart(ViewerRow parent, int style, int rowIndex) { if (parent == null) { if (rowIndex >= 0) { return getViewerRowFromItem(new GridItem(grid, style, rowIndex)); } return getViewerRowFromItem(new GridItem(grid, style)); } if (rowIndex >= 0) { return getViewerRowFromItem(new GridItem((GridItem) parent .getItem(), SWT.NONE, rowIndex)); } return getViewerRowFromItem(new GridItem((GridItem) parent.getItem(), SWT.NONE)); } /** {@inheritDoc} */ protected void removeAll(Control control) { ((Grid) control).removeAll(); } /** {@inheritDoc} */ protected void setExpanded(Item item, boolean expand) { ((GridItem) item).setExpanded(expand); } /** {@inheritDoc} */ protected void setSelection(List items) { Item[] current = getSelection(getGrid()); // Don't bother resetting the same selection if (isSameSelection(items, current)) { return; } GridItem[] newItems = new GridItem[items.size()]; items.toArray(newItems); getGrid().setSelection(newItems); getGrid().showSelection(); } /** {@inheritDoc} */ protected void showItem(Item item) { getGrid().showItem((GridItem) item); } /** {@inheritDoc} */ public Control getControl() { return getGrid(); } /** {@inheritDoc} */ protected ViewerRow getViewerRowFromItem(Widget item) { if (cachedRow == null) { cachedRow = new GridViewerRow((GridItem) item); } else { cachedRow.setItem((GridItem) item); } return cachedRow; } /** {@inheritDoc} */ protected Widget getColumnViewerOwner(int columnIndex) { if (columnIndex < 0 || (columnIndex > 0 && columnIndex >= getGrid() .getColumnCount())) { return null; } if (getGrid().getColumnCount() == 0)// Hang it off the table if it return getGrid(); return getGrid().getColumn(columnIndex); } /** * Returns the number of columns of this viewer. * * @return the number of columns */ protected int doGetColumnCount() { return grid.getColumnCount(); } /** * When set to true, this grid viewer will ensure that each of * the grid's items is always automatically sized to its preferred * height. The default is false. * <p> * Since this mechanism usually leads to a grid with rows of * different heights and thus to a grid with decreased performance, * it should only be applied if that is intended. To set the * height of all items to a specific value, use {@link Grid#setItemHeight(int)} * instead. * <p> * When a column with activated word wrapping is resized * by dragging the column resizer, the items are only auto-resized * properly if you use {@link GridViewerColumn} to create the * columns. * <p> * When this method is called, existing rows are not resized to their * preferred height. Therefore it is suggested that this method be called * before rows are populated (i.e. before setInput). */ public void setAutoPreferredHeight(boolean autoPreferredHeight) { this.autoPreferredHeight = autoPreferredHeight; } /** * @return true if this grid viewer sizes its rows to their * preferred height * @see #setAutoPreferredHeight(boolean) */ public boolean getAutoPreferredHeight() { return autoPreferredHeight; } /** {@inheritDoc} */ protected void doUpdateItem(final Item item, Object element) { super.doUpdateItem(item, element); updateRowHeader(item); if(autoPreferredHeight && !item.isDisposed()) ((GridItem)item).pack(); } /** * Removes the element at the specified index of the parent. The selection is updated if required. * * @param parentOrTreePath the parent element, the input element, or a tree path to the parent element * @param index child index * @since 3.3 */ public void remove(final Object parentOrTreePath, final int index) { if (checkBusy()) return; final List oldSelection = new LinkedList(Arrays .asList(((TreeSelection) getSelection()).getPaths())); preservingSelection(new Runnable() { public void run() { TreePath removedPath = null; if (internalIsInputOrEmptyPath(parentOrTreePath)) { Tree tree = (Tree) getControl(); if (index < tree.getItemCount()) { TreeItem item = tree.getItem(index); if (item.getData() != null) { removedPath = getTreePathFromItem(item); disassociate(item); } item.dispose(); } } else { Widget[] parentItems = internalFindItems(parentOrTreePath); for (int i = 0; i < parentItems.length; i++) { TreeItem parentItem = (TreeItem) parentItems[i]; if (parentItem.isDisposed()) continue; if (index < parentItem.getItemCount()) { TreeItem item = parentItem.getItem(index); if (item.getData() != null) { removedPath = getTreePathFromItem(item); disassociate(item); } item.dispose(); } } } if (removedPath != null) { boolean removed = false; for (Iterator it = oldSelection.iterator(); it .hasNext();) { TreePath path = (TreePath) it.next(); if (path.startsWith(removedPath, getComparer())) { it.remove(); removed = true; } } if (removed) { setSelection(new TreeSelection( (TreePath[]) oldSelection .toArray(new TreePath[oldSelection .size()]), getComparer()), false); } } } }); } /** * Label provider used by calculate the row header text * * @param rowHeaderLabelProvider * the provider */ public void setRowHeaderLabelProvider( CellLabelProvider rowHeaderLabelProvider) { this.rowHeaderLabelProvider = rowHeaderLabelProvider; } private void updateRowHeader(Widget widget) { if (rowHeaderLabelProvider != null) { ViewerCell cell = getViewerRowFromItem(widget).getCell( Integer.MAX_VALUE); rowHeaderLabelProvider.update(cell); } } }
11,977
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridViewerRow.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/GridViewerRow.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * Tom Schindl <[email protected]> - various significant contributions * bug fix in: 191216 *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.ViewerRow; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Widget; /** * GridViewerRow is the concrete implementation of the part that represents items in a * Grid. */ public class GridViewerRow extends ViewerRow { private GridItem item; /** * Create a new instance of the receiver. * * @param item GridItem source. */ GridViewerRow(GridItem item) { this.item = item; } /** {@inheritDoc} */ public Rectangle getBounds(int columnIndex) { if( columnIndex == Integer.MAX_VALUE ) { //TODO Provide implementation for GridItem return null; } else { if( ! item.getParent().getColumn(columnIndex).isVisible() ) { return new Rectangle(0,0,0,0); } else { return item.getBounds(columnIndex); } } } /** {@inheritDoc} */ public Rectangle getBounds() { // TODO This is not correct. Update once item returns the correct information. return item.getBounds(0); } /** {@inheritDoc} */ public int getColumnCount() { return item.getParent().getColumnCount(); } /** {@inheritDoc} */ public Color getBackground(int columnIndex) { if( columnIndex == Integer.MAX_VALUE ) { //TODO Provide implementation for GridItem return null; } else { return item.getBackground(columnIndex); } } /** {@inheritDoc} */ public Font getFont(int columnIndex) { if( columnIndex == Integer.MAX_VALUE ) { //TODO Provide implementation for GridItem return null; } else { return item.getFont(columnIndex); } } /** {@inheritDoc} */ public Color getForeground(int columnIndex) { if( columnIndex == Integer.MAX_VALUE ) { //TODO Provide implementation for GridItem return null; } else { return item.getForeground(columnIndex); } } /** {@inheritDoc} */ public Image getImage(int columnIndex) { if( columnIndex == Integer.MAX_VALUE ) { //TODO Provide implementation for GridItem return null; } else { return item.getImage(columnIndex); } } /** {@inheritDoc} */ public String getText(int columnIndex) { if( columnIndex == Integer.MAX_VALUE ) { return item.getHeaderText(); } else { return item.getText(columnIndex); } } /** {@inheritDoc} */ public void setBackground(int columnIndex, Color color) { if( columnIndex == Integer.MAX_VALUE ) { item.setHeaderBackground(color); } else { item.setBackground(columnIndex, color); } } /** {@inheritDoc} */ public void setFont(int columnIndex, Font font) { if( columnIndex == Integer.MAX_VALUE ) { //TODO Provide implementation for GridItem } else { item.setFont(columnIndex, font); } } /** {@inheritDoc} */ public void setForeground(int columnIndex, Color color) { if( columnIndex == Integer.MAX_VALUE ) { item.setHeaderForeground(color); } else { item.setForeground(columnIndex, color); } } /** {@inheritDoc} */ public void setImage(int columnIndex, Image image) { if( columnIndex == Integer.MAX_VALUE ) { item.setHeaderImage(image); } else { item.setImage(columnIndex, image); } } /** {@inheritDoc} */ public void setText(int columnIndex, String text) { if( columnIndex == Integer.MAX_VALUE ) { item.setHeaderText(text); } else { item.setText(columnIndex, text == null ? "" : text); //$NON-NLS-1$ } } /** {@inheritDoc} */ public Control getControl() { return item.getParent(); } /** * {@inheritDoc} */ public ViewerRow getNeighbor(int direction, boolean sameLevel) { if( direction == ViewerRow.ABOVE ) { return getRowAbove(); } else if( direction == ViewerRow.BELOW ) { return getRowBelow(); } else { throw new IllegalArgumentException("Illegal value of direction argument."); //$NON-NLS-1$ } } private ViewerRow getRowAbove() { int index = item.getParent().indexOf(item) - 1; if( index >= 0 ) { return new GridViewerRow(item.getParent().getItem(index)); } return null; } private ViewerRow getRowBelow() { int index = item.getParent().indexOf(item) + 1; if( index < item.getParent().getItemCount() ) { GridItem tmp = item.getParent().getItem(index); if( tmp != null ) { return new GridViewerRow(tmp); } } return null; } /** * {@inheritDoc} */ public TreePath getTreePath() { return new TreePath(new Object[] {item.getData()}); } /** * {@inheritDoc} */ public Object clone() { return new GridViewerRow(item); } /** * {@inheritDoc} */ public Object getElement() { return item.getData(); } void setItem(GridItem item) { this.item = item; } /** * {@inheritDoc} */ public Widget getItem() { return item; } /** * {@inheritDoc} */ public int getVisualIndex(int creationIndex) { int[] order = item.getParent().getColumnOrder(); for (int i = 0; i < order.length; i++) { if (order[i] == creationIndex) { return i; } } return super.getVisualIndex(creationIndex); } /** * {@inheritDoc} */ public int getCreationIndex(int visualIndex) { if( item != null && ! item.isDisposed() && hasColumns() && isValidOrderIndex(visualIndex) ) { return item.getParent().getColumnOrder()[visualIndex]; } return super.getCreationIndex(visualIndex); } // public Rectangle getTextBounds(int index) { // return item.getTextBounds(index); // } // // /* (non-Javadoc) // * @see org.eclipse.jface.viewers.ViewerRow#getImageBounds(int) // */ // public Rectangle getImageBounds(int index) { // return item.getImageBounds(index); // } private boolean hasColumns() { return this.item.getParent().getColumnCount() != 0; } private boolean isValidOrderIndex(int currentIndex) { return currentIndex < this.item.getParent().getColumnOrder().length; } /** * Check if the column of the cell is part of is visible * * @param columnIndex the column index * * @return <code>true</code> if the column is visible */ protected boolean isColumnVisible(int columnIndex) { return item.getParent().getColumn(columnIndex).isVisible(); } }
7,442
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GridTableViewer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/GridTableViewer.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * [email protected] - various significant contributions *******************************************************************************/ package org.eclipse.nebula.jface.gridviewer; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.eclipse.jface.viewers.AbstractTableViewer; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerRow; import org.eclipse.nebula.jface.gridviewer.internal.CellSelection; import org.eclipse.nebula.jface.gridviewer.internal.SelectionWithFocusRow; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Widget; /** * A concrete viewer based on an Grid control. * <p> * This class is not intended to be subclassed outside the viewer framework. It * is designed to be instantiated with a pre-existing Grid control and * configured with a domain-specific content provider, label provider, element * filter (optional), and element sorter (optional). * <p> * Content providers for grid table viewers must not implement the {@code * ITreeContentProvider} interface. Instead a {@link GridTreeViewer} should be * used. * <p> */ public class GridTableViewer extends AbstractTableViewer { /** This viewer's grid control. */ private Grid grid; private GridViewerRow cachedRow; private CellLabelProvider rowHeaderLabelProvider; /** * If true, this grid viewer will ensure that the grid's rows / GridItems * are always sized to their preferred height. */ private boolean autoPreferredHeight = false; /** * Creates a grid viewer on a newly-created grid control under the given * parent. The grid control is created using the SWT style bits * <code>MULTI, H_SCROLL, V_SCROLL,</code> and <code>BORDER</code>. The * viewer has no input, no content provider, a default label provider, no * sorter, and no filters. * * @param parent * the parent control */ public GridTableViewer(Composite parent) { this(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); } /** * Creates a grid viewer on a newly-created grid control under the given * parent. The grid control is created using the given SWT style bits. The * viewer has no input, no content provider, a default label provider, no * sorter, and no filters. * * @param parent * the parent control * @param style * the SWT style bits used to create the grid. */ public GridTableViewer(Composite parent, int style) { this(new Grid(parent, style)); } /** * Creates a grid viewer on the given grid control. The viewer has no input, * no content provider, a default label provider, no sorter, and no filters. * * @param grid * the grid control */ public GridTableViewer(Grid grid) { this.grid = grid; hookControl(grid); } /** * Returns the underlying Grid Control. * * @return grid control. */ public Grid getGrid() { return grid; } /** {@inheritDoc} */ protected ViewerRow internalCreateNewRowPart(int style, int rowIndex) { GridItem item; if (rowIndex >= 0) { item = new GridItem(grid, style, rowIndex); } else { item = new GridItem(grid, style); } return getViewerRowFromItem(item); } /** {@inheritDoc} */ protected ColumnViewerEditor createViewerEditor() { return new GridViewerEditor(this, new ColumnViewerEditorActivationStrategy(this), ColumnViewerEditor.DEFAULT); } /** {@inheritDoc} */ protected void doClear(int index) { // TODO Fix when grid supports virtual } /** {@inheritDoc} */ protected void doClearAll() { // TODO Fix when grid supports virtual } /** {@inheritDoc} */ protected void doSetItemCount(int count) { // TODO Once grid supports virtual } /** {@inheritDoc} */ protected void doDeselectAll() { grid.deselectAll(); } /** {@inheritDoc} */ protected Widget doGetColumn(int index) { return grid.getColumn(index); } /** {@inheritDoc} */ protected int doGetColumnCount() { return grid.getColumnCount(); } /** {@inheritDoc} */ protected Item doGetItem(int index) { return grid.getItem(index); } /** {@inheritDoc} */ protected int doGetItemCount() { return grid.getItemCount(); } /** {@inheritDoc} */ protected Item[] doGetItems() { return grid.getItems(); } /** {@inheritDoc} */ protected Item[] doGetSelection() { return grid.getSelection(); } /** {@inheritDoc} */ protected int[] doGetSelectionIndices() { return grid.getSelectionIndices(); } /** {@inheritDoc} */ protected int doIndexOf(Item item) { return grid.indexOf((GridItem) item); } /** {@inheritDoc} */ protected void doRemove(int[] indices) { grid.remove(indices); } /** {@inheritDoc} */ protected void doRemove(int start, int end) { grid.remove(start, end); } /** {@inheritDoc} */ protected void doRemoveAll() { grid.removeAll(); } /** {@inheritDoc} */ protected void doSetSelection(Item[] items) { GridItem[] items2 = new GridItem[items.length]; for (int i = 0; i < items.length; i++) { items2[i] = (GridItem) items[i]; } grid.setSelection(items2); grid.showSelection(); } /** {@inheritDoc} */ protected void doSetSelection(int[] indices) { grid.setSelection(indices); } /** {@inheritDoc} */ protected void doShowItem(Item item) { grid.showItem((GridItem) item); } /** {@inheritDoc} */ protected void doShowSelection() { grid.showSelection(); } /** {@inheritDoc} */ protected Item getItemAt(Point point) { return grid.getItem(point); } /** {@inheritDoc} */ public Control getControl() { return grid; } /** {@inheritDoc} */ protected ViewerRow getViewerRowFromItem(Widget item) { if (cachedRow == null) { cachedRow = new GridViewerRow((GridItem) item); } else { cachedRow.setItem((GridItem) item); } return cachedRow; } /** * {@inheritDoc} */ protected void doResetItem(Item item) { GridItem gridItem = (GridItem) item; int columnCount = Math.max(1, grid.getColumnCount()); for (int i = 0; i < columnCount; i++) { gridItem.setText(i, ""); //$NON-NLS-1$ gridItem.setImage(null); } } /** * {@inheritDoc} */ protected void doSelect(int[] indices) { grid.select(indices); } /** * When set to true, this grid viewer will ensure that each of the grid's * items is always automatically sized to its preferred height. The default * is false. * <p> * Since this mechanism usually leads to a grid with rows of different * heights and thus to a grid with decreased performance, it should only be * applied if that is intended. To set the height of all items to a specific * value, use {@link Grid#setItemHeight(int)} instead. * <p> * When a column with activated word wrapping is resized by dragging the * column resizer, the items are only auto-resized properly if you use * {@link GridViewerColumn} to create the columns. * <p> * When this method is called, existing rows are not resized to their * preferred height. Therefore it is suggested that this method be called * before rows are populated (i.e. before setInput). */ public void setAutoPreferredHeight(boolean autoPreferredHeight) { this.autoPreferredHeight = autoPreferredHeight; } /** * @return true if this grid viewer sizes its rows to their preferred height * @see #setAutoPreferredHeight(boolean) */ public boolean getAutoPreferredHeight() { return autoPreferredHeight; } /** {@inheritDoc} */ protected void doUpdateItem(Widget widget, Object element, boolean fullMap) { super.doUpdateItem(widget, element, fullMap); updateRowHeader(widget); if (autoPreferredHeight && !widget.isDisposed()) ((GridItem) widget).pack(); } private void updateRowHeader(Widget widget) { if (rowHeaderLabelProvider != null) { ViewerCell cell = getViewerRowFromItem(widget).getCell( Integer.MAX_VALUE); rowHeaderLabelProvider.update(cell); } } /** * Label provider used by calculate the row header text * * @param rowHeaderLabelProvider * the provider */ public void setRowHeaderLabelProvider( CellLabelProvider rowHeaderLabelProvider) { this.rowHeaderLabelProvider = rowHeaderLabelProvider; } /** * Refresh row headers only * * @param element * the element to start or <code>null</code> if all rows should * be refreshed */ public void refreshRowHeaders(Object element) { boolean refresh = element == null; GridItem[] items = getGrid().getItems(); for (int i = 0; i < items.length; i++) { if (refresh || element.equals(items[i].getData())) { refresh = true; updateRowHeader(items[i]); } } } /** * {@inheritDoc} */ public void editElement(Object element, int column) { try { getControl().setRedraw(false); Widget item = findItem(element); if (item != null) { ViewerRow row = getViewerRowFromItem(item); if (row != null) { ViewerCell cell = row.getCell(column); if (cell != null) { triggerEditorActivationEvent(new ColumnViewerEditorActivationEvent( cell)); } } } } finally { getControl().setRedraw(true); } // } } /** * {@inheritDoc} */ protected void setSelectionToWidget(ISelection selection, boolean reveal) { if( ! grid.isCellSelectionEnabled() || !(selection instanceof CellSelection) ) { super.setSelectionToWidget(selection, reveal); if( selection instanceof SelectionWithFocusRow ) { Object el = ((SelectionWithFocusRow)selection).getFocusElement(); if( el != null ) { GridItem[] items = grid.getItems(); for( int i = 0; i < items.length; i++) { GridItem item = items[i]; if( item.getData() == el || item.getData().equals(el) || (getComparer() != null && getComparer().equals(item.getData(), el)) ) { grid.setFocusItem(item); break; } } } } } else { CellSelection cellSelection = (CellSelection) selection; List l = cellSelection.toList(); GridItem[] items = grid.getItems(); ArrayList pts = new ArrayList(); for( int i = 0; i < items.length; i++ ) { Iterator it = l.iterator(); Object itemObject = items[i].getData(); while( it.hasNext() ) { Object checkObject = it.next(); if( itemObject == checkObject || (getComparer() != null && getComparer().equals(itemObject, checkObject) ) ) { Iterator idxIt = cellSelection.getIndices(checkObject).iterator(); while( idxIt.hasNext() ) { Integer idx = (Integer) idxIt.next(); pts.add(new Point(idx.intValue(),i)); } } } } Point[] tmp = new Point[pts.size()]; pts.toArray(tmp); grid.setCellSelection(tmp); if( cellSelection.getFocusElement() != null ) { Object el = cellSelection.getFocusElement(); for( int i = 0; i < items.length; i++) { GridItem item = items[i]; if( item.getData() == el || item.getData().equals(el) || (getComparer() != null && getComparer().equals(item.getData(), el)) ) { grid.setFocusItem(item); break; } } } } } /** * {@inheritDoc} */ public ISelection getSelection() { if (!grid.isCellSelectionEnabled()) { IStructuredSelection selection = (IStructuredSelection) super .getSelection(); Object el = null; if (grid.getFocusItem() != null) { el = grid.getFocusItem().getData(); } return new SelectionWithFocusRow(selection.toList(), el, getComparer()); } else { return createCellSelection(); } } private CellSelection createCellSelection() { Point[] ps = grid.getCellSelection(); Arrays.sort(ps, new Comparator() { public int compare(Object arg0, Object arg1) { Point a = (Point) arg0; Point b = (Point) arg1; int rv = a.y - b.y; if (rv == 0) { rv = a.x - b.x; } return rv; } }); ArrayList objectList = new ArrayList(); ArrayList indiceLists = new ArrayList(); ArrayList indiceList = new ArrayList(); int curLine = -1; for (int i = 0; i < ps.length; i++) { if (curLine != ps[i].y) { curLine = ps[i].y; indiceList = new ArrayList(); indiceLists.add(indiceList); objectList.add(grid.getItem(curLine).getData()); } indiceList.add(new Integer(ps[i].x)); } Object focusElement = null; if (grid.getFocusItem() != null) { focusElement = grid.getFocusItem().getData(); } return new CellSelection(objectList, indiceLists, focusElement, getComparer()); } }
13,554
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CellSelection.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/internal/CellSelection.java
package org.eclipse.nebula.jface.gridviewer.internal; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.viewers.IElementComparer; import org.eclipse.jface.viewers.StructuredSelection; /** * FIXME */ public class CellSelection extends SelectionWithFocusRow { private List indicesList; private List elements; /** * Creates a structured selection from the given <code>List</code> and * element comparer. If an element comparer is provided, it will be used to * determine equality between structured selection objects provided that * they both are based on the same (identical) comparer. See bug * * @param elements * list of selected elements * @param comparer * the comparer, or null * @since 3.4 */ public CellSelection(List elements, List indicesList, Object focusElement, IElementComparer comparer) { super(elements,focusElement,comparer); this.elements = new ArrayList(elements); this.indicesList = indicesList; } /** * FIXME * @param element * @return the indices */ public List getIndices(Object element) { return (List) indicesList.get(elements.indexOf(element)); } }
1,200
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SelectionWithFocusRow.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/jface/gridviewer/internal/SelectionWithFocusRow.java
package org.eclipse.nebula.jface.gridviewer.internal; import java.util.List; import org.eclipse.jface.viewers.IElementComparer; import org.eclipse.jface.viewers.StructuredSelection; /** * FIXME */ public class SelectionWithFocusRow extends StructuredSelection { private Object focusElement; /** * FIXME * @param elements * @param focusElement * @param comparer */ public SelectionWithFocusRow(List elements, Object focusElement, IElementComparer comparer) { super(elements,comparer); this.focusElement = focusElement; } /** * FIXME * @return the focus element */ public Object getFocusElement() { return focusElement; } }
672
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/cat/ts/help/Activator.java
package net.heartsome.cat.ts.help; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { /** * The plug-in ID */ public static final String PLUGIN_ID = "net.heartsome.cat.ts.help"; // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given plug-in relative path * @param path * the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } }
1,163
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SystemResourceUtil.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/cat/ts/help/SystemResourceUtil.java
package net.heartsome.cat.ts.help; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.widgets.Display; import net.heartsome.license.LicenseAgreementDialog; import net.heartsome.license.LicenseManageDialog; import net.heartsome.license.LocalAuthorizationValidator; import net.heartsome.license.constants.Constants; import net.heartsome.license.utils.DateUtils; import net.heartsome.license.utils.FileUtils; import net.heartsome.license.webservice.ServiceUtil; public class SystemResourceUtil { public static String dateTemp; private static LocalAuthorizationValidator v = new LocalAuthorizationValidator(); private static int re; private static boolean isExsit = false; // public static void beforeload() { // isExsit = FileUtils.isExsit(); // if (isExsit) { // re = v.checkLicense(); // } // } // public static void load(boolean isShow) { // if (isExsit) { // if (Constants.STATE_VALID == re) { // try { // final int ret = ServiceUtil.check(v.getLicenseId(), v.getMacCode(), v.getInstall()); // final String date = ServiceUtil.getTempEndDate(v.getLicenseId()); // if (Constants.STATE_VALID == ret) { // if (isShow) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_VALID, date, v.getLicenseId()); // dialog.open(); // } // }); // } // } else if (ret == Constants.STATE_INVALID) { // FileUtils.removeFile(); // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_INVALID, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (ret == Constants.STATE_EXPIRED) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_EXPIRED, date, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (Constants.EXCEPTION_INT15 == ret) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.EXCEPTION_INT15, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else { // Display.getDefault().asyncExec(new Runnable() { // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), ret, null, v.getLicenseId()); // dialog.open(); // System.exit(0); // } // }); // } // } catch (Exception e) { // e.printStackTrace(); // if (v.isTrial()) { // Throwable t = e; // while(t.getCause() != null) { // t = t.getCause(); // } // if (t instanceof java.security.cert.CertificateException) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.EXCEPTION_INT16, null, v.getLicenseId()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.EXCEPTION_INT17, null, v.getLicenseId()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } // } else { // if (isShow) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_VALID, null, v.getLicenseId()); // dialog.open(); // } // }); // } // } // } // } else if (Constants.STATE_INVALID == re) { // FileUtils.removeFile(); // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_INVALID, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (Constants.EXCEPTION_INT15 == re // || Constants.EXCEPTION_INT1 == re || Constants.EXCEPTION_INT2 == re // || Constants.EXCEPTION_INT3 == re || Constants.EXCEPTION_INT4 == re) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (Constants.EXCEPTION_INT14 == re) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, v.getLicenseId()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else { // Display.getDefault().asyncExec(new Runnable() { // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, v.getLicenseId()); // dialog.open(); // System.exit(0); // } // }); // } // } else { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseAgreementDialog dialog = new LicenseAgreementDialog(Display.getDefault().getActiveShell()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } // } // public static void load() { // new Thread(new Runnable() { // public void run() { // if (DateUtils.getDate().equals(dateTemp)) { // return; // } else { // dateTemp = DateUtils.getDate(); // } // // if (FileUtils.isExsit()) { // final LocalAuthorizationValidator v = new LocalAuthorizationValidator(); // final int re = v.checkLicense(); // if (Constants.STATE_VALID == re) { // try { // final int ret = ServiceUtil.check(v.getLicenseId(), v.getMacCode(), v.getInstall()); // final String date = ServiceUtil.getTempEndDate(v.getLicenseId()); // if (Constants.STATE_VALID == ret) { // } else if (ret == Constants.STATE_INVALID) { // FileUtils.removeFile(); // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_INVALID, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (ret == Constants.STATE_EXPIRED) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_EXPIRED, date, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (Constants.EXCEPTION_INT15 == ret) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.EXCEPTION_INT15, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else { // Display.getDefault().asyncExec(new Runnable() { // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), ret, null, v.getLicenseId()); // dialog.open(); // System.exit(0); // } // }); // } // } catch (Exception e) { // e.printStackTrace(); // if (v.isTrial()) { // Throwable t = e; // while(t.getCause() != null) { // t = t.getCause(); // } // if (t instanceof java.security.cert.CertificateException) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.EXCEPTION_INT16, null, v.getLicenseId()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.EXCEPTION_INT17, null, v.getLicenseId()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } // } // } // } else if (Constants.STATE_INVALID == re) { // FileUtils.removeFile(); // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_INVALID, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (Constants.EXCEPTION_INT15 == re // || Constants.EXCEPTION_INT1 == re || Constants.EXCEPTION_INT2 == re // || Constants.EXCEPTION_INT3 == re || Constants.EXCEPTION_INT4 == re) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else if (Constants.EXCEPTION_INT14 == re) { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, v.getLicenseId()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } else { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, v.getLicenseId()); // dialog.open(); // System.exit(0); // } // }); // } // } else { // Display.getDefault().asyncExec(new Runnable() { // // public void run() { // LicenseAgreementDialog dialog = new LicenseAgreementDialog(Display.getDefault().getActiveShell()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } // }); // } // } // }).start(); // } // public static String[] load(IProgressMonitor monitor) { // String[] str = new String[3]; // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // // if (FileUtils.isExsit()) { // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // LocalAuthorizationValidator v = new LocalAuthorizationValidator(); // int re = v.checkLicense(); // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(2); // } // if (Constants.STATE_VALID == re) { // try { // str[2] = v.getLicenseId(); // int ret = ServiceUtil.check(v.getLicenseId(), v.getMacCode(), v.getInstall()); // str[0] = String.valueOf(ret); // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(2); // } // String date = ServiceUtil.getTempEndDate(v.getLicenseId()); // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(2); // } // str[1] = date; // return str; // } catch (Exception e) { // e.printStackTrace(); // if (v.isTrial()) { // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // Throwable t = e; // while(t.getCause() != null) { // t = t.getCause(); // } // // if (t instanceof java.security.cert.CertificateException) { // str[0] = String.valueOf(Constants.EXCEPTION_INT16); // } else { // str[0] = String.valueOf(Constants.EXCEPTION_INT17); // } // return str; // } else { // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // str[0] = String.valueOf(Constants.STATE_VALID); // return str; // } // } // } else if (Constants.STATE_INVALID == re) { // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // str[0] = String.valueOf(Constants.STATE_INVALID); // return str; // } else { // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // str[2] = v.getLicenseId(); // str[0] = String.valueOf(re); // return str; // } // } else { // if (monitor != null) { // if (monitor.isCanceled()) { // str[0] = String.valueOf(Constants.CANCEL); // return str; // } // monitor.worked(1); // } // // str[0] = String.valueOf(Constants.STATE_FILE_NOT_EXSIT); // return str; // } // } // public static void showDialog(String[] str) { // int re = Integer.parseInt(str[0]); // if (Constants.STATE_VALID == re) { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_VALID, str[1], str[2]); // dialog.open(); // } else if (Constants.STATE_INVALID == re) { // FileUtils.removeFile(); // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_INVALID, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } else if (Constants.STATE_EXPIRED == re) { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), Constants.STATE_EXPIRED, str[1], null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } else if (Constants.EXCEPTION_INT16 == re || Constants.EXCEPTION_INT17 == re) { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, str[2]); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } else if (Constants.CANCEL == re) { // return; // } else if (Constants.STATE_FILE_NOT_EXSIT == re) { // LicenseAgreementDialog dialog = new LicenseAgreementDialog(Display.getDefault().getActiveShell()); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } else if (Constants.EXCEPTION_INT15 == re // || Constants.EXCEPTION_INT1 == re || Constants.EXCEPTION_INT2 == re // || Constants.EXCEPTION_INT3 == re || Constants.EXCEPTION_INT4 == re) { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, null); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } else if (Constants.EXCEPTION_INT14 == re) { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, str[2]); // int result = dialog.open(); // if (result != IDialogConstants.OK_ID) { // System.exit(0); // } // } else { // LicenseManageDialog dialog = new LicenseManageDialog(Display.getDefault().getActiveShell(), re, null, str[2]); // dialog.open(); // System.exit(0); // } // } }
18,312
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Series.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/Series.java
package net.heartsome.license; public class Series { public native String getSeries(); }
91
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
OffLineActiveService.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/OffLineActiveService.java
package net.heartsome.license; import net.heartsome.license.constants.Constants; import net.heartsome.license.encrypt.InstallKeyEncrypt; import net.heartsome.license.generator.IKeyGenerator; import net.heartsome.license.generator.KeyGeneratorImpl; import net.heartsome.license.utils.FileUtils; import net.heartsome.license.utils.StringUtils; public class OffLineActiveService { private String installKey; /** * 脱机激活时选择授权文件对话框激活时的验证 * @param fileName 文件名 * @return ; */ public int activeByGrantFile(String fileName) { boolean result = FileUtils.writeFile(new byte[] {'1','1'}, ProtectionFactory.getFileName(0, Constants.PRODUCTID)); if (!result) { return Constants.EXCEPTION_INT8; } else { FileUtils.removeFile(ProtectionFactory.getFileName(0, Constants.PRODUCTID)); } byte[] key = FileUtils.readFile(fileName); if (key == null) { return Constants.EXCEPTION_INT1; } byte[] t = new LicenseReader().getLicenseInfo(key); if (t == null) { return Constants.EXCEPTION_INT2; } String[] arrInfo = getStrFromInfo(StringUtils.reverse(new String(t), 1, 5, 2)); // 修改分隔符之后,旧版本的许可文件会导致异常,所以需要在这里判断一下,如果有异常,则会删掉原有文件,重新激活即可。 if (arrInfo.length<3){ return Constants.STATE_INVALID; } String strKeyCode = arrInfo[0]; String strMacCode = arrInfo[1]; String strInstallCode = arrInfo[2]; LicenseIdValidator va = new LicenseIdValidator(strKeyCode); if (!va.checkLicense()) { return Constants.STATE_INVALID; } if (!va.checkEdition()) { return Constants.STATE_INVALID; } if (va.getType()) { return Constants.STATE_INVALID; } String curMacCode = ProtectionFactory.getSeries(); if (!strMacCode.equals(curMacCode)) { return Constants.STATE_INVALID; } byte[] b = FileUtils.readFile(ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (b == null) { return Constants.EXCEPTION_INT3; } else { b = InstallKeyEncrypt.decrypt(b); if (b == null) { return Constants.EXCEPTION_INT4; } } if (!StringUtils.reverse(new String(b), 1, 3, 2).equals(strInstallCode)) { return Constants.STATE_INVALID; } result = FileUtils.writeFile(key, ProtectionFactory.getFileName(1, Constants.PRODUCTID)); if (!result) { return Constants.EXCEPTION_INT12; } System.getProperties().setProperty("TSState", "true"); return Constants.STATE_VALID; } /** * 生成安装码文件 * @return ; */ public int generateInstallFile() { boolean result = FileUtils.writeFile(new byte[] {'1','1'}, ProtectionFactory.getFileName(0, Constants.PRODUCTID)); if (!result) { return Constants.EXCEPTION_INT8; } else { FileUtils.removeFile(ProtectionFactory.getFileName(0, Constants.PRODUCTID)); } IKeyGenerator gen = new KeyGeneratorImpl(); installKey = gen.generateInstallKey(); byte[] t = InstallKeyEncrypt.encrypt(StringUtils.handle(gen.getInstallKey(), 1, 3, 2).getBytes()); if (t == null) { return Constants.EXCEPTION_INT10; } result = FileUtils.writeFile(t, ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (!result) { return Constants.EXCEPTION_INT11; } return Constants.STATE_VALID; } public int readInstallFile() { byte[] b = FileUtils.readFile(ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (b == null) { return Constants.EXCEPTION_INT3; } else { b = InstallKeyEncrypt.decrypt(b); if (b == null) { return Constants.EXCEPTION_INT4; } } installKey = StringUtils.reverse(new String(b), 1, 3, 2); return Constants.STATE_INVALID; } public String getInstallKey() { return installKey; } private String[] getStrFromInfo(String info) { return info.split(Constants.SEPARATOR); } }
3,866
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
WindowsSeries.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/WindowsSeries.java
package net.heartsome.license; public class WindowsSeries implements SeriesInterface { public String getSeries() { try { System.loadLibrary("win_x86_Series_" + System.getProperty("sun.arch.data.model") + "bit"); } catch (UnsatisfiedLinkError e) { return null; } catch (SecurityException sex) { return null; } return new Series().getSeries(); } }
404
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ActiveMethodDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/ActiveMethodDialog.java
package net.heartsome.license; import net.heartsome.license.constants.Constants; import net.heartsome.license.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; /** * 激活方式选择对话框 * @author karl * @version * @since JDK1.6 */ public class ActiveMethodDialog extends Dialog { private Point p; /** * 构造器 * @param parentShell */ public ActiveMethodDialog(Shell parentShell) { super(parentShell); } /** * 构造器 * @param parentShell * @param p */ public ActiveMethodDialog(Shell parentShell, Point p) { super(parentShell); this.p = p; } @Override protected Point getInitialLocation(Point initialSize) { if (p == null) { return super.getInitialLocation(initialSize); } else { return p; } } @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, Messages.getString("license.LicenseManageDialog.exitBtn"), true); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("license.LicenseManageDialog.title")); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.marginWidth = 10; layout.marginTop = 5; tparent.setLayout(layout); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Group groupActiveMethod = new Group(tparent, SWT.NONE); groupActiveMethod.setText(Messages.getString("license.ActiveMethodDialog.activemethod")); GridLayout groupLayout = new GridLayout(); groupLayout.marginWidth = 20; groupLayout.marginHeight = 20; groupLayout.verticalSpacing = 10; groupLayout.numColumns = 2; groupActiveMethod.setLayout(groupLayout); GridDataFactory.fillDefaults().grab(true, true).applyTo(groupActiveMethod); Button btnOnline = new Button(groupActiveMethod, SWT.NONE); GridData btnData = new GridData(); btnData.widthHint = 200; btnData.heightHint = 40; btnOnline.setLayoutData(btnData); btnOnline.setText(Messages.getString("license.ActiveMethodDialog.activeonline")); btnOnline.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { setReturnCode(OK); Point p = getShell().getLocation(); close(); LicenseManageDialog dialog = new LicenseManageDialog(getShell(), Constants.STATE_NOT_ACTIVATED, null, null, true, p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } }); Label labelRecommend = new Label(groupActiveMethod, SWT.NONE); labelRecommend.setText(Messages.getString("license.ActiveMethodDialog.recommend")); Label labelOnline = new Label(groupActiveMethod, SWT.WRAP); labelOnline.setText(Messages.getString("license.ActiveMethodDialog.onlinemessage")); GridData dataLabel = new GridData(); dataLabel.horizontalSpan = 2; dataLabel.widthHint = 450; labelOnline.setLayoutData(dataLabel); Label labelSpace = new Label(groupActiveMethod, SWT.NONE); GridData dataSpace = new GridData(); dataSpace.horizontalSpan = 2; dataSpace.heightHint = 20; labelSpace.setLayoutData(dataSpace); Button btnOffline = new Button(groupActiveMethod, SWT.NONE); GridData btnData1 = new GridData(); btnData1.widthHint = 200; btnData1.heightHint = 40; btnData1.horizontalSpan = 2; btnOffline.setLayoutData(btnData1); btnOffline.setText(Messages.getString("license.ActiveMethodDialog.activeoffline")); btnOffline.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { setReturnCode(OK); Point p = getShell().getLocation(); close(); OfflineActiveDialog dialog = new OfflineActiveDialog(getShell(), p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } }); Label labelOffline = new Label(groupActiveMethod, SWT.WRAP); labelOffline.setText(Messages.getString("license.ActiveMethodDialog.offlinemessage")); labelOffline.setLayoutData(dataLabel); Label labelOffline1 = new Label(groupActiveMethod, SWT.WRAP); labelOffline1.setText(Messages.getString("license.ActiveMethodDialog.offlinemessage1")); GridData dataLabel1 = new GridData(); dataLabel1.horizontalSpan = 2; dataLabel1.widthHint = 450; labelOffline1.setLayoutData(dataLabel1); return super.createDialogArea(parent); } @Override protected Point getInitialSize() { return new Point(520, 470); } }
5,176
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ProtectionFactory.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/ProtectionFactory.java
package net.heartsome.license; import java.io.File; import net.heartsome.license.encrypt.Encrypt; import net.heartsome.license.encrypt.EncryptRSA; import org.eclipse.jface.util.Util; public class ProtectionFactory { public static String getSeries() { SeriesInterface s; if (Util.isWindows()) { s = new WindowsSeries(); } else if (Util.isMac()) { s = new MacosxSeries(); } else { s = new LinuxSeries(); } return s.getSeries(); } public static Encrypt getEncrypt() { Encrypt en = new EncryptRSA(); return en; } public static String getFileName(int type, String productId) { String fileName = ""; if (type == 1) { fileName = "file-permission"; } else if (type == 2) { fileName = "install"; } else { fileName = "123"; } String folder = ""; if (Util.isWindows()) { folder = System.getenv("windir"); File f1 = new File(folder); if (!f1.exists()) { f1.mkdirs(); } return System.getenv("windir") + "\\" + fileName + productId + ".inf"; } else if (Util.isMac()) { folder = System.getProperty("user.home") + "/.local"; File f1 = new File(folder); if (!f1.exists()) { f1.mkdirs(); } return System.getProperty("user.home") + "/.local" + "/" + fileName + productId + ".eps"; } else { folder = System.getProperty("user.home") + "/.local"; File f1 = new File(folder); if (!f1.exists()) { f1.mkdirs(); } return System.getProperty("user.home") + "/.local" + "/" + fileName + productId + ".msl"; } } public static String getPlatform() { if (Util.isWindows()) { if ("32".equals(System.getProperty("sun.arch.data.model"))) { return "1"; } else { return "2"; } } else if (Util.isMac()) { return "5"; } else { if ("32".equals(System.getProperty("sun.arch.data.model"))) { return "3"; } else { return "4"; } } } public static String getProduct() { if("U".equals(System.getProperty("TSEdition"))) { return "28"; } else if ("F".equals(System.getProperty("TSEdition"))) { return "27"; } else if ("P".equals(System.getProperty("TSEdition"))) { return "26"; } else { return "25"; } } public static String getProduct(String edition) { if("U".equals(edition)) { return "28"; } else if ("F".equals(edition)) { return "27"; } else if ("P".equals(edition)) { return "26"; } else { return "25"; } } public static String getVersion() { String version = System.getProperty("TSVersionDate"); version = version.substring(0, version.lastIndexOf(".")); return version.replaceAll("[.]", "_"); } }
2,601
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LinuxSeries.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/LinuxSeries.java
package net.heartsome.license; //import java.io.File; //import java.io.IOException; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; //import net.heartsome.license.utils.StringUtils; // //import org.eclipse.core.runtime.FileLocator; //import org.eclipse.core.runtime.Platform; //import org.safehaus.uuid.EthernetAddress; //import org.safehaus.uuid.NativeInterfaces; public class LinuxSeries implements SeriesInterface { public String getSeries() { // try { //// NativeInterfaces.setLibDir(new File("lib")); // NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath() // + File.separator + System.getProperty("sun.arch.data.model"))); // EthernetAddress[] macs = NativeInterfaces.getAllInterfaces(); // String series = ""; // for (EthernetAddress a : macs) { // series += a.toString() + "+"; // } // return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1)); // } catch (IOException e) { // e.printStackTrace(); // return null; // } try { String series = ""; Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface network = networkInterfaces.nextElement(); if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) { byte[] mac = network.getHardwareAddress(); if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02x", mac[i])); } sb.append("+"); series += sb.toString(); } } } return "".equals(series) ? null : series.substring(0, series.length() - 1); } catch (SocketException e) { e.printStackTrace(); return null; } } }
1,991
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
OfflineActiveDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/OfflineActiveDialog.java
package net.heartsome.license; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import net.heartsome.license.constants.Constants; import net.heartsome.license.encrypt.OffLineEncrypt; import net.heartsome.license.generator.IKeyGenerator; import net.heartsome.license.generator.KeyGeneratorImpl; import net.heartsome.license.generator.LicenseIdGenerator; import net.heartsome.license.resource.Messages; import net.heartsome.license.utils.FileUtils; import net.heartsome.license.utils.StringUtils; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 脱机激活对话框 * @author karl * @version * @since JDK1.6 */ public class OfflineActiveDialog extends Dialog { private Cursor cursor = new Cursor(Display.getDefault(), SWT.CURSOR_HAND); private Text text1; private Text text2; private Text text3; private Text text4; private Text text5; private Text text6; private Point p; protected OfflineActiveDialog(Shell parentShell) { super(parentShell); } protected OfflineActiveDialog(Shell parentShell, Point p) { super(parentShell); this.p = p; } @Override protected Point getInitialLocation(Point initialSize) { if (p == null) { return super.getInitialLocation(initialSize); } else { return p; } } @Override protected void createButtonsForButtonBar(Composite parent) { Button backBtn = createButton(parent, IDialogConstants.BACK_ID, Messages.getString("license.OfflineActiveDialog.backBtn"), false); backBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setReturnCode(OK); Point p = getShell().getLocation(); close(); ActiveMethodDialog dialog = new ActiveMethodDialog(getShell(), p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } }); super.createButtonsForButtonBar(parent); Button nextBtn = getButton(IDialogConstants.OK_ID); nextBtn.setText(Messages.getString("license.LicenseAgreementDialog.nextBtn")); Button exitBtn = getButton(IDialogConstants.CANCEL_ID); exitBtn.setText(Messages.getString("license.LicenseAgreementDialog.exitBtn")); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.marginWidth = 10; layout.marginTop = 10; tparent.setLayout(layout); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Composite compNav = new Composite(tparent, SWT.NONE); GridLayout navLayout = new GridLayout(); compNav.setLayout(navLayout); createNavigation(compNav); Group groupLicenseId = new Group(tparent, SWT.NONE); groupLicenseId.setText(Messages.getString("license.OfflineActiveDialog.licenseIdGroup")); GridDataFactory.fillDefaults().grab(true, true).applyTo(groupLicenseId); GridLayout layoutGroup = new GridLayout(2, false); layoutGroup.marginLeft = 5; layoutGroup.marginHeight = 100; groupLicenseId.setLayout(layoutGroup); Label label = new Label(groupLicenseId, SWT.NONE); label.setText(Messages.getString("license.LicenseManageDialog.licenseIdLabel")); createIdInputComp(groupLicenseId); Composite compLink = new Composite(groupLicenseId, SWT.NONE); RowLayout layoutLink = new RowLayout(); layoutLink.marginTop = 20; layoutLink.marginRight = 0; layoutLink.marginLeft = 0; layoutLink.marginBottom = 10; compLink.setLayout(layoutLink); GridData linkData = new GridData(GridData.FILL_HORIZONTAL); linkData.horizontalSpan = 2; compLink.setLayoutData(linkData); Label label1 = new Label(compLink, SWT.NONE); label1.setText(Messages.getString("license.LicenseManageDialog.label1")); if (!"L".equals(System.getProperty("TSEdition"))) { Label link1 = new Label(compLink, SWT.NONE); link1.setText(Messages.getString("license.LicenseManageDialog.link1")); link1.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); link1.setCursor(cursor); link1.addMouseListener(new MouseListener() { public void mouseUp(MouseEvent e) { } public void mouseDown(MouseEvent e) { Program.launch(Messages.getString("license.LicenseManageDialog.urlr8buy") + "&PRODUCT=" + ProtectionFactory.getProduct() + "&PLATFORM=" + ProtectionFactory.getPlatform()); } public void mouseDoubleClick(MouseEvent e) { } }); } else { Label link2 = new Label(compLink, SWT.NONE); link2.setText(Messages.getString("license.LicenseManageDialog.link2")); link2.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); link2.setCursor(cursor); link2.addMouseListener(new MouseListener() { public void mouseUp(MouseEvent e) { } public void mouseDown(MouseEvent e) { Program.launch(Messages.getString("license.LicenseManageDialog.urlr8trial") + "&PRODUCT=" + ProtectionFactory.getProduct() + "&PLATFORM=" + ProtectionFactory.getPlatform()); } public void mouseDoubleClick(MouseEvent e) { } }); } Label label3 = new Label(compLink, SWT.NONE); label3.setText(Messages.getString("license.LicenseManageDialog.label3")); return tparent; } @Override protected Point getInitialSize() { return new Point(520, 470); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("license.LicenseManageDialog.title")); } private void createNavigation(Composite parent) { Label label = new Label(parent, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.operatenavigation")); RowLayout layout = new RowLayout(); Composite comp = new Composite(parent, SWT.NONE); comp.setLayout(layout); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.inputlicenseid")); label.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.getactivekey")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.getgrantfile")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.activefinish")); } private void createIdInputComp(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(11, false); layout.marginHeight = 0; layout.marginWidth = 0; comp.setLayout(layout); GridData compData = new GridData(); comp.setLayoutData(compData); GridData textData = new GridData(); textData.widthHint = 40; GridData labelData = new GridData(); labelData.widthHint = 5; text1 = new Text(comp,SWT.BORDER); text1.setLayoutData(textData); text1.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text1.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text1.setText(s.substring(0, 4)); text2.setFocus(); text2.setText(s.substring(4)); } else if (length == 4) { text2.setFocus(); } } } else { text1.setText(s.substring(0, i)); break; } } } }); Label label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text2 = new Text(comp,SWT.BORDER); text2.setLayoutData(textData); text2.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text2.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text2.setText(s.substring(0, 4)); text3.setFocus(); text3.setText(s.substring(4)); } else if (length == 4) { text3.setFocus(); } } } else { text2.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text3 = new Text(comp,SWT.BORDER); text3.setLayoutData(textData); text3.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text3.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text3.setText(s.substring(0, 4)); text4.setFocus(); text4.setText(s.substring(4)); } else if (length == 4) { text4.setFocus(); } } } else { text3.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text4 = new Text(comp,SWT.BORDER); text4.setLayoutData(textData); text4.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text4.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text4.setText(s.substring(0, 4)); text5.setFocus(); text5.setText(s.substring(4)); } else if (length == 4) { text5.setFocus(); } } } else { text4.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text5 = new Text(comp,SWT.BORDER); text5.setLayoutData(textData); text5.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text5.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text5.setText(s.substring(0, 4)); text6.setFocus(); text6.setText(s.substring(4)); } else if (length == 4) { text6.setFocus(); } } } else { text5.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text6 = new Text(comp,SWT.BORDER); text6.setLayoutData(textData); text6.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text6.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text6.setText(s.substring(0, 4)); } } } else { text6.setText(s.substring(0, i)); } } } }); } private String getLicenseId() { return text1.getText() + text2.getText() + text3.getText() + text4.getText() + text5.getText() + text6.getText(); } private String getVersionContent(String version) { if ("U".equals(version)) { return Messages.getString("license.LicenseManageDialog.Ultimate"); } else if ("F".equals(version)) { return Messages.getString("license.LicenseManageDialog.Professional"); } else if ("P".equals(version)) { return Messages.getString("license.LicenseManageDialog.Personal"); } else { return Messages.getString("license.LicenseManageDialog.Lite"); } } @Override protected void okPressed() { LicenseIdValidator va = new LicenseIdValidator(getLicenseId()); if (va.checkLicense()) { if (va.getType()) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.OfflineActiveDialog.onlyCommercial")); } else { if (va.checkEdition()) { String series = ProtectionFactory.getSeries(); if (series == null || "".equals(series)) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), MessageFormat.format(Messages.getString("license.OfflineActiveDialog.getActiveKeyFail"), StringUtils.getErrorCode(Constants.EXCEPTION_INT5))); return; } String installKey = null; OffLineActiveService v = new OffLineActiveService(); if (FileUtils.isExsitInstall()) { int r = v.readInstallFile(); if (r == Constants.EXCEPTION_INT3 || r == Constants.EXCEPTION_INT4) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), MessageFormat.format(Messages.getString("license.OfflineActiveDialog.getActiveKeyFail"), StringUtils.getErrorCode(r))); return; } else { installKey = v.getInstallKey(); } } else { int r = v.generateInstallFile(); if (r == Constants.EXCEPTION_INT8) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.OfflineActiveDialog.getActiveKeyByAdmin")); System.exit(0); } else if (r == Constants.EXCEPTION_INT10 || r == Constants.EXCEPTION_INT11) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), MessageFormat.format(Messages.getString("license.OfflineActiveDialog.getActiveKeyFail"), StringUtils.getErrorCode(r))); return; } else { installKey = v.getInstallKey(); } } IKeyGenerator gen = new KeyGeneratorImpl(); byte[] k = gen.generateKey(getLicenseId(), series, installKey, OffLineEncrypt.publicKey); Point p = getShell().getLocation(); super.okPressed(); GetActiveKeyDialog dialog = new GetActiveKeyDialog(getShell(), StringUtils.toHexString(k), p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } else { String edition1 = getVersionContent(System.getProperty("TSEdition")); String editionInput = new LicenseIdGenerator(getLicenseId()).getVersion(); String edition2 = getVersionContent(editionInput); String message = MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoInvalid1"), edition1, edition2); ArrayList<HashMap<String, Integer>> list = new ArrayList<HashMap<String, Integer>>(); HashMap<String, Integer> map1 = new HashMap<String, Integer>(); map1.put("start", message.indexOf(edition1)); map1.put("length", edition1.length()); list.add(map1); HashMap<String, Integer> map2 = new HashMap<String, Integer>(); map2.put("start", message.indexOf(edition2)); map2.put("length", edition2.length()); list.add(map2); HashMap<String, Integer> map3 = new HashMap<String, Integer>(); map3.put("start", message.lastIndexOf(edition1)); map3.put("length", edition1.length()); list.add(map3); HashMap<String, Integer> map4 = new HashMap<String, Integer>(); map4.put("start", message.lastIndexOf(edition2)); map4.put("length", edition2.length()); list.add(map4); new CustomMessageDialog(getShell(), Messages.getString("license.LicenseManageDialog.titleInvalid"), message, list, editionInput).open(); } } } else { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleInvalid"), Messages.getString("license.LicenseManageDialog.infoInvalid")); } } }
17,385
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LicenseIdValidator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/LicenseIdValidator.java
package net.heartsome.license; import net.heartsome.license.constants.Constants; import net.heartsome.license.generator.LicenseIdGenerator; public class LicenseIdValidator { private boolean isTrial; private LicenseIdGenerator gen; public LicenseIdValidator(String licenseId) { gen = new LicenseIdGenerator(licenseId); } public boolean checkLicense() { if (!gen.checkLength()) { return false; } String temp = gen.getIsTrial(); if (!Constants.TYPE_TMEP.equals(temp) && !Constants.TYPE_BUSINESS.equals(temp)) { return false; } isTrial = Constants.TYPE_TMEP.equals(temp); if (!System.getProperty("TSVersion").equals(gen.getProductId())) { return false; } temp = gen.getVersion(); if (!"U".equals(temp) && !"F".equals(temp) && !"P".equals(temp) && !"L".equals(temp)) { return false; } return true; } public boolean checkEdition() { if (!System.getProperty("TSEdition").equals(gen.getVersion())) { return false; } System.getProperties().setProperty("TSHelp", "true"); return true; } public boolean getType() { return isTrial; } }
1,111
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LocalAuthorizationValidator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/LocalAuthorizationValidator.java
package net.heartsome.license; import net.heartsome.license.constants.Constants; import net.heartsome.license.encrypt.InstallKeyEncrypt; import net.heartsome.license.utils.FileUtils; import net.heartsome.license.utils.StringUtils; public class LocalAuthorizationValidator { private boolean isTrial = false; private String licenseId = ""; private String macCode = null; private byte[] b; public int checkLicense() { byte[] t = FileUtils.readFile(ProtectionFactory.getFileName(1, Constants.PRODUCTID)); if (t == null) { return Constants.EXCEPTION_INT1; } t = new LicenseReader().getLicenseInfo(t); if (t == null) { return Constants.EXCEPTION_INT2; } String[] arrInfo = getStrFromInfo(StringUtils.reverse(new String(t), 1, 5, 2)); // 修改分隔符之后,旧版本的许可文件会导致异常,所以需要在这里判断一下,如果有异常,则会删掉原有文件,重新激活即可。 if (arrInfo.length<3){ return Constants.STATE_INVALID; } String strKeyCode = arrInfo[0]; String strMacCode = arrInfo[1]; String strInstallCode = arrInfo[2]; LicenseIdValidator va = new LicenseIdValidator(strKeyCode); if (!va.checkLicense()) { return Constants.STATE_INVALID; } licenseId = strKeyCode; if (!va.checkEdition()) { return Constants.EXCEPTION_INT14; } isTrial = va.getType(); b = FileUtils.readFile(ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (b == null) { return Constants.EXCEPTION_INT3; } else { b = InstallKeyEncrypt.decrypt(b); if (b == null) { return Constants.EXCEPTION_INT4; } } if (!strInstallCode.equals(StringUtils.reverse(new String(b), 1, 3, 2))) { return Constants.STATE_INVALID; } String curMacCode = ProtectionFactory.getSeries(); if (!isExsitMac(curMacCode)) { return Constants.EXCEPTION_INT6; } if (!compareMacCode(curMacCode, strMacCode)) { return Constants.EXCEPTION_INT15; } macCode = curMacCode; System.getProperties().setProperty("TSState", "true"); return Constants.STATE_VALID; } private boolean isExsitMac(String curMacCode) { if (curMacCode != null && !"".equals(curMacCode)) { String[] str = curMacCode.split("%"); if (str.length == 1) { if (str[0] != null && !"".equals(str[0])) { return true; } } else if (str.length == 3) { if (str[2] != null && !"".equals(str[2])) { return true; } } } return false; } private String[] getStrFromInfo(String info) { return info.split(Constants.SEPARATOR); } /** * 比较两个硬件指纹是否可以认定为同一台机器的方法 * * @param curMacCode * @param parmMacCode * @return */ private boolean compareMacCode(String curMacCode, String parmMacCode) { if (curMacCode == null) { return false; } if (curMacCode.equals(parmMacCode)) { return true; } else { String[] str1 = curMacCode.split("%"); String[] str2 = parmMacCode.split("%"); if (str1.length == str2.length) { if (str1.length == 1) { String[] str3 = curMacCode.split("[+]"); String[] str4 = parmMacCode.split("[+]"); for (int i = 0; i < str3.length; i++) { for (int j = 0; j < str4.length; j++) { if (str3[i].equals(str4[j])) { return true; } } } } else if (str1.length == 3) { if (str1[0].equals(str2[0]) && str1[1].equals(str2[1])) { String[] str3 = str1[2].split("[+]"); String[] str4 = str2[2].split("[+]"); for (int i = 0; i < str3.length; i++) { for (int j = 0; j < str4.length; j++) { if (str3[i].equals(str4[j])) { return true; } } } } } } } return false; } public boolean isTrial() { return isTrial; } public String getLicenseId() { return licenseId; } public byte[] getInstall() { return b; } public String getMacCode() { return macCode; } }
3,942
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SelectGrantFileDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/SelectGrantFileDialog.java
package net.heartsome.license; import java.io.File; import java.text.MessageFormat; import net.heartsome.license.constants.Constants; import net.heartsome.license.resource.Messages; import net.heartsome.license.utils.StringUtils; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.PixelConverter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 选择授权文件的对话框 * @author karl * @version * @since JDK1.6 */ public class SelectGrantFileDialog extends Dialog { private Text textPath; private Button btnScan; private static final String[] FILE_IMPORT_MASK = { "*.lic" }; private Point p; protected SelectGrantFileDialog(Shell parentShell) { super(parentShell); } protected SelectGrantFileDialog(Shell parentShell, Point p) { super(parentShell); this.p = p; } @Override protected Point getInitialLocation(Point initialSize) { if (p == null) { return super.getInitialLocation(initialSize); } else { return p; } } @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, Messages.getString("license.LicenseManageDialog.activeBtn"), true); createButton(parent, IDialogConstants.CANCEL_ID, Messages.getString("license.LicenseManageDialog.exitBtn"), false); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.marginWidth = 10; layout.marginTop = 10; tparent.setLayout(layout); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Composite compNav = new Composite(tparent, SWT.NONE); GridLayout navLayout = new GridLayout(); compNav.setLayout(navLayout); createNavigation(compNav); Group groupFile = new Group(tparent, SWT.NONE); groupFile.setText(Messages.getString("license.SelectGrantFileDialog.grantfile")); GridDataFactory.fillDefaults().grab(true, true).applyTo(groupFile); GridLayout layoutGroup = new GridLayout(3, false); layoutGroup.marginWidth = 5; layoutGroup.marginHeight = 100; groupFile.setLayout(layoutGroup); Label label = new Label(groupFile, SWT.NONE); label.setText(Messages.getString("license.SelectGrantFileDialog.grantfile1")); textPath = new Text(groupFile, SWT.BORDER); textPath.setEditable(false); GridData pathData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); pathData.widthHint = new PixelConverter(textPath).convertWidthInCharsToPixels(25); textPath.setLayoutData(pathData); // browse button btnScan = new Button(groupFile, SWT.PUSH); btnScan.setText(Messages.getString("license.SelectGrantFileDialog.scan")); setButtonLayoutData(btnScan); btnScan.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse .swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(textPath.getShell(), SWT.SHEET); dialog.setFilterExtensions(FILE_IMPORT_MASK); dialog.setText(Messages.getString("license.SelectGrantFileDialog.selectgrantfile")); String fileName = textPath.getText().trim(); if (fileName.length() != 0) { File path = new File(fileName).getParentFile(); if (path != null && path.exists()) { dialog.setFilterPath(path.toString()); } } String path = dialog.open(); if (path != null) { textPath.setText(path); } } }); return tparent; } @Override protected Point getInitialSize() { return new Point(520, 470); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("license.LicenseManageDialog.title")); } private void createNavigation(Composite parent) { Label label = new Label(parent, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.operatenavigation")); RowLayout layout = new RowLayout(); Composite comp = new Composite(parent, SWT.NONE); comp.setLayout(layout); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.inputlicenseid")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.getactivekey")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.getgrantfile")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.activefinish")); label.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); } @Override protected void okPressed() { String filepath = textPath.getText(); if (filepath == null || "".equals(filepath)) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.SelectGrantFileDialog.selectfile")); } else { OffLineActiveService v = new OffLineActiveService(); int result = v.activeByGrantFile(filepath); if (result == Constants.STATE_VALID) { super.okPressed(); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.activeSuccess")); } else if (result == Constants.STATE_INVALID) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.SelectGrantFileDialog.invalidfile")); } else if (result == Constants.EXCEPTION_INT2) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.SelectGrantFileDialog.invalidfile1")); } else if (result == Constants.EXCEPTION_INT8) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.activeByAdmin")); } else { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), MessageFormat.format(Messages.getString("license.LicenseManageDialog.activeFail"), StringUtils.getErrorCode(result))); } } } }
7,385
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CustomMessageDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/CustomMessageDialog.java
package net.heartsome.license; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.heartsome.license.resource.Messages; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IconAndMessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.AccessibleAdapter; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; public class CustomMessageDialog extends IconAndMessageDialog{ private String editionInput; private String title; private StyledText text; private List<HashMap<String, Integer>> list = new ArrayList<HashMap<String, Integer>>(); private Color red = Display.getDefault().getSystemColor(SWT.COLOR_RED); public CustomMessageDialog(Shell parentShell, String title, String message, List<HashMap<String, Integer>> list, String editionInput) { super(parentShell); this.list = list; this.title = title; this.message = message; this.editionInput = editionInput; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); if (title != null) { shell.setText(title); } } @Override protected Control createDialogArea(Composite parent) { createMessageArea(parent); return super.createDialogArea(parent); } @Override protected Control createMessageArea(Composite composite) { Image image = getImage(); if (image != null) { imageLabel = new Label(composite, SWT.NULL); image.setBackground(imageLabel.getBackground()); imageLabel.setImage(image); addAccessibleListeners(imageLabel, image); GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BEGINNING) .applyTo(imageLabel); } // create message if (message != null) { text = new StyledText(composite, getMessageLabelStyle()); text.setBackground(composite.getBackground()); text.setText(message); text.setEditable(false); GridDataFactory .fillDefaults() .align(SWT.FILL, SWT.BEGINNING) .grab(true, false) .hint( convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH), SWT.DEFAULT).applyTo(text); setStyle(); } return composite; } @Override protected void createButtonsForButtonBar(Composite parent) { Button btnDownload = createButton(parent, -1, Messages.getString("license.CustomMessageDialog.download"), false); btnDownload.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Program.launch(MessageFormat.format(Messages.getString("license.CustomMessageDialog.urlDownload"), ProtectionFactory.getProduct(editionInput), ProtectionFactory.getPlatform(), ProtectionFactory.getVersion())); } }); if (!"L".equals(System.getProperty("TSEdition"))) { Button btnBuy = createButton(parent, -1, Messages.getString("license.LicenseManageDialog.link1"), false); btnBuy.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Program.launch(Messages.getString("license.LicenseManageDialog.urlr8buy") + "&PRODUCT=" + ProtectionFactory.getProduct() + "&PLATFORM=" + ProtectionFactory.getPlatform()); } }); } Button btnTrial = createButton(parent, -1, Messages.getString("license.LicenseManageDialog.link2"), false); btnTrial.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Program.launch(Messages.getString("license.LicenseManageDialog.urlr8trial") + "&PRODUCT=" + ProtectionFactory.getProduct() + "&PLATFORM=" + ProtectionFactory.getPlatform()); } }); createButton(parent, IDialogConstants.OK_ID, Messages.getString("license.CustomMessageDialog.inputAgain"), true).setFocus(); } @Override protected Image getImage() { return getInfoImage(); } private void addAccessibleListeners(Label label, final Image image) { label.getAccessible().addAccessibleListener(new AccessibleAdapter() { public void getName(AccessibleEvent event) { final String accessibleMessage = getAccessibleMessageFor(image); if (accessibleMessage == null) { return; } event.result = accessibleMessage; } }); } private String getAccessibleMessageFor(Image image) { if (image.equals(getErrorImage())) { return JFaceResources.getString("error");//$NON-NLS-1$ } if (image.equals(getWarningImage())) { return JFaceResources.getString("warning");//$NON-NLS-1$ } if (image.equals(getInfoImage())) { return JFaceResources.getString("info");//$NON-NLS-1$ } if (image.equals(getQuestionImage())) { return JFaceResources.getString("question"); //$NON-NLS-1$ } return null; } private void setStyle() { for (HashMap<String, Integer> map : list) { StyleRange styleRange = new StyleRange(); styleRange.start = map.get("start"); styleRange.length = map.get("length"); styleRange.fontStyle = SWT.BOLD; styleRange.foreground = red; text.setStyleRange(styleRange); } } }
5,695
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MacosxSeries.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/MacosxSeries.java
package net.heartsome.license; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class MacosxSeries implements SeriesInterface { public String getSeries() { try { String[] commands = new String[] {"/bin/bash", "-c", "ioreg -rd1 -c IOPlatformExpertDevice | " + "awk '/IOPlatformSerialNumber/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }'"}; Process process = Runtime.getRuntime().exec(commands); ReadThread inputReadThread = new ReadThread(process.getInputStream()); inputReadThread.start(); //确保标准与错误流都读完时才向外界返回执行结果 while (true) { if (inputReadThread.flag) { break; } else { Thread.sleep(1000); } } String series = inputReadThread.getResult(); return "".equals(series) ? null : series; } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } /* * 标准流与错误流读取线程 */ private static class ReadThread extends Thread { private InputStream is; private ArrayList<Byte> result = new ArrayList<Byte>(); public boolean flag;// 流是否读取完毕 public ReadThread(InputStream is) { this.is = is; } // 获取命令执行后输出信息,如果没有则返回空""字符串 protected String getResult() { byte[] byteArr = new byte[result.size()]; for (int i = 0; i < result.size(); i++) { byteArr[i] = ((Byte) result.get(i)).byteValue(); } return new String(byteArr); } public void run() { try { int readInt = is.read(); while (readInt != -1) { result.add(Byte.valueOf(String.valueOf((byte) readInt))); readInt = is.read(); } flag = true;// 流已读完 } catch (Exception e) { e.printStackTrace(); } } } }
1,854
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LicenseReader.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/LicenseReader.java
package net.heartsome.license; public class LicenseReader { private byte[] key = new byte[] {48,-126,4,-67,2,1,0,48,13,6,9,42,-122,72,-122,-9,13,1,1,1,5,0,4,-126,4,-89,48,-126,4,-93,2,1,0,2, -126,1,1,0,-116,-31,33,-26,26,115,95,-111,-97,62,29,91,-68,-26,19,56,-16,16,115,-127,-120,-58,-20,-52,-2,56,23,-2,-68, 43,-20,-53,61,16,-10,35,-66,-5,-6,-69,-61,109,69,-26,74,-103,124,-34,-117,-28,-19,93,105,-47,-15,-27,-115,-41,-69,10, 20,51,-54,70,-93,108,28,85,87,-120,95,-59,-30,-44,-117,8,82,104,39,-71,53,61,50,92,15,-64,-40,121,-55,21,10,86,34,21, 82,69,-69,25,86,6,-105,19,-86,-86,80,109,-55,19,-81,44,-18,-114,-125,-79,-26,-83,29,90,-127,-3,-100,-86,-4,-72,34,-66, -71,15,28,-62,93,-3,-119,-73,115,-22,-107,-90,80,-102,-41,24,3,1,-107,-26,55,-83,113,69,-47,-115,-93,7,8,70,28,-38,112, 95,-44,98,-55,51,-79,-49,-83,4,112,-6,-102,30,-86,60,-121,29,-81,-126,31,-23,-90,108,-119,94,-28,15,-22,-16,91,42,37, -90,-43,119,120,73,105,-2,31,-64,-85,94,-101,43,-87,-6,-97,19,35,-124,53,-95,-113,94,-101,-113,-18,-52,-93,92,122,-108, 73,95,85,116,45,29,-118,20,52,-41,114,73,31,-114,-15,71,-44,-38,-91,-48,72,-54,-49,48,-118,79,98,-47,-34,37,-67,95,-81, -67,2,3,1,0,1,2,-126,1,0,101,-115,-23,12,-31,-26,103,111,39,22,-12,-68,-21,-40,2,-27,89,-112,-46,98,-1,65,62,-12,-85,17, -82,-94,111,-19,78,30,88,32,0,-1,85,-82,121,89,-97,16,7,-126,114,38,96,-16,96,114,31,117,-26,81,116,-119,-31,13,49,-124, -101,121,-106,8,3,-56,108,72,76,-8,62,-23,-4,-112,-16,-60,-121,-5,19,31,-100,-76,71,-72,59,-106,-19,-74,36,-15,40,-23, 92,90,120,91,81,-5,122,-102,-9,-113,50,-56,-31,127,-78,-94,-96,-11,-57,-26,46,35,49,65,123,-42,-127,-68,91,-110,-102, -24,-10,10,-4,-123,66,-99,-7,83,56,118,27,-96,37,-64,107,120,-81,-29,87,112,-8,121,10,-93,121,-93,54,49,84,-46,-16,-69, 110,93,113,31,35,-22,-120,-121,-31,-31,17,-73,44,-31,73,114,106,7,-88,-63,48,34,43,-16,-128,-96,-24,-109,-116,92,25,39, 40,127,4,33,-26,84,-117,72,0,110,112,-6,94,23,85,115,-67,118,80,108,-110,-20,-90,-73,-27,31,-96,-115,-75,113,-29,-117, -57,-34,3,-92,124,-8,-20,-53,31,27,-88,69,-122,-103,38,42,-15,-110,-14,3,-105,50,-26,38,-14,-44,122,88,-108,70,46,88, -36,-75,73,-127,2,-127,-127,0,-19,-64,20,102,-53,-80,29,97,-12,68,10,-77,-84,-29,19,63,-77,3,-120,69,-38,80,-49,-52, 33,-9,25,-81,43,65,119,-40,-37,-76,5,-71,-57,26,-99,-64,41,40,38,124,-102,-60,-39,-121,32,-75,-104,12,95,-62,47,27,8, 29,68,14,-44,-78,-30,-109,-37,-41,-23,-109,-74,119,109,83,71,63,-62,-32,-126,32,103,-57,101,-95,123,6,-7,13,106,47,41, -102,-121,122,-28,8,49,34,-90,14,-59,-47,57,-104,124,-92,115,-78,48,-103,40,-90,79,-3,66,-123,-110,99,-128,12,-5,-58, 110,105,76,-116,-126,-91,1,-31,2,-127,-127,0,-105,-79,124,-8,1,95,35,99,-57,-45,-65,44,-53,93,-18,-17,-4,1,-57,16,-46, -115,-4,86,-19,96,-125,7,-82,98,47,38,-94,-53,-20,-45,37,86,-65,108,-57,2,108,40,31,-55,-38,-16,86,67,66,-16,104,30, 108,9,70,-26,-123,-105,-120,-106,-50,-117,31,-101,74,32,103,126,32,-83,-40,-27,-90,-22,-55,-48,124,5,-28,65,65,-102, -52,-93,65,-65,17,112,-71,29,90,-24,-68,-84,73,-119,109,-52,-25,33,-33,-73,-85,61,78,-47,106,7,-65,43,8,87,22,78,96, -101,85,50,-52,72,-102,-9,-88,48,33,93,2,-127,-128,25,-99,-119,85,45,-6,-14,-97,124,38,-36,-108,81,59,65,-10,-87,-3, -26,111,-56,62,-50,-76,-86,-80,41,-41,66,-84,-46,17,-50,82,14,15,-33,16,-46,16,67,30,-19,78,-99,-118,57,-7,-94,31, -114,-101,62,-79,-8,75,76,75,-126,-22,-86,37,-1,-35,120,97,65,-20,69,75,-122,-66,-29,61,78,108,-53,-8,91,-42,18,-16, 28,6,59,77,35,-76,-93,33,-32,24,-16,122,-91,120,-101,53,-102,64,-103,-103,1,76,-30,-98,63,56,49,54,2,6,66,101,-117, -55,38,-95,-65,122,-72,-88,-91,-77,-71,-37,-73,97,2,-127,-127,0,-109,97,-108,-93,120,-31,-80,-122,-81,-115,-95,126, -86,16,23,-89,-2,-42,-45,76,26,-26,108,-73,32,102,-42,-89,-51,-36,3,39,-84,-96,40,-10,116,-98,-75,-39,-65,-7,48,-112, 67,98,97,95,-124,-48,80,-25,54,-95,-24,33,-109,75,65,-100,-102,-50,-70,-38,28,-39,73,-55,-10,3,107,72,-67,37,83,105, 102,-81,50,-16,-98,118,112,-127,48,53,-90,25,55,-98,-89,-100,71,-55,60,22,-64,83,-49,-28,118,-28,72,114,48,-29,-98, 2,-124,-36,5,-10,-113,97,-35,-128,69,8,102,92,-74,114,12,110,118,112,92,-39,2,-127,-128,18,114,-71,-94,26,-65,-63, 87,-42,-61,44,-36,80,-63,97,127,40,-99,-67,-9,86,68,16,12,101,-71,75,-41,43,-15,54,119,-26,-126,-16,68,16,99,16, 22,-83,4,127,126,62,-52,42,-10,-30,-62,-9,-71,-41,-109,-22,98,-69,56,-53,-12,107,-66,106,22,19,-124,122,-74,106, -126,-39,-27,-37,-22,-67,41,-56,-75,118,120,50,-41,-2,19,83,-48,-53,0,-69,95,-4,18,46,81,116,121,-70,124,-14,68, -47,-35,-86,56,-34,124,27,-37,-80,56,65,-26,-17,89,121,29,-72,112,-96,98,-115,59,7,76,62,68,-73,-71}; public byte[] getLicenseInfo(byte[] b) { return ProtectionFactory.getEncrypt().decrypt(key, b); } }
4,748
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LicenseAgreementDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/LicenseAgreementDialog.java
package net.heartsome.license; import net.heartsome.license.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class LicenseAgreementDialog extends Dialog { private Button agreeBtn; public LicenseAgreementDialog(Shell parentShell) { super(parentShell); } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); Button nextBtn = getButton(IDialogConstants.OK_ID); nextBtn.setEnabled(false); nextBtn.setText(Messages.getString("license.LicenseAgreementDialog.nextBtn")); Button exitBtn = getButton(IDialogConstants.CANCEL_ID); exitBtn.setText(Messages.getString("license.LicenseAgreementDialog.exitBtn")); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.marginTop = 5; layout.marginWidth = 10; tparent.setLayout(layout); GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true); parentData.heightHint = 380; tparent.setLayoutData(parentData); Label lbl = new Label(tparent, SWT.NONE); lbl.setText(Messages.getString("license.LicenseAgreementDialog.label")); lbl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Text text = new Text(tparent, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); text.setEditable(false); text.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); text.setText(Messages.getString("license.LicenseAgreementDialog.agreement")); GridData textData = new GridData(GridData.FILL_BOTH); text.setLayoutData(textData); agreeBtn = new Button(tparent, SWT.CHECK); agreeBtn.setText(Messages.getString("license.LicenseAgreementDialog.agreeBtn")); agreeBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); agreeBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { getButton(IDialogConstants.OK_ID).setEnabled(agreeBtn.getSelection()); } }); return super.createDialogArea(parent); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("license.LicenseAgreementDialog.title")); } @Override protected Point getInitialSize() { return new Point(500, 420); } @Override protected void okPressed() { Point p = getShell().getLocation(); super.okPressed(); ActiveMethodDialog dialog = new ActiveMethodDialog(getShell(), p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } }
3,179
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
GetActiveKeyDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/GetActiveKeyDialog.java
package net.heartsome.license; import net.heartsome.cat.ts.help.Activator; import net.heartsome.license.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 获取激活码的对话框 * @author karl * @version * @since JDK1.6 */ public class GetActiveKeyDialog extends Dialog { private Text textActivekey; private String activekey; private Point p; protected GetActiveKeyDialog(Shell parentShell, String activekey) { super(parentShell); this.activekey = activekey; } protected GetActiveKeyDialog(Shell parentShell, String activekey, Point p) { super(parentShell); this.activekey = activekey; this.p = p; } @Override protected Point getInitialLocation(Point initialSize) { if (p == null) { return super.getInitialLocation(initialSize); } else { return p; } } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); Button nextBtn = getButton(IDialogConstants.OK_ID); nextBtn.setText(Messages.getString("license.LicenseAgreementDialog.nextBtn")); Button exitBtn = getButton(IDialogConstants.CANCEL_ID); exitBtn.setText(Messages.getString("license.LicenseAgreementDialog.exitBtn")); exitBtn.setFocus(); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.marginWidth = 10; layout.marginTop = 10; tparent.setLayout(layout); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Composite compNav = new Composite(tparent, SWT.NONE); GridLayout navLayout = new GridLayout(); compNav.setLayout(navLayout); createNavigation(compNav); Group groupActivekey = new Group(tparent, SWT.NONE); groupActivekey.setText(Messages.getString("license.GetActiveKeyDialog.activekey")); GridDataFactory.fillDefaults().grab(true, true).applyTo(groupActivekey); GridLayout layoutGroup = new GridLayout(2, false); layoutGroup.marginWidth = 5; layoutGroup.marginHeight = 20; groupActivekey.setLayout(layoutGroup); StyledText text = new StyledText(groupActivekey, SWT.WRAP | SWT.READ_ONLY); text.setBackground(text.getParent().getBackground()); text.setText(Messages.getString("license.GetActiveKeyDialog.activemessage")); GridData dataText = new GridData(); dataText.horizontalSpan = 2; dataText.widthHint = 470; text.setLayoutData(dataText); int start = Messages.getString("license.GetActiveKeyDialog.activemessage").indexOf( Messages.getString("license.GetActiveKeyDialog.ts")); int length = Messages.getString("license.GetActiveKeyDialog.ts").length(); StyleRange styleRange = new StyleRange(); styleRange.start = start; styleRange.length = length; styleRange.fontStyle = SWT.BOLD; styleRange.foreground = Display.getDefault().getSystemColor(SWT.COLOR_BLUE); text.setStyleRange(styleRange); Label label = new Label(groupActivekey, SWT.WRAP | SWT.NONE); label.setText(Messages.getString("license.GetActiveKeyDialog.activemessage1")); GridDataFactory.fillDefaults().span(2, 1).applyTo(label); textActivekey = new Text(groupActivekey, SWT.MULTI | SWT.WRAP); textActivekey.setEditable(false); textActivekey.setText(activekey); textActivekey.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); GridDataFactory.fillDefaults().grab(true, false).hint(SWT.DEFAULT, 150).applyTo(textActivekey); Button btnCopy = new Button(groupActivekey, SWT.NONE); GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.END).applyTo(btnCopy); btnCopy.setImage(Activator.getImageDescriptor("images/help/copy.png").createImage()); btnCopy.setToolTipText(Messages.getString("license.GetActiveKeyDialog.copytoclipboard")); btnCopy.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { Clipboard cb = new Clipboard(Display.getCurrent()); String textData = textActivekey.getText(); TextTransfer textTransfer = TextTransfer.getInstance(); cb.setContents(new Object[] { textData }, new Transfer[] { textTransfer }); } }); return tparent; } @Override protected Point getInitialSize() { return new Point(520, 470); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("license.LicenseManageDialog.title")); } private void createNavigation(Composite parent) { Label label = new Label(parent, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.operatenavigation")); RowLayout layout = new RowLayout(); Composite comp = new Composite(parent, SWT.NONE); comp.setLayout(layout); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.inputlicenseid")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.getactivekey")); label.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.getgrantfile")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.seperate")); label = new Label(comp, SWT.NONE); label.setText(Messages.getString("license.OfflineActiveDialog.activefinish")); } @Override protected void okPressed() { Point p = getShell().getLocation(); super.okPressed(); SelectGrantFileDialog dialog = new SelectGrantFileDialog(getShell(), p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } }
6,772
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LicenseManageDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/LicenseManageDialog.java
package net.heartsome.license; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.heartsome.cat.common.ui.Activator; import net.heartsome.cat.common.ui.dialog.HsPreferenceDialog; import net.heartsome.license.constants.Constants; import net.heartsome.license.generator.LicenseIdGenerator; import net.heartsome.license.resource.Messages; import net.heartsome.license.utils.StringUtils; import net.heartsome.license.webservice.ServiceUtil; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceNode; import org.eclipse.jface.preference.PreferenceLabelProvider; import org.eclipse.jface.preference.PreferenceManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; public class LicenseManageDialog extends Dialog { private int type; private String utilDate; private String licenseId; private boolean isShowBack = false; private Point p; private Text text; private Text text1; private Text text2; private Text text3; private Text text4; private Text text5; private Text text6; private Label label4; private ProgressBar bar; private Cursor cursor = new Cursor(Display.getDefault(), SWT.CURSOR_HAND); public LicenseManageDialog(Shell parent, int type, String utilDate, String licenseId) { super(parent); this.type = type; this.utilDate = utilDate; this.licenseId = licenseId; } public LicenseManageDialog(Shell parent, int type, String utilDate, String licenseId, boolean isShowBack, Point p) { super(parent); this.type = type; this.utilDate = utilDate; this.licenseId = licenseId; this.isShowBack = isShowBack; this.p = p; } @Override protected Point getInitialLocation(Point initialSize) { if (p == null) { return super.getInitialLocation(initialSize); } else { return p; } } @Override protected void createButtonsForButtonBar(Composite parent) { if (isShowBack) { Button backBtn = createButton(parent, IDialogConstants.BACK_ID, Messages.getString("license.OfflineActiveDialog.backBtn"), false); backBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setReturnCode(OK); Point p = getShell().getLocation(); close(); ActiveMethodDialog dialog = new ActiveMethodDialog(getShell(), p); int result = dialog.open(); if (result != IDialogConstants.OK_ID) { System.exit(0); } } }); } Button button = createButton(parent, 11, Messages.getString("license.LicenseManageDialog.netconnection"), false); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); PreferenceManager mgr = window.getWorkbench().getPreferenceManager(); IPreferenceNode node = null; @SuppressWarnings("unchecked") List<IPreferenceNode> lstNodes = mgr.getElements(PreferenceManager.PRE_ORDER); for (IPreferenceNode n : lstNodes) { if(n.getId().equals("org.eclipse.ui.net.proxy_preference_page_context")){ node = n; } } if(node == null){ return; } mgr = new PreferenceManager(); mgr.addToRoot(node); HsPreferenceDialog dlg = new HsPreferenceDialog(window.getShell(), mgr); dlg.create(); final List<Image> imageList = new ArrayList<Image>(); dlg.getTreeViewer().setLabelProvider(new PreferenceLabelProvider() { Image image = null; public Image getImage(Object element) { String id = ((IPreferenceNode) element).getId(); if ("org.eclipse.ui.net.proxy_preference_page_context".equals(id)) { // 网络连接 image = Activator.getImageDescriptor("icons/network.png").createImage(); imageList.add(image); return image; } else { return null; } } }); dlg.open(); for (Image img : imageList) { if (img != null && !img.isDisposed()) { img.dispose(); } } imageList.clear(); } }); boolean isDefault = false; if (type == Constants.STATE_NOT_ACTIVATED || type == Constants.STATE_INVALID || type == Constants.STATE_EXPIRED || type == Constants.EXCEPTION_INT14 || type == Constants.EXCEPTION_INT15 || type == Constants.EXCEPTION_INT1 || type == Constants.EXCEPTION_INT2 || type == Constants.EXCEPTION_INT3 || type == Constants.EXCEPTION_INT4) { createButton(parent, IDialogConstants.OK_ID, Messages.getString("license.LicenseManageDialog.activeBtn"),true); isDefault = true; } createButton(parent, IDialogConstants.CANCEL_ID, Messages.getString("license.LicenseManageDialog.exitBtn"), !isDefault).setFocus(); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.marginWidth = 10; layout.marginTop = 10; tparent.setLayout(layout); GridData data = new GridData(GridData.GRAB_HORIZONTAL|GridData.FILL_HORIZONTAL); tparent.setLayoutData(data); createStatusComp(tparent); createActiveComp(tparent); createBarComp(tparent); return super.createDialogArea(parent); } private void createStatusComp(Composite parent) { Group statusGroup = new Group(parent, SWT.NONE); statusGroup.setText(Messages.getString("license.LicenseManageDialog.statusGroup")); GridData dataStatusGroup = new GridData(GridData.GRAB_HORIZONTAL|GridData.FILL_HORIZONTAL); dataStatusGroup.heightHint = 150; statusGroup.setLayoutData(dataStatusGroup); statusGroup.setLayout(new GridLayout()); GridData data = new GridData(GridData.GRAB_HORIZONTAL|GridData.FILL_HORIZONTAL); RowLayout layout = new RowLayout(); layout.center = true; Composite comp0 = new Composite(statusGroup, SWT.NONE); comp0.setLayoutData(data); comp0.setLayout(layout); Label statusLbl = new Label(comp0, SWT.NONE); statusLbl.setText(Messages.getString("license.LicenseManageDialog.statusLabel")); if (type == Constants.STATE_NOT_ACTIVATED) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.notActiveLabel")); } else if (type == Constants.STATE_VALID) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.activeLabel")); new Label(comp0, SWT.NONE).setLayoutData(new RowData(30, SWT.DEFAULT)); Button btnCancelActive = new Button(comp0, SWT.NONE); btnCancelActive.setText(Messages.getString("license.LicenseManageDialog.cancelActiveButton")); btnCancelActive.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean result = MessageDialog.openConfirm(getShell(), Messages.getString("license.LicenseManageDialog.confirm"), Messages.getString("license.LicenseManageDialog.confirmMessage")); if (result) { try { int re = ServiceUtil.cancel(); if (re == Constants.LOGOUT_SUCCESS) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.unactiveSuccess")); LicenseManageDialog.this.close(); PlatformUI.getWorkbench().restart(); } else { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.unactiveFail")); } } catch (Exception e1) { e1.printStackTrace(); Throwable t = e1; while(t.getCause() != null) { t = t.getCause(); } if (t instanceof java.security.cert.CertificateException) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleNet"), MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoNet"), Constants.EXCEPTION_STRING16)); } else { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleNet"), MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoNet"), Constants.EXCEPTION_STRING17)); } } } } }); Composite comp1 = new Composite(statusGroup, SWT.NONE); comp1.setLayoutData(data); comp1.setLayout(layout); Label typeLbl = new Label(comp1, SWT.NONE); typeLbl.setText(Messages.getString("license.LicenseManageDialog.typeLabel")); Label typeLbl1 = new Label(comp1, SWT.NONE); typeLbl1.setText(Messages.getString(utilDate == null ? "license.LicenseManageDialog.typeBusiness" : "license.LicenseManageDialog.typeTemp")); if (utilDate != null ) { Composite comp2 = new Composite(statusGroup, SWT.NONE); comp2.setLayoutData(data); comp2.setLayout(layout); Label typeLbl2 = new Label(comp2, SWT.NONE); typeLbl2.setText(Messages.getString("license.LicenseManageDialog.utilDate")); Label dateLbl = new Label(comp2, SWT.NONE); dateLbl.setText(utilDate); } } else if (type == Constants.STATE_INVALID) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.invalidLicense")); } else if (type == Constants.STATE_EXPIRED) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.expired")); Composite comp1 = new Composite(statusGroup, SWT.NONE); comp1.setLayoutData(data); comp1.setLayout(layout); Label typeLbl = new Label(comp1, SWT.NONE); typeLbl.setText(Messages.getString("license.LicenseManageDialog.typeLabel")); Label typeLbl1 = new Label(comp1, SWT.NONE); typeLbl1.setText(Messages.getString(utilDate == null ? "license.LicenseManageDialog.typeBusiness" : "license.LicenseManageDialog.typeTemp")); if (utilDate != null ) { Composite comp2 = new Composite(statusGroup, SWT.NONE); comp2.setLayoutData(data); comp2.setLayout(layout); Label typeLbl2 = new Label(comp2, SWT.NONE); typeLbl2.setText(Messages.getString("license.LicenseManageDialog.utilDate")); Label dateLbl = new Label(comp2, SWT.NONE); dateLbl.setText(utilDate); } } else if (type == Constants.EXCEPTION_INT16 || type == Constants.EXCEPTION_INT17) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.unvalidate")); Composite comp1 = new Composite(statusGroup, SWT.NONE); GridData data1 = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_BOTH); comp1.setLayoutData(data1); GridLayout layout1 = new GridLayout(); comp1.setLayout(layout1); Label noticeLbl = new Label(comp1, SWT.WRAP); GridData dataLabel = new GridData(GridData.FILL_HORIZONTAL); noticeLbl.setLayoutData(dataLabel); noticeLbl.setText(MessageFormat.format(Messages.getString("license.LicenseManageDialog.noticeLbl"), StringUtils.getErrorCode(type))); } else if (type == Constants.EXCEPTION_INT14) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.licenseException")); Composite comp1 = new Composite(statusGroup, SWT.NONE); GridData data1 = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_BOTH); comp1.setLayoutData(data1); GridLayout layout1 = new GridLayout(); comp1.setLayout(layout1); Label noticeLbl = new Label(comp1, SWT.WRAP); GridData dataLabel = new GridData(GridData.FILL_HORIZONTAL); noticeLbl.setLayoutData(dataLabel); noticeLbl.setText(MessageFormat.format(Messages.getString("license.LicenseManageDialog.noSameVersion"), getVersionContent(System.getProperty("TSEdition")), getVersionContent(new LicenseIdGenerator(licenseId).getVersion()))); } else if (type == Constants.EXCEPTION_INT15) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.licenseException")); Composite comp1 = new Composite(statusGroup, SWT.NONE); GridData data1 = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_BOTH); comp1.setLayoutData(data1); GridLayout layout1 = new GridLayout(); comp1.setLayout(layout1); Label noticeLbl = new Label(comp1, SWT.WRAP); GridData dataLabel = new GridData(GridData.FILL_HORIZONTAL); noticeLbl.setLayoutData(dataLabel); noticeLbl.setText(Messages.getString("license.LicenseManageDialog.maccodeError")); } else if (type == Constants.EXCEPTION_INT1 || type == Constants.EXCEPTION_INT2 || type == Constants.EXCEPTION_INT3 || type == Constants.EXCEPTION_INT4) { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.licenseException")); Composite comp1 = new Composite(statusGroup, SWT.NONE); GridData data1 = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_BOTH); comp1.setLayoutData(data1); GridLayout layout1 = new GridLayout(); comp1.setLayout(layout1); Label noticeLbl = new Label(comp1, SWT.WRAP); GridData dataLabel = new GridData(GridData.FILL_HORIZONTAL); noticeLbl.setLayoutData(dataLabel); noticeLbl.setText(MessageFormat.format(Messages.getString("license.LicenseManageDialog.licenseExceptionInfo1"), StringUtils.getErrorCode(type))); } else { Label statusLbl1 = new Label(comp0, SWT.NONE); statusLbl1.setText(Messages.getString("license.LicenseManageDialog.licenseException")); Composite comp1 = new Composite(statusGroup, SWT.NONE); GridData data1 = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_BOTH); comp1.setLayoutData(data1); GridLayout layout1 = new GridLayout(); comp1.setLayout(layout1); Label noticeLbl = new Label(comp1, SWT.WRAP); GridData dataLabel = new GridData(GridData.FILL_HORIZONTAL); noticeLbl.setLayoutData(dataLabel); noticeLbl.setText(MessageFormat.format(Messages.getString("license.LicenseManageDialog.licenseExceptionInfo"), StringUtils.getErrorCode(type))); } } private void createActiveComp(Composite parent) { Group licenseIdGroup = new Group(parent, SWT.NONE); licenseIdGroup.setText(Messages.getString("license.LicenseManageDialog.licenseIdGroup")); GridData dataLicenseIdGroup = new GridData(GridData.GRAB_HORIZONTAL|GridData.FILL_HORIZONTAL); dataLicenseIdGroup.heightHint = 110; licenseIdGroup.setLayoutData(dataLicenseIdGroup); GridLayout layoutGroup = new GridLayout(2, false); layoutGroup.marginLeft = 5; layoutGroup.marginHeight = 10; licenseIdGroup.setLayout(layoutGroup); Label label = new Label(licenseIdGroup,SWT.NONE); label.setText(Messages.getString("license.LicenseManageDialog.licenseIdLabel")); createIdInputComp(licenseIdGroup); Composite compLink = new Composite(licenseIdGroup, SWT.NONE); RowLayout layoutLink = new RowLayout(); layoutLink.marginTop = 20; layoutLink.marginRight = 0; layoutLink.marginLeft = 0; layoutLink.marginBottom = 10; compLink.setLayout(layoutLink); GridData linkData = new GridData(GridData.FILL_HORIZONTAL); linkData.horizontalSpan = 2; compLink.setLayoutData(linkData); Label label1 = new Label(compLink, SWT.NONE); label1.setText(Messages.getString("license.LicenseManageDialog.label1")); if (!"L".equals(System.getProperty("TSEdition"))) { Label link1 = new Label(compLink, SWT.NONE); link1.setText(Messages.getString("license.LicenseManageDialog.link1")); link1.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); link1.setCursor(cursor); link1.addMouseListener(new MouseListener() { public void mouseUp(MouseEvent e) { } public void mouseDown(MouseEvent e) { Program.launch(Messages.getString("license.LicenseManageDialog.urlr8buy") + "&PRODUCT=" + ProtectionFactory.getProduct() + "&PLATFORM=" + ProtectionFactory.getPlatform()); } public void mouseDoubleClick(MouseEvent e) { } }); Label label2 = new Label(compLink, SWT.NONE); label2.setText(Messages.getString("license.LicenseManageDialog.label2")); } Label link2 = new Label(compLink, SWT.NONE); link2.setText(Messages.getString("license.LicenseManageDialog.link2")); link2.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE)); link2.setCursor(cursor); link2.addMouseListener(new MouseListener() { public void mouseUp(MouseEvent e) { } public void mouseDown(MouseEvent e) { Program.launch(Messages.getString("license.LicenseManageDialog.urlr8trial") + "&PRODUCT=" + ProtectionFactory.getProduct() + "&PLATFORM=" + ProtectionFactory.getPlatform()); } public void mouseDoubleClick(MouseEvent e) { } }); Label label3 = new Label(compLink, SWT.NONE); label3.setText(Messages.getString("license.LicenseManageDialog.label3")); } private void createBarComp(Composite parent) { Composite barComp = new Composite(parent, SWT.NONE); GridLayout barLayout = new GridLayout(); barLayout.marginTop = 10; barComp.setLayout(barLayout); barComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label4 = new Label(barComp, SWT.NONE); label4.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); bar = new ProgressBar(barComp, SWT.NONE); bar.setMaximum(10); bar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); setVisible(false); } private void setVisible(boolean b) { if (b) { label4.setVisible(true); label4.setText(Messages.getString("license.LicenseManageDialog.label4")); bar.setVisible(true); } else { label4.setVisible(false); label4.setText(""); bar.setVisible(false); bar.setSelection(0); } } private void createIdInputComp(Composite parent) { if (type == Constants.STATE_NOT_ACTIVATED || type == Constants.STATE_INVALID || type == Constants.STATE_EXPIRED || type == Constants.EXCEPTION_INT14 || type == Constants.EXCEPTION_INT15 || type == Constants.EXCEPTION_INT1 || type == Constants.EXCEPTION_INT2 || type == Constants.EXCEPTION_INT3 || type == Constants.EXCEPTION_INT4) { Composite comp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(11, false); layout.marginHeight = 0; layout.marginWidth = 0; comp.setLayout(layout); GridData compData = new GridData(); comp.setLayoutData(compData); GridData textData = new GridData(); textData.widthHint = 40; GridData labelData = new GridData(); labelData.widthHint = 5; text1 = new Text(comp,SWT.BORDER); text1.setLayoutData(textData); text1.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text1.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text1.setText(s.substring(0, 4)); text2.setFocus(); text2.setText(s.substring(4)); } else if (length == 4) { text2.setFocus(); } } } else { text1.setText(s.substring(0, i)); break; } } } }); Label label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text2 = new Text(comp,SWT.BORDER); text2.setLayoutData(textData); text2.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text2.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text2.setText(s.substring(0, 4)); text3.setFocus(); text3.setText(s.substring(4)); } else if (length == 4) { text3.setFocus(); } } } else { text2.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text3 = new Text(comp,SWT.BORDER); text3.setLayoutData(textData); text3.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text3.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text3.setText(s.substring(0, 4)); text4.setFocus(); text4.setText(s.substring(4)); } else if (length == 4) { text4.setFocus(); } } } else { text3.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text4 = new Text(comp,SWT.BORDER); text4.setLayoutData(textData); text4.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text4.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text4.setText(s.substring(0, 4)); text5.setFocus(); text5.setText(s.substring(4)); } else if (length == 4) { text5.setFocus(); } } } else { text4.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text5 = new Text(comp,SWT.BORDER); text5.setLayoutData(textData); text5.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text5.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text5.setText(s.substring(0, 4)); text6.setFocus(); text6.setText(s.substring(4)); } else if (length == 4) { text6.setFocus(); } } } else { text5.setText(s.substring(0, i)); } } } }); label = new Label(comp,SWT.NONE); label.setLayoutData(labelData); text6 = new Text(comp,SWT.BORDER); text6.setLayoutData(textData); text6.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String s = text6.getText(); s = s.replaceAll("-", ""); int length = s.length(); for (int i = 0; i < 4; i++) { if (i >= length) { break; } char c = s.charAt(i); if (Character.isDigit(c) || Character.isLetter(c)) { if (i == 3) { if (length > 4) { text6.setText(s.substring(0, 4)); } } } else { text6.setText(s.substring(0, i)); } } } }); } else { text = new Text(parent,SWT.NONE); text.setText(StringUtils.groupString(licenseId)); text.setBackground(parent.getBackground()); text.setEditable(false); } } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("license.LicenseManageDialog.title")); } @Override protected Point getInitialSize() { return new Point(630, 470); } @Override protected void okPressed() { LicenseIdValidator va = new LicenseIdValidator(getLicenseId()); if (va.checkLicense()) { if (va.checkEdition()) { setVisible(true); try { int r = ServiceUtil.active(getLicenseId(), bar); if (r == Constants.ACTIVE_OK_INT) { setVisible(false); super.okPressed(); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.activeSuccess")); } else if (r == Constants.RETURN_MUTILTEMPBUNDLE_INT){ setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.tempMutilActive")); } else if (r == Constants.RETURN_INVALIDBUNDLE_INT){ setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.activedLicense")); } else if (r == Constants.RETURN_INVALIDLICENSE_INT){ setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.infoInvalid")); } else if (r == Constants.RETURN_EXPIREDLICENSE_INT){ setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.expired")); } else if (r == Constants.RETURN_STOPLICENSE_INT){ setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.stopLicense")); } else if (r == Constants.EXCEPTION_INT8){ setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), Messages.getString("license.LicenseManageDialog.activeByAdmin")); System.exit(0); } else { setVisible(false); MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.notice"), MessageFormat.format(Messages.getString("license.LicenseManageDialog.activeFail"), StringUtils.getErrorCode(r))); } } catch (Exception e) { setVisible(false); e.printStackTrace(); Throwable t = e; while(t.getCause() != null) { t = t.getCause(); } if (t instanceof java.security.cert.CertificateException) { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleNet"), MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoNet"), Constants.EXCEPTION_STRING16)); } else { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleNet"), MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoNet"), Constants.EXCEPTION_STRING17)); } } } else { // MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleInvalid"), // MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoInvalid1"), // getVersionContent(System.getProperty("TSEdition")), getVersionContent(new LicenseIdGenerator(getLicenseId()).getVersion()))); String edition1 = getVersionContent(System.getProperty("TSEdition")); String editionInput = new LicenseIdGenerator(getLicenseId()).getVersion(); String edition2 = getVersionContent(editionInput); String message = MessageFormat.format(Messages.getString("license.LicenseManageDialog.infoInvalid1"), edition1, edition2); ArrayList<HashMap<String, Integer>> list = new ArrayList<HashMap<String, Integer>>(); HashMap<String, Integer> map1 = new HashMap<String, Integer>(); map1.put("start", message.indexOf(edition1)); map1.put("length", edition1.length()); list.add(map1); HashMap<String, Integer> map2 = new HashMap<String, Integer>(); map2.put("start", message.indexOf(edition2)); map2.put("length", edition2.length()); list.add(map2); HashMap<String, Integer> map3 = new HashMap<String, Integer>(); map3.put("start", message.lastIndexOf(edition1)); map3.put("length", edition1.length()); list.add(map3); HashMap<String, Integer> map4 = new HashMap<String, Integer>(); map4.put("start", message.lastIndexOf(edition2)); map4.put("length", edition2.length()); list.add(map4); new CustomMessageDialog(getShell(), Messages.getString("license.LicenseManageDialog.titleInvalid"), message, list, editionInput).open(); } } else { MessageDialog.openInformation(getShell(), Messages.getString("license.LicenseManageDialog.titleInvalid"), Messages.getString("license.LicenseManageDialog.infoInvalid")); } } private String getLicenseId() { return text1.getText() + text2.getText() + text3.getText() + text4.getText() + text5.getText() + text6.getText(); } public static void main(String[] argv) { Shell shell = new Shell(); new LicenseManageDialog(shell, 5, null, "121312345678901234567890").open(); } @Override public boolean close() { if(cursor != null && !cursor.isDisposed()){ cursor.dispose(); } return super.close(); } private String getVersionContent(String version) { if ("U".equals(version)) { return Messages.getString("license.LicenseManageDialog.Ultimate"); } else if ("F".equals(version)) { return Messages.getString("license.LicenseManageDialog.Professional"); } else if ("P".equals(version)) { return Messages.getString("license.LicenseManageDialog.Personal"); } else { return Messages.getString("license.LicenseManageDialog.Lite"); } } }
30,948
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
RandomUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/utils/RandomUtils.java
package net.heartsome.license.utils; public class RandomUtils { public static String generateRandom(int num) { char[] temp = new char[] {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z','A','B','C','D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S', 'T','U','V','W','X','Y','Z'}; int size = temp.length; StringBuffer bu = new StringBuffer(); for (int i = 0; i < num; i++) { int r = (int)(Math.random() * size); bu.append(temp[r]); } return bu.toString(); } }
612
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DateUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/utils/DateUtils.java
package net.heartsome.license.utils; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { public static String getDate() { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(date); } }
283
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FileUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/utils/FileUtils.java
package net.heartsome.license.utils; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import net.heartsome.license.ProtectionFactory; import net.heartsome.license.constants.Constants; public class FileUtils { public static boolean writeFile(byte[] b, String fileName) { try { DataOutputStream out = new DataOutputStream(new FileOutputStream( fileName)); out.write(b); out.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static byte[] readFile(String fileName) { try { DataInputStream in = new DataInputStream(new BufferedInputStream( new FileInputStream(fileName))); int n = in.available(); byte[] t = new byte[n]; int i = 0; while (in.available() != 0) { t[i] = in.readByte(); i++; } in.close(); return t; } catch (Exception e) { e.printStackTrace(); } return null; } public static boolean removeFile() { boolean flag1 = false; boolean flag2 = false; File file = new File(ProtectionFactory.getFileName(1, Constants.PRODUCTID)); if (file.isFile() && file.exists()) { file.delete(); flag1 = true; } file = new File(ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (file.isFile() && file.exists()) { file.delete(); flag2 = true; } return flag1 && flag2; } public static void removeFile(String fileName) { File file = new File(fileName); if (file.isFile() && file.exists()) { file.delete(); } } public static boolean isExsit() { boolean flag1 = false; boolean flag2 = false; File file = new File(ProtectionFactory.getFileName(1, Constants.PRODUCTID)); if (file.isFile() && file.exists()) { flag1 = true; } file = new File(ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (file.isFile() && file.exists()) { flag2 = true; } return flag1 && flag2; } public static boolean isExsitInstall() { boolean flag = false; File file = new File(ProtectionFactory.getFileName(2, Constants.PRODUCTID)); if (file.isFile() && file.exists()) { flag = true; } return flag; } }
2,403
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
StringUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/utils/StringUtils.java
package net.heartsome.license.utils; import net.heartsome.license.constants.Constants; public class StringUtils { public static String handle(String key, int interval, int start, int num) { char[] temp = new char[] {'0','1','2','3','4','5','6','7','8','9', 'g','h','i','j','k','l','m','n','o','T','U','V','W','X','Y', 'p','q','r','s','t','u','v','w','x','y','z','A','B','C','D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S', 'Z'}; int size = temp.length; StringBuffer bu = new StringBuffer(key); int length = key.length(); for (int i = start; i < length;) { for (int j = 0; j < num; j++) { int r = (int)(Math.random() * size); bu.insert(i, temp[r]); } i += interval + num; length += num; } return bu.toString(); } public static String reverse(String key, int interval, int start, int num) { StringBuffer bu = new StringBuffer(key); int length = key.length(); for (int i = start; i < length;) { for (int j = 0; j < num; j++) { bu.deleteCharAt(i); } i += interval; length -= num; } return bu.toString(); } public static String removeColon(String str) { return str.replaceAll(":", ""); } public static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]); sb.append(HEXCHAR[b[i] & 0x0f]); } return sb.toString(); } public static byte[] toBytes(String s) { byte[] bytes; bytes = new byte[s.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16); } return bytes; } private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * 许可 KEY,使用标准的 4 个字符一组,然后使用 - 连接。 * @return ; */ public static String groupString(String str) { if (str == null || str.length() != 24) { return str; } else { String temp = ""; for (int i = 0; i < 6; i++) { temp += str.substring(i * 4, (i + 1) * 4) + "-"; } return temp.substring(0, temp.length() - 1); } } public static String getErrorCode(int i) { if (i == Constants.EXCEPTION_INT1) { return Constants.EXCEPTION_STRING1; } else if (i == Constants.EXCEPTION_INT2) { return Constants.EXCEPTION_STRING2; } else if (i == Constants.EXCEPTION_INT3) { return Constants.EXCEPTION_STRING3; } else if (i == Constants.EXCEPTION_INT4) { return Constants.EXCEPTION_STRING4; } else if (i == Constants.EXCEPTION_INT5) { return Constants.EXCEPTION_STRING5; } else if (i == Constants.EXCEPTION_INT6) { return Constants.EXCEPTION_STRING6; } else if (i == Constants.EXCEPTION_INT7) { return Constants.EXCEPTION_STRING7; } else if (i == Constants.EXCEPTION_INT8) { return Constants.EXCEPTION_STRING8; } else if (i == Constants.EXCEPTION_INT9) { return Constants.EXCEPTION_STRING9; } else if (i == Constants.EXCEPTION_INT10) { return Constants.EXCEPTION_STRING10; } else if (i == Constants.EXCEPTION_INT11) { return Constants.EXCEPTION_STRING11; } else if (i == Constants.EXCEPTION_INT12) { return Constants.EXCEPTION_STRING12; } else if (i == Constants.EXCEPTION_INT13) { return Constants.EXCEPTION_STRING13; } else if (i == Constants.EXCEPTION_INT14) { return Constants.EXCEPTION_STRING14; } else if (i == Constants.EXCEPTION_INT15) { return Constants.EXCEPTION_STRING15; } else if (i == Constants.EXCEPTION_INT16) { return Constants.EXCEPTION_STRING16; } else { return Constants.EXCEPTION_STRING17; } } }
3,672
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LicenseManageHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/handler/LicenseManageHandler.java
package net.heartsome.license.handler; import java.lang.reflect.InvocationTargetException; import net.heartsome.cat.ts.help.SystemResourceUtil; import net.heartsome.license.resource.Messages; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Display; public class LicenseManageHandler extends AbstractHandler{ public Object execute(ExecutionEvent event) throws ExecutionException { ProgressMonitorDialog progress = new ProgressMonitorDialog(Display.getDefault().getActiveShell()); try { final String[] str = new String[3]; progress.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { monitor.beginTask(Messages.getString("license.LicenseManageHandler.progress"), 10); String[] temp = SystemResourceUtil.load(monitor); str[0] = temp[0]; str[1] = temp[1]; str[2] = temp[2]; monitor.done(); } }); SystemResourceUtil.showDialog(str); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { } return null; } }
1,486
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
KeyGeneratorImpl.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/generator/KeyGeneratorImpl.java
package net.heartsome.license.generator; import net.heartsome.license.ProtectionFactory; import net.heartsome.license.constants.Constants; import net.heartsome.license.utils.RandomUtils; public class KeyGeneratorImpl implements IKeyGenerator { private String installKey; public byte[] generateKey(String licenseId, String series, byte[] b) { String key = licenseId + Constants.SEPARATOR + series + Constants.SEPARATOR + generateInstallKey(); return ProtectionFactory.getEncrypt().encrypt(b, key.getBytes()); } public String generateInstallKey() { installKey = RandomUtils.generateRandom(20); return installKey; } public String getInstallKey() { return installKey; } public byte[] generateKey(String licenseId, String series, String installKey, byte[] b) { String key = licenseId + Constants.SEPARATOR + series + Constants.SEPARATOR + installKey; return ProtectionFactory.getEncrypt().encrypt(b, key.getBytes()); } }
947
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IKeyGenerator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/generator/IKeyGenerator.java
package net.heartsome.license.generator; public interface IKeyGenerator { byte[] generateKey(String licenseId, String series, byte[] b); byte[] generateKey(String licenseId, String series, String installKey, byte[] b); String getInstallKey(); String generateInstallKey(); }
285
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LicenseIdGenerator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/generator/LicenseIdGenerator.java
package net.heartsome.license.generator; import net.heartsome.license.utils.RandomUtils; public class LicenseIdGenerator { private String licenseId; public LicenseIdGenerator(String licenseId) { this.licenseId = licenseId; } public LicenseIdGenerator(String productId, String version, String isTrial) { this.licenseId = productId + version + isTrial + RandomUtils.generateRandom(20); } public String getProductId() { if (licenseId == null) { return null; } return licenseId.substring(0, 2); } public String getVersion() { if (licenseId == null) { return null; } return licenseId.substring(2, 3); } public String getIsTrial() { if (licenseId == null) { return null; } return licenseId.substring(3, 4); } public boolean checkLength() { return licenseId.length() == 24; } }
833
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z