issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
unknown | report_datetime
unknown | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/textmanipulation/TextEdit.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/util/Bindings.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExceptionAnalyzer.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/corext/refactoring/code/StatementAnalyzer.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeElementTreeViewer.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/InlineTempWizard.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/NewPreviewWizardPage.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/PreviewWizardPage.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameParametersWizard.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameRefactoringWizard.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/ExtractMethodAction.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodWizard.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizard.java | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
4,052 | Bug 4052 document change infrastructure - missing functionality (1GH2DWC) | AK (7/18/2001 4:45:27 PM) i stumbled across this when doing Reorder Parameters. consider the following text: m(m(1, 2),3) lets's say you want to swap the parameters. so your desired output is: m(3, m(2, 1)) you create 4 move entries in the change creator (first 'm' has position 1): . move(5, 1] -> 7 //moves the first parameter of the inner call . move[7, 1] -> 5 //moves the 2nd parameter of the inner call . move [3, 6] -> 10 //moves the first parameter of the outer call . move [10, 1] -> 3 //moves the 2nd parameter of the outer call this gets splitted into 4 replaces (will not give details here - see code of AbstractTextBufferChange) anyways, the replaces are sorted backwards before execution. to cut the story short - you end up with: m(3, m(1, 2)) the reason is: the moves are treated in the same way as replaces. they should not be, if they overlap. there should a hierarchy of moves - or another way to say: 'this move must be done before that move' in the case above - the inner moves must be done before the outer ones. this is quite serious and i'm not sure how to nicely work around it. DB (31.07.2001 15:12:06) The current change infrastructure doesn't support any kind of overlapping manipulation. So this is somehow by design. What you can do is to create two distinct text changes. The first changing m(1,2) to m(2,1) and a second one changing m(m(2,1), 3) to m(3, m(2,1)). DB (08.08.2001 14:50:58) I opt to not fix this PR since creating two document changes fixes the problem, although it is not optimal from a speed point of view (the document gets read two times). May be with an improved IBuffer implementation (see 1GEJ61L) the speed trade off isn't a problem anymore. | resolved fixed | fb51769 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T10:09:05Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/sef/SelfEncapsulateFieldWizard.java | |
5,571 | Bug 5571 JAR Packager: Reveal first checked project | If the list of projects in the JAR Packager is long it is possible that the shown projects are not checked even though there are checked projects (due to current selection). ==> reveal the first checked project. | closed fixed | 9cf7888 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T15:03:04Z" | "2001-11-06T15:20:00Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/CheckboxTreeAndListGroup.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
/**
* Combines a CheckboxTreeViewer and CheckboxListViewer.
* All viewer selection-driven interactions are handled within this viewer
*/
public class CheckboxTreeAndListGroup implements ICheckStateListener, ISelectionChangedListener, ITreeViewerListener {
private Object fRoot;
private Object fCurrentTreeSelection;
private List fExpandedTreeNodes= new ArrayList();
private Map fCheckedStateStore= new HashMap(9);
private List fWhiteCheckedTreeItems= new ArrayList();
private List fListeners= new ArrayList();
private ITreeContentProvider fTreeContentProvider;
private IStructuredContentProvider fListContentProvider;
private ILabelProvider fTreeLabelProvider;
private ILabelProvider fListLabelProvider;
// widgets
private CheckboxTreeViewer fTreeViewer;
private CheckboxTableViewer fListViewer;
/**
* Creates an instance of this class. Use this constructor if you wish to specify
* the width and/or height of the combined widget (to only hardcode one of the
* sizing dimensions, specify the other dimension's value as -1)
*
* @param parent org.eclipse.swt.widgets.Composite
* @param style int
* @param rootObject java.lang.Object
* @param childPropertyName java.lang.String
* @param parentPropertyName java.lang.String
* @param listPropertyName java.lang.String
* @param width int
* @param height int
*/
public CheckboxTreeAndListGroup(
Composite parent,
Object rootObject,
ITreeContentProvider treeContentProvider,
ILabelProvider treeLabelProvider,
IStructuredContentProvider listContentProvider,
ILabelProvider listLabelProvider,
int style,
int width,
int height) {
fRoot= rootObject;
fTreeContentProvider= treeContentProvider;
fListContentProvider= listContentProvider;
fTreeLabelProvider= treeLabelProvider;
fListLabelProvider= listLabelProvider;
createContents(parent, width, height, style);
}
/**
* This method must be called just before this window becomes visible.
*/
public void aboutToOpen() {
determineWhiteCheckedDescendents(fRoot);
checkNewTreeElements(getTreeChildren(fRoot));
fCurrentTreeSelection= null;
//select the first element in the list
Object[] elements= getTreeChildren(fRoot);
Object primary= elements.length > 0 ? elements[0] : null;
if (primary != null) {
fTreeViewer.setSelection(new StructuredSelection(primary));
}
fTreeViewer.getControl().setFocus();
}
/**
* Adds the passed listener to self's collection of clients
* that listen for changes to element checked states
*
* @param listener ICheckStateListener
*/
public void addCheckStateListener(ICheckStateListener listener) {
fListeners.add(listener);
}
/**
* Adds the receiver and all of it's ancestors to the checkedStateStore if they
* are not already there.
*/
private void addToHierarchyToCheckedStore(Object treeElement) {
// if this tree element is already gray then its ancestors all are as well
if (!fCheckedStateStore.containsKey(treeElement))
fCheckedStateStore.put(treeElement, new ArrayList());
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null)
addToHierarchyToCheckedStore(parent);
}
/**
* Returns a boolean indicating whether all children of the passed tree element
* are currently white-checked
*
* @return boolean
* @param treeElement java.lang.Object
*/
protected boolean areAllChildrenWhiteChecked(Object treeElement) {
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i) {
if (!fWhiteCheckedTreeItems.contains(children[i]))
return false;
}
return true;
}
/**
* Returns a boolean indicating whether all list elements associated with
* the passed tree element are currently checked
*
* @return boolean
* @param treeElement java.lang.Object
*/
protected boolean areAllElementsChecked(Object treeElement) {
List checkedElements= (List)fCheckedStateStore.get(treeElement);
if (checkedElements == null) // ie.- tree item not even gray-checked
return false;
return getListItemsSize(treeElement) == checkedElements.size();
}
/**
* Iterates through the passed elements which are being realized for the first
* time and check each one in the tree viewer as appropriate
*/
protected void checkNewTreeElements(Object[] elements) {
for (int i= 0; i < elements.length; ++i) {
Object currentElement= elements[i];
boolean checked= fCheckedStateStore.containsKey(currentElement);
fTreeViewer.setChecked(currentElement, checked);
fTreeViewer.setGrayed(
currentElement,
checked && !fWhiteCheckedTreeItems.contains(currentElement));
}
}
/**
* An item was checked in one of self's two views. Determine which
* view this occurred in and delegate appropriately
*
* @param event CheckStateChangedEvent
*/
public void checkStateChanged(final CheckStateChangedEvent event) {
//Potentially long operation - show a busy cursor
BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
public void run() {
if (event.getCheckable().equals(fTreeViewer))
treeItemChecked(event.getElement(), event.getChecked());
else
listItemChecked(event.getElement(), event.getChecked(), true);
notifyCheckStateChangeListeners(event);
}
});
}
/**
* Lay out and initialize self's visual components.
*
* @param parent org.eclipse.swt.widgets.Composite
* @param width int
* @param height int
*/
protected void createContents(
Composite parent,
int width,
int height,
int style) {
// group pane
Composite composite= new Composite(parent, style);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.makeColumnsEqualWidth= true;
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
createTreeViewer(composite, width / 2, height);
createListViewer(composite, width / 2, height);
initialize();
}
/**
* Creates this group's list viewer.
*/
protected void createListViewer(Composite parent, int width, int height) {
fListViewer= new CheckboxTableViewer(parent, SWT.BORDER);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= width;
data.heightHint= height;
fListViewer.getTable().setLayoutData(data);
fListViewer.setContentProvider(fListContentProvider);
fListViewer.setLabelProvider(fListLabelProvider);
fListViewer.addCheckStateListener(this);
}
/**
* Creates this group's tree viewer.
*/
protected void createTreeViewer(Composite parent, int width, int height) {
Tree tree= new Tree(parent, SWT.CHECK | SWT.BORDER);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= width;
data.heightHint= height;
tree.setLayoutData(data);
fTreeViewer= new CheckboxTreeViewer(tree);
fTreeViewer.setContentProvider(fTreeContentProvider);
fTreeViewer.setLabelProvider(fTreeLabelProvider);
fTreeViewer.addTreeListener(this);
fTreeViewer.addCheckStateListener(this);
fTreeViewer.addSelectionChangedListener(this);
}
/**
* Returns a boolean indicating whether the passed tree element should be
* at LEAST gray-checked. Note that this method does not consider whether
* it should be white-checked, so a specified tree item which should be
* white-checked will result in a <code>true</code> answer from this method.
* To determine whether a tree item should be white-checked use method
* #determineShouldBeWhiteChecked(Object).
*
* @param element java.lang.Object
* @return boolean
* @see #determineShouldBeWhiteChecked(java.lang.Object)
*/
protected boolean determineShouldBeAtLeastGrayChecked(Object treeElement) {
// if any list items associated with treeElement are checked then it
// retains its gray-checked status regardless of its children
List checked= (List) fCheckedStateStore.get(treeElement);
if (checked != null && (!checked.isEmpty()))
return true;
// if any children of treeElement are still gray-checked then treeElement
// must remain gray-checked as well
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i) {
if (fCheckedStateStore.containsKey(children[i]))
return true;
}
return false;
}
/**
* Returns a boolean indicating whether the passed tree item should be
* white-checked.
*
* @return boolean
* @param treeElement java.lang.Object
*/
protected boolean determineShouldBeWhiteChecked(Object treeElement) {
return areAllChildrenWhiteChecked(treeElement)
&& areAllElementsChecked(treeElement);
}
/**
* Recursively adds appropriate tree elements to the collection of
* known white-checked tree elements.
*
* @param treeElement java.lang.Object
*/
protected void determineWhiteCheckedDescendents(Object treeElement) {
// always go through all children first since their white-checked
// statuses will be needed to determine the white-checked status for
// this tree element
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i)
determineWhiteCheckedDescendents(children[i]);
// now determine the white-checked status for this tree element
if (determineShouldBeWhiteChecked(treeElement))
setWhiteChecked(treeElement, true);
}
/**
* Causes the tree viewer to expand all its items
*/
public void expandAll() {
fTreeViewer.expandAll();
}
/**
* Answers a flat collection of all of the checked elements in the
* list portion of self
*
* @return java.util.Vector
*/
public Iterator getAllCheckedListItems() {
Set result= new HashSet();
Iterator listCollectionsEnum= fCheckedStateStore.values().iterator();
while (listCollectionsEnum.hasNext())
result.addAll((List)listCollectionsEnum.next());
return result.iterator();
}
/**
* Answer a collection of all of the checked elements in the tree portion
* of self
*
* @return java.util.Vector
*/
public Set getAllCheckedTreeItems() {
return new HashSet(fCheckedStateStore.keySet());
}
/**
* Answers the number of elements that have been checked by the
* user.
*
* @return int
*/
public int getCheckedElementCount() {
return fCheckedStateStore.size();
}
/**
* Returns a count of the number of list items associated with a
* given tree item.
*
* @return int
* @param treeElement java.lang.Object
*/
protected int getListItemsSize(Object treeElement) {
Object[] elements= getListElements(treeElement);
return elements.length;
}
/**
* Gets the table that displays the folder content
*
* @return the table used to show the list
*/
public Table getTable() {
return fListViewer.getTable();
}
/**
* Gets the tree that displays the list for a folder
*
* @return the tree used to show the folders
*/
public Tree getTree() {
return fTreeViewer.getTree();
}
/**
* Adds the given filter to the tree viewer and
* triggers refiltering and resorting of the elements.
*
* @param filter a viewer filter
*/
public void addTreeFilter(ViewerFilter filter) {
fTreeViewer.addFilter(filter);
}
/**
* Adds the given filter to the list viewer and
* triggers refiltering and resorting of the elements.
*
* @param filter a viewer filter
*/
public void addListFilter(ViewerFilter filter) {
fListViewer.addFilter(filter);
}
/**
* Logically gray-check all ancestors of treeItem by ensuring that they
* appear in the checked table
*/
protected void grayCheckHierarchy(Object treeElement) {
// if this tree element is already gray then its ancestors all are as well
if (fCheckedStateStore.containsKey(treeElement))
return; // no need to proceed upwards from here
fCheckedStateStore.put(treeElement, new ArrayList());
if (determineShouldBeWhiteChecked(treeElement)) {
setWhiteChecked(treeElement, true);
}
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null)
grayCheckHierarchy(parent);
}
/**
* Sets the initial checked state of the passed list element to true.
*/
public void initialCheckListItem(Object element) {
Object parent= fTreeContentProvider.getParent(element);
fCurrentTreeSelection= parent;
//As this is not done from the UI then set the box for updating from the selection to false
listItemChecked(element, true, false);
updateHierarchy(parent);
}
/**
* Sets the initial checked state of the passed element to true,
* as well as to all of its children and associated list elements
*/
public void initialCheckTreeItem(Object element) {
treeItemChecked(element, true);
}
/**
* Initializes this group's viewers after they have been laid out.
*/
protected void initialize() {
fTreeViewer.setInput(fRoot);
}
/**
* Callback that's invoked when the checked status of an item in the list
* is changed by the user. Do not try and update the hierarchy if we are building the
* initial list.
*/
protected void listItemChecked(
Object listElement,
boolean state,
boolean updatingFromSelection) {
List checkedListItems= (List) fCheckedStateStore.get(fCurrentTreeSelection);
if (state) {
if (checkedListItems == null) {
// since the associated tree item has gone from 0 -> 1 checked
// list items, tree checking may need to be updated
grayCheckHierarchy(fCurrentTreeSelection);
checkedListItems= (List) fCheckedStateStore.get(fCurrentTreeSelection);
}
checkedListItems.add(listElement);
} else {
checkedListItems.remove(listElement);
if (checkedListItems.isEmpty()) {
// since the associated tree item has gone from 1 -> 0 checked
// list items, tree checking may need to be updated
ungrayCheckHierarchy(fCurrentTreeSelection);
}
}
if (updatingFromSelection)
updateHierarchy(fCurrentTreeSelection);
}
/**
* Notifies all checked state listeners that the passed element has had
* its checked state changed to the passed state
*/
protected void notifyCheckStateChangeListeners(CheckStateChangedEvent event) {
Iterator listenersEnum= fListeners.iterator();
while (listenersEnum.hasNext())
((ICheckStateListener) listenersEnum.next()).checkStateChanged(event);
}
/**
*Sets the contents of the list viewer based upon the specified selected
*tree element. This also includes checking the appropriate list items.
*
*@param treeElement java.lang.Object
*/
protected void populateListViewer(final Object treeElement) {
fListViewer.setInput(treeElement);
List listItemsToCheck= (List) fCheckedStateStore.get(treeElement);
if (listItemsToCheck != null) {
Iterator listItemsEnum= listItemsToCheck.iterator();
while (listItemsEnum.hasNext())
fListViewer.setChecked(listItemsEnum.next(), true);
}
}
/**
* Removes the passed listener from self's collection of clients
* that listen for changes to element checked states
*
* @param listener ICheckStateListener
*/
public void removeCheckStateListener(ICheckStateListener listener) {
fListeners.remove(listener);
}
/**
* Handles the selection of an item in the tree viewer
*
* @param selection ISelection
*/
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
Object selectedElement= selection.getFirstElement();
if (selectedElement == null) {
fCurrentTreeSelection= null;
fListViewer.setInput(fCurrentTreeSelection);
return;
}
// ie.- if not an item deselection
if (selectedElement != fCurrentTreeSelection)
populateListViewer(selectedElement);
fCurrentTreeSelection= selectedElement;
}
/**
* Selects or deselect all of the elements in the tree depending on the value of the selection
* boolean. Be sure to update the displayed files as well.
*/
public void setAllSelections(final boolean selection) {
//Potentially long operation - show a busy cursor
BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
public void run() {
setTreeChecked(fRoot, selection);
fListViewer.setAllChecked(selection);
}
});
}
/**
* Sets the list viewer's providers to those passed
*
* @param contentProvider ITreeContentProvider
* @param labelProvider ILabelProvider
*/
public void setListProviders(
IStructuredContentProvider contentProvider,
ILabelProvider labelProvider) {
fListViewer.setContentProvider(contentProvider);
fListViewer.setLabelProvider(labelProvider);
}
/**
* Sets the sorter that is to be applied to self's list viewer
*/
public void setListSorter(ViewerSorter sorter) {
fListViewer.setSorter(sorter);
}
/**
* Sets the root of the widget to be new Root. Regenerate all of the tables and lists from this
* value.
*
* @param newRoot
*/
public void setRoot(Object newRoot) {
this.fRoot= newRoot;
initialize();
}
/**
* Sets the checked state of the passed tree element appropriately, and
* do so recursively to all of its child tree elements as well
*/
protected void setTreeChecked(Object treeElement, boolean state) {
if (treeElement.equals(fCurrentTreeSelection)) {
fListViewer.setAllChecked(state);
}
if (state) {
Object[] listItems= getListElements(treeElement);
List listItemsChecked= new ArrayList();
for (int i= 0; i < listItems.length; ++i)
listItemsChecked.add(listItems[i]);
fCheckedStateStore.put(treeElement, listItemsChecked);
} else
fCheckedStateStore.remove(treeElement);
setWhiteChecked(treeElement, state);
fTreeViewer.setChecked(treeElement, state);
fTreeViewer.setGrayed(treeElement, false);
// now logically check/uncheck all children as well
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i) {
setTreeChecked(children[i], state);
}
}
/**
* Sets the tree viewer's providers to those passed
*
* @param contentProvider ITreeContentProvider
* @param labelProvider ILabelProvider
*/
public void setTreeProviders(
ITreeContentProvider contentProvider,
ILabelProvider labelProvider) {
fTreeViewer.setContentProvider(contentProvider);
fTreeViewer.setLabelProvider(labelProvider);
}
/**
* Sets the sorter that is to be applied to self's tree viewer
*/
public void setTreeSorter(ViewerSorter sorter) {
fTreeViewer.setSorter(sorter);
}
/**
* Adjusts the collection of references to white-checked tree elements appropriately.
*
* @param treeElement java.lang.Object
* @param isWhiteChecked boolean
*/
protected void setWhiteChecked(Object treeElement, boolean isWhiteChecked) {
if (isWhiteChecked) {
if (!fWhiteCheckedTreeItems.contains(treeElement))
fWhiteCheckedTreeItems.add(treeElement);
} else
fWhiteCheckedTreeItems.remove(treeElement);
}
/**
* Handle the collapsing of an element in a tree viewer
*/
public void treeCollapsed(TreeExpansionEvent event) {
// We don't need to do anything with this
}
/**
* Handles the expansionsion of an element in a tree viewer
*/
public void treeExpanded(TreeExpansionEvent event) {
Object item= event.getElement();
// First see if the children need to be given their checked state at all. If they've
// already been realized then this won't be necessary
if (!fExpandedTreeNodes.contains(item)) {
fExpandedTreeNodes.add(item);
checkNewTreeElements(getTreeChildren(item));
}
}
/**
* Callback that's invoked when the checked status of an item in the tree
* is changed by the user.
*/
protected void treeItemChecked(Object treeElement, boolean state) {
// recursively adjust all child tree elements appropriately
setTreeChecked(treeElement, state);
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent == null)
return;
// now update upwards in the tree hierarchy
if (state)
grayCheckHierarchy(parent);
else
ungrayCheckHierarchy(parent);
updateHierarchy(treeElement);
}
/**
* Logically un-gray-check all ancestors of treeItem iff appropriate.
*/
protected void ungrayCheckHierarchy(Object treeElement) {
if (!determineShouldBeAtLeastGrayChecked(treeElement))
fCheckedStateStore.remove(treeElement);
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null)
ungrayCheckHierarchy(parent);
}
/**
* Sets the checked state of self and all ancestors appropriately
*/
protected void updateHierarchy(Object treeElement) {
boolean whiteChecked= determineShouldBeWhiteChecked(treeElement);
boolean shouldBeAtLeastGray= determineShouldBeAtLeastGrayChecked(treeElement);
fTreeViewer.setChecked(treeElement, shouldBeAtLeastGray);
setWhiteChecked(treeElement, whiteChecked);
if (whiteChecked)
fTreeViewer.setGrayed(treeElement, false);
else
fTreeViewer.setGrayed(treeElement, shouldBeAtLeastGray);
// proceed up the tree element hierarchy
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null) {
updateHierarchy(parent);
}
}
/**
* Update the selections of the tree elements in items to reflect the new
* selections provided.
*
* @param Map with keys of Object (the tree element) and values of List (the selected
* list elements).
*/
public void updateSelections(final Map items) {
//Potentially long operation - show a busy cursor
BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
public void run() {
handleUpdateSelection(items);
}
});
}
/**
* Returns the result of running the given elements through the filters.
*
* @param elements the elements to filter
* @return only the elements which all filters accept
*/
protected Object[] filter(ViewerFilter[] filters, Object[] elements) {
if (filters != null) {
ArrayList filtered = new ArrayList(elements.length);
for (int i = 0; i < elements.length; i++) {
boolean add = true;
for (int j = 0; j < filters.length; j++) {
add = filters[j].select(null, null, elements[i]);
if (!add)
break;
}
if (add)
filtered.add(elements[i]);
}
return filtered.toArray();
}
return elements;
}
private Object[] getTreeChildren(Object element) {
return filter(fTreeViewer.getFilters(), fTreeContentProvider.getChildren(element));
}
private Object[] getListElements(Object element) {
return filter(fListViewer.getFilters(), fListContentProvider.getElements(element));
}
public Set getWhiteCheckedTreeItems() {
return new HashSet(fWhiteCheckedTreeItems);
}
private void handleUpdateSelection(Map items) {
Iterator keyIterator= items.keySet().iterator();
//Update the store before the hierarchy to prevent updating parents before all of the children are done
while (keyIterator.hasNext()) {
Object key= keyIterator.next();
//Replace the items in the checked state store with those from the supplied items
List selections= (List) items.get(key);
if (selections.size() == 0)
//If it is empty remove it from the list
fCheckedStateStore.remove(key);
else {
fCheckedStateStore.put(key, selections);
// proceed up the tree element hierarchy
Object parent= fTreeContentProvider.getParent(key);
if (parent != null) {
addToHierarchyToCheckedStore(parent);
}
}
}
//Now update hierarchies
keyIterator= items.keySet().iterator();
while (keyIterator.hasNext()) {
Object key= keyIterator.next();
updateHierarchy(key);
if (fCurrentTreeSelection != null && fCurrentTreeSelection.equals(key)) {
fListViewer.setAllChecked(false);
fListViewer.setCheckedElements(((List) items.get(key)).toArray());
}
}
}
}
|
5,571 | Bug 5571 JAR Packager: Reveal first checked project | If the list of projects in the JAR Packager is long it is possible that the shown projects are not checked even though there are checked projects (due to current selection). ==> reveal the first checked project. | closed fixed | 9cf7888 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T15:03:04Z" | "2001-11-06T15:20:00Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWizardPage.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.WizardExportResourcesPage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.packageview.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
/**
* Page 1 of the JAR Package wizard
*/
public class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
private JarPackage fJarPackage;
private IStructuredSelection fInitialSelection;
private CheckboxTreeAndListGroup fInputGroup;
// widgets
private Text fSourceNameField;
private Button fSourceBrowseButton;
private Button fExportClassFilesCheckbox;
private Button fExportJavaFilesCheckbox;
private Combo fDestinationNamesCombo;
private Button fDestinationBrowseButton;
private Button fCompressCheckbox;
private Button fOverwriteCheckbox;
private Composite fDescriptionFileGroup;
private Button fSaveDescriptionCheckbox;
private Label fDescriptionFileLabel;
private Text fDescriptionFileText;
private Button fDescriptionFileBrowseButton;
// dialog store id constants
private final static String PAGE_NAME= "JarPackageWizardPage"; //$NON-NLS-1$
private final static String STORE_EXPORT_CLASS_FILES= PAGE_NAME + ".EXPORT_CLASS_FILES"; //$NON-NLS-1$
private final static String STORE_EXPORT_JAVA_FILES= PAGE_NAME + ".EXPORT_JAVA_FILES"; //$NON-NLS-1$
private final static String STORE_DESTINATION_NAMES= PAGE_NAME + ".DESTINATION_NAMES_ID"; //$NON-NLS-1$
private final static String STORE_COMPRESS= PAGE_NAME + ".COMPRESS"; //$NON-NLS-1$
private final static String STORE_OVERWRITE= PAGE_NAME + ".OVERWRITE"; //$NON-NLS-1$
// other constants
private final static int SIZING_SELECTION_WIDGET_WIDTH= 400;
private final static int SIZING_SELECTION_WIDGET_HEIGHT= 150;
/**
* Create an instance of this class
*/
public JarPackageWizardPage(JarPackage jarPackage, IStructuredSelection selection) {
super(PAGE_NAME, selection);
setTitle(JarPackagerMessages.getString("JarPackageWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarPackageWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
fInitialSelection= selection;
}
/*
* Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(
new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whatToExport.label")); //$NON-NLS-1$
createInputGroup(composite);
createExportTypeGroup(composite);
new Label(composite, SWT.NONE); // vertical spacer
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whereToExport.label")); //$NON-NLS-1$
createDestinationGroup(composite);
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.options.label")); //$NON-NLS-1$
createOptionsGroup(composite);
restoreResourceSpecificationWidgetValues(); // superclass API defines this hook
restoreWidgetValues();
if (fInitialSelection != null)
setupBasedOnInitialSelections();
setControl(composite);
update();
giveFocusToDestination();
WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.JARPACKAGER_WIZARD_PAGE));
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createOptionsGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
optionsGroup.setLayout(layout);
fCompressCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fCompressCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.compress.text")); //$NON-NLS-1$
fCompressCheckbox.addListener(SWT.Selection, this);
fOverwriteCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fOverwriteCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.overwrite.text")); //$NON-NLS-1$
fOverwriteCheckbox.addListener(SWT.Selection, this);
}
/**
* Answer the contents of the destination specification widget. If this
* value does not have the required suffix then add it first.
*
* @return java.lang.String
*/
protected String getDestinationValue() {
String requiredSuffix= getOutputSuffix();
String destinationText= fDestinationNamesCombo.getText().trim();
if (!destinationText.toLowerCase().endsWith(requiredSuffix.toLowerCase()))
destinationText += requiredSuffix;
return destinationText;
}
/**
* Answer the string to display in self as the destination type
*
* @return java.lang.String
*/
protected String getDestinationLabel() {
return JarPackagerMessages.getString("JarPackageWizardPage.destination.label"); //$NON-NLS-1$
}
/**
* Answer the suffix that files exported from this wizard must have.
* If this suffix is a file extension (which is typically the case)
* then it must include the leading period character.
*
* @return java.lang.String
*/
protected String getOutputSuffix() {
return "." + JarPackage.EXTENSION; //$NON-NLS-1$
}
/**
* Returns an iterator over this page's collection of currently-specified
* elements to be exported. This is the primary element selection facility
* accessor for subclasses.
*
* @return an iterator over the collection of elements currently selected for export
*/
protected Iterator getSelectedResourcesIterator() {
return fInputGroup.getAllCheckedListItems();
}
/**
* Persists resource specification control setting that are to be restored
* in the next instance of this page. Subclasses wishing to persist
* settings for their controls should extend the hook method
* <code>internalSaveWidgetValues</code>.
*/
public final void saveWidgetValues() {
// update directory names history
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
directoryNames= new String[0];
directoryNames= addToHistory(directoryNames, getDestinationValue());
settings.put(STORE_DESTINATION_NAMES, directoryNames);
settings.put(STORE_EXPORT_CLASS_FILES, fJarPackage.areClassFilesExported());
settings.put(STORE_EXPORT_JAVA_FILES, fJarPackage.areJavaFilesExported());
// options
settings.put(STORE_COMPRESS, fJarPackage.isCompressed());
settings.put(STORE_OVERWRITE, fJarPackage.allowOverwrite());
}
// Allow subclasses to save values
internalSaveWidgetValues();
}
/**
* Hook method for subclasses to persist their settings.
*/
protected void internalSaveWidgetValues() {
}
/**
* Hook method for restoring widget values to the values that they held
* last time this wizard was used to completion.
*/
protected void restoreWidgetValues() {
if (!fJarPackage.isUsedToInitialize())
initializeJarPackage();
fExportClassFilesCheckbox.setSelection(fJarPackage.areClassFilesExported());
fExportJavaFilesCheckbox.setSelection(fJarPackage.areJavaFilesExported());
// destination
if (fJarPackage.getJarLocation().isEmpty())
fDestinationNamesCombo.setText(""); //$NON-NLS-1$
else
fDestinationNamesCombo.setText(fJarPackage.getJarLocation().toOSString());
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
if (! fDestinationNamesCombo.getText().equals(directoryNames[0]))
fDestinationNamesCombo.add(fDestinationNamesCombo.getText());
for (int i= 0; i < directoryNames.length; i++)
fDestinationNamesCombo.add(directoryNames[i]);
}
// options
fCompressCheckbox.setSelection(fJarPackage.isCompressed());
fOverwriteCheckbox.setSelection(fJarPackage.allowOverwrite());
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(settings.getBoolean(STORE_EXPORT_CLASS_FILES));
fJarPackage.setExportJavaFiles(settings.getBoolean(STORE_EXPORT_JAVA_FILES));
// options
fJarPackage.setCompress(settings.getBoolean(STORE_COMPRESS));
fJarPackage.setOverwrite(settings.getBoolean(STORE_OVERWRITE));
// destination
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
fJarPackage.setJarLocation(getPathFromString(directoryNames[0]));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
// destination
fJarPackage.setJarLocation(getPathFromString(fDestinationNamesCombo.getText()));
// options
fJarPackage.setCompress(fCompressCheckbox.getSelection());
fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
}
protected IPath getPathFromString(String text) {
return new Path(text).makeAbsolute();
}
/**
* Returns a boolean indicating whether the passed File handle is
* is valid and available for use.
*
* @return boolean
*/
protected boolean ensureTargetFileIsValid(File targetFile) {
if (targetFile.exists() && targetFile.isDirectory()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (targetFile.exists()) {
if (!targetFile.canWrite()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.jarFileExistsAndNotWritable")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
}
return true;
}
/*
* Overrides method from WizardExportPage
*/
protected void createDestinationGroup(Composite parent) {
initializeDialogUnits(parent);
// destination specification group
Composite destinationSelectionGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
destinationSelectionGroup.setLayout(layout);
destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
new Label(destinationSelectionGroup, SWT.NONE).setText(getDestinationLabel());
// destination name entry field
fDestinationNamesCombo= new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
fDestinationNamesCombo.addListener(SWT.Modify, this);
fDestinationNamesCombo.addListener(SWT.Selection, this);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= SIZING_TEXT_FIELD_WIDTH;
fDestinationNamesCombo.setLayoutData(data);
// destination browse button
fDestinationBrowseButton= new Button(destinationSelectionGroup, SWT.PUSH);
fDestinationBrowseButton.setText(JarPackagerMessages.getString("JarPackageWizardPage.browseButton.text")); //$NON-NLS-1$
fDestinationBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
SWTUtil.setButtonDimensionHint(fDestinationBrowseButton);
fDestinationBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleDestinationBrowseButtonPressed();
}
});
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDescriptionFileBrowseButtonPressed() {
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getDescriptionLocation()));
if (dialog.open() == dialog.OK) {
IPath path= dialog.getResult();
path= path.removeFileExtension().addFileExtension(JarPackage.DESCRIPTION_EXTENSION);
fDescriptionFileText.setText(path.toString());
}
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog= new FileDialog(getContainer().getShell(), SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.jar"}); //$NON-NLS-1$
String currentSourceString= getDestinationValue();
int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
dialog.setFileName(currentSourceString.substring(lastSeparatorIndex + 1, currentSourceString.length()));
}
else
dialog.setFileName(currentSourceString);
String selectedFileName= dialog.open();
if (selectedFileName != null) {
IPath path= getPathFromString(selectedFileName);
if (path.lastSegment().equals(getOutputSuffix()))
selectedFileName= ""; //$NON-NLS-1$
fDestinationNamesCombo.setText(selectedFileName);
}
}
/**
* Returns the resource for the specified path.
*
* @param path the path for which the resource should be returned
* @return the resource specified by the path or <code>null</code>
*/
protected IResource findResource(IPath path) {
IWorkspace workspace= JavaPlugin.getWorkspace();
IStatus result= workspace.validatePath(
path.toString(),
IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
if (result.isOK() && workspace.getRoot().exists(path))
return workspace.getRoot().findMember(path);
return null;
}
/**
* Creates the checkbox tree and list for selecting resources.
*
* @param parent the parent control
*/
protected void createInputGroup(Composite parent) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider treeContentProvider=
new JavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
fInputGroup= new CheckboxTreeAndListGroup(
parent,
JavaCore.create(JavaPlugin.getDefault().getWorkspace().getRoot()),
treeContentProvider,
new JavaElementLabelProvider(labelFlags),
new BaseJavaElementContentProvider(),
new JavaElementLabelProvider(labelFlags),
SWT.NONE,
SIZING_SELECTION_WIDGET_WIDTH,
SIZING_SELECTION_WIDGET_HEIGHT);
fInputGroup.addTreeFilter(new EmptyInnerPackageFilter());
fInputGroup.addTreeFilter(new ContainerFilter(ContainerFilter.FILTER_NON_CONTAINERS));
fInputGroup.addTreeFilter(new LibraryFilter());
fInputGroup.addListFilter(new ContainerFilter(ContainerFilter.FILTER_CONTAINERS));
fInputGroup.getTree().addListener(SWT.MouseUp, this);
fInputGroup.getTable().addListener(SWT.MouseUp, this);
}
/**
* Creates the export type controls.
*
* @param parent the parent control
*/
protected void createExportTypeGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout optionsLayout= new GridLayout();
optionsLayout.marginHeight= 0;
optionsGroup.setLayout(optionsLayout);
fExportClassFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportClassFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportClassFiles.text")); //$NON-NLS-1$
fExportClassFilesCheckbox.addListener(SWT.Selection, this);
fExportJavaFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportJavaFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportJavaFiles.text")); //$NON-NLS-1$
fExportJavaFilesCheckbox.addListener(SWT.Selection, this);
}
/**
* Updates the enablements of this page's controls. Subclasses may extend.
*/
protected void updateWidgetEnablements() {
}
/*
* Overrides method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
setErrorMessage(null);
return super.determinePageCompletion();
}
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
protected void update() {
updateModel();
updateWidgetEnablements();
updatePageCompletion();
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateDestinationGroup() {
if (fDestinationNamesCombo.getText().length() == 0) {
return false;
}
if (fJarPackage.getJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
return ensureTargetFileIsValid(fJarPackage.getJarLocation().toFile());
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateOptionsGroup() {
return true;
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateSourceGroup() {
if (!fExportClassFilesCheckbox.getSelection()
&& !fExportJavaFilesCheckbox.getSelection()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.noExportTypeChecked")); //$NON-NLS-1$
return false;
}
if (getSelectedResources().size() == 0)
return false;
if (fExportClassFilesCheckbox.getSelection() || !fExportJavaFilesCheckbox.getSelection())
return true;
// No class file export - check if there are source files
Iterator iter= getSelectedResourcesIterator();
while (iter.hasNext()) {
if (!(iter.next() instanceof IClassFile))
return true;
}
return false;
}
/*
* Overwrides method from WizardExportPage
*/
protected IPath getResourcePath() {
return getPathFromText(fSourceNameField);
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Set the current input focus to self's destination entry field
*/
protected void giveFocusToDestination() {
fDestinationNamesCombo.setFocus();
}
/*
* Overrides method from WizardExportResourcePage
*/
protected void setupBasedOnInitialSelections() {
Iterator enum= fInitialSelection.iterator();
while (enum.hasNext()) {
Object selectedElement= enum.next();
if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile || selectedElement instanceof IFile)
fInputGroup.initialCheckListItem(selectedElement);
else
fInputGroup.initialCheckTreeItem(selectedElement);
}
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
/*
* Method declared on IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
if (getControl() != null)
updatePageCompletion();
}
void setSelectedElementsWithoutContainedChildren() {
Set closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
closure.addAll(getExportedNonContainers());
fJarPackage.setSelectedElementsClosure(closure);
}
private Set removeContainedChildren(Set elements) {
Set newList= new HashSet(elements.size());
Set javaElementResources= getCorrespondingContainers(elements);
Iterator iter= elements.iterator();
boolean removedOne= false;
while (iter.hasNext()) {
Object element= iter.next();
Object parent;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement) {
parent= ((IJavaElement)element).getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
try {
if (pkgRoot.getCorrespondingResource() instanceof IProject)
parent= pkgRoot.getJavaProject();
} catch (JavaModelException ex) {
// leave parent as is
}
}
}
else {
// unknown type
newList.add(element);
continue;
}
if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
removedOne= true;
else
newList.add(element);
}
if (removedOne)
return removeContainedChildren(newList);
else
return newList;
}
private Set getExportedNonContainers() {
Set whiteCheckedTreeItems= fInputGroup.getWhiteCheckedTreeItems();
Set exportedNonContainers= new HashSet(whiteCheckedTreeItems.size());
Set javaElementResources= getCorrespondingContainers(whiteCheckedTreeItems);
Iterator iter= fInputGroup.getAllCheckedListItems();
while (iter.hasNext()) {
Object element= iter.next();
Object parent= null;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement)
parent= ((IJavaElement)element).getParent();
if (!whiteCheckedTreeItems.contains(parent) && !javaElementResources.contains(parent))
exportedNonContainers.add(element);
}
return exportedNonContainers;
}
/*
* Create a list with the folders / projects that correspond
* to the Java elements (Java project, package, package root)
*/
private Set getCorrespondingContainers(Set elements) {
Set javaElementResources= new HashSet(elements.size());
Iterator iter= elements.iterator();
while (iter.hasNext()) {
Object element= iter.next();
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
// exclude default package since it is covered by the root
if (!(type == IJavaElement.PACKAGE_FRAGMENT && ((IPackageFragment)element).isDefaultPackage())) {
Object resource;
try {
resource= je.getCorrespondingResource();
} catch (JavaModelException ex) {
resource= null;
}
if (resource != null)
javaElementResources.add(resource);
}
}
}
}
return javaElementResources;
}
}
|
6,478 | Bug 6478 Jar packager progress messages misleading | When exporting classes to a JAR file, the progress message says things like: "Exporting org.eclipse.foo.MyFile.java" This is misleading, because it looks like it's adding .java files to the zip, but it's actually adding class files. I actually canceled the export and went to check the jar file when I saw these messages. I suggest just trimming the .java suffix: "Exporting org.eclipse.foo.MyFile" | verified fixed | d551209 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T15:20:18Z" | "2001-11-30T17:06:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.xml.sax.SAXException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IRunnableWithProgress {
private JarWriter fJarWriter;
private JarPackage fJarPackage;
private IFile[] fDescriptionFiles;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private MultiStatus fProblems;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackage jarPackage, Shell parent) {
this(parent);
fJarPackage= jarPackage;
}
/**
* Creates an instance of this class.
*
* @param descriptions an array with JAR package descriptions
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(IFile[] descriptions, Shell parent) {
this(parent);
fDescriptionFiles= descriptions;
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$
}
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
return fJarPackage.getSelectedElements().size();
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= jProject.findPackageFragmentRoot(resource.getFullPath().uptoSegment(2));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
progressMonitor.subTask(destinationPath.toString());
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResourceFiles(pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else
exportContainer(progressMonitor, resource);
}
private void exportContainer(IProgressMonitor progressMonitor, IResource resource) throws java.lang.InterruptedException {
IResource[] children= null;
try {
children= ((IContainer) resource).members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", resource.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportResourceFiles(IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || (pkgRoot == null && !isInOutputFolder);
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
fJarWriter.write((IFile) resource, destinationPath);
} catch (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
fJarWriter.write(file, baseDestinationPath.append(file.getName()));
}
} catch (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
Iterator iter= fJarPackage.getSelectedElements().iterator();
while (iter.hasNext())
exportElement(iter.next(), progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
if (isJavaFile(file)) {
// Java CU - search files with .class ending
boolean hasErrors= fJarPackage.hasCompileErrors(file);
boolean hasWarnings= fJarPackage.hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
fClassFilesMapContainer= classContainer;
}
ArrayList classFiles= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFiles == null || classFiles.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFiles.iterator();
}
else {
// resource - search file with same name
List binaryFiles= new ArrayList(1);
IFile cpFile= outputContainer.getFile(pathInJar);
if (cpFile.isAccessible()) {
if (!cpFile.isLocal(IResource.DEPTH_ZERO))
cpFile.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
binaryFiles.add(cpFile);
}
else {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceOnCasspathNotAccessible", cpFile.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return binaryFiles.iterator();
}
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fProblems.getSeverity() == IStatus.ERROR) {
String message= null;
if (fDescriptionFiles != null && fDescriptionFiles.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
// Create new status because we want another message - no API to set message
return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null);
}
return fProblems;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.exportErrors())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
if (fJarPackage != null)
singleRun(progressMonitor);
else {
int jarCount= fDescriptionFiles.length;
for (int i= 0; i < jarCount; i++) {
fJarPackage= readJarPackage(fDescriptionFiles[i]);
if (fJarPackage != null)
singleRun(progressMonitor);
}
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int totalWork= countSelectedElements();
progressMonitor.beginTask(JarPackagerMessages.getString("JarFileExportOperation.exporting"), totalWork); //$NON-NLS-1$
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
fJarWriter= new JarWriter(fJarPackage, fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getSelectedElements() == null || fJarPackage.getSelectedElements().size() == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.doesManifestExist()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
if (dirtyEditors.length > 0) {
List unsavedFiles= new ArrayList(dirtyEditors.length);
List selection= fJarPackage.getSelectedResources();
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFile.getFullPath()), null); //$NON-NLS-1$
}
}
}
if (!unsavedFiles.isEmpty())
return false;
}
return true;
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
JarPackageWriter objectStream= new JarPackageWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
objectStream.writeXML(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
if (fJarPackage.getDescriptionFile().isAccessible()) {
if (fJarPackage.canOverwriteDescription(fParentShell))
fJarPackage.getDescriptionFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getDescriptionFile().create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (objectStream != null)
objectStream.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
if (fJarPackage.getManifestFile().isAccessible()) {
if (fJarPackage.canOverwriteManifest(fParentShell))
fJarPackage.getManifestFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getManifestFile().create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
/**
* Reads the JAR package spec from file.
*/
protected JarPackage readJarPackage(IFile description) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(JarPackage.DESCRIPTION_EXTENSION));
JarPackage jarPackage= null;
JarPackageReader reader= null;
try {
reader= new JarPackageReader(description.getContents());
// Do not save - only generate JAR
jarPackage= reader.readXML();
jarPackage.setSaveManifest(false);
jarPackage.setSaveDescription(false);
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorReadingJarPackageFromDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorReadingFile", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} catch (SAXException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.badXmlFormat", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} finally {
if ((jarPackage == null || jarPackage.logWarnings()) && reader != null)
// AddWarnings
fProblems.addAll(reader.getWarnings());
try {
if (reader != null)
reader.close();
}
catch (IOException ex) {
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorClosingJarPackageDescriptionReader", description.getFullPath()), ex); //$NON-NLS-1$
}
}
return jarPackage;
}
}
|
5,853 | Bug 5853 Jar packager: progress reporting not optimal | - follow smoke test until step "Create a Jar from a Jar Package Description" - do the steps observe: the progress bar show 100% right from the beginning. | resolved fixed | dc99df8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T16:02:43Z" | "2001-11-13T16:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.xml.sax.SAXException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IRunnableWithProgress {
private JarWriter fJarWriter;
private JarPackage fJarPackage;
private IFile[] fDescriptionFiles;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private MultiStatus fProblems;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackage jarPackage, Shell parent) {
this(parent);
fJarPackage= jarPackage;
}
/**
* Creates an instance of this class.
*
* @param descriptions an array with JAR package descriptions
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(IFile[] descriptions, Shell parent) {
this(parent);
fDescriptionFiles= descriptions;
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$
}
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
return fJarPackage.getSelectedElements().size();
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= jProject.findPackageFragmentRoot(resource.getFullPath().uptoSegment(2));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResourceFiles(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else
exportContainer(progressMonitor, resource);
}
private void exportContainer(IProgressMonitor progressMonitor, IResource resource) throws java.lang.InterruptedException {
IResource[] children= null;
try {
children= ((IContainer) resource).members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", resource.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportResourceFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || (pkgRoot == null && !isInOutputFolder);
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(destinationPath.toString());
fJarWriter.write((IFile) resource, destinationPath);
} catch (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(classFilePath.toString());
fJarWriter.write(file, classFilePath);
}
} catch (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
Iterator iter= fJarPackage.getSelectedElements().iterator();
while (iter.hasNext())
exportElement(iter.next(), progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
if (isJavaFile(file)) {
// Java CU - search files with .class ending
boolean hasErrors= fJarPackage.hasCompileErrors(file);
boolean hasWarnings= fJarPackage.hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
fClassFilesMapContainer= classContainer;
}
ArrayList classFiles= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFiles == null || classFiles.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFiles.iterator();
}
else {
// resource - search file with same name
List binaryFiles= new ArrayList(1);
IFile cpFile= outputContainer.getFile(pathInJar);
if (cpFile.isAccessible()) {
if (!cpFile.isLocal(IResource.DEPTH_ZERO))
cpFile.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
binaryFiles.add(cpFile);
}
else {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceOnCasspathNotAccessible", cpFile.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return binaryFiles.iterator();
}
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fProblems.getSeverity() == IStatus.ERROR) {
String message= null;
if (fDescriptionFiles != null && fDescriptionFiles.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
// Create new status because we want another message - no API to set message
return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null);
}
return fProblems;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.exportErrors())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
if (fJarPackage != null)
singleRun(progressMonitor);
else {
int jarCount= fDescriptionFiles.length;
for (int i= 0; i < jarCount; i++) {
fJarPackage= readJarPackage(fDescriptionFiles[i]);
if (fJarPackage != null)
singleRun(progressMonitor);
}
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int totalWork= countSelectedElements();
progressMonitor.beginTask(JarPackagerMessages.getString("JarFileExportOperation.exporting"), totalWork); //$NON-NLS-1$
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
fJarWriter= new JarWriter(fJarPackage, fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getSelectedElements() == null || fJarPackage.getSelectedElements().size() == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.doesManifestExist()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
if (dirtyEditors.length > 0) {
List unsavedFiles= new ArrayList(dirtyEditors.length);
List selection= fJarPackage.getSelectedResources();
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFile.getFullPath()), null); //$NON-NLS-1$
}
}
}
if (!unsavedFiles.isEmpty())
return false;
}
return true;
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
JarPackageWriter objectStream= new JarPackageWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
objectStream.writeXML(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
if (fJarPackage.getDescriptionFile().isAccessible()) {
if (fJarPackage.canOverwriteDescription(fParentShell))
fJarPackage.getDescriptionFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getDescriptionFile().create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (objectStream != null)
objectStream.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
if (fJarPackage.getManifestFile().isAccessible()) {
if (fJarPackage.canOverwriteManifest(fParentShell))
fJarPackage.getManifestFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getManifestFile().create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
/**
* Reads the JAR package spec from file.
*/
protected JarPackage readJarPackage(IFile description) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(JarPackage.DESCRIPTION_EXTENSION));
JarPackage jarPackage= null;
JarPackageReader reader= null;
try {
reader= new JarPackageReader(description.getContents());
// Do not save - only generate JAR
jarPackage= reader.readXML();
jarPackage.setSaveManifest(false);
jarPackage.setSaveDescription(false);
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorReadingJarPackageFromDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorReadingFile", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} catch (SAXException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.badXmlFormat", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} finally {
if ((jarPackage == null || jarPackage.logWarnings()) && reader != null)
// AddWarnings
fProblems.addAll(reader.getWarnings());
try {
if (reader != null)
reader.close();
}
catch (IOException ex) {
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorClosingJarPackageDescriptionReader", description.getFullPath()), ex); //$NON-NLS-1$
}
}
return jarPackage;
}
}
|
6,672 | Bug 6672 jar no longer exported after attach source | 1206 1. Create a project test. 2. Add a jar (say resources.jar) to the classpath and export the entry 3. Attach source (say resourcessrc.zip) to the jar. Notice, the jar is no longer exported - this information is discarded during the attach source process. | verified fixed | 787255e | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-07T16:59:44Z" | "2001-12-07T15:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.ZipFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.swt.MGridData;
import org.eclipse.jdt.internal.ui.wizards.swt.MGridLayout;
/**
* UI to set the source attachment archive and root.
* Same implementation for both setting attachments for libraries from
* variable entries and for normal (internal or external) jar.
*/
public class SourceAttachmentBlock {
private IStatusChangeListener fContext;
private StringButtonDialogField fFileNameField;
private SelectionButtonDialogField fInternalButtonField;
private StringButtonDialogField fPrefixField;
private StringButtonDialogField fJavaDocField;
private boolean fIsVariableEntry;
private IStatus fNameStatus;
private IStatus fPrefixStatus;
private IStatus fJavaDocStatus;
private IPath fJARPath;
/**
* The file to which the archive path points to.
* Only set when the file exists.
*/
private File fResolvedFile;
/**
* The path to which the archive variable points.
* Null if invalid path or not resolvable. Must not exist.
*/
private IPath fFileVariablePath;
private URL fJavaDocLocation;
private IWorkspaceRoot fRoot;
private Control fSWTWidget;
private CLabel fFullPathResolvedLabel;
private CLabel fPrefixResolvedLabel;
private IClasspathEntry fOldEntry;
public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) {
fContext= context;
fRoot= root;
fOldEntry= oldEntry;
// fIsVariableEntry specifies if the UI is for a variable entry
fIsVariableEntry= (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE);
fNameStatus= new StatusInfo();
fPrefixStatus= new StatusInfo();
fJavaDocStatus= new StatusInfo();
fJARPath= (oldEntry != null) ? oldEntry.getPath() : Path.EMPTY;
SourceAttachmentAdapter adapter= new SourceAttachmentAdapter();
// create the dialog fields (no widgets yet)
if (fIsVariableEntry) {
fFileNameField= new VariablePathDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.varlabel")); //$NON-NLS-1$
fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.varbutton")); //$NON-NLS-1$
((VariablePathDialogField)fFileNameField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.variable.button")); //$NON-NLS-1$
fPrefixField= new VariablePathDialogField(adapter);
fPrefixField.setDialogFieldListener(adapter);
fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varlabel")); //$NON-NLS-1$
fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varbutton")); //$NON-NLS-1$
((VariablePathDialogField)fPrefixField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.variable.button")); //$NON-NLS-1$
} else {
fFileNameField= new StringButtonDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.label")); //$NON-NLS-1$
fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.button")); //$NON-NLS-1$
fInternalButtonField= new SelectionButtonDialogField(SWT.PUSH);
fInternalButtonField.setDialogFieldListener(adapter);
fInternalButtonField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.internal.button")); //$NON-NLS-1$
fPrefixField= new StringButtonDialogField(adapter);
fPrefixField.setDialogFieldListener(adapter);
fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.label")); //$NON-NLS-1$
fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.button")); //$NON-NLS-1$
}
// not used
fJavaDocField= new StringButtonDialogField(adapter);
fJavaDocField.setDialogFieldListener(adapter);
fJavaDocField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.label")); //$NON-NLS-1$
fJavaDocField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.button")); //$NON-NLS-1$
// set the old settings
setDefaults();
}
public void setDefaults() {
if (fOldEntry != null && fOldEntry.getSourceAttachmentPath() != null) {
fFileNameField.setText(fOldEntry.getSourceAttachmentPath().toString());
} else {
fFileNameField.setText(""); //$NON-NLS-1$
}
if (fOldEntry != null && fOldEntry.getSourceAttachmentRootPath() != null) {
fPrefixField.setText(fOldEntry.getSourceAttachmentRootPath().toString());
} else {
fPrefixField.setText(""); //$NON-NLS-1$
}
}
/**
* Gets the source attachment path chosen by the user
*/
public IPath getSourceAttachmentPath() {
if (fFileNameField.getText().length() == 0) {
return null;
}
return new Path(fFileNameField.getText());
}
/**
* Gets the source attachment root chosen by the user
*/
public IPath getSourceAttachmentRootPath() {
if (getSourceAttachmentPath() == null) {
return null;
} else {
return new Path(fPrefixField.getText());
}
}
/**
* Creates the control
*/
public Control createControl(Composite parent) {
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
MGridLayout layout= new MGridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.minimumWidth= SWTUtil.convertWidthInCharsToPixels(80, composite);
layout.numColumns= 4;
composite.setLayout(layout);
int widthHint= SWTUtil.convertWidthInCharsToPixels(fIsVariableEntry ? 50 : 60, composite);
MGridData gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 4;
Label message= new Label(composite, SWT.LEFT);
message.setLayoutData(gd);
message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fJARPath.lastSegment()));
if (fIsVariableEntry) {
DialogField.createEmptySpace(composite, 1);
gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= widthHint;
Label desc= new Label(composite, SWT.LEFT + SWT.WRAP);
desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description"));
desc.setLayoutData(gd);
DialogField.createEmptySpace(composite, 2);
}
// archive name field
fFileNameField.doFillIntoGrid(composite, 4);
gd= (MGridData)fFileNameField.getTextControl(null).getLayoutData();
gd.widthHint= widthHint;
if (!fIsVariableEntry) {
// aditional 'browse workspace' button for normal jars
DialogField.createEmptySpace(composite, 3);
fInternalButtonField.doFillIntoGrid(composite, 1);
} else {
// label that shows the resolved path for variable jars
DialogField.createEmptySpace(composite, 1);
fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT);
fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true));
fFullPathResolvedLabel.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(composite, 2);
}
// prefix description
DialogField.createEmptySpace(composite, 1);
gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= widthHint;
Label desc= new Label(composite, SWT.LEFT + SWT.WRAP);
desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.description"));
desc.setLayoutData(gd);
DialogField.createEmptySpace(composite, 2);
// root path field
fPrefixField.doFillIntoGrid(composite, 4);
gd= (MGridData)fPrefixField.getTextControl(null).getLayoutData();
gd.widthHint= widthHint;
if (fIsVariableEntry) {
// label that shows the resolved path for variable jars
DialogField.createEmptySpace(composite, 1);
fPrefixResolvedLabel= new CLabel(composite, SWT.LEFT);
fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false));
fPrefixResolvedLabel.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(composite, 2);
}
fFileNameField.postSetFocusOnDialogField(parent.getDisplay());
//DialogField.createEmptySpace(composite, 1);
//Label jdocDescription= new Label(composite, SWT.LEFT + SWT.WRAP);
//jdocDescription.setText(NewWizardMessages.getString(JAVADOC + ".description"));
//DialogField.createEmptySpace(composite, 1);
//fJavaDocField.doFillIntoGrid(composite, 3);
WorkbenchHelp.setHelp(composite, new Object[] { IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK });
return composite;
}
private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
attachmentChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
attachmentDialogFieldChanged(field);
}
}
private void attachmentChangeControlPressed(DialogField field) {
if (field == fFileNameField) {
IPath jarFilePath= chooseExtJarFile();
if (jarFilePath != null) {
fFileNameField.setText(jarFilePath.toString());
}
} else if (field == fPrefixField) {
IPath prefixPath= choosePrefix();
if (prefixPath != null) {
fPrefixField.setText(prefixPath.toString());
}
} else if (field == fJavaDocField) {
URL jdocURL= chooseJavaDocLocation();
if (jdocURL != null) {
fJavaDocField.setText(jdocURL.toExternalForm());
}
}
}
// ---------- IDialogFieldListener --------
private void attachmentDialogFieldChanged(DialogField field) {
if (field == fFileNameField) {
fNameStatus= updateFileNameStatus();
} else if (field == fInternalButtonField) {
IPath jarFilePath= chooseInternalJarFile(fFileNameField.getText());
if (jarFilePath != null) {
fFileNameField.setText(jarFilePath.toString());
}
return;
} else if (field == fPrefixField) {
fPrefixStatus= updatePrefixStatus();
} else if (field == fJavaDocField) {
fJavaDocStatus= updateJavaDocLocationStatus();
}
doStatusLineUpdate();
}
private void doStatusLineUpdate() {
fPrefixField.enableButton(canBrowsePrefix());
fFileNameField.enableButton(canBrowseFileName());
// set the resolved path for variable jars
if (fFullPathResolvedLabel != null) {
fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true));
}
if (fPrefixResolvedLabel != null) {
fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false));
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus, fPrefixStatus, fJavaDocStatus });
fContext.statusChanged(status);
}
private boolean canBrowseFileName() {
if (!fIsVariableEntry) {
return true;
}
// to browse with a variable JAR, the variable name must point to a directory
if (fFileVariablePath != null) {
return fFileVariablePath.toFile().isDirectory();
}
return false;
}
private boolean canBrowsePrefix() {
// can browse when the archive name is poiting to a existing file
// and (if variable) the prefix variable name is existing
if (fResolvedFile != null) {
if (fIsVariableEntry) {
// prefix has valid format, is resolvable and not empty
return fPrefixStatus.isOK() && fPrefixField.getText().length() > 0;
}
return true;
}
return false;
}
private String getResolvedLabelString(String path, boolean osPath) {
IPath resolvedPath= getResolvedPath(new Path(path));
if (resolvedPath != null) {
if (osPath) {
return resolvedPath.toOSString();
} else {
return resolvedPath.toString();
}
}
return ""; //$NON-NLS-1$
}
private IPath getResolvedPath(IPath path) {
if (path != null) {
String varName= path.segment(0);
if (varName != null) {
IPath varPath= JavaCore.getClasspathVariable(varName);
if (varPath != null) {
return varPath.append(path.removeFirstSegments(1));
}
}
}
return null;
}
private IStatus updatePrefixStatus() {
StatusInfo status= new StatusInfo();
String prefix= fPrefixField.getText();
if (prefix.length() == 0) {
// no source attachment path
return status;
} else {
if (!Path.EMPTY.isValidPath(prefix)) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.notvalid")); //$NON-NLS-1$
return status;
}
IPath path= new Path(prefix);
if (fIsVariableEntry) {
IPath resolvedPath= getResolvedPath(path);
if (resolvedPath == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.varnotexists")); //$NON-NLS-1$
return status;
}
if (resolvedPath.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinvar")); //$NON-NLS-1$
return status;
}
} else {
if (path.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinpath")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
private IStatus updateFileNameStatus() {
StatusInfo status= new StatusInfo();
fResolvedFile= null;
fFileVariablePath= null;
String fileName= fFileNameField.getText();
if (fileName.length() == 0) {
// no source attachment
return status;
} else {
if (!Path.EMPTY.isValidPath(fileName)) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$
return status;
}
IPath filePath= new Path(fileName);
IPath resolvedPath;
if (fIsVariableEntry) {
if (filePath.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.deviceinpath")); //$NON-NLS-1$
return status;
}
String varName= filePath.segment(0);
if (varName == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$
return status;
}
fFileVariablePath= JavaCore.getClasspathVariable(varName);
if (fFileVariablePath == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.varnotexists")); //$NON-NLS-1$
return status;
}
resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
if (resolvedPath.isEmpty()) {
status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.filename.warning.varempty")); //$NON-NLS-1$
return status;
}
File file= resolvedPath.toFile();
if (!file.isFile()) {
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$
status.setWarning(message);
return status;
}
fResolvedFile= file;
} else {
File file= filePath.toFile();
IResource res= fRoot.findMember(filePath);
if (res != null) {
file= res.getLocation().toFile();
}
if (!file.isFile()) {
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$
status.setError(message);
return status;
}
fResolvedFile= file;
}
}
return status;
}
private IStatus updateJavaDocLocationStatus() {
StatusInfo status= new StatusInfo();
fJavaDocLocation= null;
String jdocLocation= fJavaDocField.getText();
if (!"".equals(jdocLocation)) { //$NON-NLS-1$
try {
URL url= new URL(jdocLocation);
if ("file".equals(url.getProtocol())) { //$NON-NLS-1$
File dir= new File(url.getFile());
if (!dir.isDirectory()) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.error.notafolder")); //$NON-NLS-1$
return status;
}
/*else {
File indexFile= new File(dir, "index.html");
File packagesFile= new File(dir, "package-list");
if (!packagesFile.exists() || !indexFile.exists()) {
fJavaDocStatusInfo.setWarning(NewWizardMessages.getString(ERR_JDOCLOCATION_IDXNOTFOUND));
// only a warning, go on
}
}*/
}
fJavaDocLocation= url;
} catch (MalformedURLException e) {
status.setError(NewWizardMessages.getFormattedString("SourceAttachmentBlock.javadoc.error.malformed", e.getLocalizedMessage())); //$NON-NLS-1$
return status;
}
}
return status;
}
/*
* Opens a dialog to choose a jar from the file system.
*/
private IPath chooseExtJarFile() {
IPath currPath= new Path(fFileNameField.getText());
if (currPath.isEmpty()) {
currPath= fJARPath;
}
IPath resolvedPath= currPath;
if (fIsVariableEntry) {
resolvedPath= getResolvedPath(currPath);
if (resolvedPath == null) {
resolvedPath= Path.EMPTY;
}
}
if (ArchiveFileFilter.isArchivePath(resolvedPath)) {
resolvedPath= resolvedPath.removeLastSegments(1);
}
FileDialog dialog= new FileDialog(getShell());
dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extjardialog.text")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(resolvedPath.toOSString());
String res= dialog.open();
if (res != null) {
IPath returnPath= new Path(res).makeAbsolute();
if (fIsVariableEntry) {
returnPath= modifyPath(returnPath, currPath.segment(0));
}
return returnPath;
}
return null;
}
/*
* Opens a dialog to choose an internal jar.
*/
private IPath chooseInternalJarFile(String initSelection) {
Class[] acceptedClasses= new Class[] { IFile.class };
ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
ViewerFilter filter= new ArchiveFileFilter(null);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSel= fRoot.findMember(new Path(initSelection));
if (initSel == null) {
initSel= fRoot.findMember(fJARPath);
}
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setAllowMultiple(false);
dialog.setValidator(validator);
dialog.addFilter(filter);
dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.message")); //$NON-NLS-1$
dialog.setInput(fRoot);
dialog.setInitialSelection(initSel);
if (dialog.open() == dialog.OK) {
IFile file= (IFile) dialog.getFirstResult();
return file.getFullPath();
}
return null;
}
/*
* Opens a dialog to choose path in a zip file.
*/
private IPath choosePrefix() {
if (fResolvedFile != null) {
IPath currPath= new Path(fPrefixField.getText());
String initSelection= null;
if (fIsVariableEntry) {
IPath resolvedPath= getResolvedPath(currPath);
if (resolvedPath != null) {
initSelection= resolvedPath.toString();
}
} else {
initSelection= currPath.toString();
}
try {
ZipFile zipFile= new ZipFile(fResolvedFile);
ZipContentProvider contentProvider= new ZipContentProvider();
contentProvider.setInitialInput(zipFile);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), new ZipLabelProvider(), contentProvider);
dialog.setAllowMultiple(false);
dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.message")); //$NON-NLS-1$
dialog.setInput(zipFile);
dialog.setInitialSelection(contentProvider.getSelectedNode(initSelection));
if (dialog.open() == dialog.OK) {
Object obj= dialog.getFirstResult();
IPath path= new Path(obj.toString());
if (fIsVariableEntry) {
path= modifyPath(path, currPath.segment(0));
}
return path;
}
} catch (IOException e) {
String title= NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.prefixdialog.error.message", fResolvedFile.getPath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
JavaPlugin.log(e);
}
}
return null;
}
/*
* Opens a dialog to choose a root in the file system.
*/
private URL chooseJavaDocLocation() {
String initPath= ""; //$NON-NLS-1$
if (fJavaDocLocation != null && "file".equals(fJavaDocLocation.getProtocol())) { //$NON-NLS-1$
initPath= (new File(fJavaDocLocation.getFile())).getPath();
}
DirectoryDialog dialog= new DirectoryDialog(getShell());
dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.jdocdialog.text")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.jdocdialog.message")); //$NON-NLS-1$
dialog.setFilterPath(initPath);
String res= dialog.open();
if (res != null) {
try {
return (new File(res)).toURL();
} catch (MalformedURLException e) {
// should not happen
JavaPlugin.log(e);
}
}
return null;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Takes a path and replaces the beginning with a variable name
* (if the beginning matches with the variables value)
*/
private IPath modifyPath(IPath path, String varName) {
if (varName == null || path == null) {
return null;
}
if (path.isEmpty()) {
return new Path(varName);
}
IPath varPath= JavaCore.getClasspathVariable(varName);
if (varPath != null) {
if (varPath.isPrefixOf(path)) {
path= path.removeFirstSegments(varPath.segmentCount());
} else {
path= new Path(path.lastSegment());
}
} else {
path= new Path(path.lastSegment());
}
return new Path(varName).append(path);
}
/**
* Creates a runnable that sets the source attachment by modifying the project's classpath.
*/
public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
IClasspathEntry newEntry;
if (fIsVariableEntry) {
newEntry= JavaCore.newVariableEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), false);
} else {
newEntry= JavaCore.newLibraryEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), false);
}
IClasspathEntry[] entries= modifyClasspath(jproject, newEntry, shell);
if (entries != null) {
jproject.setRawClasspath(entries, monitor);
}
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
}
}
};
}
private IClasspathEntry[] modifyClasspath(IJavaProject jproject, IClasspathEntry newEntry, Shell shell) throws JavaModelException{
IClasspathEntry[] oldClasspath= jproject.getRawClasspath();
int nEntries= oldClasspath.length;
ArrayList newEntries= new ArrayList(nEntries + 1);
int entryKind= newEntry.getEntryKind();
IPath jarPath= newEntry.getPath();
boolean found= false;
for (int i= 0; i < nEntries; i++) {
IClasspathEntry curr= oldClasspath[i];
if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) {
// add modified entry
newEntries.add(newEntry);
found= true;
} else {
newEntries.add(curr);
}
}
if (!found) {
if (newEntry.getSourceAttachmentPath() == null || !putJarOnClasspathDialog(shell)) {
return null;
}
// add new
newEntries.add(newEntry);
}
return (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]);
}
private boolean putJarOnClasspathDialog(Shell shell) {
final boolean[] result= new boolean[1];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.message"); //$NON-NLS-1$
result[0]= MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
});
return result[0];
}
} |
6,722 | Bug 6722 JavaElementLabelProvider API - small issue | everytime i use this label provider it annoys me that i have to type new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT) if it's default then it should be default, if you know what i mean. all i need is: public JavaElementLabelProvider() { this(JavaElementLabelProvider.SHOW_DEFAULT); } it'd make things easier. i'd fix it myself but it's API so i guess it should be blessed first. | resolved fixed | 566e615 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-10T16:13:28Z" | "2001-12-10T13:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementLabelProvider.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.resources.IStorage;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.viewsupport.IErrorTickProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Standard label provider for Java elements.
* Use this class when you want to present the Java elements in a viewer.
* <p>
* The implementation also handles non-Java elements by forwarding the requests to an
* internal <code>WorkbenchLabelProvider</code>.
* </p>
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @see org.eclipse.ui.model.WorkbenchLabelProvider
*/
public class JavaElementLabelProvider extends LabelProvider {
/**
* Flag (bit mask) indicating that methods labels include the method return type. (prepended)
*/
public final static int SHOW_RETURN_TYPE= 0x001;
/**
* Flag (bit mask) indicating that method label include method parameter types.
*/
public final static int SHOW_PARAMETERS= 0x002;
/**
* Flag (bit mask) indicating that the label of a member should include the container.
* For example, include the name of the type enclosing a field.
* @deprecated Use SHOW_QUALIFIED or SHOW_ROOT instead
*/
public final static int SHOW_CONTAINER= 0x004;
/**
* Flag (bit mask) indicating that the label of a type should be fully qualified.
* For example, include the fully qualified name of the type enclosing a type.
* @deprecated Use SHOW_QUALIFIED instead
*/
public final static int SHOW_CONTAINER_QUALIFICATION= 0x008;
/**
* Flag (bit mask) indicating that the label should include overlay icons
* for element type and modifiers.
*/
public final static int SHOW_OVERLAY_ICONS= 0x010;
/**
* Flag (bit mask) indicating thata field label should include the declared type.
*/
public final static int SHOW_TYPE= 0x020;
/**
* Flag (bit mask) indicating that the label should include the name of the
* package fragment root (appended).
*/
public final static int SHOW_ROOT= 0x040;
/**
* Flag (bit mask) indicating that the label qualification of a type should
* be shown after the name.
* @deprecated SHOW_POST_QUALIFIED instead
*/
public final static int SHOW_POSTIFIX_QUALIFICATION= 0x080;
/**
* Flag (bit mask) indicating that the label should show the icons with no space
* reserved for overlays.
*/
public final static int SHOW_SMALL_ICONS= 0x100;
/**
* Flag (bit mask) indicating that the packagefragment roots from variables should
* be rendered with the variable in the name
*/
public final static int SHOW_VARIABLE= 0x200;
/**
* Flag (bit mask) indicating that Complation Units, Class Files, Types, Declarations and Members
* should be rendered qualified.
* Examples: java.lang.String, java.util.Vector.size()
*/
public final static int SHOW_QUALIFIED= 0x400;
/**
* Flag (bit mask) indicating that Complation Units, Class Files, Types, Declarations and Members
* should be rendered qualified. The qualifcation is appended
* Examples: String - java.lang, size() - java.util.Vector
*/
public final static int SHOW_POST_QUALIFIED= 0x800;
/**
* Constant (value <code>0</code>) indicating that the label should show
* the basic images only.
*/
public final static int SHOW_BASICS= 0x000;
/**
* Constant indicating the default label rendering.
* Currently the default is equivalent to
* <code>SHOW_PARAMETERS | SHOW_OVERLAY_ICONS</code>.
*/
public final static int SHOW_DEFAULT= new Integer(SHOW_PARAMETERS | SHOW_OVERLAY_ICONS).intValue();
private JavaElementImageProvider fImageLabelProvider;
private WorkbenchLabelProvider fWorkbenchLabelProvider;
private int fFlags;
private int fImageFlags;
private int fTextFlags;
// map images for JarEntryFiles, key = extension - value = image
// the cached images will be disposed wen the label provider is disposed.
private Map fJarImageMap= new HashMap(10);
/**
* Creates a new label provider.
*
* @param flags the initial options; a bitwise OR of <code>SHOW_* </code> constants
*/
public JavaElementLabelProvider(int flags) {
fImageLabelProvider= new JavaElementImageProvider();
fWorkbenchLabelProvider= new WorkbenchLabelProvider();
fFlags= flags;
updateImageProviderFlags();
updateTextProviderFlags();
}
private boolean getFlag( int flag) {
return (fFlags & flag) != 0;
}
/**
* Turns on the rendering options specified in the given flags.
*
* @param flags the options; a bitwise OR of <code>SHOW_* </code> constants
*/
public void turnOn(int flags) {
fFlags |= flags;
updateImageProviderFlags();
updateTextProviderFlags();
}
/**
* Turns off the rendering options specified in the given flags.
*
* @param flags the initial options; a bitwise OR of <code>SHOW_* </code> constants
*/
public void turnOff(int flags) {
fFlags &= (~flags);
updateImageProviderFlags();
updateTextProviderFlags();
}
private void updateImageProviderFlags() {
fImageFlags= 0;
if (getFlag(SHOW_OVERLAY_ICONS)) {
fImageFlags |= JavaElementImageProvider.OVERLAY_ICONS;
}
if (getFlag(SHOW_SMALL_ICONS)) {
fImageFlags |= JavaElementImageProvider.SMALL_ICONS;
}
}
private void updateTextProviderFlags() {
fTextFlags= 0;
if (getFlag(SHOW_RETURN_TYPE)) {
fTextFlags |= JavaElementLabels.M_PRE_RETURNTYPE;
}
if (getFlag(SHOW_PARAMETERS)) {
fTextFlags |= JavaElementLabels.M_PARAMETER_TYPES;
}
if (getFlag(SHOW_CONTAINER)) {
fTextFlags |= JavaElementLabels.P_POST_QUALIFIED | JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.F_POST_QUALIFIED;
}
if (getFlag(SHOW_POSTIFIX_QUALIFICATION)) {
fTextFlags |= (JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED);
} else if (getFlag(SHOW_CONTAINER_QUALIFICATION)) {
fTextFlags |=(JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED);
}
if (getFlag(SHOW_TYPE)) {
fTextFlags |= JavaElementLabels.F_APP_TYPE_SIGNATURE;
}
if (getFlag(SHOW_ROOT)) {
fTextFlags |= JavaElementLabels.APPEND_ROOT_PATH;
}
if (getFlag(SHOW_VARIABLE)) {
fTextFlags |= JavaElementLabels.ROOT_VARIABLE;
}
if (getFlag(SHOW_QUALIFIED)) {
fTextFlags |= (JavaElementLabels.F_FULLY_QUALIFIED | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.I_FULLY_QUALIFIED
| JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.D_QUALIFIED | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED);
}
if (getFlag(SHOW_POST_QUALIFIED)) {
fTextFlags |= (JavaElementLabels.F_POST_QUALIFIED | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.I_POST_QUALIFIED
| JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.D_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED);
}
}
/* (non-Javadoc)
* @see ILabelProvider#getImage
*/
public Image getImage(Object element) {
if (element instanceof IJavaElement) {
IJavaElement e= (IJavaElement) element;
return fImageLabelProvider.getImageLabel(e, fImageFlags);
}
Image result= fWorkbenchLabelProvider.getImage(element);
if (result != null) {
return result;
}
if (element instanceof IStorage)
return getImageForJarEntry((IStorage)element);
return super.getImage(element);
}
/* (non-Javadoc)
* @see ILabelProvider#getText
*/
public String getText(Object element) {
if (element instanceof IJavaElement) {
return JavaElementLabels.getElementLabel((IJavaElement) element, fTextFlags);
}
String text= fWorkbenchLabelProvider.getText(element);
if (text.length() > 0) {
return text;
}
if (element instanceof IStorage) {
return ((IStorage)element).getName();
}
return super.getText(element);
}
/* (non-Javadoc)
*
* @see IBaseLabelProvider#dispose
*/
public void dispose() {
fWorkbenchLabelProvider.dispose();
disposeJarEntryImages();
}
public void setErrorTickManager(IErrorTickProvider provider) {
fImageLabelProvider.setErrorTickProvider(provider);
}
/*
* Dispose the cached images for JarEntry files
*/
private void disposeJarEntryImages() {
Iterator each= fJarImageMap.values().iterator();
while (each.hasNext()) {
Image image= (Image)each.next();
image.dispose();
}
fJarImageMap.clear();
}
/*
* Gets and caches an image for a JarEntryFile.
* The image for a JarEntryFile is retrieved from the EditorRegistry.
*/
private Image getImageForJarEntry(IStorage element) {
String extension= element.getFullPath().getFileExtension();
Image image= (Image)fJarImageMap.get(extension);
if (image != null)
return image;
IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry();
ImageDescriptor desc= registry.getImageDescriptor(element.getName());
image= desc.createImage();
fJarImageMap.put(extension, image);
return image;
}
}
|
6,238 | Bug 6238 jar packager: ide freezes on page flip, no progress shown | i selected org.eclipse.jdt.ui org.eclipse.jdt.ui.tests.refactoring (couple thousands of files) and opened the jar packager or flipping the page the whole ide froze. and there was no progress report shown. it took more or less 2 minutes - of total freeze - to flip to the other wizard page. i suggest performing it in another thread and showing progress | resolved fixed | d5959ae | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-10T18:11:45Z" | "2001-11-22T17:26:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/CheckboxTreeAndListGroup.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
/**
* Combines a CheckboxTreeViewer and CheckboxListViewer.
* All viewer selection-driven interactions are handled within this viewer
*/
public class CheckboxTreeAndListGroup implements ICheckStateListener, ISelectionChangedListener, ITreeViewerListener {
private Object fRoot;
private Object fCurrentTreeSelection;
private List fExpandedTreeNodes= new ArrayList();
private Map fCheckedStateStore= new HashMap(9);
private List fWhiteCheckedTreeItems= new ArrayList();
private List fListeners= new ArrayList();
private ITreeContentProvider fTreeContentProvider;
private IStructuredContentProvider fListContentProvider;
private ILabelProvider fTreeLabelProvider;
private ILabelProvider fListLabelProvider;
// widgets
private CheckboxTreeViewer fTreeViewer;
private CheckboxTableViewer fListViewer;
/**
* Creates an instance of this class. Use this constructor if you wish to specify
* the width and/or height of the combined widget (to only hardcode one of the
* sizing dimensions, specify the other dimension's value as -1)
*
* @param parent org.eclipse.swt.widgets.Composite
* @param style int
* @param rootObject java.lang.Object
* @param childPropertyName java.lang.String
* @param parentPropertyName java.lang.String
* @param listPropertyName java.lang.String
* @param width int
* @param height int
*/
public CheckboxTreeAndListGroup(
Composite parent,
Object rootObject,
ITreeContentProvider treeContentProvider,
ILabelProvider treeLabelProvider,
IStructuredContentProvider listContentProvider,
ILabelProvider listLabelProvider,
int style,
int width,
int height) {
fRoot= rootObject;
fTreeContentProvider= treeContentProvider;
fListContentProvider= listContentProvider;
fTreeLabelProvider= treeLabelProvider;
fListLabelProvider= listLabelProvider;
createContents(parent, width, height, style);
}
/**
* This method must be called just before this window becomes visible.
*/
public void aboutToOpen() {
determineWhiteCheckedDescendents(fRoot);
checkNewTreeElements(getTreeChildren(fRoot));
fCurrentTreeSelection= null;
//select the first element in the list
Object[] elements= getTreeChildren(fRoot);
Object primary= elements.length > 0 ? elements[0] : null;
if (primary != null) {
fTreeViewer.setSelection(new StructuredSelection(primary));
}
fTreeViewer.getControl().setFocus();
}
/**
* Adds the passed listener to self's collection of clients
* that listen for changes to element checked states
*
* @param listener ICheckStateListener
*/
public void addCheckStateListener(ICheckStateListener listener) {
fListeners.add(listener);
}
/**
* Adds the receiver and all of it's ancestors to the checkedStateStore if they
* are not already there.
*/
private void addToHierarchyToCheckedStore(Object treeElement) {
// if this tree element is already gray then its ancestors all are as well
if (!fCheckedStateStore.containsKey(treeElement))
fCheckedStateStore.put(treeElement, new ArrayList());
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null)
addToHierarchyToCheckedStore(parent);
}
/**
* Returns a boolean indicating whether all children of the passed tree element
* are currently white-checked
*
* @return boolean
* @param treeElement java.lang.Object
*/
protected boolean areAllChildrenWhiteChecked(Object treeElement) {
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i) {
if (!fWhiteCheckedTreeItems.contains(children[i]))
return false;
}
return true;
}
/**
* Returns a boolean indicating whether all list elements associated with
* the passed tree element are currently checked
*
* @return boolean
* @param treeElement java.lang.Object
*/
protected boolean areAllElementsChecked(Object treeElement) {
List checkedElements= (List)fCheckedStateStore.get(treeElement);
if (checkedElements == null) // ie.- tree item not even gray-checked
return false;
return getListItemsSize(treeElement) == checkedElements.size();
}
/**
* Iterates through the passed elements which are being realized for the first
* time and check each one in the tree viewer as appropriate
*/
protected void checkNewTreeElements(Object[] elements) {
for (int i= 0; i < elements.length; ++i) {
Object currentElement= elements[i];
boolean checked= fCheckedStateStore.containsKey(currentElement);
fTreeViewer.setChecked(currentElement, checked);
fTreeViewer.setGrayed(
currentElement,
checked && !fWhiteCheckedTreeItems.contains(currentElement));
}
}
/**
* An item was checked in one of self's two views. Determine which
* view this occurred in and delegate appropriately
*
* @param event CheckStateChangedEvent
*/
public void checkStateChanged(final CheckStateChangedEvent event) {
//Potentially long operation - show a busy cursor
BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
public void run() {
if (event.getCheckable().equals(fTreeViewer))
treeItemChecked(event.getElement(), event.getChecked());
else
listItemChecked(event.getElement(), event.getChecked(), true);
notifyCheckStateChangeListeners(event);
}
});
}
/**
* Lay out and initialize self's visual components.
*
* @param parent org.eclipse.swt.widgets.Composite
* @param width int
* @param height int
*/
protected void createContents(
Composite parent,
int width,
int height,
int style) {
// group pane
Composite composite= new Composite(parent, style);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.makeColumnsEqualWidth= true;
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
createTreeViewer(composite, width / 2, height);
createListViewer(composite, width / 2, height);
initialize();
}
/**
* Creates this group's list viewer.
*/
protected void createListViewer(Composite parent, int width, int height) {
fListViewer= new CheckboxTableViewer(parent, SWT.BORDER);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= width;
data.heightHint= height;
fListViewer.getTable().setLayoutData(data);
fListViewer.setContentProvider(fListContentProvider);
fListViewer.setLabelProvider(fListLabelProvider);
fListViewer.addCheckStateListener(this);
}
/**
* Creates this group's tree viewer.
*/
protected void createTreeViewer(Composite parent, int width, int height) {
Tree tree= new Tree(parent, SWT.CHECK | SWT.BORDER);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= width;
data.heightHint= height;
tree.setLayoutData(data);
fTreeViewer= new CheckboxTreeViewer(tree);
fTreeViewer.setContentProvider(fTreeContentProvider);
fTreeViewer.setLabelProvider(fTreeLabelProvider);
fTreeViewer.addTreeListener(this);
fTreeViewer.addCheckStateListener(this);
fTreeViewer.addSelectionChangedListener(this);
}
/**
* Returns a boolean indicating whether the passed tree element should be
* at LEAST gray-checked. Note that this method does not consider whether
* it should be white-checked, so a specified tree item which should be
* white-checked will result in a <code>true</code> answer from this method.
* To determine whether a tree item should be white-checked use method
* #determineShouldBeWhiteChecked(Object).
*
* @param element java.lang.Object
* @return boolean
* @see #determineShouldBeWhiteChecked(java.lang.Object)
*/
protected boolean determineShouldBeAtLeastGrayChecked(Object treeElement) {
// if any list items associated with treeElement are checked then it
// retains its gray-checked status regardless of its children
List checked= (List) fCheckedStateStore.get(treeElement);
if (checked != null && (!checked.isEmpty()))
return true;
// if any children of treeElement are still gray-checked then treeElement
// must remain gray-checked as well
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i) {
if (fCheckedStateStore.containsKey(children[i]))
return true;
}
return false;
}
/**
* Returns a boolean indicating whether the passed tree item should be
* white-checked.
*
* @return boolean
* @param treeElement java.lang.Object
*/
protected boolean determineShouldBeWhiteChecked(Object treeElement) {
return areAllChildrenWhiteChecked(treeElement)
&& areAllElementsChecked(treeElement);
}
/**
* Recursively adds appropriate tree elements to the collection of
* known white-checked tree elements.
*
* @param treeElement java.lang.Object
*/
protected void determineWhiteCheckedDescendents(Object treeElement) {
// always go through all children first since their white-checked
// statuses will be needed to determine the white-checked status for
// this tree element
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i)
determineWhiteCheckedDescendents(children[i]);
// now determine the white-checked status for this tree element
if (determineShouldBeWhiteChecked(treeElement))
setWhiteChecked(treeElement, true);
}
/**
* Causes the tree viewer to expand all its items
*/
public void expandAll() {
fTreeViewer.expandAll();
}
/**
* Answers a flat collection of all of the checked elements in the
* list portion of self
*
* @return java.util.Vector
*/
public Iterator getAllCheckedListItems() {
Set result= new HashSet();
Iterator listCollectionsEnum= fCheckedStateStore.values().iterator();
while (listCollectionsEnum.hasNext())
result.addAll((List)listCollectionsEnum.next());
return result.iterator();
}
/**
* Answer a collection of all of the checked elements in the tree portion
* of self
*
* @return java.util.Vector
*/
public Set getAllCheckedTreeItems() {
return new HashSet(fCheckedStateStore.keySet());
}
/**
* Answers the number of elements that have been checked by the
* user.
*
* @return int
*/
public int getCheckedElementCount() {
return fCheckedStateStore.size();
}
/**
* Returns a count of the number of list items associated with a
* given tree item.
*
* @return int
* @param treeElement java.lang.Object
*/
protected int getListItemsSize(Object treeElement) {
Object[] elements= getListElements(treeElement);
return elements.length;
}
/**
* Gets the table that displays the folder content
*
* @return the table used to show the list
*/
public Table getTable() {
return fListViewer.getTable();
}
/**
* Gets the tree that displays the list for a folder
*
* @return the tree used to show the folders
*/
public Tree getTree() {
return fTreeViewer.getTree();
}
/**
* Adds the given filter to the tree viewer and
* triggers refiltering and resorting of the elements.
*
* @param filter a viewer filter
*/
public void addTreeFilter(ViewerFilter filter) {
fTreeViewer.addFilter(filter);
}
/**
* Adds the given filter to the list viewer and
* triggers refiltering and resorting of the elements.
*
* @param filter a viewer filter
*/
public void addListFilter(ViewerFilter filter) {
fListViewer.addFilter(filter);
}
/**
* Logically gray-check all ancestors of treeItem by ensuring that they
* appear in the checked table
*/
protected void grayCheckHierarchy(Object treeElement) {
// if this tree element is already gray then its ancestors all are as well
if (fCheckedStateStore.containsKey(treeElement))
return; // no need to proceed upwards from here
fCheckedStateStore.put(treeElement, new ArrayList());
if (determineShouldBeWhiteChecked(treeElement)) {
setWhiteChecked(treeElement, true);
}
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null)
grayCheckHierarchy(parent);
}
/**
* Sets the initial checked state of the passed list element to true.
*/
public void initialCheckListItem(Object element) {
Object parent= fTreeContentProvider.getParent(element);
fCurrentTreeSelection= parent;
//As this is not done from the UI then set the box for updating from the selection to false
listItemChecked(element, true, false);
updateHierarchy(parent);
}
/**
* Sets the initial checked state of the passed element to true,
* as well as to all of its children and associated list elements
*/
public void initialCheckTreeItem(Object element) {
treeItemChecked(element, true);
}
/**
* Initializes this group's viewers after they have been laid out.
*/
protected void initialize() {
fTreeViewer.setInput(fRoot);
}
/**
* Callback that's invoked when the checked status of an item in the list
* is changed by the user. Do not try and update the hierarchy if we are building the
* initial list.
*/
protected void listItemChecked(
Object listElement,
boolean state,
boolean updatingFromSelection) {
List checkedListItems= (List) fCheckedStateStore.get(fCurrentTreeSelection);
if (state) {
if (checkedListItems == null) {
// since the associated tree item has gone from 0 -> 1 checked
// list items, tree checking may need to be updated
grayCheckHierarchy(fCurrentTreeSelection);
checkedListItems= (List) fCheckedStateStore.get(fCurrentTreeSelection);
}
checkedListItems.add(listElement);
} else {
checkedListItems.remove(listElement);
if (checkedListItems.isEmpty()) {
// since the associated tree item has gone from 1 -> 0 checked
// list items, tree checking may need to be updated
ungrayCheckHierarchy(fCurrentTreeSelection);
}
}
if (updatingFromSelection)
updateHierarchy(fCurrentTreeSelection);
}
/**
* Notifies all checked state listeners that the passed element has had
* its checked state changed to the passed state
*/
protected void notifyCheckStateChangeListeners(CheckStateChangedEvent event) {
Iterator listenersEnum= fListeners.iterator();
while (listenersEnum.hasNext())
((ICheckStateListener) listenersEnum.next()).checkStateChanged(event);
}
/**
*Sets the contents of the list viewer based upon the specified selected
*tree element. This also includes checking the appropriate list items.
*
*@param treeElement java.lang.Object
*/
protected void populateListViewer(final Object treeElement) {
if (treeElement == fCurrentTreeSelection)
return;
fCurrentTreeSelection= treeElement;
fListViewer.setInput(treeElement);
List listItemsToCheck= (List) fCheckedStateStore.get(treeElement);
if (listItemsToCheck != null) {
Iterator listItemsEnum= listItemsToCheck.iterator();
while (listItemsEnum.hasNext())
fListViewer.setChecked(listItemsEnum.next(), true);
}
}
/**
* Removes the passed listener from self's collection of clients
* that listen for changes to element checked states
*
* @param listener ICheckStateListener
*/
public void removeCheckStateListener(ICheckStateListener listener) {
fListeners.remove(listener);
}
/**
* Handles the selection of an item in the tree viewer
*
* @param selection ISelection
*/
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
Object selectedElement= selection.getFirstElement();
if (selectedElement == null) {
fCurrentTreeSelection= null;
fListViewer.setInput(fCurrentTreeSelection);
return;
}
populateListViewer(selectedElement);
}
/**
* Selects or deselect all of the elements in the tree depending on the value of the selection
* boolean. Be sure to update the displayed files as well.
*/
public void setAllSelections(final boolean selection) {
//Potentially long operation - show a busy cursor
BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
public void run() {
setTreeChecked(fRoot, selection);
fListViewer.setAllChecked(selection);
}
});
}
/**
* Sets the list viewer's providers to those passed
*
* @param contentProvider ITreeContentProvider
* @param labelProvider ILabelProvider
*/
public void setListProviders(
IStructuredContentProvider contentProvider,
ILabelProvider labelProvider) {
fListViewer.setContentProvider(contentProvider);
fListViewer.setLabelProvider(labelProvider);
}
/**
* Sets the sorter that is to be applied to self's list viewer
*/
public void setListSorter(ViewerSorter sorter) {
fListViewer.setSorter(sorter);
}
/**
* Sets the root of the widget to be new Root. Regenerate all of the tables and lists from this
* value.
*
* @param newRoot
*/
public void setRoot(Object newRoot) {
this.fRoot= newRoot;
initialize();
}
/**
* Sets the checked state of the passed tree element appropriately, and
* do so recursively to all of its child tree elements as well
*/
protected void setTreeChecked(Object treeElement, boolean state) {
if (treeElement.equals(fCurrentTreeSelection)) {
fListViewer.setAllChecked(state);
}
if (state) {
Object[] listItems= getListElements(treeElement);
List listItemsChecked= new ArrayList();
for (int i= 0; i < listItems.length; ++i)
listItemsChecked.add(listItems[i]);
fCheckedStateStore.put(treeElement, listItemsChecked);
} else
fCheckedStateStore.remove(treeElement);
setWhiteChecked(treeElement, state);
fTreeViewer.setChecked(treeElement, state);
fTreeViewer.setGrayed(treeElement, false);
// now logically check/uncheck all children as well
Object[] children= getTreeChildren(treeElement);
for (int i= 0; i < children.length; ++i) {
setTreeChecked(children[i], state);
}
}
/**
* Sets the tree viewer's providers to those passed
*
* @param contentProvider ITreeContentProvider
* @param labelProvider ILabelProvider
*/
public void setTreeProviders(
ITreeContentProvider contentProvider,
ILabelProvider labelProvider) {
fTreeViewer.setContentProvider(contentProvider);
fTreeViewer.setLabelProvider(labelProvider);
}
/**
* Sets the sorter that is to be applied to self's tree viewer
*/
public void setTreeSorter(ViewerSorter sorter) {
fTreeViewer.setSorter(sorter);
}
/**
* Adjusts the collection of references to white-checked tree elements appropriately.
*
* @param treeElement java.lang.Object
* @param isWhiteChecked boolean
*/
protected void setWhiteChecked(Object treeElement, boolean isWhiteChecked) {
if (isWhiteChecked) {
if (!fWhiteCheckedTreeItems.contains(treeElement))
fWhiteCheckedTreeItems.add(treeElement);
} else
fWhiteCheckedTreeItems.remove(treeElement);
}
/**
* Handle the collapsing of an element in a tree viewer
*/
public void treeCollapsed(TreeExpansionEvent event) {
// We don't need to do anything with this
}
/**
* Handles the expansionsion of an element in a tree viewer
*/
public void treeExpanded(TreeExpansionEvent event) {
Object item= event.getElement();
// First see if the children need to be given their checked state at all. If they've
// already been realized then this won't be necessary
if (!fExpandedTreeNodes.contains(item)) {
fExpandedTreeNodes.add(item);
checkNewTreeElements(getTreeChildren(item));
}
}
/**
* Callback that's invoked when the checked status of an item in the tree
* is changed by the user.
*/
protected void treeItemChecked(Object treeElement, boolean state) {
// recursively adjust all child tree elements appropriately
setTreeChecked(treeElement, state);
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent == null)
return;
// now update upwards in the tree hierarchy
if (state)
grayCheckHierarchy(parent);
else
ungrayCheckHierarchy(parent);
updateHierarchy(treeElement);
}
/**
* Logically un-gray-check all ancestors of treeItem iff appropriate.
*/
protected void ungrayCheckHierarchy(Object treeElement) {
if (!determineShouldBeAtLeastGrayChecked(treeElement))
fCheckedStateStore.remove(treeElement);
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null)
ungrayCheckHierarchy(parent);
}
/**
* Sets the checked state of self and all ancestors appropriately
*/
protected void updateHierarchy(Object treeElement) {
boolean whiteChecked= determineShouldBeWhiteChecked(treeElement);
boolean shouldBeAtLeastGray= determineShouldBeAtLeastGrayChecked(treeElement);
fTreeViewer.setChecked(treeElement, shouldBeAtLeastGray);
setWhiteChecked(treeElement, whiteChecked);
if (whiteChecked)
fTreeViewer.setGrayed(treeElement, false);
else
fTreeViewer.setGrayed(treeElement, shouldBeAtLeastGray);
// proceed up the tree element hierarchy
Object parent= fTreeContentProvider.getParent(treeElement);
if (parent != null) {
updateHierarchy(parent);
}
}
/**
* Update the selections of the tree elements in items to reflect the new
* selections provided.
*
* @param Map with keys of Object (the tree element) and values of List (the selected
* list elements).
*/
public void updateSelections(final Map items) {
//Potentially long operation - show a busy cursor
BusyIndicator.showWhile(fTreeViewer.getControl().getDisplay(), new Runnable() {
public void run() {
handleUpdateSelection(items);
}
});
}
/**
* Returns the result of running the given elements through the filters.
*
* @param elements the elements to filter
* @return only the elements which all filters accept
*/
protected Object[] filter(ViewerFilter[] filters, Object[] elements) {
if (filters != null) {
ArrayList filtered = new ArrayList(elements.length);
for (int i = 0; i < elements.length; i++) {
boolean add = true;
for (int j = 0; j < filters.length; j++) {
add = filters[j].select(null, null, elements[i]);
if (!add)
break;
}
if (add)
filtered.add(elements[i]);
}
return filtered.toArray();
}
return elements;
}
private Object[] getTreeChildren(Object element) {
return filter(fTreeViewer.getFilters(), fTreeContentProvider.getChildren(element));
}
private Object[] getListElements(Object element) {
return filter(fListViewer.getFilters(), fListContentProvider.getElements(element));
}
public Set getWhiteCheckedTreeItems() {
return new HashSet(fWhiteCheckedTreeItems);
}
private void handleUpdateSelection(Map items) {
Iterator keyIterator= items.keySet().iterator();
//Update the store before the hierarchy to prevent updating parents before all of the children are done
while (keyIterator.hasNext()) {
Object key= keyIterator.next();
//Replace the items in the checked state store with those from the supplied items
List selections= (List) items.get(key);
if (selections.size() == 0)
//If it is empty remove it from the list
fCheckedStateStore.remove(key);
else {
fCheckedStateStore.put(key, selections);
// proceed up the tree element hierarchy
Object parent= fTreeContentProvider.getParent(key);
if (parent != null) {
addToHierarchyToCheckedStore(parent);
}
}
}
//Now update hierarchies
keyIterator= items.keySet().iterator();
while (keyIterator.hasNext()) {
Object key= keyIterator.next();
updateHierarchy(key);
if (fCurrentTreeSelection != null && fCurrentTreeSelection.equals(key)) {
fListViewer.setAllChecked(false);
fListViewer.setCheckedElements(((List) items.get(key)).toArray());
}
}
}
}
|
6,238 | Bug 6238 jar packager: ide freezes on page flip, no progress shown | i selected org.eclipse.jdt.ui org.eclipse.jdt.ui.tests.refactoring (couple thousands of files) and opened the jar packager or flipping the page the whole ide froze. and there was no progress report shown. it took more or less 2 minutes - of total freeze - to flip to the other wizard page. i suggest performing it in another thread and showing progress | resolved fixed | d5959ae | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-10T18:11:45Z" | "2001-11-22T17:26:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWizardPage.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.WizardExportResourcesPage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.packageview.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementSorter;
/**
* Page 1 of the JAR Package wizard
*/
public class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
private JarPackage fJarPackage;
private IStructuredSelection fInitialSelection;
private CheckboxTreeAndListGroup fInputGroup;
// widgets
private Text fSourceNameField;
private Button fSourceBrowseButton;
private Button fExportClassFilesCheckbox;
private Button fExportJavaFilesCheckbox;
private Combo fDestinationNamesCombo;
private Button fDestinationBrowseButton;
private Button fCompressCheckbox;
private Button fOverwriteCheckbox;
private Composite fDescriptionFileGroup;
private Button fSaveDescriptionCheckbox;
private Label fDescriptionFileLabel;
private Text fDescriptionFileText;
private Button fDescriptionFileBrowseButton;
// dialog store id constants
private final static String PAGE_NAME= "JarPackageWizardPage"; //$NON-NLS-1$
private final static String STORE_EXPORT_CLASS_FILES= PAGE_NAME + ".EXPORT_CLASS_FILES"; //$NON-NLS-1$
private final static String STORE_EXPORT_JAVA_FILES= PAGE_NAME + ".EXPORT_JAVA_FILES"; //$NON-NLS-1$
private final static String STORE_DESTINATION_NAMES= PAGE_NAME + ".DESTINATION_NAMES_ID"; //$NON-NLS-1$
private final static String STORE_COMPRESS= PAGE_NAME + ".COMPRESS"; //$NON-NLS-1$
private final static String STORE_OVERWRITE= PAGE_NAME + ".OVERWRITE"; //$NON-NLS-1$
// other constants
private final static int SIZING_SELECTION_WIDGET_WIDTH= 400;
private final static int SIZING_SELECTION_WIDGET_HEIGHT= 150;
/**
* Create an instance of this class
*/
public JarPackageWizardPage(JarPackage jarPackage, IStructuredSelection selection) {
super(PAGE_NAME, selection);
setTitle(JarPackagerMessages.getString("JarPackageWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarPackageWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
fInitialSelection= selection;
}
/*
* Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(
new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whatToExport.label")); //$NON-NLS-1$
createInputGroup(composite);
createExportTypeGroup(composite);
new Label(composite, SWT.NONE); // vertical spacer
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whereToExport.label")); //$NON-NLS-1$
createDestinationGroup(composite);
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.options.label")); //$NON-NLS-1$
createOptionsGroup(composite);
restoreResourceSpecificationWidgetValues(); // superclass API defines this hook
restoreWidgetValues();
if (fInitialSelection != null)
setupBasedOnInitialSelections();
setControl(composite);
update();
giveFocusToDestination();
WorkbenchHelp.setHelp(composite, new DialogPageContextComputer(this, IJavaHelpContextIds.JARPACKAGER_WIZARD_PAGE));
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createOptionsGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
optionsGroup.setLayout(layout);
fCompressCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fCompressCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.compress.text")); //$NON-NLS-1$
fCompressCheckbox.addListener(SWT.Selection, this);
fOverwriteCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fOverwriteCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.overwrite.text")); //$NON-NLS-1$
fOverwriteCheckbox.addListener(SWT.Selection, this);
}
/**
* Answer the contents of the destination specification widget. If this
* value does not have the required suffix then add it first.
*
* @return java.lang.String
*/
protected String getDestinationValue() {
String requiredSuffix= getOutputSuffix();
String destinationText= fDestinationNamesCombo.getText().trim();
if (!destinationText.toLowerCase().endsWith(requiredSuffix.toLowerCase()))
destinationText += requiredSuffix;
return destinationText;
}
/**
* Answer the string to display in self as the destination type
*
* @return java.lang.String
*/
protected String getDestinationLabel() {
return JarPackagerMessages.getString("JarPackageWizardPage.destination.label"); //$NON-NLS-1$
}
/**
* Answer the suffix that files exported from this wizard must have.
* If this suffix is a file extension (which is typically the case)
* then it must include the leading period character.
*
* @return java.lang.String
*/
protected String getOutputSuffix() {
return "." + JarPackage.EXTENSION; //$NON-NLS-1$
}
/**
* Returns an iterator over this page's collection of currently-specified
* elements to be exported. This is the primary element selection facility
* accessor for subclasses.
*
* @return an iterator over the collection of elements currently selected for export
*/
protected Iterator getSelectedResourcesIterator() {
return fInputGroup.getAllCheckedListItems();
}
/**
* Persists resource specification control setting that are to be restored
* in the next instance of this page. Subclasses wishing to persist
* settings for their controls should extend the hook method
* <code>internalSaveWidgetValues</code>.
*/
public final void saveWidgetValues() {
// update directory names history
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
directoryNames= new String[0];
directoryNames= addToHistory(directoryNames, getDestinationValue());
settings.put(STORE_DESTINATION_NAMES, directoryNames);
settings.put(STORE_EXPORT_CLASS_FILES, fJarPackage.areClassFilesExported());
settings.put(STORE_EXPORT_JAVA_FILES, fJarPackage.areJavaFilesExported());
// options
settings.put(STORE_COMPRESS, fJarPackage.isCompressed());
settings.put(STORE_OVERWRITE, fJarPackage.allowOverwrite());
}
// Allow subclasses to save values
internalSaveWidgetValues();
}
/**
* Hook method for subclasses to persist their settings.
*/
protected void internalSaveWidgetValues() {
}
/**
* Hook method for restoring widget values to the values that they held
* last time this wizard was used to completion.
*/
protected void restoreWidgetValues() {
if (!fJarPackage.isUsedToInitialize())
initializeJarPackage();
fExportClassFilesCheckbox.setSelection(fJarPackage.areClassFilesExported());
fExportJavaFilesCheckbox.setSelection(fJarPackage.areJavaFilesExported());
// destination
if (fJarPackage.getJarLocation().isEmpty())
fDestinationNamesCombo.setText(""); //$NON-NLS-1$
else
fDestinationNamesCombo.setText(fJarPackage.getJarLocation().toOSString());
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
if (! fDestinationNamesCombo.getText().equals(directoryNames[0]))
fDestinationNamesCombo.add(fDestinationNamesCombo.getText());
for (int i= 0; i < directoryNames.length; i++)
fDestinationNamesCombo.add(directoryNames[i]);
}
// options
fCompressCheckbox.setSelection(fJarPackage.isCompressed());
fOverwriteCheckbox.setSelection(fJarPackage.allowOverwrite());
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(settings.getBoolean(STORE_EXPORT_CLASS_FILES));
fJarPackage.setExportJavaFiles(settings.getBoolean(STORE_EXPORT_JAVA_FILES));
// options
fJarPackage.setCompress(settings.getBoolean(STORE_COMPRESS));
fJarPackage.setOverwrite(settings.getBoolean(STORE_OVERWRITE));
// destination
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
fJarPackage.setJarLocation(getPathFromString(directoryNames[0]));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
// destination
fJarPackage.setJarLocation(getPathFromString(fDestinationNamesCombo.getText()));
// options
fJarPackage.setCompress(fCompressCheckbox.getSelection());
fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
}
protected IPath getPathFromString(String text) {
return new Path(text).makeAbsolute();
}
/**
* Returns a boolean indicating whether the passed File handle is
* is valid and available for use.
*
* @return boolean
*/
protected boolean ensureTargetFileIsValid(File targetFile) {
if (targetFile.exists() && targetFile.isDirectory()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (targetFile.exists()) {
if (!targetFile.canWrite()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.jarFileExistsAndNotWritable")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
}
return true;
}
/*
* Overrides method from WizardExportPage
*/
protected void createDestinationGroup(Composite parent) {
initializeDialogUnits(parent);
// destination specification group
Composite destinationSelectionGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
destinationSelectionGroup.setLayout(layout);
destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
new Label(destinationSelectionGroup, SWT.NONE).setText(getDestinationLabel());
// destination name entry field
fDestinationNamesCombo= new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
fDestinationNamesCombo.addListener(SWT.Modify, this);
fDestinationNamesCombo.addListener(SWT.Selection, this);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= SIZING_TEXT_FIELD_WIDTH;
fDestinationNamesCombo.setLayoutData(data);
// destination browse button
fDestinationBrowseButton= new Button(destinationSelectionGroup, SWT.PUSH);
fDestinationBrowseButton.setText(JarPackagerMessages.getString("JarPackageWizardPage.browseButton.text")); //$NON-NLS-1$
fDestinationBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
SWTUtil.setButtonDimensionHint(fDestinationBrowseButton);
fDestinationBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleDestinationBrowseButtonPressed();
}
});
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDescriptionFileBrowseButtonPressed() {
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getDescriptionLocation()));
if (dialog.open() == dialog.OK) {
IPath path= dialog.getResult();
path= path.removeFileExtension().addFileExtension(JarPackage.DESCRIPTION_EXTENSION);
fDescriptionFileText.setText(path.toString());
}
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog= new FileDialog(getContainer().getShell(), SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.jar"}); //$NON-NLS-1$
String currentSourceString= getDestinationValue();
int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
dialog.setFileName(currentSourceString.substring(lastSeparatorIndex + 1, currentSourceString.length()));
}
else
dialog.setFileName(currentSourceString);
String selectedFileName= dialog.open();
if (selectedFileName != null) {
IPath path= getPathFromString(selectedFileName);
if (path.lastSegment().equals(getOutputSuffix()))
selectedFileName= ""; //$NON-NLS-1$
fDestinationNamesCombo.setText(selectedFileName);
}
}
/**
* Returns the resource for the specified path.
*
* @param path the path for which the resource should be returned
* @return the resource specified by the path or <code>null</code>
*/
protected IResource findResource(IPath path) {
IWorkspace workspace= JavaPlugin.getWorkspace();
IStatus result= workspace.validatePath(
path.toString(),
IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
if (result.isOK() && workspace.getRoot().exists(path))
return workspace.getRoot().findMember(path);
return null;
}
/**
* Creates the checkbox tree and list for selecting resources.
*
* @param parent the parent control
*/
protected void createInputGroup(Composite parent) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider treeContentProvider=
new JavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
fInputGroup= new CheckboxTreeAndListGroup(
parent,
JavaCore.create(JavaPlugin.getDefault().getWorkspace().getRoot()),
treeContentProvider,
new JavaElementLabelProvider(labelFlags),
new BaseJavaElementContentProvider(),
new JavaElementLabelProvider(labelFlags),
SWT.NONE,
SIZING_SELECTION_WIDGET_WIDTH,
SIZING_SELECTION_WIDGET_HEIGHT);
fInputGroup.addTreeFilter(new EmptyInnerPackageFilter());
fInputGroup.setTreeSorter(new JavaElementSorter());
fInputGroup.setListSorter(new JavaElementSorter());
fInputGroup.addTreeFilter(new ContainerFilter(ContainerFilter.FILTER_NON_CONTAINERS));
fInputGroup.addTreeFilter(new LibraryFilter());
fInputGroup.addListFilter(new ContainerFilter(ContainerFilter.FILTER_CONTAINERS));
fInputGroup.getTree().addListener(SWT.MouseUp, this);
fInputGroup.getTable().addListener(SWT.MouseUp, this);
}
/**
* Creates the export type controls.
*
* @param parent the parent control
*/
protected void createExportTypeGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout optionsLayout= new GridLayout();
optionsLayout.marginHeight= 0;
optionsGroup.setLayout(optionsLayout);
fExportClassFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportClassFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportClassFiles.text")); //$NON-NLS-1$
fExportClassFilesCheckbox.addListener(SWT.Selection, this);
fExportJavaFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportJavaFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportJavaFiles.text")); //$NON-NLS-1$
fExportJavaFilesCheckbox.addListener(SWT.Selection, this);
}
/**
* Updates the enablements of this page's controls. Subclasses may extend.
*/
protected void updateWidgetEnablements() {
}
/*
* Overrides method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
setErrorMessage(null);
return super.determinePageCompletion();
}
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
protected void update() {
updateModel();
updateWidgetEnablements();
updatePageCompletion();
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateDestinationGroup() {
if (fDestinationNamesCombo.getText().length() == 0) {
return false;
}
if (fJarPackage.getJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
return ensureTargetFileIsValid(fJarPackage.getJarLocation().toFile());
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateOptionsGroup() {
return true;
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateSourceGroup() {
if (!fExportClassFilesCheckbox.getSelection()
&& !fExportJavaFilesCheckbox.getSelection()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.noExportTypeChecked")); //$NON-NLS-1$
return false;
}
if (getSelectedResources().size() == 0)
return false;
if (fExportClassFilesCheckbox.getSelection() || !fExportJavaFilesCheckbox.getSelection())
return true;
// No class file export - check if there are source files
Iterator iter= getSelectedResourcesIterator();
while (iter.hasNext()) {
if (!(iter.next() instanceof IClassFile))
return true;
}
return false;
}
/*
* Overwrides method from WizardExportPage
*/
protected IPath getResourcePath() {
return getPathFromText(fSourceNameField);
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Set the current input focus to self's destination entry field
*/
protected void giveFocusToDestination() {
fDestinationNamesCombo.setFocus();
}
/*
* Overrides method from WizardExportResourcePage
*/
protected void setupBasedOnInitialSelections() {
Iterator enum= fInitialSelection.iterator();
while (enum.hasNext()) {
Object selectedElement= enum.next();
if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile || selectedElement instanceof IFile)
fInputGroup.initialCheckListItem(selectedElement);
else
fInputGroup.initialCheckTreeItem(selectedElement);
}
TreeItem[] items= fInputGroup.getTree().getItems();
int i= 0;
while (i < items.length && !items[i].getChecked())
i++;
if (i < items.length) {
fInputGroup.getTree().setSelection(new TreeItem[] {items[i]});
fInputGroup.getTree().showSelection();
fInputGroup.populateListViewer(items[i].getData());
}
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
/*
* Method declared on IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
if (getControl() != null)
updatePageCompletion();
}
void setSelectedElementsWithoutContainedChildren() {
Set closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
closure.addAll(getExportedNonContainers());
fJarPackage.setSelectedElementsClosure(closure);
}
private Set removeContainedChildren(Set elements) {
Set newList= new HashSet(elements.size());
Set javaElementResources= getCorrespondingContainers(elements);
Iterator iter= elements.iterator();
boolean removedOne= false;
while (iter.hasNext()) {
Object element= iter.next();
Object parent;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement) {
parent= ((IJavaElement)element).getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
try {
if (pkgRoot.getCorrespondingResource() instanceof IProject)
parent= pkgRoot.getJavaProject();
} catch (JavaModelException ex) {
// leave parent as is
}
}
}
else {
// unknown type
newList.add(element);
continue;
}
if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
removedOne= true;
else
newList.add(element);
}
if (removedOne)
return removeContainedChildren(newList);
else
return newList;
}
private Set getExportedNonContainers() {
Set whiteCheckedTreeItems= fInputGroup.getWhiteCheckedTreeItems();
Set exportedNonContainers= new HashSet(whiteCheckedTreeItems.size());
Set javaElementResources= getCorrespondingContainers(whiteCheckedTreeItems);
Iterator iter= fInputGroup.getAllCheckedListItems();
while (iter.hasNext()) {
Object element= iter.next();
Object parent= null;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement)
parent= ((IJavaElement)element).getParent();
if (!whiteCheckedTreeItems.contains(parent) && !javaElementResources.contains(parent))
exportedNonContainers.add(element);
}
return exportedNonContainers;
}
/*
* Create a list with the folders / projects that correspond
* to the Java elements (Java project, package, package root)
*/
private Set getCorrespondingContainers(Set elements) {
Set javaElementResources= new HashSet(elements.size());
Iterator iter= elements.iterator();
while (iter.hasNext()) {
Object element= iter.next();
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
// exclude default package since it is covered by the root
if (!(type == IJavaElement.PACKAGE_FRAGMENT && ((IPackageFragment)element).isDefaultPackage())) {
Object resource;
try {
resource= je.getCorrespondingResource();
} catch (JavaModelException ex) {
resource= null;
}
if (resource != null)
javaElementResources.add(resource);
}
}
}
}
return javaElementResources;
}
}
|
6,754 | Bug 6754 Hierarchy does not show selection on F4 | Build 20011206 - opened hierarchy on org.eclipse.jface.dialogs.MessageDialog - selected Dialog superclass and hit F4 - the resulting hierarchy was scrolled to the end, with the selection (Dialog) not visible | resolved fixed | 19bbeec | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T13:07:53Z" | "2001-12-10T18:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
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.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.IInputSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.help.ViewContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.compare.JavaReplaceWithEditionAction;
import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.BuildGroup;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of inut elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private IProblemChangedListener fHierarchyProblemListener;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private MethodsViewer fMethodsViewer;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private boolean fIsEnableMemberFilter;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaElementLabelProvider fPaneLabelProvider;
private IDialogSettings fDialogSettings;
private ToggleViewAction[] fViewActions;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private int fCurrentOrientation;
private EnableMemberFilterAction fEnableMemberFilterAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private IPartListener fPartListener;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fHierarchyProblemListener= null;
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fHistoryDropDownAction= new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions= new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS);
fPaneLabelProvider.setErrorTickManager(new MarkerErrorTickProvider());
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {}
public void partClosed(IWorkbenchPart part) {}
public void partDeactivated(IWorkbenchPart part) {}
public void partOpened(IWorkbenchPart part) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list
*/
public void selectMember(IMember member) {
ICompilationUnit cu= member.getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
member= (IMember) cu.getOriginal(member);
if (member == null) {
return;
}
}
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
fMethodsViewer.getControl().setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
}
if (element.getElementType() == IJavaElement.METHOD || element.getElementType() == IJavaElement.FIELD || element.getElementType() == IJavaElement.INITIALIZER) {
element= ((IMember) element).getDeclaringType();
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
// turn off member filtering
enableMemberFilter(false);
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement);
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
fPagebook.showPage(fTypeMethodsSplitter);
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer();
}
IType root= getSelectableType(fInputElement);
internalSelectType(root);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
}
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer();
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
getSite().getPage().removePartListener(fPartListener);
if (fHierarchyProblemListener != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener);
}
if (fMethodsViewer != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fMethodsViewer);
}
super.dispose();
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
HierarchyLabelProvider lprovider= new HierarchyLabelProvider(this, new MarkerErrorTickProvider());
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F4) {
OpenTypeHierarchyUtil.open(getSite().getSelectionProvider().getSelection(), getSite().getWorkbenchWindow());
return;
} else if (event.keyCode == SWT.F5) {
updateHierarchyViewer();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addSelectionChangedListener(fSelectionChangedListener);
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fMethodsViewer);
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_COPY;
DragSource source= new DragSource(fMethodsViewer.getControl(), ops);
source.setTransfer(transfers);
source.addDragListener(new BasicSelectionTransferDragAdapter(fMethodsViewer));
for (int i= 0; i < fAllViewers.length; i++) {
TypeHierarchyViewer curr= fAllViewers[i];
curr.addDropSupport(ops, transfers, new TypeHierarchyTransferDropAdapter(curr));
}
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
initDragAndDrop();
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
int orientation;
try {
orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if (orientation < 0 || orientation > 2) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation= -1;
// will fill the main tool bar
setOrientation(orientation);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
IJavaElement input= determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
// fixed for 1GETAYN: ITPJUI:WIN - F1 help does nothing
WorkbenchHelp.setHelp(fPagebook, new ViewContextComputer(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW));
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
updateMainToolbar(horizontal);
}
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(boolean horizontal) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (horizontal) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
viewer.contributeToContextMenu(menu);
IStructuredSelection selection= (IStructuredSelection)viewer.getSelection();
if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) {
addOpenPerspectiveItem(menu, selection);
}
addOpenWithMenu(menu, selection);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnTypeAction);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnSelectionAction);
addRefactoring(menu, viewer);
ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, viewer);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
//menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer));
addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection());
addRefactoring(menu, fMethodsViewer);
ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, fMethodsViewer);
}
private void addRefactoring(IMenuManager menu, IInputSelectionProvider viewer){
MenuManager refactoring= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.refactor")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, viewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
Object element= selection.getFirstElement();
if (!(element instanceof IJavaElement))
return;
IResource resource= null;
try {
resource= ((IJavaElement)element).getUnderlyingResource();
} catch(JavaModelException e) {
// ignore
}
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
private void addOpenPerspectiveItem(IMenuManager menu, IStructuredSelection selection) {
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, selection);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
updateHierarchyViewer();
updateTitle();
}
private IType getSelectableType(IJavaElement elem) {
ISelection sel= null;
if (elem.getElementType() != IJavaElement.TYPE) {
return (IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY);
viewer.addSelectionChangedListener(fSelectionChangedListener);
}
private void internalSelectMember(IMember member) {
fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener);
fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY);
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer() {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent();
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(IType input) {
if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
fMethodsViewer.setInput(input);
}
}
private void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
} else {
typeSelectionChanged(e.getSelection());
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
try {
getSite().getPage().removePartListener(fPartListener);
EditorUtility.openInEditor(elem, false);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer();
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement));
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
if (fHierarchyProblemListener != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener);
}
fHierarchyProblemListener= getCurrentViewer();
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fHierarchyProblemListener);
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
doTypeHierarchyChangedOnViewers(changedTypes);
}
});
}
}
private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (changedTypes == null) {
// hierarchy change
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement);
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
updateHierarchyViewer();
}
} else {
// elements in hierarchy modified
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer();
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
return (IJavaElement) input;
}
return null;
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
memento.putString(TAG_INPUT, fInputElement.getHandleIdentifier());
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fMethodsViewer.saveState(memento);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (!input.exists()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
String selectionId= memento.getString(TAG_SELECTION);
if (selectionId != null) {
IJavaElement elem= JavaCore.create(selectionId);
if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
internalSelectType((IMember)elem);
}
}
fMethodsViewer.restoreState(memento);
}
/**
* Link selection to active editor.
*/
private void editorActivated(IEditorPart editor) {
if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i]);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
} |
6,758 | Bug 6758 Class name corrupted by creating member class using wizard | Build 20011206 - opened org.eclipse.ui.actions.DeleteResourceAction - using new class wizard, created member class named DeleteProjectDialog as a subclass of MessageDialog (in org.eclipse.jface.dialogs) - the result was: ... public class DeleteRes ourceAction extends SelectionListenerAction { public class DeleteProjectDialog extends MessageDialog { } ... Note the extra tab in DeleteResourceAction, and the strange formatting for the new class. | resolved fixed | 5a7c982 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T14:32:55Z" | "2001-12-10T18:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/TypePage.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.compiler.env.IConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.text.template.Template;
import org.eclipse.jdt.internal.ui.text.template.Templates;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.swt.MGridData;
/**
* <code>TypePage</code> contains controls and validation routines for a 'New Type WizardPage'
* Implementors decide which components to add and to enable. Implementors can also
* customize the validation code.
* <code>TypePage</code> is intended to serve as base class of all wizards that create types.
* Applets, Servlets, Classes, Interfaces...
* See <code>NewClassCreationWizardPage</code> or <code>NewInterfaceCreationWizardPage</code> for an
* example usage of TypePage.
*/
public abstract class TypePage extends ContainerPage {
private final static String PAGE_NAME= "TypePage"; //$NON-NLS-1$
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
public TypePage(boolean isClass, String pageName, IWorkspaceRoot root) {
super(pageName, root);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("TypePage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("TypePage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("TypePage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("TypePage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("TypePage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("TypePage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("TypePage.interfaces.class.label") : NewWizardMessages.getString("TypePage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("TypePage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("TypePage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("TypePage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("TypePage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("TypePage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the type page with a given
* Java element as selection.
* @param elem The initial selection of this page or null if no
* selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= JavaModelUtil.findPrimaryType(cu);
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
// ignore this exception now
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName("", true); //$NON-NLS-1$
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, 4);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the enclosing type name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
fEnclosingTypeSelection.doFillIntoGrid(composite, 1);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
MGridData gd= new MGridData(MGridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
c= fEnclosingTypeDialogField.getChangeControl(composite);
c.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL));
}
/**
* Creates the controls for the type name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
MGridData gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the superclass name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
MGridData gd= (MGridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the container if empty, elso on type name.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(DialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(DialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/**
* Called whenever a content of a field has changed.
* Implementors of TypePage can hook in.
* @see ContainerPage#handleFieldChanged
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Gets the text of package field.
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Gets the text of enclosing type field.
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
* @return Returns <code>null</code> if the input could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment.
* This will update model and the text of the control.
* @param canBeModified Selects if the package fragment can be changed by the user
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the encloding type corresponding to the current input.
* @return Returns <code>null</code> if enclosing type is not selected or the input could not
* be resolved.
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the package fragment.
* This will update model and the text of the control.
* @param canBeModified Selects if the enclosing type can be changed by the user
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns <code>true</code> if the enclosing type selection check box is enabled.
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type selection checkbox.
* @param canBeModified Selects if the enclosing type selection can be changed by the user
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Gets the type name.
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name.
* @param canBeModified Selects if the type name can be changed by the user
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Gets the selected modifiers.
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= IConstants.AccPublic;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= IConstants.AccPrivate;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= IConstants.AccProtected;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= IConstants.AccAbstract;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= IConstants.AccFinal;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= IConstants.AccStatic;
}
return mdf;
}
/**
* Sets the modifiers.
* @param canBeModified Selects if the modifiers can be changed by the user
* @see IConstants
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Gets the content of the super class text field.
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
* @param canBeModified Selects if the super class can be changed by the user
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Gets the currently chosen super interfaces.
* @return returns a list of String
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
* @param interfacesNames a list of String
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
// ----------- validation ----------
/**
* Called when the package field has changed.
* The method validates the package name and returns the status of the validation
* This also updates the package fragment model.
* Can be extended to add more validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
IPackageFragment pack= root.getPackageFragment(packName);
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= pack.getUnderlyingResource().getFullPath();
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("TypePage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
// let pass
}
fCurrPackage= pack;
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= fPackageDialogField.getText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Called when the enclosing type name has changed.
* The method validates the enclosing type and returns the status of the validation
* This also updates the enclosing type model.
* Can be extended to add more validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= JavaModelUtil.findType(root.getJavaProject(), enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e.getStatus());
return status;
}
}
/**
* Called when the type name has changed.
* The method validates the type name and returns the status of the validation.
* Can be extended to add more validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("TypePage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("TypePage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.exists()) {
status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Called when the superclass name has changed.
* The method validates the superclass name and returns the status of the validation.
* Can be extended to add more validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (!val.isOK()) {
status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("TypePage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e.getStatus());
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= JavaModelUtil.findType(jproject, packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= JavaModelUtil.findType(jproject, sclassName);
}
}
return type;
}
/**
* Called when the list of super interface has changed.
* The method validates the superinterfaces and returns the status of the validation.
* Can be extended to add more validation.
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= JavaModelUtil.findType(root.getJavaProject(), intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Called when the modifiers have changed.
* The method validates the modifiers and returns the status of the validation.
* Can be extended to add more validation.
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("TypePage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("TypePage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
if (fCurrPackage != null) {
dialog.setInitialSelections(new Object[] { fCurrPackage });
}
if (dialog.open() == dialog.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_TYPES);
dialog.setTitle(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
if (fCurrEnclosingType != null) {
dialog.setInitialSelections(new Object[] { fCurrEnclosingType });
dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1));
}
if (dialog.open() == dialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES);
dialog.setTitle(NewWizardMessages.getString("TypePage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.SuperClassDialog.message")); //$NON-NLS-1$
if (fSuperClass != null) {
dialog.setFilter(fSuperClass.getElementName());
}
if (dialog.open() == dialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(NewWizardMessages.getString("TypePage.InterfacesDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates a type using the current field values.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
monitor.beginTask(NewWizardMessages.getString("TypePage.operationdesc"), 10); //$NON-NLS-1$
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= fTypeNameDialogField.getText();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsStructure imports;
int indent= 0;
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
String lineDelimiter= null;
if (!isInnerClass) {
ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$
imports= new ImportsStructure(parentCU, prefOrder, threshold, false);
lineDelimiter= StubUtility.getLineDelimiterUsed(parentCU);
String content= createTypeBody(imports, lineDelimiter);
createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5));
String fileComment= getFileComment();
if (fileComment != null) {
parentCU.getBuffer().replace(0, 0, fileComment + lineDelimiter);
}
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsStructure(parentCU, prefOrder, threshold, true);
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
String content= createTypeBody(imports, lineDelimiter);
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so the type can be parsed correctly
imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1));
String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1));
if (methods.length > 0) {
for (int i= 0; i < methods.length; i++) {
createdType.createMethod(methods[i], null, false, null);
}
// add imports
imports.create(!isInnerClass, null);
}
monitor.worked(1);
ISourceRange range= isInnerClass ? createdType.getSourceRange() : createdType.getCompilationUnit().getSourceRange();
IBuffer buf= createdType.getCompilationUnit().getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter);
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
buf.save(new SubProgressMonitor(monitor, 1), false);
} else {
monitor.worked(1);
}
fCreatedType= createdType;
monitor.done();
}
/**
* Returns the created type. Only valid after createType has been invoked
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, IImportsStructure imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
buf.append(Signature.getSimpleName(typename));
if (fSuperClass != null) {
imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass));
} else {
imports.addImport(typename);
}
}
}
private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
imports.addImport(typename);
buf.append(Signature.getSimpleName(typename));
if (i < last) {
buf.append(", "); //$NON-NLS-1$
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String createTypeBody(IImportsStructure imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
String typeComment= getTypeComment();
if (typeComment != null) {
buf.append(typeComment);
buf.append(lineDelimiter);
}
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append(" {"); //$NON-NLS-1$
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* Called from createType to allow adding methods for the newly created type
* Returns array of sources of the methods that have to be added
* @param parent The type where the methods will be added to
*/
protected String[] evalMethods(IType parent, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return new String[0];
}
/**
* Called from createType to get a file comment. By default the content of template
* 'filecomment' is taken.
* Returns source or null, if no file comment should be added
*/
protected String getFileComment() {
if (CodeGenerationPreferencePage.doFileComments()) {
return getTemplate("filecomment");
}
return null;
}
/**
* Called from createType to get a type comment.
* Returns source or null, if no type comment should be added
*/
protected String getTypeComment() {
if (CodeGenerationPreferencePage.doCreateComments()) {
return getTemplate("typecomment");
}
return null;
}
protected String getTemplate(String name) {
Template[] templates= Templates.getInstance().getTemplates();
for (int i= 0; i < templates.length; i++) {
if (name.equals(templates[i].getName())) {
return templates[i].getPattern();
}
}
return null;
}
/**
* Creates the bodies of all unimplemented methods or/and all constructors
* Can be used by implementors of TypePage to add method stub checkboxes
*/
protected String[] constructInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
List newMethods= new ArrayList();
ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
StubUtility.evalConstructors(type, superclass, settings, newMethods, imports);
}
}
if (doUnimplementedMethods) {
StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, newMethods, imports);
}
return (String[]) newMethods.toArray(new String[newMethods.size()]);
}
// ---- creation ----------------
/**
* @see NewElementWizardPage#getRunnable
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
} |
6,794 | Bug 6794 ProgressMonitorPart.setTaskName should update text label as ProgressMonitorDialog does | The ProgressMonitorDialog updates the task label if the method setTaskName is called. ProgressMonitorPart doesn't do so. As a consequence progress reporting looks different if an operation in executed in a wizard or using a progress monitor dialog. I think, they should behave the same. | resolved fixed | f2717d8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T17:17:38Z" | "2001-12-11T17:00:00Z" | org.eclipse.jdt.ui/core | |
6,794 | Bug 6794 ProgressMonitorPart.setTaskName should update text label as ProgressMonitorDialog does | The ProgressMonitorDialog updates the task label if the method setTaskName is called. ProgressMonitorPart doesn't do so. As a consequence progress reporting looks different if an operation in executed in a wizard or using a progress monitor dialog. I think, they should behave the same. | resolved fixed | f2717d8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T17:17:38Z" | "2001-12-11T17:00:00Z" | refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java | |
3,959 | Bug 3959 Dupilcate entry in save before copy dialog (1GF9IYY) | Open two java perspectives in two windows. Open the same .java file in both perspectives Change the contents of the file but do not save Select copy from the file's popup menu Note that in the dialog that appears the file is listed twice. NOTES: | resolved fixed | ae06abd | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T18:59:35Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui | |
3,959 | Bug 3959 Dupilcate entry in save before copy dialog (1GF9IYY) | Open two java perspectives in two windows. Open the same .java file in both perspectives Change the contents of the file but do not save Select copy from the file's popup menu Note that in the dialog that appears the file is listed twice. NOTES: | resolved fixed | ae06abd | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T18:59:35Z" | "2001-10-11T03:13:20Z" | refactoring/org/eclipse/jdt/internal/ui/refactoring/PreviewWizardPage.java | |
3,959 | Bug 3959 Dupilcate entry in save before copy dialog (1GF9IYY) | Open two java perspectives in two windows. Open the same .java file in both perspectives Change the contents of the file but do not save Select copy from the file's popup menu Note that in the dialog that appears the file is listed twice. NOTES: | resolved fixed | ae06abd | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-11T18:59:35Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart;
import org.eclipse.jdt.internal.ui.preferences.ClasspathVariablesPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.CompilerPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.RefactoringPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.TemplatePreferencePage;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
private static JavaPlugin fgJavaPlugin;
private CompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
return getActiveWorkbenchWindow().getShell();
}
/**
* Returns an array of all dirty editor parts.
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart editor= editors[z];
if (editor.isDirty())
result.add(editor);
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().fImageDescriptorRegistry;
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
fImageDescriptorRegistry= new ImageDescriptorRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() {
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(new JavaElementAdapterFactory(), IJavaElement.class);
manager.registerAdapters(new MarkerAdapterFactory(), IMarker.class);
manager.registerAdapters(new EditorInputAdapterFactory(), IEditorInput.class);
manager.registerAdapters(new ResourceAdapterFactory(), IResource.class);
try {
JavaRuntime.initializeJREVariables(null);
} catch (CoreException e) {
log(e.getStatus());
}
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
fImageDescriptorRegistry.dispose();
super.shutdown();
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
}
private IWorkbenchPage internalGetActivePage() {
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public IWorkingCopyManager getWorkingCopyManager() {
return getCompilationUnitDocumentProvider();
}
public ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore());
return fJavaTextTools;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_OPEN));
menu.add(new Separator(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
store.setDefault(IPreferencesConstants.EDITOR_SHOW_HOVER, true);
store.setDefault(IPreferencesConstants.EDITOR_SHOW_SEGMENTS, false);
JavaBasePreferencePage.initDefaults(store);
ImportOrganizePreferencePage.initDefaults(store);
ClasspathVariablesPreferencePage.initDefaults(store);
RefactoringPreferencePage.initDefaults(store);
CodeFormatterPreferencePage.initDefaults(store);
CompilerPreferencePage.initDefaults(store);
PackageExplorerPart.initDefaults(store);
JavaEditorPreferencePage.initDefaults(store);
TemplatePreferencePage.initDefaults(store);
CodeGenerationPreferencePage.initDefaults(store);
}
} |
6,389 | Bug 6389 System threads show suspended at startup | Version 20011127 1. Launch Eclipse from Eclipse. 2. Note that the system threads are incorrectly rendered as suspended in the DebugView. 3. Close the DebugView and reopen it. 4. The threads are rendered correctly Somewhere along the line we're not firing a changed (suspended, etc.) event. | verified fixed | 1b2b942 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T13:06:52Z" | "2001-11-28T17:53:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TypeSelectionDialog.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.util.AllTypesSearchEngine;
import org.eclipse.jdt.internal.ui.util.StringMatcher;
import org.eclipse.jdt.internal.ui.util.TypeInfo;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
/**
* A dialog to select a type from a list of types.
*/
public class TypeSelectionDialog extends TwoPaneElementSelector {
private static class TypeFilterMatcher implements FilteredList.FilterMatcher {
private StringMatcher fMatcher;
private StringMatcher fQualifierMatcher;
/*
* @see FilteredList.FilterMatcher#setFilter(String, boolean)
*/
public void setFilter(String pattern, boolean ignoreCase, boolean igoreWildCards) {
int qualifierIndex= pattern.lastIndexOf("."); //$NON-NLS-1$
// type
if (qualifierIndex == -1) {
fQualifierMatcher= null;
fMatcher= new StringMatcher(pattern + '*', ignoreCase, igoreWildCards);
// qualified type
} else {
fQualifierMatcher= new StringMatcher(pattern.substring(0, qualifierIndex), ignoreCase, igoreWildCards);
fMatcher= new StringMatcher(pattern.substring(qualifierIndex + 1), ignoreCase, igoreWildCards);
}
}
/*
* @see FilteredList.FilterMatcher#match(Object)
*/
public boolean match(Object element) {
if (!(element instanceof TypeInfo))
return false;
TypeInfo type= (TypeInfo) element;
if (!fMatcher.match(type.getTypeName()))
return false;
if (fQualifierMatcher == null)
return true;
return fQualifierMatcher.match(type.getTypeContainerName());
}
}
/*
* A string comparator which is aware of obfuscated code
* (type names starting with lower case characters).
*/
private static class StringComparator implements Comparator {
public int compare(Object left, Object right) {
String leftString= (String) left;
String rightString= (String) right;
// XXX workaround for 6385
if (leftString.length() == 0) {
JavaPlugin.log(new StringIndexOutOfBoundsException("type name was empty"));
return -1;
}
// XXX
if (rightString.length() == 0) {
JavaPlugin.log(new StringIndexOutOfBoundsException("type name was empty"));
return +1;
}
if (Character.isLowerCase(leftString.charAt(0)) &&
!Character.isLowerCase(rightString.charAt(0)))
return +1;
if (Character.isLowerCase(rightString.charAt(0)) &&
!Character.isLowerCase(leftString.charAt(0)))
return -1;
return leftString.compareToIgnoreCase(rightString);
}
}
private IRunnableContext fRunnableContext;
private IJavaSearchScope fScope;
private int fStyle;
/**
* Constructs a type selection dialog.
* @param parent the parent shell.
* @param context the runnable context.
* @param scope the java search scope.
* @param style the widget style.
*/
public TypeSelectionDialog(Shell parent, IRunnableContext context,
IJavaSearchScope scope, int style)
{
super(parent, new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY),
new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider.SHOW_ROOT_POSTFIX));
Assert.isNotNull(context);
Assert.isNotNull(scope);
fRunnableContext= context;
fScope= scope;
fStyle= style;
setUpperListLabel(JavaUIMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$
setLowerListLabel(JavaUIMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$
}
public void create() {
if (getFilter() == null)
setFilter("A"); //$NON-NLS-1$
super.create();
}
/*
* @see AbstractElementListSelectionDialog#createFilteredList(Composite)
*/
protected FilteredList createFilteredList(Composite parent) {
FilteredList list= super.createFilteredList(parent);
fFilteredList.setFilterMatcher(new TypeFilterMatcher());
fFilteredList.setComparator(new StringComparator());
return list;
}
/**
* @see Window#open()
*/
public int open() {
AllTypesSearchEngine engine= new AllTypesSearchEngine(JavaPlugin.getWorkspace());
List typeList= engine.searchTypes(fRunnableContext, fScope, fStyle);
if (typeList.isEmpty()) {
String title= JavaUIMessages.getString("TypeSelectionDialog.notypes.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.notypes.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
return CANCEL;
}
TypeInfo[] typeRefs= (TypeInfo[])typeList.toArray(new TypeInfo[typeList.size()]);
setElements(typeRefs);
return super.open();
}
/**
* @see SelectionStatusDialog#computeResult()
*/
protected void computeResult() {
TypeInfo ref= (TypeInfo) getLowerSelectedElement();
if (ref == null)
return;
try {
IType type= ref.resolveType(fScope);
if (type == null) {
// not a class file or compilation unit
String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
setResult(null);
} else {
List result= new ArrayList(1);
result.add(type);
setResult(result);
}
} catch (JavaModelException e) {
String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
setResult(null);
}
}
} |
6,503 | Bug 6503 Search page - should offer case sensitivity check box | null | verified fixed | a25d0d8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T15:01:24Z" | "2001-12-03T14:33:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/FindDeclarationsAction.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class FindDeclarationsAction extends ElementSearchAction {
public FindDeclarationsAction() {
this(SearchMessages.getString("Search.FindDeclarationAction.label"), new Class[] {IField.class, IMethod.class, IType.class, IPackageDeclaration.class, IImportDeclaration.class, IPackageFragment.class}); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindDeclarationAction.tooltip")); //$NON-NLS-1$
}
public FindDeclarationsAction(String label, Class[] validTypes) {
super(label, validTypes);
setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
}
protected JavaSearchOperation makeOperation(IJavaElement element) throws JavaModelException {
if (element.getElementType() == IJavaElement.METHOD) {
IMethod method= (IMethod)element;
int searchFor= IJavaSearchConstants.METHOD;
if (method.isConstructor())
searchFor= IJavaSearchConstants.CONSTRUCTOR;
IType type= getType(element);
String pattern= PrettySignature.getUnqualifiedMethodSignature(method);
return new JavaSearchOperation(JavaPlugin.getWorkspace(), pattern,
searchFor, getLimitTo(), getScope(type), getScopeDescription(type), getCollector());
}
else
return super.makeOperation(element);
}
protected int getLimitTo() {
return IJavaSearchConstants.DECLARATIONS;
}
} |
6,503 | Bug 6503 Search page - should offer case sensitivity check box | null | verified fixed | a25d0d8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T15:01:24Z" | "2001-12-03T14:33:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/FindDeclarationsInWorkingSetAction.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.search.ui.IWorkingSet;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jface.util.Assert;
public class FindDeclarationsInWorkingSetAction extends FindDeclarationsAction {
private IWorkingSet fWorkingSet;
public FindDeclarationsInWorkingSetAction(IWorkingSet workingSet) {
this();
fWorkingSet= workingSet;
}
public FindDeclarationsInWorkingSetAction() {
setText(SearchMessages.getString("Search.FindDeclarationsInWorkingSetAction.label")); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindDeclarationsInWorkingSetAction.tooltip")); //$NON-NLS-1$
}
protected JavaSearchOperation makeOperation(IJavaElement element) throws JavaModelException {
IWorkingSet workingSet= fWorkingSet;
if (fWorkingSet == null) {
workingSet= queryWorkingSet();
if (workingSet == null)
return null;
}
updateLRUWorkingSet(workingSet);
if (element.getElementType() == IJavaElement.METHOD) {
IMethod method= (IMethod)element;
int searchFor= IJavaSearchConstants.METHOD;
if (method.isConstructor())
searchFor= IJavaSearchConstants.CONSTRUCTOR;
String pattern= PrettySignature.getUnqualifiedMethodSignature(method);
return new JavaSearchOperation(JavaPlugin.getWorkspace(), pattern, searchFor, getLimitTo(), getScope(workingSet), getScopeDescription(workingSet), getCollector());
}
else
return new JavaSearchOperation(JavaPlugin.getWorkspace(), element, getLimitTo(), getScope(workingSet), getScopeDescription(workingSet), getCollector());
};
private IJavaSearchScope getScope(IWorkingSet workingSet) throws JavaModelException {
return JavaSearchScopeFactory.getInstance().createJavaSearchScope(workingSet);
}
private String getScopeDescription(IWorkingSet workingSet) {
return SearchMessages.getFormattedString("WorkingSetScope", new String[] {workingSet.getName()}); //$NON-NLS-1$
}
private IWorkingSet queryWorkingSet() throws JavaModelException {
SelectionDialog dialog= SearchUI.createWorkingSetDialog(JavaPlugin.getActiveWorkbenchShell());
if (dialog.open() == dialog.OK)
return (IWorkingSet)dialog.getResult()[0];
else
return null;
}
}
|
6,503 | Bug 6503 Search page - should offer case sensitivity check box | null | verified fixed | a25d0d8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T15:01:24Z" | "2001-12-03T14:33:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchOperation.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class JavaSearchOperation extends WorkspaceModifyOperation {
private IWorkspace fWorkspace;
private IJavaElement fElementPattern;
private int fLimitTo;
private String fStringPattern;
private int fSearchFor;
private IJavaSearchScope fScope;
private String fScopeDescription;
private JavaSearchResultCollector fCollector;
protected JavaSearchOperation(
IWorkspace workspace,
int limitTo,
IJavaSearchScope scope,
String scopeDescription,
JavaSearchResultCollector collector) {
fWorkspace= workspace;
fLimitTo= limitTo;
fScope= scope;
fScopeDescription= scopeDescription;
fCollector= collector;
fCollector.setOperation(this);
}
public JavaSearchOperation(
IWorkspace workspace,
IJavaElement pattern,
int limitTo,
IJavaSearchScope scope,
String scopeDescription,
JavaSearchResultCollector collector) {
this(workspace, limitTo, scope, scopeDescription, collector);
fElementPattern= pattern;
}
public JavaSearchOperation(
IWorkspace workspace,
String pattern,
int searchFor,
int limitTo,
IJavaSearchScope scope,
String scopeDescription,
JavaSearchResultCollector collector) {
this(workspace, limitTo, scope, scopeDescription, collector);
fStringPattern= pattern;
fSearchFor= searchFor;
}
protected void execute(IProgressMonitor monitor) throws CoreException {
fCollector.setProgressMonitor(monitor);
SearchEngine engine= new SearchEngine();
if (fElementPattern != null)
engine.search(fWorkspace, fElementPattern, fLimitTo, fScope, fCollector);
else
engine.search(fWorkspace, fStringPattern, fSearchFor, fLimitTo, fScope, fCollector);
}
String getSingularLabel() {
String desc= null;
if (fElementPattern != null) {
if (fLimitTo == IJavaSearchConstants.REFERENCES
&& fElementPattern.getElementType() == IJavaElement.METHOD)
desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)fElementPattern);
else
desc= fElementPattern.getElementName();
if ("".equals(desc) && fElementPattern.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$
desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$
}
else
desc= fStringPattern;
String[] args= new String[] {desc, fScopeDescription}; //$NON-NLS-1$
switch (fLimitTo) {
case IJavaSearchConstants.IMPLEMENTORS:
return SearchMessages.getFormattedString("JavaSearchOperation.singularImplementorsPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.DECLARATIONS:
return SearchMessages.getFormattedString("JavaSearchOperation.singularDeclarationsPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.REFERENCES:
return SearchMessages.getFormattedString("JavaSearchOperation.singularReferencesPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.ALL_OCCURRENCES:
return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.READ_ACCESSES:
return SearchMessages.getFormattedString("JavaSearchOperation.singularReadReferencesPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.WRITE_ACCESSES:
return SearchMessages.getFormattedString("JavaSearchOperation.singularWriteReferencesPostfix", args); //$NON-NLS-1$
default:
return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$;
}
}
String getPluralLabelPattern() {
String desc= null;
if (fElementPattern != null) {
if (fLimitTo == IJavaSearchConstants.REFERENCES
&& fElementPattern.getElementType() == IJavaElement.METHOD)
desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)fElementPattern);
else
desc= fElementPattern.getElementName();
if ("".equals(desc) && fElementPattern.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$
desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$
}
else
desc= fStringPattern;
String[] args= new String[] {desc, "{0}", fScopeDescription}; //$NON-NLS-1$
switch (fLimitTo) {
case IJavaSearchConstants.IMPLEMENTORS:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralImplementorsPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.DECLARATIONS:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralDeclarationsPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.REFERENCES:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralReferencesPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.ALL_OCCURRENCES:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.READ_ACCESSES:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralReadReferencesPostfix", args); //$NON-NLS-1$
case IJavaSearchConstants.WRITE_ACCESSES:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralWriteReferencesPostfix", args); //$NON-NLS-1$
default:
return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$;
}
}
ImageDescriptor getImageDescriptor() {
if (fLimitTo == IJavaSearchConstants.IMPLEMENTORS || fLimitTo == IJavaSearchConstants.DECLARATIONS)
return JavaPluginImages.DESC_OBJS_SEARCH_DECL;
else
return JavaPluginImages.DESC_OBJS_SEARCH_REF;
}
} |
6,503 | Bug 6503 Search page - should offer case sensitivity check box | null | verified fixed | a25d0d8 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T15:01:24Z" | "2001-12-03T14:33:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPage.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
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;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.search.ui.IWorkingSet;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.util.RowLayouter;
public class JavaSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants {
public static final String EXTENSION_POINT_ID= "org.eclipse.jdt.ui.JavaSearchPage"; //$NON-NLS-1$
private static List fgPreviousSearchPatterns= new ArrayList(20);
private Combo fPattern;
private String fInitialPattern;
private boolean fFirstTime= true;
private ISearchPageContainer fContainer;
private Button[] fSearchFor;
private String[] fSearchForText= {
SearchMessages.getString("SearchPage.searchFor.type"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.method"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.package"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.constructor"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.field")}; //$NON-NLS-1$
private Button[] fLimitTo;
private String[] fLimitToText= {
SearchMessages.getString("SearchPage.limitTo.declarations"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.implementors"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.references"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.allOccurrences"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.readReferences"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.writeReferences")}; //$NON-NLS-1$
private IJavaElement fJavaElement;
private static class SearchPatternData {
int searchFor;
int limitTo;
String pattern;
IJavaElement javaElement;
int scope;
IWorkingSet workingSet;
public SearchPatternData(int s, int l, String p, IJavaElement element) {
this(s, l, p, element, ISearchPageContainer.WORKSPACE_SCOPE, null);
}
public SearchPatternData(int s, int l, String p, IJavaElement element, int scope, IWorkingSet workingSet) {
searchFor= s;
limitTo= l;
pattern= p;
javaElement= element;
this.scope= scope;
this.workingSet= workingSet;
}
}
//---- Action Handling ------------------------------------------------
public boolean performAction() {
SearchPatternData data= getPatternData();
IWorkspace workspace= JavaPlugin.getWorkspace();
// Setup search scope
IJavaSearchScope scope= null;
String scopeDescription= ""; //$NON-NLS-1$
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$
scope= SearchEngine.createWorkspaceScope();
break;
case ISearchPageContainer.SELECTION_SCOPE:
scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getSelection());
break;
case ISearchPageContainer.WORKING_SET_SCOPE:
IWorkingSet workingSet= getContainer().getSelectedWorkingSet();
// should not happen - just to be sure
if (workingSet == null)
return false;
scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", new String[] {workingSet.getName()}); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSet());
ElementSearchAction.updateLRUWorkingSet(getContainer().getSelectedWorkingSet());
}
JavaSearchResultCollector collector= new JavaSearchResultCollector();
JavaSearchOperation op= null;
if (data.javaElement != null && getPattern().equals(fInitialPattern))
op= new JavaSearchOperation(workspace, data.javaElement, data.limitTo, scope, scopeDescription, collector);
else {
data.javaElement= null;
op= new JavaSearchOperation(workspace, data.pattern, data.searchFor, data.limitTo, scope, scopeDescription, collector);
}
Shell shell= getControl().getShell();
try {
getContainer().getRunnableContext().run(true, true, op);
} catch (InvocationTargetException ex) {
ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$
return false;
} catch (InterruptedException ex) {
return false;
}
return true;
}
private int getLimitTo() {
for (int i= 0; i < fLimitTo.length; i++) {
if (fLimitTo[i].getSelection())
return i;
}
return -1;
}
private void setLimitTo(int searchFor) {
fLimitTo[DECLARATIONS].setEnabled(true);
fLimitTo[IMPLEMENTORS].setEnabled(false);
fLimitTo[REFERENCES].setEnabled(true);
fLimitTo[ALL_OCCURRENCES].setEnabled(true);
fLimitTo[READ_ACCESSES].setEnabled(false);
fLimitTo[WRITE_ACCESSES].setEnabled(false);
if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) {
fLimitTo[IMPLEMENTORS].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) {
fLimitTo[getLimitTo()].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
switch (searchFor) {
case TYPE | INTERFACE:
fLimitTo[IMPLEMENTORS].setEnabled(true);
case FIELD:
fLimitTo[READ_ACCESSES].setEnabled(true);
fLimitTo[WRITE_ACCESSES].setEnabled(true);
break;
default :
break;
}
}
private String[] getPreviousSearchPatterns() {
// Search results are not persistent
int patternCount= fgPreviousSearchPatterns.size();
String [] patterns= new String[patternCount];
for (int i= 0; i < patternCount; i++)
patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).pattern;
return patterns;
}
private int getSearchFor() {
for (int i= 0; i < fSearchFor.length; i++) {
if (fSearchFor[i].getSelection())
return i;
}
Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$
return -1;
}
private String getPattern() {
return fPattern.getText();
}
/**
* Return search pattern data and update previous searches.
* An existing entry will be updated.
*/
private SearchPatternData getPatternData() {
String pattern= getPattern();
SearchPatternData match= null;
int i= 0;
int size= fgPreviousSearchPatterns.size();
while (match == null && i < size) {
match= (SearchPatternData) fgPreviousSearchPatterns.get(i);
i++;
if (!pattern.equals(match.pattern))
match= null;
};
if (match == null) {
match= new SearchPatternData(
getSearchFor(),
getLimitTo(),
getPattern(),
fJavaElement,
getContainer().getSelectedScope(),
getContainer().getSelectedWorkingSet());
fgPreviousSearchPatterns.add(match);
}
else {
match.searchFor= getSearchFor();
match.limitTo= getLimitTo();
match.javaElement= fJavaElement;
match.scope= getContainer().getSelectedScope();
match.workingSet= getContainer().getSelectedWorkingSet();
};
return match;
}
/*
* Implements method from IDialogPage
*/
public void setVisible(boolean visible) {
if (visible && fPattern != null) {
if (fFirstTime) {
fFirstTime= false;
// Set item and text here to prevent page from resizing
fPattern.setItems(getPreviousSearchPatterns());
initSelections();
}
fPattern.setFocus();
getContainer().setPerformActionEnabled(fPattern.getText().length() > 0 && getContainer().hasValidScope());
}
super.setVisible(visible);
}
public boolean isValid() {
return true;
}
//---- Widget creation ------------------------------------------------
/**
* Creates the page's content.
*/
public void createControl(Composite parent) {
GridData gd;
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2; layout.makeColumnsEqualWidth= true;
layout.horizontalSpacing= 10;
result.setLayout(layout);
RowLayouter layouter= new RowLayouter(layout.numColumns);
gd= new GridData();
gd.horizontalAlignment= gd.FILL;
layouter.setDefaultGridData(gd, 0);
layouter.setDefaultGridData(gd, 1);
layouter.setDefaultSpan();
layouter.perform(createExpression(result));
layouter.perform(createSearchFor(result), createLimitTo(result), -1);
SelectionAdapter javaElementInitializer= new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
fJavaElement= null;
setLimitTo(getSearchFor());
}
};
fSearchFor[TYPE].addSelectionListener(javaElementInitializer);
fSearchFor[METHOD].addSelectionListener(javaElementInitializer);
fSearchFor[FIELD].addSelectionListener(javaElementInitializer);
fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer);
fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer);
setControl(result);
WorkbenchHelp.setHelp(result, new Object[] { IJavaHelpContextIds.JAVA_SEARCH_PAGE });
}
private Control createExpression(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 1;
result.setLayout(layout);
// Pattern combo
fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER);
fPattern.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handlePatternSelected();
}
});
fPattern.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
getContainer().setPerformActionEnabled(getPattern().length() > 0 && getContainer().hasValidScope());
}
});
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= convertWidthInCharsToPixels(30);
fPattern.setLayoutData(gd);
// Pattern info
Label label= new Label(result, SWT.LEFT);
label.setText(SearchMessages.getString("SearchPage.expression.pattern")); //$NON-NLS-1$
return result;
}
private void handlePatternSelected() {
if (fPattern.getSelectionIndex() < 0)
return;
int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex();
SearchPatternData values= (SearchPatternData) fgPreviousSearchPatterns.get(index);
for (int i= 0; i < fSearchFor.length; i++)
fSearchFor[i].setSelection(false);
for (int i= 0; i < fLimitTo.length; i++)
fLimitTo[i].setSelection(false);
fSearchFor[values.searchFor].setSelection(true);
setLimitTo(values.searchFor);
fLimitTo[values.limitTo].setSelection(true);
fInitialPattern= values.pattern;
fPattern.setText(fInitialPattern);
fJavaElement= values.javaElement;
if (values.workingSet != null)
getContainer().setSelectedWorkingSet(values.workingSet);
else
getContainer().setSelectedScope(values.scope);
}
private Control createSearchFor(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 3;
result.setLayout(layout);
result.setLayoutData(new GridData(GridData.FILL_VERTICAL));
fSearchFor= new Button[fSearchForText.length];
for (int i= 0; i < fSearchForText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fSearchForText[i]);
fSearchFor[i]= button;
}
return result;
}
private Control createLimitTo(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 2;
result.setLayout(layout);
fLimitTo= new Button[fLimitToText.length];
for (int i= 0; i < fLimitToText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fLimitToText[i]);
fLimitTo[i]= button;
}
return result;
}
private void initSelections() {
fJavaElement= null;
ISelection selection= getSelection();
SearchPatternData values= null;
values= tryTypedTextSelection(selection);
if (values == null)
values= trySelection(selection);
if (values == null)
values= trySimpleTextSelection(selection);
if (values == null)
values= getDefaultInitValues();
fSearchFor[values.searchFor].setSelection(true);
setLimitTo(values.searchFor);
fLimitTo[values.limitTo].setSelection(true);
fInitialPattern= values.pattern;
fPattern.setText(fInitialPattern);
fJavaElement= values.javaElement;
}
private SearchPatternData tryTypedTextSelection(ISelection selection) {
if (selection instanceof ITextSelection) {
IEditorPart e= getEditorPart();
if (e != null) {
ITextSelection ts= (ITextSelection)selection;
ICodeAssist assist= getCodeAssist(e);
if (assist != null) {
IJavaElement[] elements= null;
try {
elements= assist.codeSelect(ts.getOffset(), ts.getLength());
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.createJavaElement.title"), SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-2$ //$NON-NLS-1$
}
if (elements != null && elements.length > 0) {
if (elements.length == 1)
fJavaElement= elements[0];
else
fJavaElement= chooseFromList(elements);
if (fJavaElement != null)
return determineInitValuesFrom(fJavaElement);
}
}
}
}
return null;
}
private ICodeAssist getCodeAssist(IEditorPart editorPart) {
IEditorInput input= editorPart.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input);
}
private SearchPatternData trySelection(ISelection selection) {
SearchPatternData result= null;
if (selection == null)
return result;
Object o= null;
if (selection instanceof IStructuredSelection)
o= ((IStructuredSelection)selection).getFirstElement();
if (o instanceof IJavaElement) {
fJavaElement= (IJavaElement)o;
result= determineInitValuesFrom(fJavaElement);
} else if (o instanceof ISearchResultViewEntry) {
fJavaElement= getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker());
result= determineInitValuesFrom(fJavaElement);
} else if (o instanceof IAdaptable) {
IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class);
if (element != null) {
result= determineInitValuesFrom(element);
} else {
IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class);
result= new SearchPatternData(TYPE, REFERENCES, adapter.getLabel(o), null);
}
}
return result;
}
private IJavaElement getJavaElement(IMarker marker) {
try {
return JavaCore.create((String)marker.getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID));
} catch (CoreException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.createJavaElement.title"), SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-2$ //$NON-NLS-1$
return null;
}
}
private SearchPatternData determineInitValuesFrom(IJavaElement element) {
if (element == null)
return null;
int searchFor= UNKNOWN;
int limitTo= UNKNOWN;
String pattern= null;
switch (element.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.PACKAGE_DECLARATION:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.IMPORT_DECLARATION:
pattern= element.getElementName();
IImportDeclaration declaration= (IImportDeclaration)element;
if (declaration.isOnDemand()) {
searchFor= PACKAGE;
int index= pattern.lastIndexOf('.');
pattern= pattern.substring(0, index);
} else {
searchFor= TYPE;
}
limitTo= DECLARATIONS;
break;
case IJavaElement.TYPE:
searchFor= TYPE;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName((IType)element);
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit cu= (ICompilationUnit)element;
String mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$
IType mainType= cu.getType(mainTypeName);
mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType);
try {
mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName);
if (mainType == null) {
// fetch type which is declared first in the file
IType[] types= cu.getTypes();
if (types.length > 0)
mainType= types[0];
else
break;
}
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
searchFor= TYPE;
element= mainType;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName((IType)mainType);
break;
case IJavaElement.CLASS_FILE:
IClassFile cf= (IClassFile)element;
try {
mainType= cf.getType();
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
if (mainType == null)
break;
element= mainType;
searchFor= TYPE;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName(mainType);
break;
case IJavaElement.FIELD:
searchFor= FIELD;
limitTo= REFERENCES;
IType type= ((IField)element).getDeclaringType();
StringBuffer buffer= new StringBuffer();
buffer.append(JavaModelUtil.getFullyQualifiedName(type));
buffer.append('.');
buffer.append(element.getElementName());
pattern= buffer.toString();
break;
case IJavaElement.METHOD:
searchFor= METHOD;
try {
IMethod method= (IMethod)element;
if (method.isConstructor())
searchFor= CONSTRUCTOR;
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
limitTo= REFERENCES;
pattern= PrettySignature.getMethodSignature((IMethod)element);
break;
}
if (searchFor != UNKNOWN && limitTo != UNKNOWN && pattern != null)
return new SearchPatternData(searchFor, limitTo, pattern, element);
return null;
}
private SearchPatternData trySimpleTextSelection(ISelection selection) {
SearchPatternData result= null;
if (selection instanceof ITextSelection) {
BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText()));
String text;
try {
text= reader.readLine();
if (text == null)
text= ""; //$NON-NLS-1$
} catch (IOException ex) {
text= ""; //$NON-NLS-1$
}
result= new SearchPatternData(TYPE, REFERENCES, text, null);
}
return result;
}
private SearchPatternData getDefaultInitValues() {
return new SearchPatternData(TYPE, REFERENCES, "", null); //$NON-NLS-1$
}
private IJavaElement chooseFromList(IJavaElement[] openChoices) {
int flags= JavaElementLabelProvider.SHOW_DEFAULT | JavaElementLabelProvider.SHOW_QUALIFIED;
ILabelProvider labelProvider= new JavaElementLabelProvider(flags);
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setTitle(SearchMessages.getString("SearchElementSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(SearchMessages.getString("SearchElementSelectionDialog.message")); //$NON-NLS-1$
dialog.setElements(openChoices);
if (dialog.open() == dialog.OK)
return (IJavaElement)dialog.getFirstResult();
return null;
}
/*
* Implements method from ISearchPage
*/
public void setContainer(ISearchPageContainer container) {
fContainer= container;
}
/**
* Returns the search page's container.
*/
private ISearchPageContainer getContainer() {
return fContainer;
}
/**
* Returns the current active selection.
*/
private ISelection getSelection() {
return fContainer.getSelection();
}
/**
* Returns the current active editor part.
*/
private IEditorPart getEditorPart() {
IWorkbenchWindow window= JavaPlugin.getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page= window.getActivePage();
if (page != null)
return page.getActiveEditor();
}
return null;
}
} |
6,765 | Bug 6765 Type hierarchy missing buttons when in "Hierarchy View Only" mode | Build 20011206, Win2000 Steps: 1) Put the type hierarchy view in "Hierarchy View Only" 2) Shutdown the workbench and restart 3) The type hierarchy is now missing its toolbar buttons, the ones that cycle between the different type hierarchy modes. Workaround is to switch to "Vertical Viewer Orientation", then back to "Hierarchy View Only", then the buttons reappear. Side note: This seems to be the only place in the UI that the term "Viewer" is used. Maybe it should say "Vertical View Orientation", etc. There's probably a JFace viewer underneath, but users are only aware of views, not viewers. | resolved fixed | edd94b3 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T16:23:22Z" | "2001-12-10T21:33:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
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.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.IInputSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.help.ViewContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.compare.JavaReplaceWithEditionAction;
import org.eclipse.jdt.internal.ui.dnd.BasicSelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.BuildGroup;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of inut elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private IProblemChangedListener fHierarchyProblemListener;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private MethodsViewer fMethodsViewer;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private boolean fIsEnableMemberFilter;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaElementLabelProvider fPaneLabelProvider;
private IDialogSettings fDialogSettings;
private ToggleViewAction[] fViewActions;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private int fCurrentOrientation;
private EnableMemberFilterAction fEnableMemberFilterAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private IPartListener fPartListener;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fHierarchyProblemListener= null;
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fHistoryDropDownAction= new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions= new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS);
fPaneLabelProvider.setErrorTickManager(new MarkerErrorTickProvider());
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {}
public void partClosed(IWorkbenchPart part) {}
public void partDeactivated(IWorkbenchPart part) {}
public void partOpened(IWorkbenchPart part) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list
*/
public void selectMember(IMember member) {
ICompilationUnit cu= member.getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
member= (IMember) cu.getOriginal(member);
if (member == null) {
return;
}
}
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
fMethodsViewer.getControl().setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(element);
}
if (element.getElementType() == IJavaElement.METHOD || element.getElementType() == IJavaElement.FIELD || element.getElementType() == IJavaElement.INITIALIZER) {
element= ((IMember) element).getDeclaringType();
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
// turn off member filtering
enableMemberFilter(false);
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement);
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
fPagebook.showPage(fTypeMethodsSplitter);
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer();
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
}
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer();
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
getSite().getPage().removePartListener(fPartListener);
if (fHierarchyProblemListener != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener);
}
if (fMethodsViewer != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fMethodsViewer);
}
super.dispose();
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
HierarchyLabelProvider lprovider= new HierarchyLabelProvider(this, new MarkerErrorTickProvider());
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, lprovider, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F4) {
OpenTypeHierarchyUtil.open(getSite().getSelectionProvider().getSelection(), getSite().getWorkbenchWindow());
return;
} else if (event.keyCode == SWT.F5) {
updateHierarchyViewer();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addSelectionChangedListener(fSelectionChangedListener);
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fMethodsViewer);
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_COPY;
DragSource source= new DragSource(fMethodsViewer.getControl(), ops);
source.setTransfer(transfers);
source.addDragListener(new BasicSelectionTransferDragAdapter(fMethodsViewer));
for (int i= 0; i < fAllViewers.length; i++) {
TypeHierarchyViewer curr= fAllViewers[i];
curr.addDropSupport(ops, transfers, new TypeHierarchyTransferDropAdapter(curr));
}
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
initDragAndDrop();
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
int orientation;
try {
orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if (orientation < 0 || orientation > 2) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation= -1;
// will fill the main tool bar
setOrientation(orientation);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
IJavaElement input= determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
// fixed for 1GETAYN: ITPJUI:WIN - F1 help does nothing
WorkbenchHelp.setHelp(fPagebook, new ViewContextComputer(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW));
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
updateMainToolbar(horizontal);
}
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(boolean horizontal) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (horizontal) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
viewer.contributeToContextMenu(menu);
IStructuredSelection selection= (IStructuredSelection)viewer.getSelection();
if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) {
addOpenPerspectiveItem(menu, selection);
}
addOpenWithMenu(menu, selection);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnTypeAction);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fFocusOnSelectionAction);
addRefactoring(menu, viewer);
ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, viewer);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
//menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer));
addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection());
addRefactoring(menu, fMethodsViewer);
ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(), new ReorgGroup() }, fMethodsViewer);
}
private void addRefactoring(IMenuManager menu, IInputSelectionProvider viewer){
MenuManager refactoring= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.refactor")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, viewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
Object element= selection.getFirstElement();
if (!(element instanceof IJavaElement))
return;
IResource resource= null;
try {
resource= ((IJavaElement)element).getUnderlyingResource();
} catch(JavaModelException e) {
// ignore
}
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
private void addOpenPerspectiveItem(IMenuManager menu, IStructuredSelection selection) {
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, selection);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
updateHierarchyViewer();
updateTitle();
internalSelectType(fSelectedType, true);
}
private IType getSelectableType(IJavaElement elem) {
ISelection sel= null;
if (elem.getElementType() != IJavaElement.TYPE) {
return (IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem, boolean reveal) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(fSelectionChangedListener);
}
private void internalSelectMember(IMember member) {
fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener);
fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY);
fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer() {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent();
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(IType input) {
if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
fMethodsViewer.setInput(input);
}
}
private void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
} else {
typeSelectionChanged(e.getSelection());
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
try {
getSite().getPage().removePartListener(fPartListener);
EditorUtility.openInEditor(elem, false);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer();
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement), false);
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
if (fHierarchyProblemListener != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fHierarchyProblemListener);
}
fHierarchyProblemListener= getCurrentViewer();
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fHierarchyProblemListener);
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput, true);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType, true);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
doTypeHierarchyChangedOnViewers(changedTypes);
}
});
}
}
private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (changedTypes == null) {
// hierarchy change
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement);
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
updateHierarchyViewer();
}
} else {
// elements in hierarchy modified
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer();
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
return (IJavaElement) input;
}
return null;
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
memento.putString(TAG_INPUT, fInputElement.getHandleIdentifier());
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fMethodsViewer.saveState(memento);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (!input.exists()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
String selectionId= memento.getString(TAG_SELECTION);
if (selectionId != null) {
IJavaElement elem= JavaCore.create(selectionId);
if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
internalSelectType((IMember)elem, false);
}
}
fMethodsViewer.restoreState(memento);
}
/**
* Link selection to active editor.
*/
private void editorActivated(IEditorPart editor) {
if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type, true);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i], true);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
} |
6,765 | Bug 6765 Type hierarchy missing buttons when in "Hierarchy View Only" mode | Build 20011206, Win2000 Steps: 1) Put the type hierarchy view in "Hierarchy View Only" 2) Shutdown the workbench and restart 3) The type hierarchy is now missing its toolbar buttons, the ones that cycle between the different type hierarchy modes. Workaround is to switch to "Vertical Viewer Orientation", then back to "Hierarchy View Only", then the buttons reappear. Side note: This seems to be the only place in the UI that the term "Viewer" is used. Maybe it should say "Vertical View Orientation", etc. There's probably a JFace viewer underneath, but users are only aware of views, not viewers. | resolved fixed | edd94b3 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-12T16:23:22Z" | "2001-12-10T21:33:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewer.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.actions.OpenJavaElementAction;
import org.eclipse.jdt.internal.ui.actions.ShowInPackageViewAction;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.wizards.NewGroup;
public abstract class TypeHierarchyViewer extends ProblemTreeViewer implements IProblemChangedListener {
private OpenJavaElementAction fOpen;
private ShowInPackageViewAction fShowInPackageViewAction;
private ContextMenuGroup[] fStandardGroups;
public TypeHierarchyViewer(Composite parent, IContentProvider contentProvider, ILabelProvider lprovider, IWorkbenchPart part) {
super(new Tree(parent, SWT.SINGLE));
setContentProvider(contentProvider);
setLabelProvider(lprovider);
setSorter(new ViewerSorter() {
public boolean isSorterProperty(Object element, Object property) {
return true;
}
public int category(Object element) {
if (element instanceof IType) {
try {
return (((IType)element).isInterface()) ? 2 : 1;
} catch (JavaModelException e) {
}
} else if (element instanceof IMember) {
return 0;
}
return 3;
}
});
fOpen= new OpenJavaElementAction(this);
addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fOpen.run();
}
});
fShowInPackageViewAction= new ShowInPackageViewAction();
fStandardGroups= new ContextMenuGroup[] {
new JavaSearchGroup(), new NewGroup(), new GenerateGroup()
};
}
/**
* Attaches a contextmenu listener to the tree
*/
public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(menuListener);
Menu menu= menuMgr.createContextMenu(getTree());
getTree().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
/**
* Fills up the context menu with items for the hierarchy viewer
* Should be called by the creator of the context menu
*/
public void contributeToContextMenu(IMenuManager menu) {
if (fOpen.canActionBeAdded()) {
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
}
// XXX need to decide when to contribute the Show in PackagesView action
// if (fShowInPackageViewAction.canOperateOn())
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fShowInPackageViewAction);
ContextMenuGroup.add(menu, fStandardGroups, this);
}
/**
* Set the member filter
*/
public void setMemberFilter(IMember[] memberFilter) {
getHierarchyContentProvider().setMemberFilter(memberFilter);
}
/**
* Returns if method filtering is enabled.
*/
public boolean isMethodFiltering() {
return getHierarchyContentProvider().getMemberFilter() != null;
}
/**
* Returns true if the hierarchy contains elements. Returns one of them
* With member filtering it is possible that no elements are visible
*/
public Object containsElements() {
Object[] elements= ((IStructuredContentProvider)getContentProvider()).getElements(null);
if (elements.length > 0) {
return elements[0];
}
return null;
}
/**
* Returns true if the hierarchy contains elements. Returns one of them
* With member filtering it is possible that no elements are visible
*/
public IType getTreeRootType() {
Object[] elements= ((IStructuredContentProvider)getContentProvider()).getElements(null);
if (elements.length > 0 && elements[0] instanceof IType) {
return (IType) elements[0];
}
return null;
}
/**
* Returns true if the hierarchy contains element the element.
*/
public boolean isElementShown(Object element) {
return findItem(element) != null;
}
/**
* Updates the content of this viewer: refresh and expanding the tree in the way wanted.
*/
public abstract void updateContent();
/**
* Returns the title for the current view
*/
public abstract String getTitle();
/*
* @see StructuredViewer#setContentProvider
* Content provider must be of type TypeHierarchyContentProvider
*/
public void setContentProvider(IContentProvider cp) {
Assert.isTrue(cp instanceof TypeHierarchyContentProvider);
super.setContentProvider(cp);
}
protected TypeHierarchyContentProvider getHierarchyContentProvider() {
return (TypeHierarchyContentProvider)getContentProvider();
}
} |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddMethodStubOperation.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/IImplementMethodQuery.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/core | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddUnimplementedMethodsAction.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* Evaluates unimplemented methods of a type.
* Will open an editor for the type. Changes are unsaved.
*/
public class AddUnimplementedMethodsAction extends Action {
private ISelectionProvider fSelectionProvider;
public AddUnimplementedMethodsAction(ISelectionProvider selProvider) {
super(JavaUIMessages.getString("AddUnimplementedMethodsAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddUnimplementedMethodsAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddUnimplementedMethodsAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= selProvider;
WorkbenchHelp.setHelp(this, new Object[] { IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION });
}
public void run() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
IType type= getSelectedType();
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), JavaUIMessages.getString("AddUnimplementedMethodsAction.error.type_removed_in_editor")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedMethodsOperation op= new AddUnimplementedMethodsOperation(type, settings, false);
try {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), JavaUIMessages.getString("AddUnimplementedMethodsAction.error.nothing_found")); //$NON-NLS-2$ //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), null, e.getStatus()); //$NON-NLS-1$
}
}
private IType getSelectedType() throws JavaModelException {
ISelection sel= fSelectionProvider.getSelection();
if (sel instanceof IStructuredSelection) {
Object[] elements= ((IStructuredSelection)sel).toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
}
return null;
}
public boolean canActionBeAdded() {
try {
return getSelectedType() != null;
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
return false;
}
} |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/ImplementMethodQuery.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenSuperImplementationAction.java |
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
/**
* On a selected method; opens the implementation in the super type (if existing)
*/
public class OpenSuperImplementationAction extends Action implements IUpdate, IObjectActionDelegate {
private StructuredSelectionProvider fSelectionProvider;
/**
* Use only for IWorkbenchWindowActionDelegates!
*/
public OpenSuperImplementationAction() {
this(null);
}
public OpenSuperImplementationAction(StructuredSelectionProvider provider) {
super();
setText(JavaUIMessages.getString("OpenSuperImplementationAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("OpenSuperImplementationAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("OpenSuperImplementationAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= provider;
}
public void update() {
setEnabled(canOperateOn());
}
private boolean canOperateOn() {
return getMethod() != null;
}
private IMethod getMethod() {
if (fSelectionProvider == null) {
return null;
}
IStructuredSelection selection= fSelectionProvider.getSelection(StructuredSelectionProvider.FLAGS_DO_ELEMENT_AT_OFFSET);
if (selection.size() != 1)
return null;
try {
Object element= selection.getFirstElement();
if (element instanceof IMethod) {
IMethod method= (IMethod) element;
if (method.exists()) {
int flags= method.getFlags();
if (!Flags.isStatic(flags) && !Flags.isPrivate(flags)) {
return method;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
public void run() {
IMethod method= getMethod();
if (method == null) {
return;
}
try {
IType declaringType= method.getDeclaringType();
ICompilationUnit cu= declaringType.getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
declaringType= (IType) cu.getOriginal(declaringType);
if (!declaringType.exists()) {
return;
}
}
ITypeHierarchy hierarchy= declaringType.newSupertypeHierarchy(null);
IMethod impl= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, method.getElementName(), method.getParameterTypes(), method.isConstructor());
if (impl != null) {
IEditorPart part= EditorUtility.openInEditor(impl);
EditorUtility.revealInEditor(part, impl);
}
} catch (CoreException e) {
JavaPlugin.log(e);
String title= JavaUIMessages.getString("OpenSuperImplementationAction.error.title");
String message= JavaUIMessages.getString("OpenSuperImplementationAction.error.message");
ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message, e.getStatus());
}
}
/*
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
run();
}
/*
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
}
/*
* @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
fSelectionProvider= StructuredSelectionProvider.createFrom(targetPart.getSite().getWorkbenchWindow().getSelectionService());
}
} |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/SelectionStatusDialog.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import java.util.Arrays;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
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.Shell;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.core.runtime.IStatus;
/**
* An abstract base class for dialogs with a status bar and ok/cancel buttons.
* The status message must be passed over as StatusInfo object and can be
* an error, warning or ok. The OK button is enabled or disabled depending
* on the status.
*/
public abstract class SelectionStatusDialog extends SelectionDialog {
private MessageLine fStatusLine;
private IStatus fLastStatus;
private Image fImage;
private boolean fStatusLineAboveButtons= false;
/**
* Creates an instance of a <code>SelectionStatusDialog</code>.
*/
public SelectionStatusDialog(Shell parent) {
super(parent);
}
/**
* Controls whether status line appears to the left of the buttons (default)
* or above them.
*
* @param aboveButtons if <code>true</code> status line is placed above buttons; if
* <code>false</code> to the right
*/
public void setStatusLineAboveButtons(boolean aboveButtons) {
fStatusLineAboveButtons= aboveButtons;
}
/**
* Sets the image for this dialog.
* @param image the image.
*/
public void setImage(Image image) {
fImage= image;
}
/**
* Returns the first element from the list of results. Returns <code>null</code>
* if no element has been selected.
*
* @return the first result element if one exists. Otherwise <code>null</code> is
* returned.
*/
public Object getFirstResult() {
Object[] result= getResult();
if (result == null || result.length == 0)
return null;
return result[0];
}
/**
* Sets a result element at the given position.
*/
protected void setResult(int position, Object element) {
Object[] result= getResult();
result[position]= element;
setResult(Arrays.asList(result));
}
/**
* Compute the result and return it.
*/
protected abstract void computeResult();
/*
* @see Window#configureShell(shell)
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
if (fImage != null)
shell.setImage(fImage);
}
/**
* Update the dialog's status line to reflect the given status. It is safe to call
* this method before the dialog has been opened.
*/
protected void updateStatus(IStatus status) {
fLastStatus= status;
if (fStatusLine != null && !fStatusLine.isDisposed()) {
updateButtonsEnableState(status);
StatusUtil.applyToStatusLine(fStatusLine, status);
}
}
/**
* Update the status of the ok button to reflect the given status. Subclasses
* may override this method to update additional buttons.
*/
protected void updateButtonsEnableState(IStatus status) {
Button okButton= getOkButton();
if (okButton != null && !okButton.isDisposed())
okButton.setEnabled(!status.matches(IStatus.ERROR));
}
/*
* @see Dialog#okPressed()
*/
protected void okPressed() {
computeResult();
super.okPressed();
}
/*
* @see Window#create()
*/
public void create() {
super.create();
if (fLastStatus != null)
updateStatus(fLastStatus);
}
/*
* @see Dialog#createButtonBar(Composite)
*/
protected Control createButtonBar(Composite parent) {
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
if (fStatusLineAboveButtons) {
layout.verticalSpacing= 0;
} else {
layout.numColumns= 2;
}
layout.marginHeight= 0; layout.marginWidth= 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fStatusLine= new MessageLine(composite);
fStatusLine.setAlignment(SWT.LEFT);
fStatusLine.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fStatusLine.setMessage(""); //$NON-NLS-1$
super.createButtonBar(composite);
return composite;
}
} |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java | package org.eclipse.jdt.internal.ui.text.java;
import java.util.ArrayList;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.textmanipulation.TextUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class AnonymousTypeCompletionProposal extends JavaCompletionProposal {
private IType fDeclaringType;
private ICompilationUnit fCompilationUnit;
private ImportsStructure fImportStructure;
public AnonymousTypeCompletionProposal(ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName) {
super(constructorCompletion, start, length, null, displayName);
Assert.isNotNull(cu);
Assert.isNotNull(declaringTypeName);
fCompilationUnit= cu;
fDeclaringType= getDeclaringType(cu.getJavaProject(), declaringTypeName);
setImage(getImageForType(fDeclaringType));
setCursorPosition(constructorCompletion.indexOf('(') + 1);
}
private Image getImageForType(IType type) {
String imageName= JavaPluginImages.IMG_OBJS_CLASS; // default
if (type != null) {
try {
if (type.isInterface()) {
imageName= JavaPluginImages.IMG_OBJS_INTERFACE;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return JavaPluginImages.get(imageName);
}
private IType getDeclaringType(IJavaProject project, String typeName) {
try {
return JavaModelUtil.findType(project, typeName);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/*
* @see JavaCompletionProposal#applyImports(IDocument)
*/
protected void applyImports(IDocument document) {
if (fImportStructure != null) {
try {
fImportStructure.create(false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger) {
try {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
fImportStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true);
String replacementString= getReplacementString();
// construct replacement text
StringBuffer buf= new StringBuffer();
buf.append(replacementString);
if (!replacementString.endsWith(")")) {
buf.append(')');
}
buf.append(" {\n");
createStubs(buf, fImportStructure);
buf.append("};");
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
int tabWidth= CodeFormatterPreferencePage.getTabSize();
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int indent= TextUtil.getIndent(document.get(region.getOffset(), region.getLength()), tabWidth);
String replacement= StubUtility.codeFormat(buf.toString(), indent, lineDelim);
replacement= TextUtil.removeLeadingWhiteSpaces(replacement);
setReplacementString(replacement);
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
super.apply(document, trigger);
}
private void createStubs(StringBuffer buf, ImportsStructure imports) throws JavaModelException {
if (fDeclaringType == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ArrayList res= new ArrayList();
ITypeHierarchy hierarchy= fDeclaringType.newSupertypeHierarchy(null);
StubUtility.evalUnimplementedMethods(fDeclaringType, hierarchy, true, settings, res, imports);
for (int i= 0; i < res.size(); i++) {
buf.append((String) res.get(i));
buf.append('\n');
}
}
}
|
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java | |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/TypePage.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.compiler.env.IConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.text.template.Template;
import org.eclipse.jdt.internal.ui.text.template.Templates;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.swt.MGridData;
/**
* <code>TypePage</code> contains controls and validation routines for a 'New Type WizardPage'
* Implementors decide which components to add and to enable. Implementors can also
* customize the validation code.
* <code>TypePage</code> is intended to serve as base class of all wizards that create types.
* Applets, Servlets, Classes, Interfaces...
* See <code>NewClassCreationWizardPage</code> or <code>NewInterfaceCreationWizardPage</code> for an
* example usage of TypePage.
*/
public abstract class TypePage extends ContainerPage {
private final static String PAGE_NAME= "TypePage"; //$NON-NLS-1$
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPlugin.getDefault().getImageRegistry().get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
public TypePage(boolean isClass, String pageName, IWorkspaceRoot root) {
super(pageName, root);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("TypePage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("TypePage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("TypePage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("TypePage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("TypePage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("TypePage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("TypePage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("TypePage.interfaces.class.label") : NewWizardMessages.getString("TypePage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("TypePage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("TypePage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("TypePage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("TypePage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("TypePage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("TypePage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("TypePage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the type page with a given
* Java element as selection.
* @param elem The initial selection of this page or null if no
* selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= JavaModelUtil.findPrimaryType(cu);
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
// ignore this exception now
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName("", true); //$NON-NLS-1$
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, 4);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the enclosing type name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
fEnclosingTypeSelection.doFillIntoGrid(composite, 1);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
MGridData gd= new MGridData(MGridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
c= fEnclosingTypeDialogField.getChangeControl(composite);
c.setLayoutData(new MGridData(MGridData.HORIZONTAL_ALIGN_FILL));
}
/**
* Creates the controls for the type name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
MGridData gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new MGridData(MGridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the superclass name field.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
MGridData gd= (MGridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the container if empty, elso on type name.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(DialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(DialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/**
* Called whenever a content of a field has changed.
* Implementors of TypePage can hook in.
* @see ContainerPage#handleFieldChanged
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Gets the text of package field.
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Gets the text of enclosing type field.
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
* @return Returns <code>null</code> if the input could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment.
* This will update model and the text of the control.
* @param canBeModified Selects if the package fragment can be changed by the user
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the encloding type corresponding to the current input.
* @return Returns <code>null</code> if enclosing type is not selected or the input could not
* be resolved.
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the package fragment.
* This will update model and the text of the control.
* @param canBeModified Selects if the enclosing type can be changed by the user
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns <code>true</code> if the enclosing type selection check box is enabled.
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type selection checkbox.
* @param canBeModified Selects if the enclosing type selection can be changed by the user
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Gets the type name.
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name.
* @param canBeModified Selects if the type name can be changed by the user
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Gets the selected modifiers.
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= IConstants.AccPublic;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= IConstants.AccPrivate;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= IConstants.AccProtected;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= IConstants.AccAbstract;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= IConstants.AccFinal;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= IConstants.AccStatic;
}
return mdf;
}
/**
* Sets the modifiers.
* @param canBeModified Selects if the modifiers can be changed by the user
* @see IConstants
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Gets the content of the super class text field.
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
* @param canBeModified Selects if the super class can be changed by the user
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Gets the currently chosen super interfaces.
* @return returns a list of String
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
* @param interfacesNames a list of String
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
// ----------- validation ----------
/**
* Called when the package field has changed.
* The method validates the package name and returns the status of the validation
* This also updates the package fragment model.
* Can be extended to add more validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
IPackageFragment pack= root.getPackageFragment(packName);
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= pack.getUnderlyingResource().getFullPath();
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("TypePage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
// let pass
}
fCurrPackage= pack;
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= fPackageDialogField.getText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("TypePage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Called when the enclosing type name has changed.
* The method validates the enclosing type and returns the status of the validation
* This also updates the enclosing type model.
* Can be extended to add more validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= JavaModelUtil.findType(root.getJavaProject(), enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("TypePage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e.getStatus());
return status;
}
}
/**
* Called when the type name has changed.
* The method validates the type name and returns the status of the validation.
* Can be extended to add more validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("TypePage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("TypePage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("TypePage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.exists()) {
status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("TypePage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Called when the superclass name has changed.
* The method validates the superclass name and returns the status of the validation.
* Can be extended to add more validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (!val.isOK()) {
status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("TypePage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("TypePage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e.getStatus());
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= JavaModelUtil.findType(jproject, res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= JavaModelUtil.findType(jproject, packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= JavaModelUtil.findType(jproject, sclassName);
}
}
return type;
}
/**
* Called when the list of super interface has changed.
* The method validates the superinterfaces and returns the status of the validation.
* Can be extended to add more validation.
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= JavaModelUtil.findType(root.getJavaProject(), intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("TypePage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Called when the modifiers have changed.
* The method validates the modifiers and returns the status of the validation.
* Can be extended to add more validation.
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("TypePage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("TypePage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("TypePage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
if (fCurrPackage != null) {
dialog.setInitialSelections(new Object[] { fCurrPackage });
}
if (dialog.open() == dialog.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_TYPES);
dialog.setTitle(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
if (fCurrEnclosingType != null) {
dialog.setInitialSelections(new Object[] { fCurrEnclosingType });
dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1));
}
if (dialog.open() == dialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES);
dialog.setTitle(NewWizardMessages.getString("TypePage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.SuperClassDialog.message")); //$NON-NLS-1$
if (fSuperClass != null) {
dialog.setFilter(fSuperClass.getElementName());
}
if (dialog.open() == dialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(NewWizardMessages.getString("TypePage.InterfacesDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("TypePage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates a type using the current field values.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
monitor.beginTask(NewWizardMessages.getString("TypePage.operationdesc"), 10); //$NON-NLS-1$
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= fTypeNameDialogField.getText();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsStructure imports;
int indent= 0;
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
String lineDelimiter= null;
if (!isInnerClass) {
ICompilationUnit parentCU= pack.getCompilationUnit(clName + ".java"); //$NON-NLS-1$
imports= new ImportsStructure(parentCU, prefOrder, threshold, false);
lineDelimiter= StubUtility.getLineDelimiterUsed(parentCU);
String content= createTypeBody(imports, lineDelimiter);
createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 5));
String fileComment= getFileComment();
if (fileComment != null) {
parentCU.getBuffer().replace(0, 0, fileComment + lineDelimiter);
}
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsStructure(parentCU, prefOrder, threshold, true);
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
String content= createTypeBody(imports, lineDelimiter);
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so the type can be parsed correctly
imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1));
String[] methods= evalMethods(createdType, imports, new SubProgressMonitor(monitor, 1));
if (methods.length > 0) {
for (int i= 0; i < methods.length; i++) {
createdType.createMethod(methods[i], null, false, null);
}
// add imports
imports.create(!isInnerClass, null);
}
monitor.worked(1);
ICompilationUnit cu= createdType.getCompilationUnit();
ISourceRange range;
if (isInnerClass) {
synchronized(cu) {
cu.reconcile();
}
range= createdType.getSourceRange();
} else {
range= cu.getSourceRange();
}
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter);
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
buf.save(new SubProgressMonitor(monitor, 1), false);
} else {
monitor.worked(1);
}
fCreatedType= createdType;
monitor.done();
}
/**
* Returns the created type. Only valid after createType has been invoked
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, IImportsStructure imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
buf.append(Signature.getSimpleName(typename));
if (fSuperClass != null) {
imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass));
} else {
imports.addImport(typename);
}
}
}
private void writeSuperInterfaces(StringBuffer buf, IImportsStructure imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
imports.addImport(typename);
buf.append(Signature.getSimpleName(typename));
if (i < last) {
buf.append(", "); //$NON-NLS-1$
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String createTypeBody(IImportsStructure imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
String typeComment= getTypeComment();
if (typeComment != null) {
buf.append(typeComment);
buf.append(lineDelimiter);
}
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append(" {"); //$NON-NLS-1$
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* Called from createType to allow adding methods for the newly created type
* Returns array of sources of the methods that have to be added
* @param parent The type where the methods will be added to
*/
protected String[] evalMethods(IType parent, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return new String[0];
}
/**
* Called from createType to get a file comment. By default the content of template
* 'filecomment' is taken.
* Returns source or null, if no file comment should be added
*/
protected String getFileComment() {
if (CodeGenerationPreferencePage.doFileComments()) {
return getTemplate("filecomment");
}
return null;
}
/**
* Called from createType to get a type comment.
* Returns source or null, if no type comment should be added
*/
protected String getTypeComment() {
if (CodeGenerationPreferencePage.doCreateComments()) {
return getTemplate("typecomment");
}
return null;
}
protected String getTemplate(String name) {
Template[] templates= Templates.getInstance().getTemplates();
for (int i= 0; i < templates.length; i++) {
if (name.equals(templates[i].getName())) {
return templates[i].getPattern();
}
}
return null;
}
/**
* Creates the bodies of all unimplemented methods or/and all constructors
* Can be used by implementors of TypePage to add method stub checkboxes
*/
protected String[] constructInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
List newMethods= new ArrayList();
ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
StubUtility.evalConstructors(type, superclass, settings, newMethods, imports);
}
}
if (doUnimplementedMethods) {
StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, newMethods, imports);
}
return (String[]) newMethods.toArray(new String[newMethods.size()]);
}
// ---- creation ----------------
/**
* @see NewElementWizardPage#getRunnable
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
} |
6,638 | Bug 6638 "Add Method Overrides" menu pick | It would be nice to have an "Add Method Overrides" menu pick (analogous to the "Add Unimplemented Methods" menu pick in certain context menus) that would bring up a selection box of currently-unoverridden base-class methods and insert stubs for the selected methods. | verified fixed | 3042550 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T18:58:39Z" | "2001-12-06T14:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/ITypeHierarchyViewPart.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui;
import org.eclipse.ui.IViewPart;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
/**
* The standard type hierarchy view presents a type hierarchy for a given input class
* or interface. Visually, this view consists of a pair of viewers, one showing the type
* hierarchy, the other showing the members of the type selected in the first.
* <p>
* This interface is not intended to be implemented by clients.
* </p>
*
* @see JavaUI#ID_TYPE_HIERARCHY
*/
public interface ITypeHierarchyViewPart extends IViewPart {
/**
* Sets the input element of this type hierarchy view to a type.
*
* @param type the input element of this type hierarchy view, or <code>null</code>
* to clear any input element
* @deprecated use getInputElement instead
*/
public void setInput(IType type);
/**
* Sets the input element of this type hierarchy view. The element must be of type
* <code>IType</code> or <code>IPackageFragment</code>.
*
* @param type the input element of this type hierarchy view, or <code>null</code>
* to clear any input element
*/
public void setInputElement(IJavaElement element);
/**
* Returns the input element of this type hierarchy view
*
* @return the input element, or <code>null</code> if no input element is set
* or the input is not a type
* @see #setInput
* @deprecated use getInputElement instead
*/
public IType getInput();
/**
* Returns the input element of this type hierarchy view.
*
* @return the input element, or <code>null</code> if no input element is set
* @see #setInput
*/
public IJavaElement getInputElement();
} |
5,458 | Bug 5458 Add unimplemented deprecated methods | Build 20011025 (aka 206) When generating stubs for unimplemented methods, the @deprecated tag should be inserted in case the method to implement was itself deprecated. | resolved fixed | 6e01756 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T19:20:01Z" | "2001-11-02T11:20:00Z" | org.eclipse.jdt.ui/core | |
5,458 | Bug 5458 Add unimplemented deprecated methods | Build 20011025 (aka 206) When generating stubs for unimplemented methods, the @deprecated tag should be inserted in case the method to implement was itself deprecated. | resolved fixed | 6e01756 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T19:20:01Z" | "2001-11-02T11:20:00Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java | |
5,458 | Bug 5458 Add unimplemented deprecated methods | Build 20011025 (aka 206) When generating stubs for unimplemented methods, the @deprecated tag should be inserted in case the method to implement was itself deprecated. | resolved fixed | 6e01756 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T19:20:01Z" | "2001-11-02T11:20:00Z" | org.eclipse.jdt.ui/core | |
5,458 | Bug 5458 Add unimplemented deprecated methods | Build 20011025 (aka 206) When generating stubs for unimplemented methods, the @deprecated tag should be inserted in case the method to implement was itself deprecated. | resolved fixed | 6e01756 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-13T19:20:01Z" | "2001-11-02T11:20:00Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddMethodStubOperation.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/IImplementMethodQuery.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/IOverrideMethodQuery.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/core | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddMethodStubAction.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.corext.codemanipulation.AddMethodStubOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Creates method stubs in a type.
* The type has to be set before usage (init)
* Always forces the type to open in an editor. The result is unsaved,
* so the user can decide if the changes are acceptable.
*/
public class AddMethodStubAction extends Action {
private ISelection fSelection;
private IType fParentType;
public AddMethodStubAction() {
super(JavaUIMessages.getString("AddMethodStubAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddMethodStubAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddMethodStubAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, new Object[] { IJavaHelpContextIds.ADD_METHODSTUB_ACTION });
}
public boolean init(IType parentType, ISelection selection) {
if (canActionBeAdded(parentType, selection)) {
fParentType= parentType;
fSelection= selection;
if (parentType != null) {
setText(JavaUIMessages.getFormattedString("AddMethodStubAction.detailedlabel", parentType.getElementName())); //$NON-NLS-1$
} else {
setText(JavaUIMessages.getString("AddMethodStubAction.label")); //$NON-NLS-1$
}
return true;
}
fParentType= null;
fSelection= null;
return false;
}
public void run() {
if (!canActionBeAdded(fParentType, fSelection)) {
return;
}
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(fParentType);
IType usedType= (IType)EditorUtility.getWorkingCopy(fParentType);
if (usedType == null) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddMethodStubAction.error.title"), JavaUIMessages.getString("AddMethodStubAction.error.type_removed_in_editor")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
List list= ((IStructuredSelection)fSelection).toList();
IMethod[] methods= (IMethod[]) list.toArray(new IMethod[list.size()]);
AddMethodStubOperation op= new AddMethodStubOperation(usedType, methods, settings, createOverrideQuery(), createReplaceQuery(), false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res != null && res.length > 0 && editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddMethodStubAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
JavaPlugin.log(e.getTargetException());
} catch (CoreException e) {
ErrorDialog.openError(shell, JavaUIMessages.getString("AddMethodStubAction.error.title"), null, e.getStatus()); //$NON-NLS-1$
JavaPlugin.log(e.getStatus());
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
}
private IRequestQuery createOverrideQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String declTypeName= JavaElementLabels.getElementLabel(method.getDeclaringType(), 0);
String formattedMessage;
try {
if (Flags.isFinal(method.getFlags())) {
formattedMessage= JavaUIMessages.getFormattedString("AddMethodStubAction.OverridesFinalDialog.message", new String[] { methodName, declTypeName }); //$NON-NLS-1$
} else {
formattedMessage= JavaUIMessages.getFormattedString("AddMethodStubAction.OverridesPrivateDialog.message", new String[] { methodName, declTypeName }); //$NON-NLS-1$
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
return IRequestQuery.CANCEL;
}
return showQueryDialog(formattedMessage);
}
};
}
private IRequestQuery createReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= JavaUIMessages.getFormattedString("AddMethodStubAction.ReplaceExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage);
}
};
}
private int showQueryDialog(final String message) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
final Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddMethodStubAction.showQueryDialog: No active shell found");
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= JavaUIMessages.getString("AddMethodStubAction.QueryDialog.title"); //$NON-NLS-1$
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.CANCEL_LABEL};
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, options, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
/**
* Tests if the action can run with given arguments
*/
public static boolean canActionBeAdded(IType parentType, ISelection selection) {
if (parentType == null || parentType.getCompilationUnit() == null ||
!(selection instanceof IStructuredSelection) || selection.isEmpty()) {
return false;
}
Object[] elems= ((IStructuredSelection)selection).toArray();
int nSelected= elems.length;
if (nSelected > 0) {
for (int i= 0; i < nSelected; i++) {
Object elem= elems[i];
if (!(elem instanceof IMethod)) {
return false;
}
IMethod meth= (IMethod)elem;
if (meth.getDeclaringType().equals(parentType)) {
return false;
}
}
return true;
}
return false;
}
} |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddUnimplementedMethodsAction.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Evaluates unimplemented methods of a type.
* Will open an editor for the type. Changes are unsaved.
*/
public class AddUnimplementedMethodsAction extends Action {
private ISelectionProvider fSelectionProvider;
public AddUnimplementedMethodsAction(ISelectionProvider selProvider) {
super(JavaUIMessages.getString("AddUnimplementedMethodsAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddUnimplementedMethodsAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddUnimplementedMethodsAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= selProvider;
WorkbenchHelp.setHelp(this, new Object[] { IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION });
}
public void run() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
IType type= getSelectedType();
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), JavaUIMessages.getString("AddUnimplementedMethodsAction.error.type_removed_in_editor")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
ImplementMethodQuery selectionQuery= new ImplementMethodQuery(shell, false);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedMethodsOperation op= new AddUnimplementedMethodsOperation(type, settings, selectionQuery, false);
try {
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), JavaUIMessages.getString("AddUnimplementedMethodsAction.error.nothing_found")); //$NON-NLS-2$ //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), null, e.getStatus()); //$NON-NLS-1$
}
}
private IType getSelectedType() throws JavaModelException {
ISelection sel= fSelectionProvider.getSelection();
if (sel instanceof IStructuredSelection) {
Object[] elements= ((IStructuredSelection)sel).toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
}
return null;
}
public boolean canActionBeAdded() {
try {
return getSelectedType() != null;
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
return false;
}
} |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/ImplementMethodQuery.java | package org.eclipse.jdt.internal.ui.actions;
import java.util.ArrayList;
import java.util.HashSet;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.corext.codemanipulation.IImplementMethodQuery;
import org.eclipse.jdt.internal.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
public class ImplementMethodQuery implements IImplementMethodQuery {
private static class ImplementMethodContentProvider implements ITreeContentProvider {
private Object[] fTypes;
private IMethod[] fMethods;
private final Object[] fEmpty= new Object[0];
/**
* Constructor for ImplementMethodContentProvider.
*/
public ImplementMethodContentProvider(IMethod[] methods, Object[] types) {
fMethods= methods;
fTypes= types;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IType) {
ArrayList result= new ArrayList(fMethods.length);
for (int i= 0; i < fMethods.length; i++) {
if (fMethods[i].getDeclaringType().equals(parentElement)) {
result.add(fMethods[i]);
}
}
return result.toArray();
}
return fEmpty;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IMethod) {
return ((IMethod)element).getDeclaringType();
}
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fTypes;
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
private static class ImplementMethodSorter extends ViewerSorter {
private IType[] fAllTypes;
public ImplementMethodSorter(ITypeHierarchy typeHierarchy) {
IType curr= typeHierarchy.getType();
IType[] superTypes= typeHierarchy.getAllSupertypes(curr);
fAllTypes= new IType[superTypes.length + 1];
fAllTypes[0]= curr;
System.arraycopy(superTypes, 0, fAllTypes, 1, superTypes.length);
}
/*
* @see ViewerSorter#compare(Viewer, Object, Object)
*/
public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof IType && e2 instanceof IType) {
if (e1.equals(e2)) {
return 0;
}
for (int i= 0; i < fAllTypes.length; i++) {
IType curr= fAllTypes[i];
if (curr.equals(e1)) {
return -1;
}
if (curr.equals(e2)) {
return 1;
}
}
}
return 0;
}
}
private class ImplementMethodValidator implements ISelectionValidator {
/*
* @see ISelectionValidator#validate(Object[])
*/
public IStatus validate(Object[] selection) {
int count= 0;
for (int i= 0; i < selection.length; i++) {
if (selection[i] instanceof IMethod) {
count++;
}
}
if (count == 0 && !fEmptySelectionAllowed) {
return new StatusInfo(IStatus.ERROR, "");
}
if (count == 1) {
return new StatusInfo(IStatus.INFO, count + " method selected.");
} else {
return new StatusInfo(IStatus.INFO, count + " methods selected.");
}
}
}
private boolean fEmptySelectionAllowed;
private Shell fShell;
public ImplementMethodQuery(Shell shell, boolean emptySelectionAllowed) {
fShell= shell;
fEmptySelectionAllowed= emptySelectionAllowed;
}
/*
* @see IImplementMethodQuery#select(IMethod[], IMethod[], ITypeHierarchy)
*/
public IMethod[] select(IMethod[] methods, IMethod[] defaultSelected, ITypeHierarchy typeHierarchy) {
HashSet types= new HashSet(methods.length);
for (int i= 0; i < methods.length; i++) {
types.add(methods[i].getDeclaringType());
}
Object[] typesArrays= types.toArray();
ViewerSorter sorter= new ImplementMethodSorter(typeHierarchy);
sorter.sort(null, typesArrays);
HashSet expanded= new HashSet(defaultSelected.length);
for (int i= 0; i < defaultSelected.length; i++) {
expanded.add(defaultSelected[i].getDeclaringType());
}
if (expanded.isEmpty() && typesArrays.length > 0) {
expanded.add(typesArrays[0]);
}
ILabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ITreeContentProvider cprovider= new ImplementMethodContentProvider(methods, typesArrays);
CheckedTreeSelectionDialog dialog= new CheckedTreeSelectionDialog(fShell, lprovider, cprovider);
dialog.setValidator(new ImplementMethodValidator());
dialog.setTitle("Implement Methods");
dialog.setMessage("&Select methods to implement:");
dialog.setInitialSelections(defaultSelected);
dialog.setExpandedElements(expanded.toArray());
dialog.setContainerMode(true);
dialog.setSize(60, 25);
dialog.setInput(this); // input does not matter
if (dialog.open() == dialog.OK) {
Object[] checkedElements= dialog.getResult();
ArrayList result= new ArrayList(checkedElements.length);
for (int i= 0; i < checkedElements.length; i++) {
Object curr= checkedElements[i];
if (curr instanceof IMethod) {
result.add(curr);
}
}
return (IMethod[]) result.toArray(new IMethod[result.size()]);
}
return null;
}
}
|
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OverrideMethodQuery.java | |
3,523 | Bug 3523 'Override in ...' should be renamed to 'Implement in...' for interfaces (1G4CNPH) | AK (11/13/00 12:30:39 PM) if i select a method in a superinterface of my class i want to "implement" it, not "override" it. however, since interfaces "extend" other interfaces, not "implement them", in interfaces you "override" methods from superinterfaces. (would have to check that one in the lang spec) NOTES: EG (24.07.2001 23:28:38) we have gone back and forth on the name, should do one more iteration. MA (07.08.2001 15:43:40) The name is 'Create in ...' now, and for works for interfaces / classes, for super or sub types. EG(13.08.2001 12:16:32) "Create in" isn't intuitive to me. Why can't the string be more sensitive? | verified fixed | 460d05b | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:35:21Z" | "2001-10-11T03:13:20Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java | package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.textmanipulation.TextUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.ImplementMethodQuery;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class AnonymousTypeCompletionProposal extends JavaCompletionProposal {
private IType fDeclaringType;
private ICompilationUnit fCompilationUnit;
private ImportsStructure fImportStructure;
public AnonymousTypeCompletionProposal(ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName) {
super(constructorCompletion, start, length, null, displayName);
Assert.isNotNull(cu);
Assert.isNotNull(declaringTypeName);
fCompilationUnit= cu;
fDeclaringType= getDeclaringType(cu.getJavaProject(), declaringTypeName);
setImage(getImageForType(fDeclaringType));
setCursorPosition(constructorCompletion.indexOf('(') + 1);
}
private Image getImageForType(IType type) {
String imageName= JavaPluginImages.IMG_OBJS_CLASS; // default
if (type != null) {
try {
if (type.isInterface()) {
imageName= JavaPluginImages.IMG_OBJS_INTERFACE;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return JavaPluginImages.get(imageName);
}
private IType getDeclaringType(IJavaProject project, String typeName) {
try {
return JavaModelUtil.findType(project, typeName);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/*
* @see JavaCompletionProposal#applyImports(IDocument)
*/
protected void applyImports(IDocument document) {
if (fImportStructure != null) {
try {
fImportStructure.create(false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger) {
try {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
fImportStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true);
String replacementString= getReplacementString();
// construct replacement text
StringBuffer buf= new StringBuffer();
buf.append(replacementString);
if (!replacementString.endsWith(")")) {
buf.append(')');
}
buf.append(" {\n");
if (!createStubs(buf, fImportStructure)) {
return;
}
buf.append("};");
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
int tabWidth= CodeFormatterPreferencePage.getTabSize();
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int indent= TextUtil.getIndent(document.get(region.getOffset(), region.getLength()), tabWidth);
String replacement= StubUtility.codeFormat(buf.toString(), indent, lineDelim);
replacement= TextUtil.removeLeadingWhiteSpaces(replacement);
setReplacementString(replacement);
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
super.apply(document, trigger);
}
private boolean createStubs(StringBuffer buf, ImportsStructure imports) throws JavaModelException {
if (fDeclaringType == null) {
return true;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ITypeHierarchy hierarchy= fDeclaringType.newSupertypeHierarchy(null);
ImplementMethodQuery selectionQuery= fDeclaringType.isClass() ? new ImplementMethodQuery(JavaPlugin.getActiveWorkbenchShell(), true) : null;
String[] unimplemented= StubUtility.evalUnimplementedMethods(fDeclaringType, hierarchy, true, settings, selectionQuery, imports);
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
buf.append(unimplemented[i]);
buf.append('\n');
}
return true;
}
return false;
}
}
|
6,903 | Bug 6903 1GOMQ6H:- NullPointerException when exporting to a jar | null | resolved fixed | 1324d10 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T14:36:44Z" | "2001-12-13T19:00:00Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.xml.sax.SAXException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IRunnableWithProgress {
private JarWriter fJarWriter;
private JarPackage fJarPackage;
private IFile[] fDescriptionFiles;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private MultiStatus fProblems;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackage jarPackage, Shell parent) {
this(parent);
fJarPackage= jarPackage;
}
/**
* Creates an instance of this class.
*
* @param descriptions an array with JAR package descriptions
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(IFile[] descriptions, Shell parent) {
this(parent);
fDescriptionFiles= descriptions;
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$
}
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
Iterator iter= fJarPackage.getSelectedElements().iterator();
while (iter.hasNext()) {
Object element= iter.next();
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= jProject.findPackageFragmentRoot(resource.getFullPath().uptoSegment(2));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResourceFiles(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else
exportContainer(progressMonitor, resource);
}
private void exportContainer(IProgressMonitor progressMonitor, IResource resource) throws java.lang.InterruptedException {
IResource[] children= null;
try {
children= ((IContainer) resource).members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", resource.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportResourceFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || (pkgRoot == null && !isInOutputFolder);
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(destinationPath.toString());
fJarWriter.write((IFile) resource, destinationPath);
} catch (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(classFilePath.toString());
fJarWriter.write(file, classFilePath);
}
} catch (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
Iterator iter= fJarPackage.getSelectedElements().iterator();
while (iter.hasNext())
exportElement(iter.next(), progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
if (isJavaFile(file)) {
// Java CU - search files with .class ending
boolean hasErrors= fJarPackage.hasCompileErrors(file);
boolean hasWarnings= fJarPackage.hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
fClassFilesMapContainer= classContainer;
}
ArrayList classFiles= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFiles == null || classFiles.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFiles.iterator();
}
else {
// resource - search file with same name
List binaryFiles= new ArrayList(1);
IFile cpFile= outputContainer.getFile(pathInJar);
if (cpFile.isAccessible()) {
if (!cpFile.isLocal(IResource.DEPTH_ZERO))
cpFile.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
binaryFiles.add(cpFile);
}
else {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceOnCasspathNotAccessible", cpFile.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return binaryFiles.iterator();
}
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fProblems.getSeverity() == IStatus.ERROR) {
String message= null;
if (fDescriptionFiles != null && fDescriptionFiles.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
// Create new status because we want another message - no API to set message
return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null);
}
return fProblems;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.exportErrors())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
if (fJarPackage != null)
singleRun(progressMonitor);
else {
int jarCount= fDescriptionFiles.length;
for (int i= 0; i < jarCount; i++) {
fJarPackage= readJarPackage(fDescriptionFiles[i]);
if (fJarPackage != null)
singleRun(progressMonitor);
}
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int totalWork= countSelectedElements();
progressMonitor.beginTask(JarPackagerMessages.getString("JarFileExportOperation.exporting"), totalWork); //$NON-NLS-1$
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
fJarWriter= new JarWriter(fJarPackage, fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getSelectedElements() == null || fJarPackage.getSelectedElements().size() == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.doesManifestExist()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
if (dirtyEditors.length > 0) {
List unsavedFiles= new ArrayList(dirtyEditors.length);
List selection= fJarPackage.getSelectedResources();
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFile.getFullPath()), null); //$NON-NLS-1$
}
}
}
if (!unsavedFiles.isEmpty())
return false;
}
return true;
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
JarPackageWriter objectStream= new JarPackageWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
objectStream.writeXML(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
if (fJarPackage.getDescriptionFile().isAccessible()) {
if (fJarPackage.canOverwriteDescription(fParentShell))
fJarPackage.getDescriptionFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getDescriptionFile().create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (objectStream != null)
objectStream.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
if (fJarPackage.getManifestFile().isAccessible()) {
if (fJarPackage.canOverwriteManifest(fParentShell))
fJarPackage.getManifestFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getManifestFile().create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
/**
* Reads the JAR package spec from file.
*/
protected JarPackage readJarPackage(IFile description) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(JarPackage.DESCRIPTION_EXTENSION));
JarPackage jarPackage= null;
JarPackageReader reader= null;
try {
reader= new JarPackageReader(description.getContents());
// Do not save - only generate JAR
jarPackage= reader.readXML();
jarPackage.setSaveManifest(false);
jarPackage.setSaveDescription(false);
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorReadingJarPackageFromDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorReadingFile", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} catch (SAXException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.badXmlFormat", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} finally {
if ((jarPackage == null || jarPackage.logWarnings()) && reader != null)
// AddWarnings
fProblems.addAll(reader.getWarnings());
try {
if (reader != null)
reader.close();
}
catch (IOException ex) {
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorClosingJarPackageDescriptionReader", description.getFullPath()), ex); //$NON-NLS-1$
}
}
return jarPackage;
}
}
|
6,691 | Bug 6691 Hierarchy View: Show inherited members + Show members | 20011206 (Win2K) - Open a deep hierarchy in a Hierarchy view (I opened the SWT Widget hierarchy) - Select a class that is low in the hierarchy and overrides at least one method from a superclass (I selected Table) - Click on the "Show inherited members" tool, so that you see all implementors of overridden methods (for example, in Table, you can see 3 implementors of callWindowProc(int, int, int) ) - Select more than one method with the same signature (for example, I had all 3 implementors of callWindowProc(int, int, int) selected). - Now selet the "Lock View and Show Members in Hierarchy" tool. You will have multiple versions of the method under each class that implements the method. There should only be one. | verified fixed | 93e12ef | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-14T16:51:56Z" | "2001-12-07T21:20:00Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyContentProvider.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
/**
* Base class for content providers for type hierarchy viewers.
* Implementors must override 'getTypesInHierarchy'.
* Java delta processing is also performed by the content provider
*/
public abstract class TypeHierarchyContentProvider implements ITreeContentProvider {
protected static final Object[] NO_ELEMENTS= new Object[0];
protected TypeHierarchyLifeCycle fTypeHierarchy;
protected IMember[] fMemberFilter;
protected boolean fShowAllTypes;
protected TreeViewer fViewer;
public TypeHierarchyContentProvider(TypeHierarchyLifeCycle lifecycle) {
fTypeHierarchy= lifecycle;
fMemberFilter= null;
fShowAllTypes= false;
}
/**
* Sets members to filter the hierarchy for. Set to <code>null</code> to disable member filtering.
* When member filtering is enabled, the hierarchy contains only types that contain
* an implementation of one of the filter members and the members themself.
* The hierarchy can be empty as well.
*/
public void setMemberFilter(IMember[] memberFilter) {
fMemberFilter= memberFilter;
}
/**
* The members to filter or <code>null</code> if member filtering is disabled.
*/
public IMember[] getMemberFilter() {
return fMemberFilter;
}
/**
* In member filtering mode, show all types even if they do not contain one
* of the filtered members
*/
public void showAllTypes(boolean show) {
fShowAllTypes= show;
}
protected final ITypeHierarchy getHierarchy() {
return fTypeHierarchy.getHierarchy();
}
/*
* Called for the root element
* @see IStructuredContentProvider#getElements
*/
public Object[] getElements(Object parent) {
ITypeHierarchy hierarchy= getHierarchy();
if (hierarchy != null) {
IType input= hierarchy.getType();
if (input != null) {
return new IType[] { input };
}
// opened on a region: dont show
}
return NO_ELEMENTS;
}
/**
* Hook to overwrite. Filter will be applied on the returned types
*/
protected abstract IType[] getTypesInHierarchy(IType type);
/*
* Called for the tree children.
* @see ITreeContentProvider#getChildren
*/
public Object[] getChildren(Object element) {
if (element instanceof IType) {
IType type= (IType)element;
IType[] childrenTypes= getTypesInHierarchy(type);
if (fMemberFilter != null) {
List children= new ArrayList();
addFilteredMembers(type, children);
addFilteredTypes(childrenTypes, children);
return children.toArray();
} else {
return childrenTypes;
}
}
return NO_ELEMENTS;
}
/*
* @see ITreeContentProvider#hasChildren
*/
public boolean hasChildren(Object element) {
if (element instanceof IType) {
IType type= (IType)element;
IType[] childrenTypes= getTypesInHierarchy(type);
if (fMemberFilter != null) {
List children= new ArrayList();
addFilteredMembers(type, children);
addFilteredTypes(childrenTypes, children);
return children.size() > 0;
} else {
return childrenTypes.length > 0;
}
}
return false;
}
private void addFilteredMembers(IType parent, List children) {
try {
IMethod[] methods= parent.getMethods();
for (int i= 0; i < fMemberFilter.length; i++) {
IMember member= fMemberFilter[i];
if (parent.equals(member.getDeclaringType())) {
children.add(member);
} else if (member instanceof IMethod) {
IMethod curr= (IMethod)member;
IMethod meth= JavaModelUtil.findMethod(curr.getElementName(), curr.getParameterTypes(), curr.isConstructor(), methods);
if (meth != null) {
children.add(meth);
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private void addFilteredTypes(IType[] types, List children) {
try {
for (int i= 0; i < types.length; i++) {
if (hasFilteredChildren(types[i])) {
children.add(types[i]);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private boolean hasFilteredChildren(IType type) throws JavaModelException {
if (fShowAllTypes) {
return true;
}
IMethod[] methods= type.getMethods();
for (int i= 0; i < fMemberFilter.length; i++) {
IMember member= fMemberFilter[i];
if (type.equals(member.getDeclaringType())) {
return true;
} else if (member instanceof IMethod) {
IMethod curr= (IMethod)member;
IMethod meth= JavaModelUtil.findMethod(curr.getElementName(), curr.getParameterTypes(), curr.isConstructor(), methods);
if (meth != null) {
return true;
}
}
}
IType[] childrenTypes= getTypesInHierarchy(type);
for (int i= 0; i < childrenTypes.length; i++) {
if (hasFilteredChildren(childrenTypes[i])) {
return true;
}
}
return false;
}
/*
* @see IContentProvider#inputChanged
*/
public void inputChanged(Viewer part, Object oldInput, Object newInput) {
Assert.isTrue(part instanceof TreeViewer);
fViewer= (TreeViewer)part;
}
/*
* @see IContentProvider#dispose
*/
public void dispose() {
}
/*
* @see ITreeContentProvider#getParent
*/
public Object getParent(Object element) {
return null;
}
} |
6,969 | Bug 6969 NPE in code formatter preference page | 20011206 Open the code formatter preference page Go to the style tab Go to the number of spaces... field Backspace until the field is empty NPE | resolved fixed | b340474 | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-17T10:23:25Z" | "2001-12-14T22:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeFormatterPreferencePage.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.formatter.CodeFormatter;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
/*
* The page for setting code formatter options
*/
public class CodeFormatterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_NEWLINE_OPENING_BRACES= "org.eclipse.jdt.core.formatter.newline.openingBrace";
private static final String PREF_NEWLINE_CONTROL_STATEMENT= "org.eclipse.jdt.core.formatter.newline.controlStatement";
private static final String PREF_NEWLINE_CLEAR_ALL= "org.eclipse.jdt.core.formatter.newline.clearAll";
private static final String PREF_NEWLINE_ELSE_IF= "org.eclipse.jdt.core.formatter.newline.elseIf";
private static final String PREF_NEWLINE_EMPTY_BLOCK= "org.eclipse.jdt.core.formatter.newline.emptyBlock";
private static final String PREF_LINE_SPLIT= "org.eclipse.jdt.core.formatter.lineSplit";
private static final String PREF_STYLE_COMPACT_ASSIGNEMENT= "org.eclipse.jdt.core.formatter.style.assignment";
private static final String PREF_TAB_CHAR= "org.eclipse.jdt.core.formatter.tabulation.char";
private static final String PREF_TAB_SIZE= "org.eclipse.jdt.core.formatter.tabulation.size";
// values
private static final String INSERT= "insert";
private static final String DO_NOT_INSERT= "do not insert";
private static final String COMPACT= "compact";
private static final String NORMAL= "normal";
private static final String TAB= "tab";
private static final String SPACE= "space";
private static final String CLEAR_ALL= "clear all";
private static final String PRESERVE_ONE= "preserve one";
private static String[] getAllKeys() {
return new String[] {
PREF_NEWLINE_OPENING_BRACES, PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL,
PREF_NEWLINE_ELSE_IF, PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT,
PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE
};
}
/**
* Gets the currently configured tab size
*/
public static int getTabSize() {
String string= (String) JavaCore.getOptions().get(PREF_TAB_SIZE);
return getIntValue(string, 4);
}
/**
* Gets the current compating assignement configuration
*/
public static boolean isCompactingAssignment() {
return COMPACT.equals(JavaCore.getOptions().get(PREF_STYLE_COMPACT_ASSIGNEMENT));
}
/**
* Gets the current compating assignement configuration
*/
public static boolean useSpaces() {
return SPACE.equals(JavaCore.getOptions().get(PREF_TAB_CHAR));
}
private static int getIntValue(String string, int dflt) {
try {
return Integer.parseInt(string);
} catch (NumberFormatException e) {
}
return dflt;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("CodeFormatterPreferencePage: value is null: " + key);
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
private static class ControlData {
private String fKey;
private String[] fValues;
public ControlData(String key, String[] values) {
fKey= key;
fValues= values;
}
public String getKey() {
return fKey;
}
public String getValue(boolean selection) {
int index= selection ? 0 : 1;
return fValues[index];
}
public String getValue(int index) {
return fValues[index];
}
public int getSelection(String value) {
for (int i= 0; i < fValues.length; i++) {
if (value.equals(fValues[i])) {
return i;
}
}
throw new IllegalArgumentException();
}
}
private Hashtable fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fTextBoxes;
private SelectionListener fButtonSelectionListener;
private ModifyListener fTextModifyListener;
private String fPreviewText;
private IDocument fPreviewDocument;
private Text fTabSizeTextBox;
private SourceViewer fSourceViewer;
public CodeFormatterPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
fCheckBoxes= new ArrayList();
fTextBoxes= new ArrayList();
fButtonSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
if (!e.widget.isDisposed()) {
controlChanged((Button) e.widget);
}
}
};
fTextModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (!e.widget.isDisposed()) {
textChanged((Text) e.widget);
}
}
};
fPreviewDocument= new Document();
fPreviewText= loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$
}
/*
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), new DialogPageContextComputer(this, IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE));
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
String[] insertNotInsert= new String[] { INSERT, DO_NOT_INSERT };
layout= new GridLayout();
layout.numColumns= 2;
Composite newlineComposite= new Composite(folder, SWT.NULL);
newlineComposite.setLayout(layout);
String label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, insertNotInsert);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, insertNotInsert);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, new String[] { CLEAR_ALL, PRESERVE_ONE } );
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, insertNotInsert);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, insertNotInsert);
layout= new GridLayout();
layout.numColumns= 2;
Composite lineSplittingComposite= new Composite(folder, SWT.NULL);
lineSplittingComposite.setLayout(layout);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$
addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT);
layout= new GridLayout();
layout.numColumns= 2;
Composite styleComposite= new Composite(folder, SWT.NULL);
styleComposite.setLayout(layout);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, new String[] { COMPACT, NORMAL } );
label= JavaUIMessages.getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, SPACE } );
label= JavaUIMessages.getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$
fTabSizeTextBox= addTextField(styleComposite, label, PREF_TAB_SIZE);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
item.setControl(newlineComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(lineSplittingComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_REF));
item.setControl(styleComposite);
fSourceViewer= createPreview(parent);
updatePreview();
return composite;
}
private SourceViewer createPreview(Composite parent) {
SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
previewViewer.configure(new JavaSourceViewerConfiguration(tools, null));
previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT));
previewViewer.getTextWidget().setTabs(Integer.parseInt((String) fWorkingValues.get(PREF_TAB_SIZE)));
previewViewer.setEditable(false);
previewViewer.setDocument(fPreviewDocument);
Control control= previewViewer.getControl();
GridData gdata= new GridData(GridData.FILL_BOTH);
gdata.widthHint= convertWidthInCharsToPixels(80);
gdata.heightHint= convertHeightInCharsToPixels(15);
control.setLayoutData(gdata);
return previewViewer;
}
private Button addCheckBox(Composite parent, String label, String key, String[] values) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
checkBox.addSelectionListener(fButtonSelectionListener);
fCheckBoxes.add(checkBox);
return checkBox;
}
private Text addTextField(Composite parent, String label, String key) {
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(new GridData());
Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
textBox.setData(key);
textBox.setLayoutData(new GridData());
String currValue= (String)fWorkingValues.get(key);
textBox.setText(String.valueOf(getIntValue(currValue, 1)));
textBox.setTextLimit(3);
textBox.addModifyListener(fTextModifyListener);
GridData gd= new GridData();
gd.widthHint= convertWidthInCharsToPixels(5);
textBox.setLayoutData(gd);
fTextBoxes.add(textBox);
return textBox;
}
private void controlChanged(Button button) {
ControlData data= (ControlData) button.getData();
boolean selection= button.getSelection();
String newValue= data.getValue(selection);
fWorkingValues.put(data.getKey(), newValue);
updatePreview();
if (PREF_TAB_CHAR.equals(data.getKey())) {
updateStatus(new StatusInfo());
if (selection) {
fTabSizeTextBox.setText((String)fWorkingValues.get(PREF_TAB_SIZE));
}
}
}
private void textChanged(Text textControl) {
String key= (String) textControl.getData();
String number= textControl.getText();
IStatus status= validatePositiveNumber(number);
if (!status.matches(IStatus.ERROR)) {
fWorkingValues.put(key, number);
}
if (PREF_TAB_SIZE.equals(key)) {
fSourceViewer.getTextWidget().setTabs(Integer.parseInt(number));
}
updateStatus(status);
updatePreview();
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
return super.performOk();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
updateControls();
super.performDefaults();
}
private String loadPreviewFile(String filename) {
String separator= System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer btxt= new StringBuffer(512);
BufferedReader rin= null;
try {
rin= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename)));
String line;
while ((line= rin.readLine()) != null) {
btxt.append(line);
btxt.append(separator);
}
} catch (IOException io) {
JavaPlugin.log(io);
} finally {
if (rin != null) {
try { rin.close(); } catch (IOException e) {}
}
}
return btxt.toString();
}
private void updatePreview() {
fPreviewDocument.set(new CodeFormatter(fWorkingValues).format(fPreviewText));
}
private void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
Text curr= (Text) fTextBoxes.get(i);
String key= (String) curr.getData();
String currValue= (String) fWorkingValues.get(key);
curr.setText(currValue);
}
}
private IStatus validatePositiveNumber(String number) {
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(JavaUIMessages.getString("CodeFormatterPreferencePage.empty_input"));
} else {
try {
int value= Integer.parseInt(number);
if (value < 0) {
status.setError(JavaUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number));
}
} catch (NumberFormatException e) {
status.setError(JavaUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number));
}
}
return status;
}
private void updateStatus(IStatus status) {
if (!status.matches(IStatus.ERROR)) {
// look if there are more severe errors
for (int i= 0; i < fTextBoxes.size(); i++) {
Text curr= (Text) fTextBoxes.get(i);
if (!(curr == fTabSizeTextBox && usesTabs())) {
IStatus currStatus= validatePositiveNumber(curr.getText());
status= StatusUtil.getMoreSevere(currStatus, status);
}
}
}
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private boolean usesTabs() {
return TAB.equals(fWorkingValues.get(PREF_TAB_CHAR));
}
}
|
5,264 | Bug 5264 Class detail filtering options in packages view. | Build 20011018. The new build allows the user to expand classes in the packages view and look at their contents. (methods and fields) It would be nice to be able to filter out this view so it didn't show you the field if you didn't want it to. (e.g. have the same options as you do in the Outline view for a Java file) | resolved fixed | 425b5aa | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-17T11:01:14Z" | "2001-10-25T22:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/MembersFilterAction.java | |
5,264 | Bug 5264 Class detail filtering options in packages view. | Build 20011018. The new build allows the user to expand classes in the packages view and look at their contents. (methods and fields) It would be nice to be able to filter out this view so it didn't show you the field if you didn't want it to. (e.g. have the same options as you do in the Outline view for a Java file) | resolved fixed | 425b5aa | JDT | https://github.com/eclipse-jdt/eclipse.jdt.ui | eclipse-jdt/eclipse.jdt.ui | java | null | null | null | "2001-12-17T11:01:14Z" | "2001-10-25T22:46:40Z" | org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java | /*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.IPreferencesConstants;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.actions.StructuredSelectionProvider;
import org.eclipse.jdt.internal.ui.reorg.DeleteAction;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementSorter;
import org.eclipse.jdt.internal.ui.viewsupport.MarkerErrorTickProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.ui.wizards.NewGroup;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.search.ui.IWorkingSet;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenPerspectiveMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.help.ViewContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.internal.framelist.BackAction;
import org.eclipse.ui.views.internal.framelist.ForwardAction;
import org.eclipse.ui.views.internal.framelist.FrameList;
import org.eclipse.ui.views.internal.framelist.GoIntoAction;
import org.eclipse.ui.views.internal.framelist.UpAction;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener {
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_SHOWLIBRARIES = "showLibraries"; //$NON-NLS-1$
static final String TAG_SHOWBINARIES = "showBinaries"; //$NON-NLS-1$
static final String TAG_WORKINGSET = "workingset"; //$NON-NLS-1$
private JavaElementPatternFilter fPatternFilter= new JavaElementPatternFilter();
private LibraryFilter fLibraryFilter= new LibraryFilter();
private BinaryProjectFilter fBinaryFilter= new BinaryProjectFilter();
private WorkingSetFilter fWorkingSetFilter= new WorkingSetFilter();
private ProblemTreeViewer fViewer;
private PackagesFrameSource fFrameSource;
private FrameList fFrameList;
private ContextMenuGroup[] fStandardGroups;
private Menu fContextMenu;
private OpenResourceAction fOpenCUAction;
private Action fOpenToAction;
private Action fShowTypeHierarchyAction;
private Action fShowNavigatorAction;
private Action fPropertyDialogAction;
private RefactoringAction fDeleteAction;
private RefreshAction fRefreshAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private GoIntoAction fZoomInAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private AddBookmarkAction fAddBookmarkAction;
private FilterSelectionAction fFilterAction;
private ShowLibrariesAction fShowLibrariesAction;
private ShowBinariesAction fShowBinariesAction;
private FilterWorkingSetAction fFilterWorkingSetAction;
private RemoveWorkingSetFilterAction fRemoveWorkingSetAction;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
public PackageExplorerPart() {
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/**
* Initializes the default preferences
*/
public static void initDefaults(IPreferenceStore store) {
store.setDefault(TAG_SHOWLIBRARIES, true);
store.setDefault(TAG_SHOWBINARIES, true);
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fViewer != null)
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fViewer);
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
fViewer.setContentProvider(new JavaElementContentProvider(showCUChildren, false));
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fViewer);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(getLabelProviderFlags());
labelProvider.setErrorTickManager(new MarkerErrorTickProvider());
fViewer.setLabelProvider(new DecoratingLabelProvider(labelProvider, null));
fViewer.setSorter(new JavaElementSorter());
fViewer.addFilter(new EmptyInnerPackageFilter());
fViewer.setUseHashlookup(true);
fViewer.addFilter(fPatternFilter);
fViewer.addFilter(fLibraryFilter);
//fViewer.addFilter(fBinaryFilter);
fViewer.addFilter(fWorkingSetFilter);
if(fMemento != null)
restoreFilters();
else
initFilterFromPreferences();
// Set input after filter and sorter has been set. This avoids resorting
// and refiltering.
fViewer.setInput(findInputElement());
initDragAndDrop();
initFrameList();
initKeyListener();
updateTitle();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
getSite().registerContextMenu(menuMgr, fViewer);
makeActions(); // call before registering for selection changes
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick(event);
}
});
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
getSite().setSelectionProvider(fViewer);
getSite().getPage().addPartListener(fPartListener);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
// Set help for the view
// fixed for 1GETAYN: ITPJUI:WIN - F1 help does nothing
WorkbenchHelp.setHelp(fViewer.getControl(), new ViewContextComputer(this, IJavaHelpContextIds.PACKAGE_VIEW));
fillActionBars();
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
actionBars.updateActionBars();
IMenuManager menu= actionBars.getMenuManager();
menu.add(fFilterAction);
menu.add(fShowLibrariesAction);
//menu.add(fShowBinariesAction);
menu.add(fFilterWorkingSetAction);
menu.add(fRemoveWorkingSetAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= ((ILabelProvider) getViewer().getLabelProvider()).getText(element);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
IWorkingSet ws= fWorkingSetFilter.getWorkingSet();
if (ws == null)
return result;
String wsstr= "Working Set: "+ws.getName();
if (result.length() == 0)
return wsstr;
return result + " - " + wsstr;
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Sets the working set to be used for filtering this part
*/
public void setWorkingSet(IWorkingSet ws) {
fWorkingSetFilter.setWorkingSet(ws);
firePropertyChange(IWorkbenchPart.PROP_TITLE);
fFilterWorkingSetAction.setChecked(ws != null);
fRemoveWorkingSetAction.setEnabled(ws != null);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
boolean selectionHasElements= !selection.isEmpty();
Object element= selection.getFirstElement();
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// updateActions(selection);
if (selection.size() == 1 && fViewer.isExpandable(element))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
addGotoMenu(menu);
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction);
addOpenWithMenu(menu, selection);
addOpenToMenu(menu, selection);
addRefactoring(menu);
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
if (fAddBookmarkAction.canOperateOnSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddBookmarkAction);
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
fRefreshAction.selectionChanged(selection);
if (selectionHasElements) {
// update the action to use the right selection since the refresh
// action doesn't listen to selection changes.
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
}
void addGotoMenu(IMenuManager menu) {
MenuManager gotoMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.gotoTitle")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, gotoMenu);
gotoMenu.add(fBackAction);
gotoMenu.add(fForwardAction);
gotoMenu.add(fUpAction);
gotoMenu.add(fGotoTypeAction);
gotoMenu.add(fGotoPackageAction);
}
private void makeActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenCUAction= new OpenResourceAction(provider);
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
// fShowTypeHierarchyAction= new ShowTypeHierarchyAction(provider);
fShowNavigatorAction= new ShowInNavigatorAction(provider);
fAddBookmarkAction= new AddBookmarkAction(provider);
fStandardGroups= new ContextMenuGroup[] {
//new NewGroup(),
new BuildGroup(),
new ReorgGroup(),
new JavaSearchGroup()
};
fDeleteAction= new DeleteAction(provider);
fRefreshAction= new RefreshAction(getShell());
fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$
fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$
fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$
fBackAction= new BackAction(fFrameList);
fForwardAction= new ForwardAction(fFrameList);
fZoomInAction= new GoIntoAction(fFrameList);
fUpAction= new UpAction(fFrameList);
fGotoTypeAction= new GotoTypeAction(this);
fGotoPackageAction= new GotoPackageAction(this);
IActionBars actionService= getViewSite().getActionBars();
actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction);
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) {
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable) selection.getFirstElement();
IResource resource= (IResource)element.getAdapter(IResource.class);
if ((resource instanceof IContainer)) {
// Create a menu flyout.
MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$
submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource));
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE;
final LocalSelectionTransfer lt= LocalSelectionTransfer.getInstance();
Transfer[] transfers= new Transfer[] {
lt,
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
/**
* Handles key events in viewer.
*/
void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0){
fDeleteAction.update();
if (fDeleteAction.isEnabled())
fDeleteAction.run();
}
}
/**
* Handles double clicks in viewer.
* Opens editor if file double-clicked.
*/
private void handleDoubleClick(DoubleClickEvent event) {
IStructuredSelection s= (IStructuredSelection) event.getSelection();
Object element= s.getFirstElement();
if (fOpenCUAction.isEnabled()) {
fOpenCUAction.run();
return;
}
if (fViewer.isExpandable(element)) {
if (JavaBasePreferencePage.doubleClockGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
fViewer.setExpandedState(element, !fViewer.getExpandedState(element));
//expandMainType(element);
}
}
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel= (IStructuredSelection) event.getSelection();
//updateGlobalActions(sel);
fZoomInAction.update();
linkToEditor(sel);
}
public void selectReveal(ISelection selection) {
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
}
private ISelection convertSelection(ISelection s) {
List converted= new ArrayList();
if (s instanceof StructuredSelection) {
Object[] elements= ((StructuredSelection)s).toArray();
for (int i= 0; i < elements.length; i++) {
Object e= elements[i];
if (e instanceof IJavaElement)
converted.add(e);
else if (e instanceof IResource) {
IJavaElement element= JavaCore.create((IResource)e);
if (element != null)
converted.add(element);
else
converted.add(e);
}
}
}
return new StructuredSelection(converted.toArray());
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return JavaBasePreferencePage.linkPackageSelectionToEditor();
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
//if (!isLinkingEnabled())
// return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveScrollState(memento, fViewer.getTree());
savePatternFilterState(memento);
saveFilterState(memento);
saveWorkingSetState(memento);
}
protected void saveFilterState(IMemento memento) {
boolean showLibraries= getLibraryFilter().getShowLibraries();
String show= "true"; //$NON-NLS-1$
if (!showLibraries)
show= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWLIBRARIES, show);
//save binary filter
boolean showBinaries= getBinaryFilter().getShowBinaries();
String showBinString= "true"; //$NON-NLS-1$
if (!showBinaries)
showBinString= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWBINARIES, showBinString);
}
protected void savePatternFilterState(IMemento memento) {
String filters[] = getPatternFilter().getPatterns();
if(filters.length > 0) {
IMemento filtersMem = memento.createChild(TAG_FILTERS);
for (int i = 0; i < filters.length; i++){
IMemento child = filtersMem.createChild(TAG_FILTER);
child.putString(TAG_ELEMENT,filters[i]);
}
}
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
protected void saveWorkingSetState(IMemento memento) {
IWorkingSet ws= getWorkingSetFilter().getWorkingSet();
if (ws != null) {
memento.putString(TAG_WORKINGSET, ws.getName());
}
}
void restoreState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
restoreScrollState(memento, fViewer.getTree());
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
doKeyPressed(event);
}
});
}
private void doKeyPressed(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} else if (key == SWT.F4) {
OpenTypeHierarchyUtil.open(getSelection(), getSite().getWorkbenchWindow());
} else if (key == SWT.F3) {
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
fOpenCUAction.run();
}
}
void initFrameList() {
fFrameSource= new PackagesFrameSource(this);
fFrameList= new FrameList(fFrameSource);
fFrameSource.connectTo(fFrameList);
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IMember) {
IMember m= (IMember)o;
if (element.equals(m.getCompilationUnit()))
return;
if (element.equals(m.getClassFile()))
return;
}
}
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
}
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the pattern filter for this view.
* @return the pattern filter
*/
JavaElementPatternFilter getPatternFilter() {
return fPatternFilter;
}
/**
* Returns the library filter for this view.
* @return the library filter
*/
LibraryFilter getLibraryFilter() {
return fLibraryFilter;
}
/**
* Returns the working set filter for this view.
* @return the working set filter
*/
WorkingSetFilter getWorkingSetFilter() {
return fWorkingSetFilter;
}
/**
* Returns the Binary filter for this view.
* @return the binary filter
*/
BinaryProjectFilter getBinaryFilter() {
return fBinaryFilter;
}
void restoreFilters() {
IMemento filtersMem= fMemento.getChild(TAG_FILTERS);
if(filtersMem != null) {
IMemento children[]= filtersMem.getChildren(TAG_FILTER);
String filters[]= new String[children.length];
for (int i = 0; i < children.length; i++) {
filters[i]= children[i].getString(TAG_ELEMENT);
}
getPatternFilter().setPatterns(filters);
} else {
getPatternFilter().setPatterns(new String[0]);
}
//restore library
String show= fMemento.getString(TAG_SHOWLIBRARIES);
if (show != null)
getLibraryFilter().setShowLibraries(show.equals("true")); //$NON-NLS-1$
else
initLibraryFilterFromPreferences();
//restore binary fileter
String showbin= fMemento.getString(TAG_SHOWBINARIES);
if (showbin != null)
getBinaryFilter().setShowBinaries(showbin.equals("true")); //$NON-NLS-1$
else
initBinaryFilterFromPreferences();
//restore working set
String workingSetName= fMemento.getString(TAG_WORKINGSET);
if (workingSetName != null) {
IWorkingSet ws= SearchUI.findWorkingSet(workingSetName);
if (ws != null) {
getWorkingSetFilter().setWorkingSet(ws);
}
}
}
void initFilterFromPreferences() {
initBinaryFilterFromPreferences();
initLibraryFilterFromPreferences();
}
void initLibraryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean show= plugin.getPreferenceStore().getBoolean(TAG_SHOWLIBRARIES);
getLibraryFilter().setShowLibraries(show);
}
void initBinaryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean showbin= plugin.getPreferenceStore().getBoolean(TAG_SHOWBINARIES);
getBinaryFilter().setShowBinaries(showbin);
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= getViewer().getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
ILabelProvider labelProvider = (ILabelProvider) getViewer().getLabelProvider();
String inputText= labelProvider.getText(input);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
*/
public void setLabelDecorator(ILabelDecorator decorator) {
JavaElementLabelProvider javaProvider= new JavaElementLabelProvider(getLabelProviderFlags());
javaProvider.setErrorTickManager(new MarkerErrorTickProvider());
if (decorator == null) {
fViewer.setLabelProvider(javaProvider);
} else {
fViewer.setLabelProvider(new DecoratingLabelProvider(javaProvider, decorator));
}
}
/**
* Gets the standard label flags
*/
private int getLabelProviderFlags() {
return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS |
JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS;
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty() != IPreferencesConstants.SHOW_CU_CHILDREN)
return;
if (fViewer != null) {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
boolean b= store.getBoolean(IPreferencesConstants.SHOW_CU_CHILDREN);
((JavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(b);
fViewer.refresh();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.